+1 vote
1 view
in Java by (1.1k points)

I need to concatenate two String arrays in Java.

void f(String[] first, String[] second) {
    String[] both = ???

What is the easiest way to do this?

2 Answers

0 votes
by (13.2k points)

There are multiple ways of concatenating two arrays but since you asked the easiest one, it has to be using addAll, take a look here.


public static void main(String[] args) {

   String[] s1 = new String[]{"D", "a", "r", "t", "h" };

    String[] s2 = new String[]{"V", "a", "d", "e", "r" };

        String[] res = ArrayUtils.addAll(s1, s2);


      int[] in1 = new int[]{1,2,3};

        int[] in2 = new int[]{4,5,6};

        int[] result2 = ArrayUtils.addAll(in1, in2);




[D, a, r, t, h, V, a, d, e, r]

[1, 2, 3, 4, 5, 6]

0 votes
by (25.8k points)

Try using Apache Commons Lang library i.e. ArrayUtils.addAll(T[], T...)

Are you interested to learn Java from scratch! Have a look at this video on Java:

Use like this:

String[] both = ArrayUtils.addAll(first, second);

For more information, refer to this 


Welcome to Intellipaat Community. Get your technical queries answered by top developers !