1

I have a bit of an odd question regarding how primitive types work in Java. When using Objects when you assign an ObjectA to be ObjectB be like such

Rectangle ObjectB = new Rectangle();
ObjectA = ObjectB;

Any calls to ObjectA refer now to ObjectB's memory location. However when using integers or other primitive types this is not the case. For example

int x = 3;
int y = x;
int x = 5;
return y;

y will return 3, the value of x when y was initialized.

The question I have is why does assignment for objects create references in memory, whereas primitives make a copy of the values of each other? Other than the fact that this is useful, how is this implemented in Java?

I'd appreciate anyone who can provide me a greater understanding of how assignment works between primitive types and objects.

  • 2
    [Is Java “pass-by-reference” or “pass-by-value”?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Ferrybig Jan 22 '16 at 17:50
  • 1
    Java has two types of variables. Primitives and reference only. When you copy a primitive, it is the primitive values which is copied, when you copy a reference, it is the reference value which is copied. There is no "assignment for objects" – Peter Lawrey Jan 22 '16 at 18:45

1 Answers1

7

The exact same thing is done whether the variables are of primitive type or reference type: The value held in the variable is copied to the other variable.

The only difference is that the value held in a variable with a reference type is a reference to the actual thing (the object), not the actual thing itself, whereas the value in the variable for primitive types is the actual thing (the primitive value).

Say you have:

int a = 5;

That's a bit like Joe having a piece of paper (the variable a) with 5 written on it.

Now:

int b = a;

The value in a is copied into b. That's a bit like Mary coming along, getting out a piece of paper, and copying down what's on Joe's piece of paper (the number 5).

Now, say you have:

Map a = new HashMap();

It's a bit like Joe having a piece of paper with his address written on it. The piece of paper is the variable a; the HashMap object is his house.

Now:

Map b = a;

The value in a is copied into b. It's like Mary coming along and getting out a piece of paper and copying Joe's address from his piece of paper onto it. The house hasn't been copied, just the information about where it is.

That's what an object reference is: Information (like a number) telling the JVM where the object is in memory.

I go into it in some detail in this answer (Java), and this one (which is about JavaScript, but the concept of values, variables, and object references is the same in the two languages [and many others]).

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875