On Day 10, we learn about arrays. An array in Java is a container object that holds multiple values of the same type. Instead of declaring many variables, we can store a list of values in one array. Arrays use indexes (starting from 0) to access elements.
1. Creating an Array
int[] numbers = new int[5]; // array of size 5
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
Explanation: Here we created an integer array with 5 slots. Each element is assigned using its index (0 to 4).
2. Accessing Array Elements
System.out.println(numbers[0]); // prints 10
System.out.println(numbers[4]); // prints 50
Explanation: We can access array elements directly by their index. Trying to access an index outside the range will cause an error.
3. Looping Through Arrays (for loop)
public class ArrayLoopExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
Explanation: The property numbers.length
gives the size of the array. Using a for
loop, we can access all elements.
4. Looping with for-each
public class ForEachExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
System.out.println(num);
}
}
}
Explanation: The for-each
loop automatically goes through every element of the array without using indexes.
Summary
Arrays let you store and process multiple values efficiently. You can create arrays with a fixed size, access them using indexes, and iterate with loops like for
and for-each
.