Java Program to Concatenate Two Arrays - The Coding Shala

Home >> Java Programs >> Concatenate Two Arrays

 In this post, we will learn how to concatenate two arrays using a Java program.

Java Program to Concatenate Two Arrays

Write a Java program to concatenate two given arrays and print the new array.

Example 1:
Input: arr1 = [1, 2, 3]
            are2 = [4, 5]
Output: [1, 2, 3, 4, 5]

Solution 1

We can create a new array and the size of this array will be the size of array1 + the size of array2, and copy all the elements from array1 and array2 to this new array.

Java Program: 

/**
 * https://www.thecodingshala.com/
 */

public class Main {

    public static void arrayConcat(int[] arr1, int[] arr2) {
        int len1 = arr1.length;
        int len2 = arr2.length;
        int[] res = new int[len1 + len2];

        int index = 0;
        // add first array
        for (int i=0; i<len1; i++) {
            res[index] = arr1[i];
            index++;
        }

        // add second array
        for (int i=0; i<len2; i++) {
            res[index] = arr2[i];
            index++;
        }

        // print array
        for (int i=0; i<res.length; i++) {
            System.out.print(res[i] + " ");
        }
    }

    public static void main(String[] args) {
        // concat integer arrays
        int[] arr1 = {1, 2, 3, 4, 5};
        int[] arr2 = {6, 7, 8, 9, 10};
        System.out.println("First array is: ");
        for (int i=0; i<arr1.length; i++) {
            System.out.print(arr1[i] + " ");
        }

        System.out.println();
        System.out.println("Second array is: ");
        for (int i=0; i<arr2.length; i++) {
            System.out.print(arr2[i] + " ");
        }

        System.out.println();
        System.out.println("Array after concatenate: ");
        arrayConcat(arr1, arr2);
    }
}

Output: 

First array is: 
1 2 3 4 5 
Second array is: 
6 7 8 9 10 
Array after concatenate: 
1 2 3 4 5 6 7 8 9 10 


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala