Java Arrays

An array keeps many values of the same type in one variable. The size is fixed when you create it, and the items are numbered from 0.

Create an array

public class Main {
    public static void main(String[] args) {
        int[] marks = {70, 85, 90, 65};            // with values
        String[] names = new String[3];            // empty, size 3
        names[0] = "Riya";
        names[1] = "Aman";
        names[2] = "Meera";

        System.out.println(marks[1]);
        System.out.println(names[2]);
        System.out.println(marks.length);          // length is a field, no ()
        System.out.println(java.util.Arrays.toString(marks));
    }
}
Output

85
Meera
4
[70, 85, 90, 65]

Default values

A new array is filled with default values: 0 for numbers, false for boolean, and null for objects.

import java.util.Arrays;

public class Defaults {
    public static void main(String[] args) {
        int[] a = new int[3];
        boolean[] b = new boolean[2];
        String[] s = new String[2];
        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.toString(b));
        System.out.println(Arrays.toString(s));
    }
}
Output

[0, 0, 0]
[false, false]
[null, null]

Loop through an array

public class Loop {
    public static void main(String[] args) {
        int[] marks = {70, 85, 90, 65};
        int sum = 0;
        for (int i = 0; i < marks.length; i++) {
            sum += marks[i];
        }
        System.out.println("Total: " + sum);
        System.out.println("Average: " + (double) sum / marks.length);

        for (int m : marks) {              // for each
            System.out.print(m + " ");
        }
        System.out.println();
    }
}
Output

Total: 310
Average: 77.5
70 85 90 65

The Arrays helper class

import java.util.Arrays;

public class Helper {
    public static void main(String[] args) {
        int[] n = {5, 2, 9, 1, 7};

        Arrays.sort(n);
        System.out.println(Arrays.toString(n));
        System.out.println(Arrays.binarySearch(n, 7));        // array must be sorted
        System.out.println(Arrays.equals(n, new int[]{1, 2, 5, 7, 9}));

        int[] copy = Arrays.copyOf(n, 7);                      // longer copy
        System.out.println(Arrays.toString(copy));
        int[] part = Arrays.copyOfRange(n, 1, 4);
        System.out.println(Arrays.toString(part));

        int[] filled = new int[4];
        Arrays.fill(filled, 8);
        System.out.println(Arrays.toString(filled));
    }
}
Output

[1, 2, 5, 7, 9]
3
true
[1, 2, 5, 7, 9, 0, 0]
[2, 5, 7]
[8, 8, 8, 8]

A common error

If you use an index which does not exist, Java throws an ArrayIndexOutOfBoundsException. The last valid index is length - 1.

public class Oob {
    public static void main(String[] args) {
        int[] a = {1, 2, 3};
        System.out.println(a[3]);
    }
}
Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Oob.main(Oob.java:4)

Array facts

  • The size can not be changed. Use ArrayList when you need a list that grows (Java ArrayList).
  • b = a does not copy the array. Both variables point to the same array.
  • Printing an array directly shows a code like [I@1b6d3586. Use Arrays.toString().
Note: Find the maximum with a loop: keep a variable max and update it when you find a bigger value. Next: Java Multidimensional Arrays.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.