π What is an Array?
An array is a collection of elements that are:
Stored in contiguous memory locations
Of the same data type
Accessed using a zero-based index
Arrays allow us to store multiple values under a single variable name.
β Key Characteristics
Fixed Size: The size is set during array creation and cannot be changed.
Indexed Access: Elements are accessed using indices starting from
0.Homogeneous Elements: All elements must be of the same data type.
Object in Java: Even primitive type arrays (like
int[]) are objects.
π Array Declaration
There are two ways to declare an array in Java:
int[] numbers; // Recommended
int numbers[]; // Also validποΈ Array Creation (Instantiation)
After declaration, we create the array using new:
numbers = new int[5]; // Creates an array to hold 5 integersElements will be automatically initialized (e.g., 0 for int, false for boolean, null for objects).
π§Ύ Declaration + Initialization Together
You can declare and initialize an array in one line:
int[] scores = {90, 85, 78, 92, 88};Here, the array size is inferred automatically (5 in this case).
π§ Array Memory Representation
Example:
int[] marks = {60, 70, 80};Index | Value |
|---|---|
0 | 60 |
1 | 70 |
2 | 80 |
π Length of an Array
You can use .length to find the size of the array:
int[] marks = {95, 88, 76};
System.out.println(marks.length); // Output:33π Note: .length is a property, not a method (so no parentheses like length()).
β οΈ ArrayIndexOutOfBoundsException
Trying to access an index outside the valid range will throw an exception:
int[] marks = {95, 88, 76};
System.out.println(marks[5]); // β Error: Index 5 out of boundsException in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3 at ArrayExample.main(ArrayExample.java:4)π§ͺ Sample Program
public class ArrayExample {
public static void main(String[] args) {
int[] ages = {18, 21, 24};
System.out.println("First element: " + ages[0]);
System.out.println("Array length: " + ages.length);
}
}First element: 18
Array length: 3