Intern
What are arrays in Java?
sobes.tech AI
Answer from AI
These are objects that store a fixed number of homogeneous elements. They are indexed starting from 0. The size of the array is determined at its creation.
When an array is created, its elements are initialized with default values:
- for numeric types -
0 - for
boolean-false - for reference types -
null
Array declaration:
// declaring an array of integers
int[] numbers;
// declaring an array of strings
String[] names;
Creating and initializing an array:
// creating an array of 5 integers
int[] numbers = new int[5];
// creating an array of strings with predefined values
String[] names = {"Alice", "Bob", "Charlie"};
Accessing array elements:
// accessing the first element of the numbers array
int firstNumber = numbers[0];
// changing the value of the second element in the names array
names[1] = "David";
Array length:
// getting the length of the numbers array
int length = numbers.length;
Arrays in Java are objects and are stored in the heap. The array variable holds a reference to this object.
Multidimensional arrays in Java are implemented as arrays of arrays.
// declaring and creating a 3x4 two-dimensional array
int[][] matrix = new int[3][4];
// accessing an element in the first row, second column
int value = matrix[0][1];