In Java, arrays are objects that store multiple values of the same data type. When you want to make a copy of an array, you can use the clone()
method provided by the Object
class. The clone()
method creates a new array with the same length and values as the original array. This allows you to modify the cloned array without affecting the original one.
Let’s take a look at an example to understand how to clone a Java array:
public class ArrayCloningExample {
public static void main(String[] args) {
int[] originalArray = {1, 2, 3, 4, 5};
// Using the clone() method to create a clone of the original array
int[] clonedArray = originalArray.clone();
// Modifying a value in the cloned array
clonedArray[0] = 10;
// Printing the original array
System.out.println("Original Array:");
for (int i = 0; i < originalArray.length; i++) {
System.out.print(originalArray[i] + " ");
}
// Printing the cloned array
System.out.println("\nCloned Array:");
for (int i = 0; i < clonedArray.length; i++) {
System.out.print(clonedArray[i] + " ");
}
}
}
In the example above, we have an original array named originalArray
with values {1, 2, 3, 4, 5}
. We use the clone()
method to create a clone of the original array, which is assigned to the clonedArray
variable. Then, we modify the first value of the clonedArray
to 10.
When we print the originalArray
, it remains unchanged with values {1, 2, 3, 4, 5}
. However, the clonedArray
now contains the modified value and is printed as {10, 2, 3, 4, 5}
.
By cloning an array, you can create an independent copy that can be modified without impacting the original array. This can be useful in scenarios where you want to perform operations on an array without altering the original data.
Conclusion
In this article, we learned how to clone a Java array using the clone()
method. Cloning an array allows you to create a separate copy that can be modified independently of the original array. This can be useful in various programming scenarios. Cloning an array is a straightforward process that can be accomplished using the built-in clone()
method.