</>
Skip to content
Java lessons (19/47)

Java — Arrays

What is an array?

An array holds multiple values of the same type under one name. Instead of writing 10 separate variables, you write one array:

// Without arrays — tedious
String fruit1 = "apple";
String fruit2 = "banana";
String fruit3 = "cherry";

// With arrays — clean
String[] fruits = {"apple", "banana", "cherry"};

Arrays are fixed-size — once created, you can't add or remove elements. For dynamic sizing, use ArrayList (covered later).

Declaration and initialization

Three ways to create an array:

// 1. Literal initialization
int[] numbers = {10, 20, 30, 40, 50};

// 2. Specifying size (elements get default values)
String[] names = new String[5];   // all null

// 3. Combining both
int[] scores = new int[]{95, 87, 72};

Default values for new Type[size]:

TypeDefault
int0
double0.0
booleanfalse
Stringnull

Accessing elements

Arrays are zero-indexed — the first element is at position 0:

String[] colors = {"red", "green", "blue"};

System.out.println(colors[0]);  // red
System.out.println(colors[1]);  // green
System.out.println(colors[2]);  // blue

Accessing beyond the array size throws ArrayIndexOutOfBoundsException:

System.out.println(colors[3]);  // crash!

Modifying elements

int[] scores = {10, 20, 30};
scores[1] = 25;
System.out.println(scores[1]);  // 25

You can change any element at any time — the array size stays the same.

Array length

String[] fruits = {"apple", "banana", "cherry"};
System.out.println(fruits.length);  // 3

Note: length is a property, not a method — no parentheses. This differs from String.length() and ArrayList.size().

Iterating over arrays

int[] numbers = {10, 20, 30, 40, 50};

// Classic for loop
for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}

// Enhanced for loop (cleaner, no index needed)
for (int num : numbers) {
    System.out.println(num);
}

Use the enhanced loop when you just need values. Use the indexed loop when you need the position — like modifying elements or comparing neighbors.

Common array operations

Sum and average

int[] grades = {85, 92, 78, 90, 88};
int sum = 0;

for (int grade : grades) {
    sum += grade;
}

double average = (double) sum / grades.length;
System.out.println("Average: " + average);  // 86.6

Finding min and max

int[] temps = {72, 68, 75, 80, 65};
int min = temps[0];
int max = temps[0];

for (int temp : temps) {
    if (temp < min) min = temp;
    if (temp > max) max = temp;
}

System.out.println("Min: " + min + ", Max: " + max);

Searching for a value

String[] names = {"Ada", "Grace", "Linus"};
String target = "Grace";
int position = -1;

for (int i = 0; i < names.length; i++) {
    if (names[i].equals(target)) {
        position = i;
        break;
    }
}

if (position != -1) {
    System.out.println(target + " found at index " + position);
} else {
    System.out.println(target + " not found");
}

Passing arrays to methods

Arrays are reference types — when you pass one to a method, changes inside the method affect the original:

static void doubleValues(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
        arr[i] *= 2;
    }
}

public static void main(String[] args) {
    int[] nums = {1, 2, 3};
    doubleValues(nums);
    System.out.println(Arrays.toString(nums));  // [2, 4, 6]
}

The method receives a reference to the same array, not a copy.

Arrays utility class

Java provides java.util.Arrays with helpful static methods:

int[] nums = {5, 2, 8, 1, 9};

Arrays.sort(nums);                          // sorts in place
System.out.println(Arrays.toString(nums));   // [1, 2, 5, 8, 9]

int index = Arrays.binarySearch(nums, 5);   // 2 (index of 5)
System.out.println(index);

int[] filled = new int[5];
Arrays.fill(filled, 42);                    // [42, 42, 42, 42, 42]

int[] copied = Arrays.copyOf(nums, nums.length);  // copy

Multidimensional arrays

Arrays of arrays:

int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

System.out.println(matrix[0][0]);  // 1
System.out.println(matrix[1][2]);  // 6

Iterating with nested loops:

for (int row = 0; row < matrix.length; row++) {
    for (int col = 0; col < matrix[row].length; col++) {
        System.out.print(matrix[row][col] + " ");
    }
    System.out.println();
}

Output:

1 2 3
4 5 6
7 8 9

Array limitations

  • Fixed size — can't grow or shrink
  • Can only store one type
  • No built-in methods for common operations (searching, filtering)
  • Creating a new array copies all elements manually

When you need flexibility, ArrayList provides dynamic sizing with methods for adding, removing, and searching.

Mini Practice

  1. Create an array of 5 integers and print each value with its index
  2. Write a method that reverses an array in place
  3. Find the second largest number in an integer array
  4. Merge two sorted arrays into one sorted array
  5. Count how many times a specific value appears in an array

Next: reusable code with methods →

Related Topics

Frequently Asked Questions about Arrays

What is Arrays in Java?

Arrays is a fundamental concept in Java. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Arrays?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Arrays.

Why is Arrays important in Java?

Arrays is essential for Java development. Understanding this concept will help you write better code and solve real-world problems more effectively.