Java Copying Arrays Using Assignment Operator

Java Copying Arrays Using Assignment Operator

In Java, you can use the assignment operator (=) to copy the elements of one array to another array, as long as both arrays are of the same type.

For example, to copy the elements of an int array called original to another int array called copy, you can use the following code:

int[] original = {1, 2, 3, 4, 5};
int[] copy = original;
‮oS‬urce:www.lautturi.com

This code creates a new int array called copy and assigns it the value of the original array. However, it is important to note that this code does not create a new copy of the original array. Instead, it creates a reference to the original array, so any changes made to the copy array will also be reflected in the original array.

If you want to create a new copy of the original array, you can use the clone method of the Object class, like this:

int[] original = {1, 2, 3, 4, 5};
int[] copy = original.clone();

This code creates a new int array called copy and copies the elements of the original array to the copy array using the clone method.

Created Time:2017-11-03 00:14:37  Author:lautturi