1. Introduction
Cloning an array in Java means creating a copy of an existing array, where both arrays have the same length and hold the same elements. This post walks you through the process of cloning an array in Java using the clone() method and demonstrates the result of such operation.
2. Program Steps
1. Initialize the original array.
2. Use the clone() method to create a copy of the array.
3. Print the original and cloned array.
4. Modify the original array and demonstrate that the cloned array remains unaffected.
3. Code Program
public class CloneArray {
public static void main(String[] args) {
// Step 1: Initialize the original array
int[] originalArray = {1, 2, 3, 4, 5};
// Step 2: Use the clone() method to create a copy of the array
int[] clonedArray = originalArray.clone();
// Step 3: Print the original and cloned array
System.out.println("Original Array:");
for (int num : originalArray) {
System.out.print(num + " ");
}
System.out.println("\nCloned Array:");
for (int num : clonedArray) {
System.out.print(num + " ");
}
// Step 4: Modify the original array and demonstrate that the cloned array remains unaffected
originalArray[0] = 0;
System.out.println("\n\nOriginal Array after modification:");
for (int num : originalArray) {
System.out.print(num + " ");
}
System.out.println("\nCloned Array after modification of original array:");
for (int num : clonedArray) {
System.out.print(num + " ");
}
}
}
Output:
Original Array: 1 2 3 4 5 Cloned Array: 1 2 3 4 5 Original Array after modification: 0 2 3 4 5 Cloned Array after modification of original array: 1 2 3 4 5
4. Step By Step Explanation
Step 1: We initialize the original array originalArray with five integer elements.
Step 2: We use the clone() method to create a copy of the originalArray, resulting in the clonedArray. Both arrays have the same length and elements.
Step 3: We print both the original and cloned arrays to demonstrate that they contain the same elements.
Step 4: We modify the first element of the originalArray and print both arrays again to demonstrate that the clonedArray remains unaffected by changes in the originalArray. This shows that the clone() method creates a shallow copy of the array.