OneBite.Dev - Coding blog in a bite size

merge two arrays in java

Code snippet on how to merge two arrays in java

//Declare two arrays
int[] arr1 = {1,2,3};
int[] arr2 = {4,5,6};

//Declare the result array
int[] result = new int[arr1.length+arr2.length];

//Merge the two arrays
int i = 0;
for (int temp : arr1){
  result[i] = temp;
  i++;
}
for (int temp : arr2){
  result[i] = temp;
  i++;
}

//Print the result
System.out.println(Arrays.toString(result));

This code creates two integer arrays with values, arr1 and arr2, and then merges them together into a new array, result. We then iterate through each array, adding their values to the result array with an index of ā€˜iā€™ which is incremented at each iteration. Lastly, this code prints the resulting array to the console.

java