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)