Skip to content
Home » Java Programs » Merge Two Arrays in Java Program

Merge Two Arrays in Java Program

Basic merge two arrays in java program. An array is a data structure that contains a collection of elements, values, or variables, each of which is identified by an array index or key. Array types may overlap or be confused with other data types that describe aggregates of values, such as lists and strings, depending on the language.

Merge Sort in Java

In Java, an array is a collection of variables that are referred to by a single variable name and an index number. An array’s items are called elements. An array’s items must all be of the same type.

For example, an int array can hold int values, while a String array can hold strings. A data structure that contains a group of elements is known as an array. These elements are typically all of the same data type, such as an integer or a string. 

A search engine, for example, might use an array to store Web pages found during a user’s search. These are main advantages to learn array to execute the program like merge two arrays in java program.

Util Array in Java

The Java Collection Framework includes the Arrays class in the util package. This class offers static methods for creating and accessing Java arrays dynamically. It only has static methods and methods from the Object class. The class name itself can utilise the methods of this class. Using this package we can execute merge two arrays in java program

System.arraycopy in Java

The System class has methods for standard input and output, loading files and libraries, and accessing attributes defined externally. The java. arraycopy() function copies a source array from a specified beginning position to the specified destination array. 

This is sample program like merge two arrays in java program for beginners. The java. lang. System. arraycopy() function copies a source array from a specified beginning position to a specified destination array. 

The arraycopy() method copies an array from a specified source array to a specified destination array, starting at the specified position. A subset of array components is copied from the src-referenced source array to the dest-referenced destination array.

Merge Two Arrays in Java Program

//merge two arrays in java program
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{
int[] array1 = {10, 20, 30};
int[] array2 = {40, 50, 60};
int aLen = array1.length;
int bLen = array2.length;
int[] result = new int[aLen + bLen];
System.arraycopy(array1, 0, result, 0, aLen);
System.arraycopy(array2, 0, result, aLen, bLen);
System.out.println(Arrays.toString(result));
}
}

Output:

[10, 20, 30, 40, 50, 60]