Java Basics, Java Programming · December 2, 2026

Java for Beginners, Lesson 21: Arrays in Java (One-Dimensional)

Java for Beginners · Module 5: Data and Methods


🎯 Why Arrays?

To store the marks of 100 students you would not create 100 separate variables. An array stores many values of the same type under one name, in a fixed-size row, and you reach each one with a number called the index.

📌 An array is a fixed-size collection of values of one type. Indexes start at 0 and end at length – 1.

1️⃣ Creating and Using Arrays

int[] scores = {60, 75, 80, 95};
60
[0]
75
[1]
80
[2]
95
[3]
4 elements stored side by side. Index starts at 0; the last index is length - 1 = 3.

Figure 1: An array is a row of boxes, each with an index.

  • Declare and size it: int[] marks = new int[5]; makes room for 5 ints.
  • Declare with values: int[] scores = {60, 75, 80, 95}; The size is the number of values.
  • Read or write one element: marks[1].
  • Size: marks.length. It has no brackets because it is a field, not a method.
Element typeDefault value
int, short, byte, long0
double, float0.0
booleanfalse
charcharacter with code 0
String and other objectsnull

Figure 2: What an array holds before you assign anything.

Program 1: Array basics

public class ArrayBasics {
    public static void main(String[] args) {
        int[] marks = new int[5];
        marks[0] = 70;
        marks[1] = 85;
        marks[2] = 90;
        System.out.println("length = " + marks.length);
        System.out.println("marks[1] = " + marks[1]);
        System.out.println("marks[4] (not set) = " + marks[4]);

        int[] scores = {60, 75, 80, 95};
        for (int i = 0; i < scores.length; i++) {
            System.out.println("scores[" + i + "] = " + scores[i]);
        }

        String[] names = new String[2];
        double[] prices = new double[2];
        boolean[] flags = new boolean[2];
        System.out.println(names[0] + " " + prices[0] + " " + flags[0]);
    }
}
🖥️ Output:
length = 5
marks[1] = 85
marks[4] (not set) = 0
scores[0] = 60
scores[1] = 75
scores[2] = 80
scores[3] = 95
null 0.0 false
  • Elements you never set hold the default for their type: 0 for int, 0.0 for double, false for boolean and null for objects.
  • The loop condition i < scores.length visits indexes 0 to 3 exactly. A for loop is the natural partner of an array (Lesson 19).

2️⃣ Common Array Operations

TaskCode
Number of elementsa.length (no brackets!)
Print an array nicelyArrays.toString(a)
SortArrays.sort(a)
CopyArrays.copyOf(a, a.length) or a.clone()
Compare contentsArrays.equals(a, b)
Search a sorted arrayArrays.binarySearch(a, key)

Figure 4: Everyday array tools. Import java.util.Arrays.

Program 2: Sum, maximum, minimum, sort and reverse

import java.util.Arrays;

public class ArrayOps {
    public static void main(String[] args) {
        int[] a = {42, 7, 19, 3, 25};

        int sum = 0, max = a[0], min = a[0];
        for (int x : a) {
            sum += x;
            if (x > max) max = x;
            if (x < min) min = x;
        }
        System.out.println("sum = " + sum + ", max = " + max + ", min = " + min);
        System.out.println("average = " + (double) sum / a.length);

        int[] copy = Arrays.copyOf(a, a.length);
        Arrays.sort(copy);
        System.out.println("original = " + Arrays.toString(a));
        System.out.println("sorted   = " + Arrays.toString(copy));
        System.out.println("index of 19 in sorted = " + Arrays.binarySearch(copy, 19));

        for (int i = 0, j = a.length - 1; i < j; i++, j--) {
            int t = a[i]; a[i] = a[j]; a[j] = t;
        }
        System.out.println("reversed = " + Arrays.toString(a));
    }
}
🖥️ Output:
sum = 96, max = 42, min = 3
average = 19.2
original = [42, 7, 19, 3, 25]
sorted = [3, 7, 19, 25, 42]
index of 19 in sorted = 2
reversed = [25, 3, 19, 7, 42]
  • Start max and min with the first element, not with 0, so the result is right even when all numbers are negative.
  • The cast (double) sum keeps the fraction of the average (Lesson 9).
  • Arrays.sort changes the array it is given, so the program sorts a copy to keep the original order.
  • binarySearch works only on a sorted array and returns the index where the value sits.
  • Reversing swaps the first and last elements, then the second and second-last, with two indexes moving towards each other. The three-line swap with t exchanges two values.

Program 3: Counting with an array (frequency)

public class Freq {
    public static void main(String[] args) {
        int[] votes = {2, 0, 1, 2, 2, 1, 0, 2};
        int[] count = new int[3];
        for (int v : votes) {
            count[v]++;
        }
        for (int i = 0; i < count.length; i++) {
            System.out.println("Candidate " + i + ": " + count[i]);
        }
    }
}
🖥️ Output:
Candidate 0: 2
Candidate 1: 2
Candidate 2: 4
  • Each vote is used as an index into count, so count[v]++ adds one to that candidate’s tally. This trick is the basis of many counting problems.

3️⃣ Arrays Are Objects: Copying Is Not What It Looks Like

An array variable does not hold the values. It holds a reference (an address) to the array in memory. So b = a does not copy the array. It makes both names point to the same array.

a ➜ [99, 2, 3] (one array in memory) ⬅ b
c = a.clone() ➜ [99, 55, 3] (a separate copy)

Figure 3: b = a shares one array. clone() makes a new one.

import java.util.Arrays;

public class RefDemo {
    public static void main(String[] args) {
        int[] a = {1, 2, 3};
        int[] b = a;
        b[0] = 99;
        System.out.println("a = " + Arrays.toString(a));
        System.out.println("a == b ? " + (a == b));

        int[] c = a.clone();
        c[1] = 55;
        System.out.println("a = " + Arrays.toString(a));
        System.out.println("c = " + Arrays.toString(c));
        System.out.println("a == c ? " + (a == c));
        System.out.println("Arrays.equals(a, new int[]{99,2,3}) ? " + Arrays.equals(a, new int[]{99, 2, 3}));
        System.out.println(a);
    }
}
🖥️ Output:
a = [99, 2, 3]
a == b ? true
a = [99, 2, 3]
c = [99, 55, 3]
a == c ? false
Arrays.equals(a, new int[]{99,2,3}) ? true
[I@12a3a380
  • Changing b[0] also changed a, because there is only one array.
  • clone() makes a real copy, so changing c leaves a alone.
  • == on arrays asks “same array?”, not “same contents?”. Use Arrays.equals to compare contents.
  • Printing an array directly gives something like [I@12a3a380: the type and an address. The exact digits differ on each run. Use Arrays.toString.

4️⃣ Errors Beginners Meet

Index outside the array (runtime)

public class Oob {
    public static void main(String[] args) {
        int[] a = new int[3];
        for (int i = 0; i <= a.length; i++) {
            a[i] = i * 10;
        }
    }
}
🖥️ Runtime error:
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Oob.main(Oob.java:5)
  • The array has indexes 0, 1, 2. The loop condition i <= a.length reaches 3. Use i < a.length. Java checks every index, which is why it stops safely instead of damaging memory.

A negative size (runtime)

public class Neg {
    public static void main(String[] args) {
        int[] a = new int[-2];
    }
}
🖥️ Runtime error:
Exception in thread “main” java.lang.NegativeArraySizeException: -2
at Neg.main(Neg.java:3)

length() instead of length, and wrong element type

public class Bad4 {
    public static void main(String[] args) {
        int[] a = new int[3];
        int n = a.length();
        String s = a[1];
    }
}
🖥️ Compiler message:
Bad4.java:4: error: cannot find symbol
int n = a.length();
^
symbol: method length()
location: variable a of type int[]
Bad4.java:5: error: incompatible types: int cannot be converted to String
String s = a[1];
^
2 errors
  • For arrays use length without brackets. (String uses length() with brackets, see Lesson 23.)

Assigning a list of values to an existing array

public class Bad3 {
    public static void main(String[] args) {
        int[] a = new int[3];
        a = {1, 2, 3};
    }
}
🖥️ Compiler message:
Bad3.java:4: error: illegal start of expression
a = {1, 2, 3};
^
Bad3.java:4: error: not a statement
a = {1, 2, 3};
^
Bad3.java:4: error: ‘;’ expected
a = {1, 2, 3};
^
3 errors
  • The shortcut {1, 2, 3} works only in the declaration. Later, write a = new int[]{1, 2, 3};.

⚠️ Common Mistakes

MistakeProblemFix
Using i <= a.lengthIndex one too fari < a.length
a.length()length is a field for arraysa.length
b = a expecting a copyBoth names share one arraya.clone() or Arrays.copyOf
a == b to compare contentsCompares referencesArrays.equals(a, b)
Printing a directlyPrints type and addressArrays.toString(a)
Trying to resize an arraySize is fixedMake a new bigger one, or use ArrayList (Lesson 27)
Starting max with 0Wrong if all values are negativeStart with a[0]

❓ Frequently Asked Questions

Q1. Can an array hold different types?
Not a plain primitive array. All elements share one type.

Q2. Can I change the size of an array?
No. Create a new array and copy the values, or use an ArrayList.

Q3. Why do indexes start at 0?
The index is the distance from the start of the array. The first element is 0 steps from the start.

Q4. What is the difference between int[] a and int a[]?
Both work. int[] a is the Java style because the type is int[].

✅ Key Takeaways

  • An array stores same-type values in a fixed-size row, indexed from 0 to length – 1.
  • new int[5] gives five zeros. {1, 2, 3} gives the listed values.
  • a.length is the size (no brackets).
  • Arrays are objects. b = a shares the array. Use clone() or Arrays.copyOf to copy.
  • Use Arrays.toString, sort, equals and binarySearch from java.util.Arrays.
  • A bad index throws ArrayIndexOutOfBoundsException.
🎓 Practice questions: (1) Read 5 numbers into an array and print them in reverse. (2) Find the second largest element of an array. (3) Count how many even numbers an array contains. (4) Why does changing b[0] change a[0] after int[] b = a;? (5) Write a program that removes duplicates from a sorted array and prints the result.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision