Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning in Java?

Tags:

java

Say I set int A = int B. When I change A after, it will not change the value of B. But when I set a SomeClass A = SomeClass B, and I change A's contents (like a.cost), it changes B.cost as well. Can someone explain this to me?

I thought Java is assigned by value, not reference?

like image 306
Brent Avatar asked Oct 04 '10 19:10

Brent


2 Answers

Yes, it does - but the value of A is a reference, not a copy of the object itself.

I like to give the following analogy...

Suppose two people both have my address: that's like two variables of type House in Java. Now one of them comes and paints my door red. The second person will still see the red door if they visit:

House jonsHouse = new House(); // Even the variable jonsHouse is only a reference

House firstAddressCopy = jonsHouse; // Just a copy of the reference
House secondAddressCopy = jonsHouse; // Just a copy of the reference

firstAddressCopy.paintDoor(Color.Red);

Color color = secondAddressCopy.getDoorColor(); // Now color will be red

Basically, remember a few rules and things will become clear:

  • The value of an expression in Java is never an object - only ever a reference or a primitive value
  • (Corollary of first point) A variable never holds an object - only ever a reference or a primitive value
  • Assignment (and argument passing) always copies the value, whether that value is a reference or a primitive value
like image 54
Jon Skeet Avatar answered Nov 15 '22 13:11

Jon Skeet


I thought Java is assigned by value, not reference?

What does "assigned by value" mean? Are you maybe confusing it with "pass by value/reference"?

At any rate, if you handle a class instance in Java, you are actually handling a reference to that class (much like a pointer in C/C++). Your assignment only copies the reference, so both A and B refer to the same instance, i.e. the data is shared, hence the result.

like image 32
sleske Avatar answered Nov 15 '22 13:11

sleske