How to Join Two Array using Single Loop in Java

Join Two Array using Single Loop

In this example, We will show you simple program about How to join two array using single loop in Java. The program has been tested and shared in the post.

Example Program

package com.dineshkrish;

public class JoinArray {

	public static void main(String[] args) {

		// Array 1
		int array1[] = { 1, 2, 3, 4, 5 };

		// Array 2
		int array2[] = { 6, 7, 8, 9, 10 };

		// Creating Array 3 with size of Array 1 & Array 2
		int array3[] = new int[array1.length + array2.length];

		int count = 0;

		// Iterating based on the Array 3 length
		for (int i = 0; i < array3.length; i++) {

			if (count < array1.length) {

				// Copying the element form Array 1 to Array 3
				array3[count] = array1[i];

			} else {

				// Copying the element from Array 2 to Array 3
				array3[count] = array2[i - array1.length];

			}

			count++;

		}

		// This loop used to display the elements.
		for (int element : array3) {

			System.out.print(element+ " ");
		}

	}
}

Output

1 2 3 4 5 6 7 8 9 10