0

I understand that everything is passed by reference in java. But why doesn't it work in this case? I had thought it should print out "Hate" instead of "Love".

class Test {
    static class Str {
        public String str;

        public void set(String str) {
            this.str = str;
        }
    }

    public static void main(String[] args) {
        Str s = new Str();

        String str = "Love";

        s.set(str);
        str = "Hate";

        System.out.println(s.str);
    }
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
user697911
  • 10,043
  • 25
  • 95
  • 169
  • 4
    References are passed by value, that's why. – A--C Mar 13 '13 at 00:18
  • See the discussion on [This Question](http://stackoverflow.com/questions/5835386/java-string-variable-setting-reference-or-value) – Gus Mar 13 '13 at 00:26
  • In Java everything is **pass by value**. It just so happens that the "value" of an Object is the reference to its location in the heap. – Tim Bender Mar 13 '13 at 00:28
  • 1
    [My answer might help you](http://stackoverflow.com/a/9404727/597657). – Eng.Fouad Mar 13 '13 at 00:37
  • "I understand that everything is passed by reference in java." Then you have a basic *mis*-understanding. – user207421 Mar 13 '13 at 09:12

2 Answers2

1

in main function, str just stores the reference to a string. When doing str = "hate", the reference changes but the original object "love" has been stored in s.str and remains there.

See this for more clarification.

Community
  • 1
  • 1
r.v
  • 4,697
  • 6
  • 35
  • 57
1

With str = "Hate", you have only changed your local str reference to "Hate"; s.str still refers to "Love", so that's what is printed.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • The fact that "s.str still refers to "Love"", seems to show that it's passed by value, not reference. Only when it's passed by value, it won't affect the value inside the function. So, doesn't the java reference behave the same as the pointer in C++ in passing arguments to a function? – user697911 Mar 13 '13 at 00:30
  • The Java object reference is more like a C++ pointer than a C++ reference, in that if you change one Java object reference, another Java reference that was initialized with the first reference still refers to the old value. – rgettman Mar 13 '13 at 00:32
  • So, in Java, if I do: – user697911 Mar 13 '13 at 01:13