java

How to merge two arrays in Java

In this tutorial, we are going to see how to merge two arrays in Java.

To concatenate or merge two arrays into a single array so that the array elements retain their original order in the newly merged array. The items of the first array precede the items of the second array.
 

Example: Using arraycopy() method

arraycopy() is a method of the System class which is a member of java.lang package. It copies a specified source array to the specified position of the destination array. The number of elements copied is equal to the length of the array.

Example: arraycopy(arr, 0, res, 0, len) function allows you to copy “arr” array from index “0” to “res” array from index “0” to “len”.
 

 

import java.util.Arrays;

public class Main
{
	public static void main(String[] args) 
	{
		int[] arr1 = {1,2,3};
		int[] arr2 = {4,5,6};
		
		int len1 = arr1.length;
		int len2 = arr2.length;
		
		int[] res = new int[len1 + len2];
		
		System.arraycopy(arr1, 0, res, 0, len1);
		System.arraycopy(arr2, 0, res, len1, len2);
		System.out.println(Arrays.toString(res));
	}
}

Output:

[1, 2, 3, 4, 5, 6]
 

Example: Without using arraycopy() method

In the following code, we have initialized two arrays arr1 and arr2 of type int. We will manually copy each element of the two arrays into the “res” array and convert that array to a string using the toString() method of the Array class.

import java.util.Arrays;

public class Main
{
	public static void main(String[] args)
	{
		int[] arr1 = {1,2,3};
		int[] arr2 = {4,5,6};
		int len = arr1.length + arr2.length; 
		int[] res = new int[len];	
		int pos = 0;
		for (int i : arr1) 
		{
			res[pos] = i;
			pos++;				
		}
		for (int i : arr2) 
		{
			res[pos] = i;
			pos++;
		}
		System.out.println(Arrays.toString(res));	
	}
}

Output:

[1, 2, 3, 4, 5, 6]
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *