Search code examples
javastringloopsreturn

Return string in Java does nothing in compiler


My goal is to reverse a string from "def" to "fed."

In this example (below), the value of new_string is not returned. Literally, the console appears blank.

public class ReverseString {

public String reverse(String input) {
    String new_string = "";
    int iterator = 0;
    int length = input.length();

        while(iterator < length){
            char string_input = input.charAt(iterator);
            new_string = string_input + new_string;
            iterator ++;
        }
    return new_string;
}


public static void main(String[] args){
    ReverseString test = new ReverseString();
    test.reverse("def");
}
}

However, when I change my code to do a system print, I get the correct result "fed."

public class ReverseString {

public void reverse(String input) {
    String new_string = "";
    int iterator = 0;
    int length = input.length();

        while(iterator < length){
            char string_input = input.charAt(iterator);
            new_string = string_input + new_string;
            iterator ++;
        }
    System.out.println(new_string);
}


public static void main(String[] args){
    ReverseString test = new ReverseString();
    test.reverse("def");
}
}

The question is: Why when return the result is blank?


Solution

  • You probably wanted something like this? Return a string variable. Print it out.

    public class ReverseString {
    
    public String reverse(String input) {
        String new_string = "";
        int iterator = 0;
        int length = input.length();
    
            while(iterator < length){
                char string_input = input.charAt(iterator);
                new_string = string_input + new_string;
                iterator ++;
            }
        return new_string;
    }
    
    
    
    public static void main(String[] args){
        ReverseString test = new ReverseString();
        System.out.println(test.reverse("def"));
    }
    }