OneBite.Dev - Coding blog in a bite size

merge two arrays together in java

Code snippet on how to merge two arrays together in java

  int[] array1 = { 2, 5, 7 };
  int[] array2 = { 3, 6, 8 };
  int[] result = new int[array1.length + array2.length];
  
  System.arraycopy(array1, 0, result, 0, array1.length);
  System.arraycopy(array2, 0, result, array1.length, array2.length);

This code merges two arrays into one to create a single result array which contains all the items in both of the original arrays. First it declares two arrays, array1 and array2, and an empty result array with the appropriate size. Then it uses the system.arraycopy method to copy the contents of array1 into the result array starting from the beginning of result. The last line does the same for array2, but this time it starts from the end of array1 in result. After these two steps, result should contain all the elements of both array1 and array2, merged together.

java