← Back to Learn
Intermediate
Collections & Data Structures
Learn to organize and manipulate data efficiently with Java's powerful collection framework.
Topics
Collections & Data Structures
Arrays
Arrays are fixed-size containers that hold elements of the same type. They are the foundation of data structures in Java.
Declaring and Initializing Arrays
// Method 1: Declare then initialize
int[] numbers = new int[5]; // Array of 5 integers
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Method 2: Declare and initialize together
int[] scores = {95, 87, 92, 78, 88};
// String array
String[] names = {"Alice", "Bob", "Charlie"};
// Access elements
System.out.println(names[0]); // Alice
System.out.println(scores[2]); // 92
// Array length
System.out.println("Length: " + names.length); // 3Looping Through Arrays
String[] fruits = {"Apple", "Banana", "Orange", "Mango"};
// Using for loop
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}
// Using for-each loop (enhanced for loop)
for (String fruit : fruits) {
System.out.println(fruit);
}
// Using Arrays.toString() for quick printing
System.out.println(Arrays.toString(fruits));
// Output: [Apple, Banana, Orange, Mango]Multi-Dimensional Arrays
// 2D Array (matrix)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Access elements
System.out.println(matrix[0][0]); // 1
System.out.println(matrix[1][2]); // 6
// Loop through 2D array
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}Common Array Operations
import java.util.Arrays;
int[] numbers = {5, 2, 8, 1, 9};
// Sort array
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // [1, 2, 5, 8, 9]
// Binary search (array must be sorted)
int index = Arrays.binarySearch(numbers, 5);
System.out.println("Index of 5: " + index); // 2
// Fill array with a value
int[] filled = new int[5];
Arrays.fill(filled, 10);
System.out.println(Arrays.toString(filled)); // [10, 10, 10, 10, 10]
// Copy array
int[] copy = Arrays.copyOf(numbers, numbers.length);
// Compare arrays
boolean areEqual = Arrays.equals(numbers, copy);
System.out.println("Arrays equal: " + areEqual); // true