String a = "test";
String b = a;
a = "wuut";
System.out.println(b);
Prints out test
Shouldn't b hold refence of a, not just take its value?
Doesn't Java work that way with objects and stuff?
String a = "test";
String b = a;
a = "wuut";
System.out.println(b);
Prints out test
Shouldn't b hold refence of a, not just take its value?
Doesn't Java work that way with objects and stuff?
Shouldn't b hold refence of a, not just take its value?
No. The value of a is a reference. References are a way of getting to objects, not variables. The assignment operator just copies the value of the expression on the right hand side into the variable on the left hand side. That's all it does - it's very simple. There's no pass-by-reference in Java, no variable aliasing etc.
a isn't a String object. It's a reference to a String object. All your classes will work in exactly the same way.MyObject a = new MyObject(), and when I create Myobject b = a, then it is reference, and changing a also changes b?When a is created lets say it point to place memory_1 in memory.
When b is assigned to a, then b also points to the same memory_1 location.
Now, when a changes value (and because the String Object is immutable) a new value is created now in memory and now a points in memory_2.
But hey, b still points in memory_1.
PS: Immutability is:
In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created.
int which is a primitive data type but Object Integer )a changes value, it changes value. It refers to a different object. There's nothing string-specific about that.String a = test
So a is an Object Reference Variable pointing to a String Literal "test" on the heap.
String b = a;
No b is an Object Reference Variable also pointing to the same String Literal "test" on the heap.
Now,
a = "wuut";
But b is still pointing to the String Literal "test",
so Its b which holds the reference to the Object which was previously also referred by a, and but Not to a.
String a = "test";
Now a holds a reference to the string "test".
String b = a;
The value of a is copied to b. A is a reference to "test", so now b is a reference to "test" too.
a = "wuut";
Now a is assigned a reference to "wuut". This doesn't affect b, because b doesn't hold a reference to a.