Algorithm
-
Initialize Arrays:
- Declare and initialize two arrays, let's say
array1
andarray2
.
- Declare and initialize two arrays, let's say
-
Calculate Sizes:
- Determine the lengths of both arrays, denoted as
length1
andlength2
.
- Determine the lengths of both arrays, denoted as
-
Create Result Array:
- Create a new array with a size equal to the sum of
length1
andlength2
. This will be the result array to store the concatenated elements.
- Create a new array with a size equal to the sum of
-
Copy Elements:
- Copy elements from
array1
to the result array starting from index 0. - Copy elements from
array2
to the result array starting from the index equal to the length ofarray1
.
- Copy elements from
-
Display or Use Result:
- Optionally, you can display the concatenated array or use it as needed.
Code Examples
#1 Code Example- Concatenate Two Arrays using arraycopy
Code -
Java Programming
import java.util.Arrays;
public class Concat {
public static void main(String[] args) {
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};
int aLen = array1.length;
int bLen = array2.length;
int[] result = new int[aLen + bLen];
System.arraycopy(array1, 0, result, 0, aLen);
System.arraycopy(array2, 0, result, aLen, bLen);
System.out.println(Arrays.toString(result));
}
}
Copy The Code &
Try With Live Editor
Output
[1, 2, 3, 4, 5, 6]
#2 Code Example- Concatenate Two Arrays without using arraycopy
Code -
Java Programming
import java.util.Arrays;
public class Concat {
public static void main(String[] args) {
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};
int length = array1.length + array2.length;
int[] result = new int[length];
int pos = 0;
for (int element : array1) {
result[pos] = element;
pos++;
}
for (int element : array2) {
result[pos] = element;
pos++;
}
System.out.println(Arrays.toString(result));
}
}
Copy The Code &
Try With Live Editor
Output
[1, 2, 3, 4, 5, 6]
Demonstration
Java Programing Example to Concatenate Two Arrays-DevsEnv