Arrays: Working with Collections
Duration: 5 min
What are Arrays?
An array is a collection of elements of the same type stored in contiguous memory locations. Arrays allow you to store multiple values in a single variable, making it easy to work with groups of related data. Each element in an array is accessed by its index, starting from 0.
Creating and Initializing Arrays
public class ArrayBasics {
public static void main(String[] args) {
// Method 1: Declare and specify size
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Method 2: Initialize with values
String[] colors = {"Red", "Green", "Blue", "Yellow"};
// Method 3: Using new keyword with initialization
double[] prices = new double[]{19.99, 29.99, 39.99};
System.out.println("First number: " + numbers[0]);
System.out.println("Array length: " + numbers.length);
System.out.println("First color: " + colors[0]);
}
}First number: 10
Array length: 5
First color: RedAccessing and Modifying Array Elements
public class ArrayOperations {
public static void main(String[] args) {
int[] scores = {85, 90, 78, 92, 88};
// Access elements
System.out.println("First score: " + scores[0]);
System.out.println("Last score: " + scores[scores.length - 1]);
// Modify elements
scores[0] = 95;
System.out.println("Updated first score: " + scores[0]);
// Iterate through array
System.out.println("All scores:");
for (int score : scores) {
System.out.println(score);
}
}
}First score: 85
Last score: 88
Updated first score: 95
All scores:
95
90
78
92
88Multi-dimensional Arrays
Arrays can have multiple dimensions. A 2D array is like a table with rows and columns. This is useful for representing matrices, game boards, or any grid-like data.
public class MultiDimensionalArray {
public static void main(String[] args) {
// 2D array - 3 rows, 3 columns
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Access elements
System.out.println("Element at [0][0]: " + matrix[0][0]);
System.out.println("Element at [1][1]: " + matrix[1][1]);
System.out.println("Element at [2][2]: " + matrix[2][2]);
// Print entire matrix
System.out.println("\nMatrix:");
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();
}
}
}Element at [0][0]: 1
Element at [1][1]: 5
Element at [2][2]: 9
Matrix:
1 2 3
4 5 6
7 8 9💡 Tip: Array indices start at 0, not 1. The last element is at index length-1. Accessing an index outside this range causes an ArrayIndexOutOfBoundsException.
Learn more: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
❓ If an array has 5 elements, what is the index of the last element?
❓ What is a best practice when working with Arrays?
💡 Tip: Pro Tip: Master Arrays thoroughly. This foundation is crucial for writing professional Java code.