AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Skip to content

06 Arrays / Lesson 1 of 5

Arrays — fixed-size, typed, zero-based

13 min · +10 XP · 2 exercises · 5 questions

Read the text13 min
Exercises0/2
Quiz5 q

Quick answer

What is an array in Java?

An array in Java is a fixed-length, zero-based container of elements of one type, created with new int[10] or an initialiser such as {2, 3, 5}. Every array is an object on the heap: the variable holds a reference, a.length gives its size, and each slot starts at its type's default value. Every index is bounds-checked at run time.

An array is the simplest data structure Java has and the one closest to the machine: a fixed-length block of elements of one type, indexed from zero, laid out contiguously. Every other collection is built on it. This lesson covers how arrays are declared, created and indexed, what an array is at run time, and the errors that come from forgetting any of that.

Declaring and creating

int[] counts;                     // declares a variable of type "array of int"; holds null
counts = new int[10];             // creates an array of 10 ints, all 0
int[] primes = {2, 3, 5, 7};      // array initialiser — length 4, only in a declaration
int[] more = new int[] {11, 13};  // the same, usable anywhere (arguments, reassignment)
String[] names = new String[3];   // three nulls
double[] empty = new double[0];   // a legal, empty array

Two things to notice. First, the type is int[] — "array of int" — and the variable is a reference; counts is null until an array is assigned. Second, the length is fixed at creation: new int[10] is ten slots forever. To "grow" an array you create a bigger one and copy (that is exactly what ArrayList does internally).

int counts[] (C style) is also accepted by the compiler and rejected by every style guide. Put the brackets on the type.

Default values

new T[n] fills every slot with the default for T: 0 for numeric types, '\u0000' for char, false for boolean, null for any reference type. This is guaranteed — unlike C, an array is never uninitialised memory. The null defaults in a String[] are the source of many early NullPointerExceptions: names[0].length() before any assignment.

Indexing and length

int[] a = {10, 20, 30};
a[0]          // 10 — the first element
a[2]          // 30 — the last: index length - 1
a.length      // 3 — a final FIELD, no parentheses (String.length() is a method)
a[3]          // ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
a[-1]         // ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3
a[1] = 25;    // assignment
a[1] += 5;    // compound assignment works on elements

Indices run from 0 to length - 1. Every access is bounds-checked at run time; an out-of-range index throws immediately, with a message naming the index and the length. This costs a comparison per access (the JIT eliminates most of them in loops) and buys the memory safety C lacks.

The canonical loop is for (int i = 0; i < a.length; i++), and when the index is not needed, for (int v : a).

Arrays are objects

Every array is an object on the heap, even int[]:

  • It has a length and a runtime type (int[].class, String[].class).
  • Array variables hold references; int[] b = a; makes b and a the same array (next lessons).
  • a == b compares references, not contents; a.equals(b) is the same as == (arrays do not override it). Use Arrays.equals.
  • a.toString() gives [I@1b6d3586 (type code and hash), not the contents. Use Arrays.toString.
  • An array's superclass is Object; it implements Cloneable and Serializable; a.clone() makes a shallow copy.
  • Object[] o = new String[3]; compiles — arrays are covariant — and o[0] = 1; then throws ArrayStoreException at run time. Generics were designed the opposite way to avoid exactly this.

Arrays of primitives versus arrays of objects

int[] holds the numbers themselves, contiguously: 1000 ints are 4000 bytes plus a header. Integer[] holds 1000 references to Integer objects scattered on the heap. For numeric work, primitive arrays are several times faster and smaller — the reason they exist alongside List<Integer>.

Multidimensional preview

int[][] grid = new int[3][4]; — an array of 3 arrays of 4 ints. The next lesson covers these.

Common errors

ErrorCause
NullPointerException at a.lengthDeclared but never created: int[] a;
ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5<= instead of < in the loop, or a[a.length]
NegativeArraySizeExceptionnew int[n] with n < 0 — a bad computed size
ArrayStoreExceptionStoring the wrong type through a covariant reference
incompatible types: int[] cannot be converted to intint x = a; — the array, not an element
array required, but int foundIndexing a non-array: x[0] where x is an int

Arrays and main

String[] args in main is an ordinary array: args.length is the number of command-line arguments and args[0] the first. It is never null — with no arguments it is an empty array.

When to use an array

  • Fixed size known up front; numeric or character data; performance matters; multi-dimensional grids.
  • Otherwise, ArrayList (Module 14) — it grows, has add/remove/contains, and its toString is readable. The switch costs little; arrays remain the right tool for algorithms and hot loops.

Interview angle

  • "Are arrays objects in Java?" Yes — heap-allocated, with a length field and a runtime type; variables hold references.
  • "Can you change an array's size?" No; create a new one and copy (Arrays.copyOf).
  • "a.length vs s.length() vs list.size()?" Field, method, method — a classic trick question.
  • "What is stored in new String[5]?" Five nulls.

Key takeaways

  • T[] a = new T[n] — fixed length, zero-based, every slot defaulted (0/false/null).
  • a.length is a field; valid indices are 0 … length - 1; every access is bounds-checked.
  • Arrays are objects: variables are references, == is identity, toString is unreadable — use the Arrays class.
  • Primitive arrays are contiguous values; object arrays are references.

Common questions

What are the default values of an array in Java?

new T[n] fills every slot with the default for T: 0 for numeric types, false for boolean, the null character (code 0) for char and null for any reference type. An array is never uninitialised memory, so new String[3] holds three nulls.

Is array length a field or a method in Java?

A field. a.length is a final field with no parentheses, while a String uses the method s.length() and a list uses list.size() — a classic trick question. The length is fixed when the array is created and never changes.

What causes ArrayIndexOutOfBoundsException in Java?

Reading or writing an index outside 0 to length - 1, most often through <= instead of < in a loop or an access to a[a.length]. Every array access is bounds-checked at run time, and the message names both the bad index and the array's length.

Are arrays objects in Java?

Yes. Every array, even an int[], is an object on the heap with a length field and a runtime type, and its superclass is Object. Array variables hold references, so == compares identity and toString() prints a type code and hash rather than the contents.

Can you change the size of an array in Java?

No — an array's length is fixed at creation. To grow one, create a larger array and copy the elements across, for example with Arrays.copyOf(a, newLength), which is what ArrayList does internally. When the size changes often, use an ArrayList instead.

Mark as readSign in to keep your place.

Java Arrays Explained: Declare, Create and Index an Array

A Java array is a fixed-length, zero-based block of one type. Declaring and creating one, default values, the length field and ArrayIndexOutOfBoundsException.

  • Course: Java study plan
  • Module: Arrays
  • Kind: Lesson
  • Reading time: 13 min
  • Runtime: OpenJDK 18

What is an array in Java?

An array in Java is a fixed-length, zero-based container of elements of one type, created with new int[10] or an initialiser such as {2, 3, 5}. Every array is an object on the heap: the variable holds a reference, a.length gives its size, and each slot starts at its type's default value. Every index is bounds-checked at run time.

Lesson

An array is the simplest data structure Java has and the one closest to the machine: a fixed-length block of elements of one type, indexed from zero, laid out contiguously. Every other collection is built on it. This lesson covers how arrays are declared, created and indexed, what an array is at run time, and the errors that come from forgetting any of that.

Declaring and creating

int[] counts;                     // declares a variable of type "array of int"; holds null
counts = new int[10];             // creates an array of 10 ints, all 0
int[] primes = {2, 3, 5, 7};      // array initialiser — length 4, only in a declaration
int[] more = new int[] {11, 13};  // the same, usable anywhere (arguments, reassignment)
String[] names = new String[3];   // three nulls
double[] empty = new double[0];   // a legal, empty array

Two things to notice. First, the type is int[] — "array of int" — and the variable is a reference; counts is null until an array is assigned. Second, the length is fixed at creation: new int[10] is ten slots forever. To "grow" an array you create a bigger one and copy (that is exactly what ArrayList does internally).

int counts[] (C style) is also accepted by the compiler and rejected by every style guide. Put the brackets on the type.

Default values

new T[n] fills every slot with the default for T: 0 for numeric types, '\u0000' for char, false for boolean, null for any reference type. This is guaranteed — unlike C, an array is never uninitialised memory. The null defaults in a String[] are the source of many early NullPointerExceptions: names[0].length() before any assignment.

Indexing and length

int[] a = {10, 20, 30};
a[0]          // 10 — the first element
a[2]          // 30 — the last: index length - 1
a.length      // 3 — a final FIELD, no parentheses (String.length() is a method)
a[3]          // ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
a[-1]         // ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3
a[1] = 25;    // assignment
a[1] += 5;    // compound assignment works on elements

Indices run from 0 to length - 1. Every access is bounds-checked at run time; an out-of-range index throws immediately, with a message naming the index and the length. This costs a comparison per access (the JIT eliminates most of them in loops) and buys the memory safety C lacks.

The canonical loop is for (int i = 0; i < a.length; i++), and when the index is not needed, for (int v : a).

Arrays are objects

Every array is an object on the heap, even int[]:

  • It has a length and a runtime type (int[].class, String[].class).
  • Array variables hold references; int[] b = a; makes b and a the same array (next lessons).
  • a == b compares references, not contents; a.equals(b) is the same as == (arrays do not override it). Use Arrays.equals.
  • a.toString() gives [I@1b6d3586 (type code and hash), not the contents. Use Arrays.toString.
  • An array's superclass is Object; it implements Cloneable and Serializable; a.clone() makes a shallow copy.
  • Object[] o = new String[3]; compiles — arrays are covariant — and o[0] = 1; then throws ArrayStoreException at run time. Generics were designed the opposite way to avoid exactly this.

Arrays of primitives versus arrays of objects

int[] holds the numbers themselves, contiguously: 1000 ints are 4000 bytes plus a header. Integer[] holds 1000 references to Integer objects scattered on the heap. For numeric work, primitive arrays are several times faster and smaller — the reason they exist alongside List<Integer>.

Multidimensional preview

int[][] grid = new int[3][4]; — an array of 3 arrays of 4 ints. The next lesson covers these.

Common errors

ErrorCause
NullPointerException at a.lengthDeclared but never created: int[] a;
ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5<= instead of < in the loop, or a[a.length]
NegativeArraySizeExceptionnew int[n] with n < 0 — a bad computed size
ArrayStoreExceptionStoring the wrong type through a covariant reference
incompatible types: int[] cannot be converted to intint x = a; — the array, not an element
array required, but int foundIndexing a non-array: x[0] where x is an int

Arrays and main

String[] args in main is an ordinary array: args.length is the number of command-line arguments and args[0] the first. It is never null — with no arguments it is an empty array.

When to use an array

  • Fixed size known up front; numeric or character data; performance matters; multi-dimensional grids.
  • Otherwise, ArrayList (Module 14) — it grows, has add/remove/contains, and its toString is readable. The switch costs little; arrays remain the right tool for algorithms and hot loops.

Interview angle

  • "Are arrays objects in Java?" Yes — heap-allocated, with a length field and a runtime type; variables hold references.
  • "Can you change an array's size?" No; create a new one and copy (Arrays.copyOf).
  • "a.length vs s.length() vs list.size()?" Field, method, method — a classic trick question.
  • "What is stored in new String[5]?" Five nulls.

Key takeaways

  • T[] a = new T[n] — fixed length, zero-based, every slot defaulted (0/false/null).
  • a.length is a field; valid indices are 0 … length - 1; every access is bounds-checked.
  • Arrays are objects: variables are references, == is identity, toString is unreadable — use the Arrays class.
  • Primitive arrays are contiguous values; object arrays are references.

Common questions

What are the default values of an array in Java?

new T[n] fills every slot with the default for T: 0 for numeric types, false for boolean, the null character (code 0) for char and null for any reference type. An array is never uninitialised memory, so new String[3] holds three nulls.

Is array length a field or a method in Java?

A field. a.length is a final field with no parentheses, while a String uses the method s.length() and a list uses list.size() — a classic trick question. The length is fixed when the array is created and never changes.

What causes ArrayIndexOutOfBoundsException in Java?

Reading or writing an index outside 0 to length - 1, most often through <= instead of < in a loop or an access to a[a.length]. Every array access is bounds-checked at run time, and the message names both the bad index and the array's length.

Are arrays objects in Java?

Yes. Every array, even an int[], is an object on the heap with a length field and a runtime type, and its superclass is Object. Array variables hold references, so == compares identity and toString() prints a type code and hash rather than the contents.

Can you change the size of an array in Java?

No — an array's length is fixed at creation. To grow one, create a larger array and copy the elements across, for example with Arrays.copyOf(a, newLength), which is what ArrayList does internally. When the size changes often, use an ArrayList instead.

Exercises

Fill and report

Read an integer n, then n integers into an int[]. Print three lines: the array reversed (space-separated), sum=<total>, and evens=<count of even values>. Use the array's length and index loops.

For n = 0 the first line is empty.

Example: 4 then 1 2 3 4 →

4 3 2 1
sum=10
evens=2

Dice histogram

Read an integer n and n dice rolls (each 1–6). Count them in an int[7] indexed by face (index 0 unused), then print one line per face <face>: <count> <stars> with one * per roll, and finally mode=<the most rolled face, lowest on ties>.

Example: 6 then 3 1 3 6 3 1 →

1: 2 **
2: 0
3: 3 ***
4: 0
5: 0
6: 1 *
mode=3

In this module: Arrays

← Checkpoint — Methods · Two-dimensional and jagged arrays →