Java - Concatenate two arrays with System.arraycopy

In this tutorial, we're going to learn how to merge two tables. The following two examples provide two different ways for concatenation: an academic method for learning and the second with the System.arraycopy().

1) Classic method: browse both arrays

public class ConcatArrays {

public static void main(String[] args) {
String[] t1 = {"1","2","3"};
String[] t2 = {"4","5","6"};
String[] t12 = new String[t1.length+t2.length];

/*Concatenation*/
for(int i = 0 ; i < t1.length; i++)
t12[i]=t1[i];
for(int i = 0 ; i < t2.length; i++)
//we continue copying in t12 from the index
//which we have stopped which is the length of t1
t12[i+t1.length]=t2[i];

for(int i = 0 ; i < t12.length; i++)
System.out.println(t12[i]);
}
}
Output

1
2
3
4
5
6

2) With the System.arraycopy()

This method is efficient, You can use it to copy items from a source table to the destination table. It accepts five arguments:
  1. The source array (t1 and t2).
  2. from which position of the source array you want to start(in our case 0).
  3. The destination array (t12).
  4. from which position of the destination array you want to start.
    1. 0 for t1.
    2. t1.lenght for t2.
  5. The number of elements you want to copy (not the stop position).
public class ConcatArrays {

public static void main(String[] args) {
char[] t1 = {'a', 'b','c'};
char[] t2 = {'d','e','f'};
char[] t12 = new char[t1.length+t2.length];

//copy of first array
System.arraycopy(t1, 0, t12, 0, t1.length);
//copy of the second array array
System.arraycopy(t2, 0, t12, t1.length, t2.length);

for(int i = 0 ; i < t12.length; i++)
System.out.println(t12[i]);
}
}
Output

a
b
c
d
e
f
References
Oracle documentation: The System
TutorialsPoint:  Java.lang.System.arraycopy() Method