How to copy an Array in Java – Four different ways
There are four ways to copy an array in Java. Following are the different ways
- Using for Loop
- Using copyOf() method of Array Class
- Using clone() Method
- Using arraycopy() method Of System Class
Using for Loop
package com.javaindetail.arraycopy;
public class UsingForLoop {
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5 };
int[] b = new int[a.length];
//copy an array in Java
//copying a to b
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
//printing a
System.out.print("A Array ::");
for (int i = 0; i < a.length; i++) {
System.out.print(" "+a[i]);
}
//printing b
System.out.print("nB Array ::");
for (int i = 0; i < b.length; i++) {
System.out.print(" "+b[i]);
}
}
}
Output
A Array :: 1 2 3 4 5
B Array :: 1 2 3 4 5
Using copyOf() method of Array Class
package com.javaindetail.arraycopy;
import java.util.Arrays;
public class UsingCopyOf {
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5 };
// copy an array in Java
// creating a copy of array 'a' using copyOf() method of java.util.Arrays
int[] b = Arrays.copyOf(a, a.length);
// printing a
System.out.print("A Array ::");
for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i]);
}
// printing b
System.out.print("nB Array ::");
for (int i = 0; i < b.length; i++) {
System.out.print(" " + b[i]);
}
}
}
Output
A Array :: 1 2 3 4 5
B Array :: 1 2 3 4 5
Using clone() Method
package com.javaindetail.arraycopy;
public class UsingClone {
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5 };
// creating a copy of array 'a' using clone() method
int[] b = a.clone();
// printing a
System.out.print("A Array ::");
for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i]);
}
// printing b
System.out.print("nB Array ::");
for (int i = 0; i < b.length; i++) {
System.out.print(" " + b[i]);
}
}
}
Output
A Array :: 1 2 3 4 5
B Array :: 1 2 3 4 5
Using arraycopy() method Of System Class
package com.javaindetail.arraycopy;
public class UsingArrayCopy {
public static void main(String[] args) {
int[] a = { 1,2,3,4,5 };
int[] b = new int[a.length];
// copy an array in Java
// creating a copy of array 'a' using arraycopy() method of System class
System.arraycopy(a, 0, b, 0, a.length);
// printing a
System.out.print("A Array ::");
for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i]);
}
// printing b
System.out.print("nB Array ::");
for (int i = 0; i < b.length; i++) {
System.out.print(" " + b[i]);
}
}
}
Output
A Array :: 1 2 3 4 5
B Array :: 1 2 3 4 5
Enjoy Reading This Article?
Here are some more articles you might like to read next: