Java Program to Concatenate Two Arrays

Java Programming Object Oriented ProgrammingJava8

One way of doing it is, create an array of length equals to the sum of lengths of the two arrays and, add elements of both arrays to it one by one.

Example

Live Demo

public class HelloWorld {
   public static void main(String[] args) {
      int[]a = {1,2,3,4};
      int[]b = {4,16,1,2,3,22};
      int[]c = new int[a.length+b.length];
      int count = 0;

      for(int i = 0; i<a.length; i++) {
         c[i] = a[i];
         count++;
      }

      for(int j = 0;j<b.length;j++) {
         c[count++] = b[j];
      }

      for(int i = 0;i<c.length;i++) System.out.print(c[i]+" ");
   }
}

Output

1 2 3 4 4 16 1 2 3 22
raja
Published on 26-Apr-2018 11:04:30
Advertisements