Reading history

Java Arrays: Declare, Loop, Sort and 2D Arrays

4 min read 0 views

Learn Java arrays: creating and filling them, length, looping, Arrays.sort and binarySearch, 2D arrays, copying and index errors.

An array stores a fixed number of values of the same type under one name: the marks of four students, the prices of three items. Each value has an index starting at 0. This lesson covers creating, reading, changing and looping over arrays, the helpful Arrays class, 2D arrays, copying, and the error you get when you go past the end.

In this lesson you will learn

  • Two ways to create an array, and the default values
  • How to read, change and loop over elements
  • Sorting, searching and printing with java.util.Arrays
  • Two-dimensional arrays
  • Why assigning an array does not copy it

Creating and Using Arrays

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] marks = {78, 92, 65, 88};
        System.out.println("First: " + marks[0] + ", length: " + marks.length);

        marks[2] = 70;
        int total = 0;
        for (int m : marks) total += m;
        System.out.println("Average: " + (double) total / marks.length);

        double[] prices = new double[3];      // filled with 0.0
        prices[0] = 120.5;
        System.out.println(Arrays.toString(prices));

        Arrays.sort(marks);
        System.out.println(Arrays.toString(marks));
        System.out.println("Index of 88: " + Arrays.binarySearch(marks, 88));
    }
}

Output

First: 78, length: 4
Average: 82.0
[120.5, 0.0, 0.0]
[70, 78, 88, 92]
Index of 88: 2
  • int[] marks = {78, 92, 65, 88}; creates and fills an array in one line.
  • new double[3] creates an empty array of size 3. Numbers default to 0, booleans to false, and objects to null.
  • marks.length (no brackets) gives the size, which cannot change after creation.
  • The (double) cast makes the average a decimal instead of an integer.
  • Arrays.toString() prints the contents; printing the array directly shows a meaningless code such as [I@1b6d3586.
  • Arrays.binarySearch() only works on a sorted array. See Binary Search for how it works.

2D Arrays, Copies and Index Errors

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] grid = {
            {1, 2, 3},
            {4, 5, 6}
        };
        System.out.println(grid[1][2] + " rows=" + grid.length + " cols=" + grid[0].length);
        for (int[] row : grid) {
            System.out.println(Arrays.toString(row));
        }

        int[] a = {1, 2, 3};
        int[] alias = a;              // same array, two names
        int[] copy = a.clone();       // a real copy
        alias[0] = 99;
        System.out.println(a[0] + " " + copy[0]);

        try {
            System.out.println(a[3]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output

6 rows=2 cols=3
[1, 2, 3]
[4, 5, 6]
99 1
Error: Index 3 out of bounds for length 3
  • A 2D array is an array of arrays. grid[1][2] is row 1, column 2 (counting from 0), which holds 6.
  • int[] alias = a; does not copy anything; both names point to the same array, so changing alias[0] also changed a[0].
  • a.clone() or Arrays.copyOf(a, a.length) makes a real copy.
  • Reading a[3] from a 3-element array throws ArrayIndexOutOfBoundsException.

Useful Arrays Methods

MethodWhat it does
Arrays.toString(a)Readable text of the contents
Arrays.sort(a)Sorts in place, ascending
Arrays.binarySearch(a, x)Finds x in a sorted array
Arrays.fill(a, v)Sets every element to v
Arrays.copyOf(a, n)Copies into a new array of length n
Arrays.equals(a, b)Compares contents

Need a list that can grow? Use ArrayList instead of an array.

Common Mistakes

  1. Looping with i <= a.length, which goes one past the end.
  2. Comparing arrays with ==, which compares references. Use Arrays.equals().
  3. Thinking assignment copies. It shares; use clone().
  4. Writing a.length(). Arrays use the field length; strings use the method length().

Practice Exercises

Exercise 1. Find the largest value in {12, 45, 7, 33} without sorting.

Show answer
int[] a = {12, 45, 7, 33};
int max = a[0];
for (int v : a) if (v > max) max = v;
System.out.println(max);   // 45

Exercise 2. Print the sum of each row of {{1, 2}, {3, 4}, {5, 6}}.

Show answer
int[][] g = {{1, 2}, {3, 4}, {5, 6}};
for (int[] row : g) {
    int s = 0;
    for (int v : row) s += v;
    System.out.println(s);   // 3, 7, 11
}

Frequently Asked Questions

Can a Java array change size?

No. Its length is fixed when it is created. Create a bigger array and copy, or use ArrayList.

What is the difference between an array and an ArrayList?

An array has a fixed size and can hold primitives. An ArrayList grows and shrinks automatically, but holds objects only (for example Integer instead of int).

Summary

  • Arrays hold a fixed number of same-type values, indexed from 0.
  • length gives the size; going past it throws an exception.
  • java.util.Arrays sorts, searches, prints and copies.
  • Assignment shares an array; clone() copies it.

Next: Java Strings.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *