Arrays in Java
Clear, exam-focused notes on Java arrays: what they are, how to declare/use them, important rules (indexing, defaults, covariance), common library methods, and three runnable example programs with exact input/output.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Arrays are the simplest container for many problems: they store a fixed-size sequence of values all of the same type and let an engineer perform bulk numeric, table, or sequence operations efficiently. In Java you will use arrays for numerical computation, storage of objects, implementing data-structure building blocks, and as the underlying representation for variable-length arguments (varargs).
Key ideas
Exact definition (as expected in exams): An array of component type T and length N is an object that stores N values each of type T, and provides O(1) access to the value at index i for integers 0 ≤ i < N. The array length N is fixed at creation time.
Important assumptions: a) elements are typically stored in contiguous element slots (a useful logical model; the Java Language Specification does not mandate physical contiguity). b) Java arrays are objects; array variables are references.
Element: An element is one item stored in an array. For primitive component types (int, double, boolean, etc.) the element is the primitive value. For reference component types (e.g. String, Object, MyClass) the element is a reference to an object.
Index: The integer position used to access an element. Access with bracket syntax
a[i]. Valid indices are 0 througha.length - 1. Access outside the range throws ArrayIndexOutOfBoundsException at runtime.Declaration, allocation, initialization: The common steps are: declare a variable to hold the array reference; allocate the array object with
new; initialize elements explicitly or rely on default initialization.- Declaration syntax examples:
int[] a;orint a[];(both declare a variable that can refer to an int array). - Allocation:
a = new int[5];creates an array object with length 5. - Combined:
int[] a = new int[5];
- Declaration syntax examples:
Default values: When an array is created with
new, every element receives a default value: for numeric primitives the default is zero of the appropriate kind (0forbyte,short, andint,0Lforlong,0.0fforfloat,0.0fordouble), forcharit is'\u0000', forbooleanit isfalse, and for reference types it isnull.Length property: Arrays have a public final instance field
length(not a method). Usea.lengthto get the array length.Multidimensional arrays: Java supports multidimensional arrays as arrays of arrays. A two-dimensional array
T[][] mis an array whose elements areT[]. This allows rectangular arrays (all rows same length) and jagged arrays (rows different lengths).Exactly state: A 2-D array is a reference to an array of references to 1-D arrays.
Arrays are objects: Every array is an instance of a class whose runtime type encodes the component type and number of dimensions. Arrays inherit from
Object. Thereforea.getClass()anda instanceof Objectapply. All array types implementCloneableandjava.io.Serializable. Primitive arrays are not compatible withObject[](e.g.,int[]is not anObject[]).Identity and equality:
==compares array references (identity), not element-wise equality. To compare contents usejava.util.Arrays.equalsfor 1-D primitives/objects andArrays.deepEqualsfor nested arrays.Covariance and runtime checks: Arrays in Java are covariant: if S is a subtype of T, then S[] is a subtype of T[]. This is a compile-time relationship that allows assignments like
Object[] o = new String[5];. However, storing into such arrays is checked at runtime and may throwArrayStoreExceptionif an incompatible type is assigned.Exact rule: For reference types R1 and R2, R1[] is assignable to R2[] if and only if R1 is assignable to R2.
Copying arrays: There are multiple ways: manual loops,
System.arraycopy,Arrays.copyOf, andclone(). Important:clone()andArrays.copyOfperform a shallow copy for arrays of references (they copy the references, not the objects). For primitives they copy values.Common library helpers:
Arrays.sort,Arrays.fill,Arrays.binarySearch,Arrays.equals,Arrays.deepEquals,Arrays.copyOfare commonly used.System.arraycopyis fast native copy used for performance-sensitive code. Note:Arrays.binarySearchrequires the array to be sorted using the same order beforehand.Varargs: A method declared
void m(T... args)receives itsargsas an arrayT[]inside the method. Callingm(a, b, c)is compiled to passing an array of the three arguments. You can also pass an existingT[], and calling with no arguments passes a zero-length array.Drawing to explain arrays (diagram to draw on answer script): For a one-dimensional
int[] a = new int[4];draw a horizontal row of 4 boxes. Under each box draw the index: 0, 1, 2, 3. Inside each box write its value (initially 0). To show reference semantics draw a separate box representing the variableawith an arrow to the array block (not to any specific element).
Formulas
- Declare and allocate:
T[] name = new T[n];orT[] name = {v0, v1, v2};for array literals. For assignment after declaration, usename = new T[]{v0, v1, v2};. - Access:
name[i]where0 ≤ i < name.length. Enhanced for loop:for (T x : name) { ... }iterates elements in index order. - Multi-dim allocation:
T[][] m = new T[rows][];then for each rowm[i] = new T[rowLength];(jagged allowed). Rectangular in one step:T[][] m = new T[rows][cols];. - Clone:
T[] b = a.clone();shallow copy for reference components. - System copy:
System.arraycopy(src, srcPos, dest, destPos, length);copieslengthelements. Performs bounds and type checks; may throwIndexOutOfBoundsException,ArrayStoreException, orNullPointerException.
Explain symbols: T is a Java type (primitive or reference); name is an identifier; n, i, rows, rowLength are ints; srcPos, destPos, length are ints.
Worked examples
Example 1 — Sum and average of integer array (reads input)
import java.util.Scanner;
class SumAvg {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
sum += a[i];
}
double avg = (n > 0) ? (double) sum / n : 0.0;
System.out.printf("Sum = %d\nAverage = %.2f\n", sum, avg);
}
}
Sample input:
5
2 4 6 8 10
Exact output:
Sum = 30
Average = 6.00
Example 2 — Jagged 2-D array creation and display (no input)
class JaggedDemo {
public static void main(String[] args) {
int[][] a = new int[3][]; // 3 rows
a[0] = new int[1]; // row 0 length 1
a[1] = new int[2]; // row 1 length 2
a[2] = new int[3]; // row 2 length 3
int val = 1;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = val++;
}
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
Exact output:
1
2 3
4 5 6
Example 3 — Demonstrate clone() is a shallow copy for reference arrays
class Box { int v; Box(int v){this.v = v;} }
class CloneShallow {
public static void main(String[] args) {
Box[] orig = { new Box(10), new Box(20) };
Box[] copy = orig.clone();
// Modify the object referenced by orig[0]
orig[0].v = 99;
System.out.println("orig[0].v = " + orig[0].v);
System.out.println("copy[0].v = " + copy[0].v);
}
}
Exact output:
orig[0].v = 99
copy[0].v = 99
This shows that clone copied references, not the objects (shallow copy).
Common mistakes
- Assuming
==checks element-wise equality.==checks reference identity for arrays. - Expecting clone or Arrays.copyOf to deep-copy object graphs; they copy references (shallow copy).
- Ignoring ArrayStoreException possibility when assigning into covariant arrays:
Object[] o = new String[2]; o[0] = new Integer(5);fails at runtime. - Not initializing rows of a 2-D array created with
new T[rows][]before accessing them. - Assuming arrays can change size after allocation. To change size, create a new array and copy elements.
For your exam
Types of questions you will get:
- Definitions: define array, element, index, jagged array, shallow vs deep copy. Full-marks answer includes concise definition, valid index range, and example code or diagram.
- Short notes: default initialization, arrays are objects, length property, covariance and ArrayStoreException.
Include the precise default values, mention
lengthis a field, and give a short code example showing the exception. - Derivations/diagrams: draw and explain layout of a 2-D jagged array and show where references point.
- Programs: declare/allocate arrays, compute sum/average, find max/min, transpose a rectangular matrix, demonstrate clone behavior. Provide complete compilable code and sample I/O.
- Comparisons: difference between
clone(),System.arraycopy, andArrays.copyOf(state shallow/deep behavior and complexity).
What a full-marks program answer includes:
- Correct program header and imports, required classes and main method.
- Correct handling of input and edge cases (zero length arrays).
- Accurate output exactly matching expected format.
- Comments or short explanation if asked.
Quick check
- Define an array and give the valid index range for
int[] a = new int[10];. - What is printed by:
int[] a = {1,2,3};
int[] b = a;
b[0] = 9;
System.out.println(a[0]);
- What is the default value of elements in
new boolean[3]? Answers: 1) An array is a fixed-size ordered collection; indices 0..9. 2) 9. 3) false
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?