-6

I would like to combine all the Strings in an array to one String just by loops. How do I do it?

public class HelloWorld {

    public static void main(String[] args) {

        String [] x = {"ab", "bc", "cd"};

        String z = concatination(x, 3);

        System.out.println(z);
    }

    public static String concatination(String [] array, int i ){

        for(int j = 0; j<array.length-1; j++){
            return (array[j]);
        }
        return " ";
    }
}
output: 
java unreachable statement

Expected output:
abbccd

Thank you

Pri ya
  • 47
  • 3

2 Answers2

0
public static void main(String[] args) {

    String [] x = {"ab", "bc", "cd"};

    String z = concatination(x);

    System.out.println(z);
}

public static String concatination(String[] array) {
    String concat = "";
    for(int j = 0; j<array.length; j++) {
        concat += array[j];
    }
    return concat;
}

OUTPUT: abbccd

Ridwan
  • 214
  • 4
  • 17
0

Please try code below:-

public class HelloWorld{

     public static void main(String []args){
        String [] x = {"ab", "bc", "cd"};
        
        String z = concatination(x, 3);

        //With loop
        System.out.println(z);
        //Without loop
        System.out.println(String.join("",x));
     }

    public static String concatination(String [] array, int i ){
        StringBuilder builder = new StringBuilder();
        for(int j = 0; j<array.length; j++){
            builder.append(array[j]);
        }
        return builder.toString();
    }
}