Java Program to copy all elements of one array into another array
Answers
Explanation:
STEP 1: START
STEP 2: INITIALIZE arr1[] ={1, 2, 3, 4, 5}
STEP 3: CREATE arr2[] of size arr1[].
STEP 4: COPY elements of arr1[] to arr2[]
STEP 5: REPEAT STEP 6 UNTIL (i<arr1.length)
STEP 6: arr2[i] =arr1[i]
STEP 7: DISPLAY elements of arr1[].
STEP 8: REPEAT STEP 9 UNTIL (i<arr1.length)
STEP 9: PRINT arr1[i]
STEP 10: DISPLAY elements of arr2[].
STEP 11: REPEAT STEP 12 UNTIL (i<arr2.length)
STEP 12: PRINT arr2[i].
STEP 13: END
We can clone or copy an Object using the clone( ) method of Object class so, we can ultimately clone an Array too.
Demonstration
Code:
import java.util.Arrays;
public class CopyArray {
public static void main(String[ ] args) {
// Test array to copied
int[ ] array = {1, 5, 2, 4, 7, 6, 9, 3, 0};
System.out.println("Original Array - " + Arrays.toString(array));
// New copied array
int[ ] newArray = array.clone( );
System.out.println("New Array - " + Arrays.toString(newArray));
}
}
Output:
Original Array - [1, 5, 2, 4, 7, 6, 9, 3, 0]
New Array - [1, 5, 2, 4, 7, 6, 9, 3, 0]