Quantcast
Channel: The Crazy Programmer
Viewing all articles
Browse latest Browse all 761

How to Copy One Array to Another in Java

$
0
0

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

There are mainly four different ways to copy all elements of one array into another array in Java.

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

Lets discuss each of them in brief.

How to Copy One Array to Another in Java

How to Copy One Array to Another in Java

1. Manually

In this method we manually copy elements one by one. It is not an efficient way. Below 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]+" ");
		}
	}
}

 

2. Arrays.copyOf()

We can directly copy one array to another by using Arrays.copyOf() method. It has 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]+" ");
		}
	}
}

 

3. System.arraycopy()

It is another method that directly copies one array to another. It has 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]+" ");
		}
	}
}

 

4. Object.clone()

We can also use clone() method of 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]+" ");
		}
	}
}

 

Comment below if you have any doubt related to above tutorial or you know about any other way to copy one array to another in Java.

The post How to Copy One Array to Another in Java appeared first on The Crazy Programmer.


Viewing all articles
Browse latest Browse all 761

Trending Articles