+91 81900 98289

Java Arrays

An array holds a fixed number of values of one type. new int[3] creates three ints, all starting at 0. Indexes start at 0. The last valid index is length - 1. Reading past the end throws ArrayIndexOutOfBoundsException.

length on an array is a field, not a method, so it has no parentheses. An array cannot grow. When the size must change as the program runs, use an ArrayList.

Example

The array has three items. Index 1 is the second item, 85.

public class Scores { public static void main(String[] args) { int[] marks = {70, 85, 90}; System.out.println(marks.length); System.out.println(marks[1]); } }
Assigning one array variable to another does not copy the values. Both names then point at the same array. Arrays.copyOf copies the values into a new array.