CKTIS / Java
array.clone() — a shallow array copy
array.clone() creates a new array containing copies of its component values. Primitive values are independent, but references still point to the same objects; in multidimensional arrays, subarrays remain shared.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
array.clone()array.clone() creates a new array of the same length and copies its component values. Unlike the assignment copy = array, the result is a separate array object.
For an expression of type T[], the result has type T[], including when T is a primitive type; no cast is needed. The array's clone() method is public and throws no checked exceptions, so handling CloneNotSupportedException is unnecessary.
This is a shallow copy, not a deep copy. For int[], changing a component in the copy does not change the original. For arrays of objects, references are copied, not objects. For int[][], only the outer array is new: subarrays remain shared. Replacing an outer-array component and modifying a shared subarray are different operations.
Examples
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2};
int[] copy = numbers.clone();
copy[0] = 9;
System.out.println(numbers == copy);
System.out.println(numbers[0] + " " + copy[0]);
int[][] rows = {{3, 4}};
int[][] rowsCopy = rows.clone();
System.out.println(rows == rowsCopy);
System.out.println(rows[0] == rowsCopy[0]);
rowsCopy[0][0] = 8;
System.out.println(rows[0][0]);
}
}Result
false 1 9 false true 8
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.