Arrays & Collections

Arrays

Store multiple values of the same type.

Declaring Arrays

// Method 1: Declare then initialize
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;

// Method 2: Declare and initialize
int[] scores = {85, 90, 78, 92, 88};

Accessing Elements

int[] arr = {10, 20, 30};

arr[0];     // 10 (first element)
arr[2];     // 30 (third element)
arr.length; // 3 (array size)

Looping Through Arrays

int[] nums = {1, 2, 3, 4, 5};

// For loop
for (int i = 0; i < nums.length; i++) {
    System.out.println(nums[i]);
}

// Enhanced for loop
for (int num : nums) {
    System.out.println(num);
}
Visualizer
$ java Main.java
Scores: [85, 90, 78, 92, 88] Average: 86.6

Interactive Visualization

java
Loading...
Output
Run execution to see output...