Java Program to Concatenate Two Arrays - The Coding Shala
Home >> Java Programs >> Concatenate Two Arrays
Other Posts You May Like
In this post, we will learn how to concatenate two arrays using a Java program.
Java Program to Concatenate Two Arrays
Write a Java program to concatenate two given arrays and print the new array.
Example 1:
Input: arr1 = [1, 2, 3]
are2 = [4, 5]
Output: [1, 2, 3, 4, 5]
Solution 1
We can create a new array and the size of this array will be the size of array1 + the size of array2, and copy all the elements from array1 and array2 to this new array.
Java Program:
/** * https://www.thecodingshala.com/ */ public class Main { public static void arrayConcat(int[] arr1, int[] arr2) { int len1 = arr1.length; int len2 = arr2.length; int[] res = new int[len1 + len2]; int index = 0; // add first array for (int i=0; i<len1; i++) { res[index] = arr1[i]; index++; } // add second array for (int i=0; i<len2; i++) { res[index] = arr2[i]; index++; } // print array for (int i=0; i<res.length; i++) { System.out.print(res[i] + " "); } } public static void main(String[] args) { // concat integer arrays int[] arr1 = {1, 2, 3, 4, 5}; int[] arr2 = {6, 7, 8, 9, 10}; System.out.println("First array is: "); for (int i=0; i<arr1.length; i++) { System.out.print(arr1[i] + " "); } System.out.println(); System.out.println("Second array is: "); for (int i=0; i<arr2.length; i++) { System.out.print(arr2[i] + " "); } System.out.println(); System.out.println("Array after concatenate: "); arrayConcat(arr1, arr2); } }
Output:
First array is: 1 2 3 4 5 Second array is: 6 7 8 9 10 Array after concatenate: 1 2 3 4 5 6 7 8 9 10
- Java Program to Print the Sum of all Elements of the Array
- Java Program to Reverse an Array
- Java Program to Count Negative Numbers in a Sorted Matrix
- Java Program to Sort an Array
- Java Program to Find the Largest Element in the Array
Comments
Post a Comment