Array copying and aliasing
What you will learn
Assigning an array to another variable copies the reference, not the elements. Both variables reach the same array. Create a separate copy when independent primitive data is needed.
public class Main { public static void main(String[] args) { int[] original = {3, 5}; int[] alias = original; alias[0] = 8; System.out.println(original[0]); System.out.println(original == alias); }}Expected output:
8trueBoth names refer to the same object.
How it works
int[] alias = original creates a second reference to the same object. original.clone() creates a new array of the same type and length, copying each component. Arrays.copyOf(original, n) truncates or pads to the requested length. Arrays.sort(int[]) modifies the supplied array; sort a copy to preserve order. Arrays.equals(int[], int[]) compares values and order, whereas == compares identity. A reference array copy is shallow: it copies references rather than the objects they point to. Nested arrays illustrate this in the next lesson.
import java.util.Arrays;public class Main { public static void main(String[] args) { int[] original = {9, 2, 5}; int[] copy = original.clone(); Arrays.sort(copy); System.out.println(Arrays.toString(original)); System.out.println(Arrays.toString(copy)); }}Expected output:
[9, 2, 5][2, 5, 9]Sorting modifies only the cloned primitive array.
Check a boundary or unusual input
import java.util.Arrays;public class Main { public static void main(String[] args) { int[] source = {6, 4}; int[] larger = Arrays.copyOf(source, 3); int[] same = Arrays.copyOf(source, 2); System.out.println(Arrays.toString(larger)); System.out.println(source == same); System.out.println(Arrays.equals(source, same)); }}Expected output:
[6, 4, 0]falsetrueThe extra component defaults to zero. Equal contents do not imply identical objects.
Common mistakes
Never treat == as an element comparison or assume clone recursively copies objects. A null source passed to copyOf fails with NullPointerException, and a negative new length with NegativeArraySizeException.
Try it yourself
Write static int[] sortedCopy(int[] values). Return a new sorted array even for empty input, without modifying the non-null input.
Save each example independently as Main.java; compile with javac --release 21 -encoding UTF-8 Main.java and launch using java Main. Local Java practice only; automatic ByteMind Java grading is not established.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Array copying and aliasing — knowledge check
Practice core behavior and boundary cases.
What does int[] b = a copy?
Which sorts in place?
Extra int slots when copying to a longer length?
Which compares int array contents?
What does a reference-array clone copy?