Skip to main content
Browse topics

Merge Two Arrays Example in Java

2 min read Updated May 29, 2026
Share

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

java
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

plaintext
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

  1. Execution begins in the main method — the JVM calls this method when you run the class.

  2. import java.util.Arrays; imports a class used later in the program.

  3. A println / print call writes text to the console — part of the sample output below.

  4. int[] values1 = { 10, 20, 30 }; updates a variable used in the calculation or output.

  5. A loop repeats the block until its condition becomes false.

  6. A println / print call writes text to the console — part of the sample output below.

  7. A println / print call writes text to the console — part of the sample output below.

  8. A loop repeats the block until its condition becomes false.

Best Practices

Common Mistakes

Frequently Asked Questions

What does the Merge Two Arrays program demonstrate?
It shows how to implement merge two arrays in Java with a complete runnable example and expected console output.
How do I run this Java program?
Save the code in a `.java` file matching the public class name, compile with `javac`, then run with `java ClassName`.
When would I use this pattern?
Use this pattern whenever you need the same logic in homework, practice or small utility tools.

Related tutorials

Search tutorials