Algorithm


  1. Initialize Arrays:

    • Declare and initialize two arrays, let's say array1 and array2.
  2. Calculate Sizes:

    • Determine the lengths of both arrays, denoted as length1 and length2.
  3. Create Result Array:

    • Create a new array with a size equal to the sum of length1 and length2. This will be the result array to store the concatenated elements.
  4. Copy Elements:

    • Copy elements from array1 to the result array starting from index 0.
    • Copy elements from array2 to the result array starting from the index equal to the length of array1.
  5. Display or Use Result:

    • Optionally, you can display the concatenated array or use it as needed.

 

Code Examples

#1 Code Example- Concatenate Two Arrays using arraycopy

Code - Java Programming

import java.util.Arrays;

public class Concat {

    public static void main(String[] args) {
        int[] array1 = {1, 2, 3};
        int[] array2 = {4, 5, 6};

        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));
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
[1, 2, 3, 4, 5, 6]

#2 Code Example- Concatenate Two Arrays without using arraycopy

Code - Java Programming

import java.util.Arrays;

public class Concat {

    public static void main(String[] args) {
        int[] array1 = {1, 2, 3};
        int[] array2 = {4, 5, 6};

        int length = array1.length + array2.length;

        int[] result = new int[length];
        int pos = 0;
        for (int element : array1) {
            result[pos] = element;
            pos++;
        }

        for (int element : array2) {
            result[pos] = element;
            pos++;
        }

        System.out.println(Arrays.toString(result));
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
[1, 2, 3, 4, 5, 6]
Advertisements

Demonstration


Java Programing Example to Concatenate Two Arrays-DevsEnv