Definition:
An Array is a collection of similar types of elements which has a contiguous memory location. In Java, arrays are objects that store a fixed-size sequential collection of elements of the same type.
1. Declaration and Execution
To use an array, you first define the type of data it will hold, followed by square brackets [].
public class ArraySample {
public static void main(String[] args) {
// Creating an array of Strings
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
// Accessing the first element
System.out.println("First car: " + cars[0]);
// Changing an element
cars[0] = "Tesla";
System.out.println("Updated first car: " + cars[0]);
}
}
// Output:
First car: Volvo
Updated first car: Tesla
2. Zero-Based Indexing
Important: Computers start counting from 0.
[0] is the 1st element.
[1] is the 2nd element.
If you have 4 items, the last index is 3.
3. Finding Array Length
You can find out how many elements an array has using the .length property. This is very useful for loops.
The most common way to process array data is using a for loop or the "Enhanced For Loop" (for-each).
String[] fruits = {"Apple", "Banana", "Cherry"};
// The 'For-Each' Loop (Easier to read)
for (String f : fruits) {
System.out.println("Fruit name: " + f);
}
// Output:
Fruit name: Apple
Fruit name: Banana
Fruit name: Cherry
Pro Insight: Once you create an array in Java, you cannot change its size. If you need a list that grows and shrinks, you would use something called an ArrayList, which is part of the Java Collections Framework.