How to Concatenate two arrays in java


In this tutorial we will learn How to Concatenate two arrays in Java with program and examples. Also Read how to Merge two sorted arrays in java. we will Concatenate two arrays using ArrayUtils in java which is class from apache commons library.




How to Concatenate two arrays in Java >
  • Program/Example 1 to Concatenate two arrays in Java
  • Program/Example 2 to Concatenate two arrays using NumberUtils in java which is class from apache commons library.


Program/Example 1 to Concatenate two arrays in Java

package ConcatenateTwoArrays;
import java.util.Arrays;
public class Main{
   public static void main(String[] args) {
          int firstArray[] = { 1, 2, 3 };
          int secondArray[] = { 4, 5, 6 };
          System.out.println("Display concatenated array");
          for (int i : ConcatenateTwoArrays.concatenateTwoArrays(firstArray, secondArray)) {
                 System.out.print(i + " ");
          }
   }
}
/**
* ConcatenateTwoArrays class contains  concatenateTwoArrays method which concatenates 2 arrays.
*/
class ConcatenateTwoArrays {
  
   /**
   * method  concatenates two arrays.
   */
   public static int[] concatenateTwoArrays(int[] firstArray, int[] secondArray) {
         
          int concatenatedArrayLength = firstArray.length + secondArray.length;
                      
          int[] concatenatedArray = Arrays.copyOf(firstArray, concatenatedArrayLength);
         
          System.arraycopy(secondArray, 0, concatenatedArray, firstArray.length,
                       secondArray.length);
         
          return concatenatedArray;
   }
}
/*OUTPUT
Display concatenated array
1 2 3 4 5 6
*/



Program/Example 2 to Concatenate two arrays using NumberUtils in java which is class from apache commons library.

package ConcatenateTwoArrays;
import org.apache.commons.lang.ArrayUtils;
public class ConcatenateTwoArraysUsingApacheCommonsLibrary {
   public static void main(String[] args) {
          int firstArray[] = { 1, 2, 3 };
          int secondArray[] = { 4, 5, 6 };
          int[] concatenatedArray = (int[])ArrayUtils.addAll(firstArray, secondArray);
          System.out.println("Display concatenated array");
          for (int i : concatenatedArray) {
                 System.out.print(i + " ");
          }
   }
  
}
/*OUTPUT
Display concatenated array
1 2 3 4 5 6
*/



Summary -
In this tutorial we learned How to Concatenate two arrays in Java with program and examples. we concatenated two arrays using ArrayUtils in java which is class from apache commons library.

Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.



RELATED LINKS>

Merge two sorted arrays

How to convert ArrayList to HashSet and Set to Array in Java examples

Collection - List, Set and Map all properties in tabular form



eEdit
Must read for you :