Java Reference ยท Types and Literals
Java arrays
Reference for Java arrays: declaring, creating and initializing arrays, default values, length, bounds checking, copying, covariance and the Arrays utilities.
An array is a fixed-size, ordered sequence of elements of one type, stored contiguously and accessed by a zero-based index. Arrays are objects: they live on the heap, have a public final length field, and inherit from Object. The size is set when the array is created and cannot change.
Arrays can hold primitives (int[]) or references (String[]). Elements start with the type's default value: 0, 0.0, false, '\u0000' or null. For a resizable sequence, use ArrayList.
int[] scores = new int[5]; String[] names = {"Ann", "Bo", "Cy"}; int n = names.length; // a field, not a method
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
Type[] name; // declaration Type[] name = new Type[length]; // default-filled Type[] name = new Type[] {e1, e2}; // explicit values Type[] name = {e1, e2}; // shorthand, declarations only Type name[]; // legal but discouraged C-style form
| Member | Description |
|---|---|
length |
Number of elements, an int field. |
a[i] |
Element at index i; throws ArrayIndexOutOfBoundsException unless 0 <= i < length. |
clone() |
Shallow copy with the same type; returns the array type directly. |
getClass() |
Array class such as [I for int[]; getClass().getComponentType() gives the element type. |
Usage notes
- Fixed length. To grow, allocate a new array and copy (
Arrays.copyOf()), or use aList. - Identity, not content.
==andequals()compare references. UseArrays.equals(),Arrays.toString()andArrays.hashCode(); for nested arrays use thedeepversions. - Reference semantics. Assigning or passing an array shares it. Use
clone()orArrays.copyOf()for a copy, and remember it is shallow for object elements. - Covariance.
String[]is assignable toObject[], but storing the wrong type throwsArrayStoreExceptionat run time. Generics are invariant and do not have this hole. - Generics and arrays mix badly.
new List<String>[3]is illegal; use aList<List<String>>. - Maximum size is just under
Integer.MAX_VALUE; very large arrays may hitOutOfMemoryError. - Zero-length arrays are valid and common (
new String[0]);argsinmainis one when no arguments are passed. - Varargs parameters are arrays under the hood.