Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
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.

Example:

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);

        System.out.println(Arrays.toString(result));

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

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

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

        System.out.println(Arrays.toString(result2));

    }

OUTPUT

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

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

0 votes
by (32.3k 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 

http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/ArrayUtils.html#addAll%28T%5B%5D,%20T...%29

Related questions

0 votes
1 answer
+2 votes
3 answers
0 votes
1 answer
asked Sep 19, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Sep 19, 2019 in Java by Anvi (10.2k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

29.3k questions

30.6k answers

501 comments

104k users

Browse Categories

...