Arrays in Java

    Atul Kabra3 min readUpdated

    An array is a fixed-size container that holds many values of the same type, laid out in order and accessed by a numeric index starting at 0. If you need to store five marks, seven temperatures, or a row of names, an array does it in one variable. Arrays are reference types: the variable holds a handle to the array object, and the array's size is set when you create it and cannot change afterward.

    Declaring and creating an array

    int[] marks = new int[5];   // an array of 5 ints, all default to 0
    String[] names = new String[3]; // 3 Strings, all default to null
    

    new int[5] allocates space for five int slots. Every slot starts at a default value: 0 for numbers, false for boolean, null for objects.

    Initializing with values

    int[] scores = {88, 92, 75, 60, 100}; // literal initializer — size is inferred
    double[] prices = {99.0, 149.5, 249.0};
    

    Accessing and changing elements

    Indexing starts at 0, so the first element is scores[0] and the last is scores[length - 1].

    int[] scores = {88, 92, 75};
    System.out.println(scores[0]); // 88  (first element)
    scores[2] = 80;                // change the third element to 80
    System.out.println(scores.length); // 3  (note: length is a field, no parentheses)
    

    Reading or writing outside the valid range throws an ArrayIndexOutOfBoundsException at runtime.

    Looping over an array

    int[] scores = {88, 92, 75, 60, 100};
    
    // Classic for loop — gives you the index.
    for (int i = 0; i < scores.length; i++) {
        System.out.println("Index " + i + ": " + scores[i]);
    }
    
    // Enhanced for loop — when you only need the values.
    int total = 0;
    for (int s : scores) {
        total += s;
    }
    System.out.println("Average: " + (total / scores.length));
    

    Want to learn this properly?

    Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.

    Browse courses

    Multidimensional arrays

    An array of arrays models a grid or table:

    // A 2x3 grid (2 rows, 3 columns).
    int[][] grid = {
        {1, 2, 3},
        {4, 5, 6}
    };
    System.out.println(grid[1][2]); // 6  (row 1, column 2)
    
    // Walk every cell.
    for (int r = 0; r < grid.length; r++) {        // rows
        for (int c = 0; c < grid[r].length; c++) { // columns in this row
            System.out.print(grid[r][c] + " ");
        }
        System.out.println();
    }
    

    The Arrays utility class

    java.util.Arrays provides ready-made helpers so you do not write sorting and searching by hand:

    import java.util.Arrays;
    
    int[] data = {5, 2, 9, 1};
    Arrays.sort(data);                       // sorts in place: {1, 2, 5, 9}
    System.out.println(Arrays.toString(data)); // [1, 2, 5, 9]
    int idx = Arrays.binarySearch(data, 5);  // 2  (only valid on a sorted array)
    int[] copy = Arrays.copyOf(data, 6);     // grows to length 6, padding with 0
    

    When an array is not enough

    Arrays have a fixed size. If you need to add or remove elements as your program runs, you want a List such as ArrayList, covered in the collections tutorial.

    Common mistakes

    • Off-by-one indexing. Valid indices are 0 to length - 1. Using scores[scores.length] throws an exception.
    • Confusing length with length(). Arrays use the field array.length (no parentheses); String uses the method text.length().
    • Expecting arrays to grow. Size is fixed at creation. Use Arrays.copyOf to make a bigger copy, or use a List.
    • Forgetting default values. A freshly created int[] is full of zeros, and a String[] is full of null — reading those nulls can cause a NullPointerException.
    • binarySearch on an unsorted array. It only works correctly after Arrays.sort.

    FAQ

    Can an array hold mixed types? No. Every element must be the declared type (or, for object arrays, a subtype of it).

    How do I copy an array? Use Arrays.copyOf or array.clone(). A plain assignment (b = a) copies only the reference, so both variables point at the same array.

    Keep going

    Next, step into objects with OOP in Java, or review Control Flow in Java. All tutorials live on the Java hub; for guided practice in Jalgaon, see the Java course.


    Build real programs with arrays and beyond at Infoplanet, Jalgaon. Join the waitlist for the Java course.

    Want to learn this properly?

    Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.

    Browse courses
    Atul Kabra

    Founder, Infoplanet

    Atul Kabra founded Infoplanet in 2001 and has spent over two decades teaching programming — C, C++, Java, databases and more — to students across Maharashtra.

    Related guides