How to concatenate two string arrays in Java

3 Answers

0 votes
public class Main {
    public static void main(String[] args) {
        String[] array1 = {"aaa", "bbb"};
        String[] array2 = {"ccc", "ddd", "eee"};
        
        String[] result = new String[array1.length + array2.length];
        
        System.arraycopy(array1, 0, result, 0, array1.length);
        System.arraycopy(array2, 0, result, array1.length, array2.length);
        
        for (String str : result) {
            System.out.print(str + " ");
        }
    }
}

   
   
/*
run:
   
aaa bbb ccc ddd eee 
  
*/

 



answered Feb 17, 2025 by avibootz
0 votes
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String[] array1 = {"aaa", "bbb"};
        String[] array2 = {"ccc", "ddd", "eee"};
        
        String[] result = Arrays.copyOf(array1, array1.length + array2.length);
        System.arraycopy(array2, 0, result, array1.length, array2.length);
        
        for (String str : result) {
            System.out.print(str + " ");
        }
    }
}

   
   
/*
run:
   
aaa bbb ccc ddd eee 
  
*/

 



answered Feb 17, 2025 by avibootz
0 votes
import java.util.Arrays;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        String[] array1 = {"aaa", "bbb"};
        String[] array2 = {"ccc", "ddd", "eee"};
        
        String[] result = Stream.concat(Arrays.stream(array1), Arrays.stream(array2))
                                .toArray(String[]::new);
        
        for (String str : result) {
            System.out.print(str + " ");
        }
    }
}

   
   
/*
run:
   
aaa bbb ccc ddd eee 
  
*/


 



answered Feb 17, 2025 by avibootz

Related questions

2 answers 262 views
1 answer 208 views
1 answer 136 views
136 views asked Aug 11, 2021 by avibootz
1 answer 214 views
1 answer 174 views
3 answers 251 views
1 answer 175 views
...