In Java, arrays are a fundamental data structure that stores a fixed-size sequential collection of elements of the same type.
Declaration
dataType[] arrayName;
Example:
int[] numbers;
Initialization
Arrays can be initialized in several ways:
Using the
new
Keywordint[] numbers = new int[5]; // Creates an array of 5 zeros
Directly with values
int[] numbers = {1, 2, 3, 4, 5};
Combining declaration and initialization
int[] numbers = new int[]{1, 2, 3, 4, 5};
Accessing Elements
Elements of an array are accessed using their index. The index starts from 0.
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[0]); // Outputs: 1
Array Length
The length of an array can be obtained using the length
property.
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers.length); // Outputs: 5
Multidimensional Arrays
Java supports multidimensional arrays, which are arrays of arrays.
Declaration
int[][] matrix = new int[3][3];
Initialization
int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
Array Methods
Java provides several utility methods for arrays in the java.util.Arrays
class.
Sorting
int[] numbers = {5, 3, 4, 1, 2}; Arrays.sort(numbers);
Searching
int[] numbers = {1, 2, 3, 4, 5}; int index = Arrays.binarySearch(numbers, 3);
Filling
int[] numbers = new int[5]; Arrays.fill(numbers, 10);
Copying
int[] numbers = {1, 2, 3, 4, 5}; int[] copy = Arrays.copyOf(numbers, numbers.length);
Array Limitations
Fixed Size: Once an array is created, its size cannot be changed.
Homogeneous: All elements in an array must be of the same type.
Array of Objects
Arrays can also hold objects.
String[] names = new String[3];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";
Enhanced for Loop
Java provides an enhanced for loop to iterate over arrays.
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
Thank you for reading!
You can support me by buying me a book.