Java Arrays: Creating, Sorting and Searching (OCP 21)
Java arrays for the OCP 21 exam: legal and illegal declarations, default values, initializers, arrays of references, covariance and ArrayStoreException, length and index bounds, Arrays.toString, sort, binarySearch return values, fill and copyOf.
kvi5hnuCode Sprout team member8 min readOn this page
An array is a fixed-size, ordered block of elements of one type, stored as an object on the heap. String and StringBuilder are built on arrays internally, and the collections you'll meet in Chapter 9 often are too. The exam tests arrays in two ways: syntax (which declarations compile) and behavior (default values, bounds, what sort and binarySearch return). This article covers both. Article 21 covers comparing arrays, varargs and multidimensional arrays.
Declaring and creating arrays
An array type is written with brackets: int[] reads as "array of int". The variable is a reference. The array itself is a separate object:
int[] counts = new int[3]; // size 3, every element 0
int[] primes = new int[] {2, 3, 5, 7}; // size taken from the initializer
int[] shortcut = {2, 3, 5, 7}; // the same, only allowed in a declaration
Brackets can go after the type or after the name, with or without spaces. All of these declare an int[]:
int[] a; int [] b; int []c; int d[]; int e [];
Placement matters when you declare more than one variable:
int[] ids, types; // both are int[]
int ids2[], count; // ids2 is int[], count is a plain int
| Code | Compiles? | Why |
|---|---|---|
new int[] | No | "array dimension missing" |
new int[2] {1, 2} | No | A size and an initializer can't be combined |
int[3] a; | No | The size goes in the new expression, not the type |
int[] a; a = {1, 2}; | No | The short {…} form only works in a declaration. Use a = new int[] {1, 2}; |
var a = {1, 2}; | No | var can't infer a type from a bare initializer. var a = new int[] {1, 2}; works |
int[] a = {1, 2,}; | Yes | A trailing comma is allowed |
int[] a = {}; | Yes | An empty array: a.length is 0 |
new int['a'] / new int[shortVar] | Yes | The size can be any int expression, including promoted char, byte and short |
new int[2L] | No | A long size needs a cast |
new int[-1] | Compiles | Throws NegativeArraySizeException at run time |
Default values
new always initializes every element:
| Element type | Default |
|---|---|
byte, short, int, long | 0 |
float, double | 0.0 |
char | '\u0000' |
boolean | false |
| any reference type | null |
This is true for local arrays too. A local array variable must be assigned before use, but once an array exists, its elements always have values.
Arrays of references
An array of objects holds references, not the objects themselves:
String[] names = new String[2]; // two slots, both null: no String objects exist yet
names[0] = "kiwi";
![Left: counts refers to an int[3] whose slots hold the value 0; names refers to a String[2] whose slot 0 holds a reference to a separate "kiwi" object and whose slot 1 is null. Right: binarySearch on the sorted array 2 4 6 8 returns 2 for key 6, and returns -3 for the missing key 5 because 5 belongs at insertion point 2](https://code-sprout-content.laxmi.solutions/asset/2026/11/ftcgsbb6gxgt3rwl.png)
A field String[] names; that is never assigned is null: there's no array at all. String[] names = new String[2]; is an array of two null slots.
Array types and covariance
Every array is an Object and inherits Object's methods. An array of a subtype can be assigned to an array variable of a supertype. This is called covariance:
String[] birds = {"kiwi", "emu"};
Object[] things = birds; // fine: String[] is an Object[]
String[] back = (String[]) things; // a cast is needed to go back down
things[0] = Integer.valueOf(1); // compiles, throws ArrayStoreException
The compiler only sees an Object[], so storing an Integer looks legal. At run time, the JVM knows the array is really a String[] and refuses. Covariance doesn't apply to primitives: long[] l = new int[2]; and Object[] o = new int[2]; don't compile, although Object o = new int[2]; does.
Using an array
int[] squares = new int[5];
for (int i = 0; i < squares.length; i++) {
squares[i] = i * i;
}
lengthis a field, not a method.squares.length()doesn't compile. It's alsofinal, sosquares.length = 6;doesn't compile either. CompareString.length()and collections'size().lengthis the number of slots, not the number of non-null elements.new String[6].lengthis 6.- Valid indexes are 0 to
length - 1. Anything else, includingarr[arr.length]and negative indexes, throwsArrayIndexOutOfBoundsExceptionat run time. A loop usingi <= arr.lengthis the classic off-by-one bug. - An array's size can never change. To "grow" an array, create a new one and copy the elements over (see
Arrays.copyOfbelow), or use anArrayList.
Printing an array variable calls Object.toString(), which gives something like [I@6d06d69c ([I means int[]). Use Arrays.toString(array) to get [0, 1, 4, 9, 16]. Arrays is in java.util, so it needs an import (or the full name). Exam snippets assume the imports are present.
Sorting
static void sort(int[] a) // and every other primitive type
static void sort(int[] a, int from, int to) // sorts [from, to) only
static void sort(Object[] a) // natural order (Comparable)
static <T> void sort(T[] a, Comparator<? super T> c) // Chapter 9
int[] numbers = {6, 9, 1, 4};
Arrays.sort(numbers); // [1, 4, 6, 9]
String[] labels = {"10", "9", "100", "banana", "Apple", "apple"};
Arrays.sort(labels); // [10, 100, 9, Apple, apple, banana]
Strings sort by character value, not numeric value: "100" comes before "9" because '1' < '9'. In ASCII, a space comes first, then digits, then uppercase letters, then lowercase letters. So digits sort before uppercase, and uppercase before lowercase.
sortchanges the array in place and returnsvoid.int[] sorted = Arrays.sort(numbers);doesn't compile.Arrays.sorton an object array that containsnullthrowsNullPointerException.Arrays.sort(arr, 1, 4)sorts only indexes 1, 2 and 3. As usual, the end is exclusive.- Primitive arrays use a dual-pivot quicksort. Object arrays use a stable merge sort (TimSort), so equal elements keep their order.
Searching: Arrays.binarySearch
Binary search halves the search range at every step, so it needs a sorted array:
| Situation | Result |
|---|---|
| Key found in a sorted array | Its index (any matching index if there are duplicates) |
| Key not found in a sorted array | -(insertion point) - 1, always negative |
| Array not sorted | Undefined: don't trust the result |
The insertion point is the index where the key would have to go to keep the array sorted. Subtracting one makes the result negative even when the insertion point is 0.
int[] sorted = {2, 4, 6, 8};
Arrays.binarySearch(sorted, 6); // 2
Arrays.binarySearch(sorted, 1); // -1 (would go at 0)
Arrays.binarySearch(sorted, 5); // -3 (would go at 2)
Arrays.binarySearch(sorted, 9); // -5 (would go at 4, past the end)
To recover the insertion point, compute -result - 1. On the exam, as soon as you see binarySearch on an array that hasn't been sorted, pick the "undefined/unpredictable" answer.
Filling and copying
int[] seats = new int[5];
Arrays.fill(seats, 1); // [1, 1, 1, 1, 1]
Arrays.fill(seats, 1, 3, 0); // [1, 0, 0, 1, 1]
int[] bigger = Arrays.copyOf(seats, 7); // pads with defaults: [1, 0, 0, 1, 1, 0, 0]
int[] middle = Arrays.copyOfRange(seats, 1, 4); // [0, 0, 1]
int[] clone = seats.clone(); // a shallow copy of the same length
clone() and copyOf copy element values. For an array of references, that means the copy points to the same objects (a shallow copy).
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
Arrays.sorton objects uses a stable merge sort (TimSort). On primitives it uses a dual-pivot quicksort. The exam tests only results, never algorithms.
Exam traps from this article
A complete example
import java.util.Arrays;
public class Solution {
static String search(int[] sorted, int key) {
int r = Arrays.binarySearch(sorted, key);
return r >= 0 ? key + " found at " + r
: key + " missing, insert at " + (-r - 1) + " (returned " + r + ")";
}
public static void main(String[] args) {
System.out.println("-- creating arrays --");
int[] counts = new int[3]; // defaults: 0
double[] weights = new double[2]; // defaults: 0.0
String[] names = new String[2]; // defaults: null
int[] primes = {2, 3, 5, 7}; // initializer: size from the values
var flags = new boolean[] {true, false}; // var needs the explicit new form
System.out.println(Arrays.toString(counts) + " " + Arrays.toString(weights) + " "
+ Arrays.toString(names) + " " + Arrays.toString(primes) + " " + Arrays.toString(flags));
int ids[], total; // ids is int[], total is just int
ids = new int[] {4, 5};
total = ids.length;
System.out.println("ids has " + total + " elements; empty array length: " + new int[0].length);
System.out.println("-- reading, writing, bounds --");
int[] squares = new int[5];
for (int i = 0; i < squares.length; i++) {
squares[i] = i * i;
}
System.out.println(Arrays.toString(squares) + " last=" + squares[squares.length - 1]);
try {
squares[squares.length] = 25;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("AIOOBE: " + e.getMessage());
}
System.out.println("plain toString() looks like [I@...: " + squares.toString().startsWith("[I@"));
System.out.println("-- arrays of references and covariance --");
String[] birds = {"kiwi", "emu"};
Object[] things = birds; // allowed: String[] is an Object[]
String[] back = (String[]) things; // cast back down
System.out.println(back == birds);
try {
things[0] = Integer.valueOf(1); // compiles, fails at run time
} catch (ArrayStoreException e) {
System.out.println("ArrayStoreException: " + e.getMessage());
}
System.out.println("-- sorting --");
int[] numbers = {6, 9, 1, 4};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
String[] labels = {"10", "9", "100", "banana", "Apple", "apple"};
Arrays.sort(labels); // digits < uppercase < lowercase
System.out.println(Arrays.toString(labels));
int[] part = {5, 3, 9, 1, 7};
Arrays.sort(part, 1, 4); // sorts indexes 1..3 only
System.out.println(Arrays.toString(part));
System.out.println("-- binary search on a sorted array --");
int[] sorted = {2, 4, 6, 8};
for (int key : new int[] {6, 1, 5, 9}) {
System.out.println(search(sorted, key));
}
System.out.println("-- fill and copy --");
int[] seats = new int[5];
Arrays.fill(seats, 1);
Arrays.fill(seats, 1, 3, 0);
int[] bigger = Arrays.copyOf(seats, 7);
int[] middle = Arrays.copyOfRange(seats, 1, 4);
System.out.println(Arrays.toString(seats) + " " + Arrays.toString(bigger) + " " + Arrays.toString(middle));
}
}
Output:
-- creating arrays --
[0, 0, 0] [0.0, 0.0] [null, null] [2, 3, 5, 7] [true, false]
ids has 2 elements; empty array length: 0
-- reading, writing, bounds --
[0, 1, 4, 9, 16] last=16
AIOOBE: Index 5 out of bounds for length 5
plain toString() looks like [I@...: true
-- arrays of references and covariance --
true
ArrayStoreException: java.lang.Integer
-- sorting --
[1, 4, 6, 9]
[10, 100, 9, Apple, apple, banana]
[5, 1, 3, 9, 7]
-- binary search on a sorted array --
6 found at 2
1 missing, insert at 0 (returned -1)
5 missing, insert at 2 (returned -3)
9 missing, insert at 4 (returned -5)
-- fill and copy --
[1, 0, 0, 1, 1] [1, 0, 0, 1, 1, 0, 0] [0, 0, 1]
Points to notice:
- Every element of a new array gets its default value.
String[]slots start asnulland noStringobjects are created. int ids[], total;makestotalanint, used here to store the length.- The cast
(String[]) thingsworks because the object really is aString[]. Storing anIntegerthroughObject[]throwsArrayStoreException. - The string sort puts
"10","100"and"9"in character order, then uppercase before lowercase. - Each negative
binarySearchresult turns back into an insertion point with-r - 1.
Common questions
Why is length a field but String.length() a method?
Arrays are a special JVM type with a built-in, unchangeable length. String is an ordinary class that exposes its size through a method. It's a historical inconsistency the exam likes to test.
Can an array hold different types?
Only through a common supertype. An Object[] can hold a String, an Integer and so on, unless the actual array object has a narrower type, in which case storing the wrong type throws ArrayStoreException.
Are arrays passed by reference? Java passes the reference by value. A method can change the elements of an array you pass it, but assigning a new array to its parameter doesn't affect your variable (Chapter 5).
Does Arrays.toString work on nested arrays?
It prints the inner arrays as [I@…. Use Arrays.deepToString for multidimensional arrays (article 21).
Summary
- Declare arrays with brackets on the type or the name.
int a[], b;declares only one array. - Create them with
new T[size](elements get default values),new T[] {…}, or{…}in a declaration. - Arrays of objects hold references. Covariant assignment to
Object[]can throwArrayStoreException. lengthis a final field. Indexes run from 0 tolength - 1, and anything else throwsArrayIndexOutOfBoundsException.Arrays.toString,sort(in place, lexicographic for strings),binarySearch(sorted arrays only,-(insertion point) - 1when the key is missing),fill,copyOf,copyOfRange.
Practice quiz
Test yourself with the arrays: create, sort and search quiz: 10 exam-style questions with explanations.
Previous: Java String Equality: ==, equals, the String Pool and intern (OCP 21)
Next: Java Arrays: equals, compare, mismatch, Varargs and Multidimensional Arrays (OCP 21)
Related reading
- Java String Equality: ==, equals, the String Pool and intern (OCP 21)
- Java StringBuilder: Mutability, Chaining and Methods (OCP 21)
- Java String Methods: Indexing, Searching, Comparing and Transforming Text (OCP 21)
- Java Strings: Creation, Concatenation and Immutability (OCP 21)
- Java break, continue, Labels, return and Unreachable Code (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.