Jaanus
Jaanus

Reputation: 16541

How does Java saving object reference work?

    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?

Upvotes: 2

Views: 4219

Answers (7)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

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.

Upvotes: 1

MaVRoSCy
MaVRoSCy

Reputation: 17839

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.

Upvotes: 2

mishadoff
mishadoff

Reputation: 10789

Let's go through this step by step.

  1. String a = "test" - create object "test" and reference a point on this object.
  2. String b = a - create new reference b point to the same object "test"
  3. a = "wuut" - reassign reference a to another object, but reference b still point to object test

Upvotes: 0

CrazyCasta
CrazyCasta

Reputation: 28352

No. b holds the value of a which is a reference to the string "test". What you're thinking about is if you modified the string that a pointed to that b would also change (something like a.append("wuut");). However it is not possible to change Java string because they are immutable.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502006

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.

Upvotes: 5

Pablo
Pablo

Reputation: 3673

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.

Upvotes: 0

user207421
user207421

Reputation: 310985

No it doesn't. b assumes the value of a. If a changes later, b doesn't. It's not an alias or anything of that nature.

Upvotes: 0

Related Questions