Search code examples
javafor-loopreturn

Return a string that has been created in a for loop


The objective was to create a String toUppercase method if it did not exist. I got most of the code, but how do you return a string that has been created in a for loop?

public String toUpperCase(String str)
{
    for (int i = 0; i > str.length; i++){
        char a = str.charAt(i);
        char b = Character.toUpperCase(a);
        String t = Character.toString(b);
    }
    return t;
}

Solution

  • Declare t outside of the loop and assign with += inside the loop.

    public String toUpperCase(String str)
        {
            String t = "";
            for (int i = 0; i < str.length(); i++){
                char a = str.charAt(i);
                char b = Character.toUpperCase(a);
                t += Character.toString(b);
            }
            return t;
        }
    

    That's what you'd do in case such a method didn't exist. Also next step would have been to take care of performance and heap impact may be using StringBuilder. But all these basic operations are already available in java.lang.String why re-invent the wheel?