Logo
TUTORIAL

Understanding Java Arrays

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 [].

Syntax:
dataType[] arrayName = {value1, value2, ...};

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.

3. Finding Array Length

You can find out how many elements an array has using the .length property. This is very useful for loops.

int[] numbers = {10, 20, 30, 40, 50}; System.out.println("Array Size: " + numbers.length);
// Output:
Array Size: 5

4. Looping through an Array

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.