-2

I have the following code

public static void main(String[] args) {

String word = "Super";

reverseString(word);

System.out.println(word);

}

public static String reverseString(String word) {

String helper = "";

int i = word.length() - 1;

while (i >= 0) {
    helper += word.charAt(i);
    i--;

}

return helper;

I do not understand why when I'm printing the "word" variable it still prints "Super" even though I changed it in the reverseString method. I understand that strings are passed by reference and not a copy like primitive values.

If I do word = reverseString(word) it prints the reverse what I expect, "repuS"

Thanks

dunn91
  • 39
  • 3
  • 1
    String is immutable in java – Jens Mar 28 '17 at 07:12
  • Possible duplicate of which might help you to under the logic behind Pass by reference http://stackoverflow.com/questions/9404625/java-pass-by-reference – Arindam Mar 28 '17 at 07:15

1 Answers1

1

You're not changing the string in reverseString, you're creating a new one and returning the new one (which you've called helper).

A second thing to note about strings in Java is that they're immutable - all string methods return a new string rather than modifying the one you're calling the method on.

iblamefish
  • 4,401
  • 3
  • 28
  • 43