-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

0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

A good answer should explain the problem. What's obvious to you might not be so for others.
@JohnnyMopp, ok thanks for the feedback. I'm still new here.
@Ridwan Thank you! How do you do the same with characters though?
@Priya, its going to be the same.
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();
    }
}

2 Comments

String z = concatination(x, 3); Why passing 3 as parameter when you are not going to use it.
No need to pass 3. Just copied given code :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.