Merge Two Arrays Example in Java
Introduction
Merge Two Arrays is a classic Java console program that demonstrates the concept with complete source code and sample output. Arrays store fixed-size sequences with fast index access — a foundation before collections.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Merge Two Arrays Example Program
import java.util.Arrays;
public class MergeTwoArrays {
public static void main(String[] args) {
System.out.println("The first array is: ");
int[] values1 = { 10, 20, 30 };
for(int i=0;i < values1.length;i++){
System.out.println(values1[i]);
}
System.out.println("The second array is: ");
int[] values2 = { 100, 200, 300 };
for(int i=0;i < values2.length;i++){
System.out.println(values2[i]);
}
int[] merge = new int[values1.length + values2.length];
for (int i = 0; i < values1.length; i++) {
merge[i] = values1[i];
}
for (int i = 0; i < values2.length; i++) {
merge[i + values1.length] = values2[i];
}
System.out.println("The merged array is: ");
System.out.println(Arrays.toString(merge));
}
}Sample Output
The first array is:
10
20
30
The second array is:
100
200
300
The merged array is:
[10, 20, 30, 100, 200, 300]When to use
Use this merge two arrays example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
import java.util.Arrays;imports a class used later in the program. -
A
println/printcall writes text to the console — part of the sample output below. -
int[] values1 = { 10, 20, 30 };updates a variable used in the calculation or output. -
A loop repeats the block until its condition becomes false.
-
A
println/printcall writes text to the console — part of the sample output below. -
A
println/printcall writes text to the console — part of the sample output below. -
A loop repeats the block until its condition becomes false.