dlsdaviddls dlsdaviddls - 24 days ago 6
Java Question

Return string in Java does nothing in compiler

first time poster and Java newbie. I am working on practice code to skill up. The problem I am running into is that return new_string; does not return any value to my 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");
}
}


Any help would be much appreciated. Searched everywhere for an answer but could not figure this out!

Answer

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"));
}
}