What is an Array in Java?
An array is a collection of elements of the same type stored in a contiguous memory location. Arrays have a fixed size once defined.
Declaring and Initializing Arrays
1️⃣ Declaration
int[] numbers; // Preferred way
String names[]; // Also valid
2️⃣ Instantiation (Create with size)
numbers = new int[5]; // Array with 5 elements, default value 0
3️⃣ Declaration + Initialization
int[] scores = new int[3]; // [0, 0, 0]
String[] cities = {"Delhi", "Mumbai", "Chennai"};
Accessing Array Elements
- Use index (starts from
0
).
System.out.println(cities[1]); // Output: Mumbai
scores[0] = 90; // Assigning value
Example 1: Integer Array
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
System.out.println("First element: " + numbers[0]); // 10
System.out.println("Third element: " + numbers[2]); // 30
}
}
Example 2: Loop Through an Array
Using a for
loop:
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
Using an enhanced for
loop:
for (int num : numbers) {
System.out.println(num);
}
Example 3: String Array
public class StringArray {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Mango"};
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
Array Properties
Property |
Example |
Fixed Size |
Can’t change after init |
Indexing |
Starts at 0 |
Default Values |
int → 0, boolean → false, Object → null |
Bonus: Multidimensional Array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(matrix[1][2]); // Output: 6