Author
Arrays are one of the most important data structures in Java. They allow you to store multiple values of the same type in a single variable, making your code more organized and efficient.
0.int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers[2]); // 30
Here, numbers is an array of integers. numbers[2] accesses the third element (index starts from 0).
Visual Representation of the Array:
Index → 0 1 2 3 4
Value → [10] [20] [30] [40] [50]There are two main steps: declaration and initialization.
int[] arr1; // Preferred way
int arr2[]; // Also valid
arr1 = new int[5]; // Creates an array of 5 integers (default 0)
int[] scores = {90, 80, 70, 60, 50};
public class ArrayIntro {
public static void main(String[] args) {
// Declaration and Initialization
int[] numbers = new int[5];
// Assign values
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Access and print values
for(int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
Output:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50