How to Copy One Array to Another in Java

How to Copy One Array to Another in Java

How to Copy One Array to Another in Java

Here you will figure out how to copy one array to another in Java.

There are for the most part four distinct approaches to copy all components of one array into another array in Java.

  1. Manually
  2. Arrays.copyOf()
  3. System.arraycopy()
  4. Object.clone()

Lets examine every one of them in short.

How to Copy One Array to Another in Java

Manually 

In this technique, we manually copy the components one by one. It’s anything but a proficient way. Underneath example shows how to do this.

Example:

package com;
 
public class CopyArrayExample {
	public static void main(String args[]){
		int a[]={10,20,30,40,50};
		int b[]=new int[a.length];
		
		//copying one array to another
		for(int i=0;i<a.length;++i){
			b[i]=a[i];
		}
		
		//printing array
		for(int i=0;i<b.length;++i){
			System.out.print(b[i]+" ");
		}
	}
}

Arrays.copyOf()

We can straightforwardly copy one array to another by utilizing Arrays.copyOf() technique. It has the following syntax.

public static int[] copyOf(int[] original,int newLength)

It is another strategy that legitimately duplicates one array to another. It has the following syntax.

public static int[] copyOf(int[] original,int newLength)

Example:

package com;
 
import java.util.Arrays;
 
public class CopyArrayExample {
	public static void main(String args[]){
		int a[]={10,20,30,40,50};
		int b[]=new int[a.length];
		
		//copying one array to another
		b=Arrays.copyOf(a,a.length);
		
		//printing array
		for(int i=0;i<b.length;++i){
			System.out.print(b[i]+" ");
		}
	}
}

System.arraycopy()

It is another technique that straightforwardly duplicates one array to another. It has the following syntax.

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

Example:

package com;
 
public class CopyArrayExample {
	public static void main(String args[]){
		int a[]={10,20,30,40,50};
		int b[]=new int[a.length];
		
		//copying one array to another
		System.arraycopy(a,0,b,0,a.length);
		
		//printing array
		for(int i=0;i<b.length;++i){
			System.out.print(b[i]+" ");
		}
	}
}

Object.clone()

We can likewise utilize clone() strategy for Object class to make a copy of an array.

Example:

package com;
 
public class CopyArrayExample {
	public static void main(String args[]){
		int a[]={10,20,30,40,50};
		int b[]=new int[a.length];
		
		//copying one array to another
		b=a.clone();
		
		//printing array
		for(int i=0;i<b.length;++i){
			System.out.print(b[i]+" ");
		}
	}
}

Remark underneath in the event that you have any uncertainty identified with the above

tutorial or you think about some other method to copy one array to another in Java.

Leave a Comment

error: Alert: Content is protected!!