First of all, the "pass by reference" statement is for parameter passing. There is no passing of anything with assignments.

To answer your question. This statement....

Assigns refa to point to the same object that is pointed to by refb. The refa and refb variables are two different variables that now happens to have the same value. Changing one of those variables later to point to something else doesn't magically change the other variable.

Of course, you have autoboxing mixed into your example, which may be adding to the confusion.

[EDIT: Missed the previous answer -- I guess I should have reloaded the page first.]

In Java there is no such thing as pass by reference. Everything is passed by value.

For objects, the assignment operator assigns the memory location of the object to the variable. When you assign refb to refa, they will both point to the same object (the Integer 24).
Now, when you assign 65 to refb, refb will point to this new Integer object. But this doesn't change the value stored in refa, which is still the memory location of the Integer 24.

The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.

Stephan van Hulst wrote:In Java there is no such thing as pass by reference. Everything is passed by value.

For objects, the assignment operator assigns the memory location of the object to the variable. When you assign refb to refa, they will both point to the same object (the Integer 24).
Now, when you assign 65 to refb, refb will point to this new Integer object. But this doesn't change the value stored in refa, which is still the memory location of the Integer 24.

Thanks for pointing that out.. All the folks here gave out an excellent explanation.
Looks like i was simply unaware of the mere fact that when I write

refb = 65 (changing from the original value) The compiler doesnt write it on its original address and instead goes like
refb = new Integer(65); //thus having a new address altogether

Courtesy : Piyush Joshi
and the previous allocated unreferenced memory block of refb (24) will hopefully be cleared by the GC (Garbage collector)

When you assign a primitive literal to an Integer variable, it's closer to Integer.valueOf(65) than new Integer(65);

The valueOf method will cache certain values, so the garbage collector does not clean them up. Anyway, this isn't something you should have to concern yourself about. It's just a bit of an optimization by Java.

When you assign a primitive literal to an Integer variable, it's closer to Integer.valueOf(65) than new Integer(65);

The valueOf method will cache certain values, so the garbage collector does not clean them up. Anyway, this isn't something you should have to concern yourself about. It's just a bit of an optimization by Java.