I have a socket which is currently connected.
Socket s; //Connected socket
If I use:
Socket d = s;
Will socket d be the same, connected socket? It depends if java is assigning by value or reference, in this case I would like it to assign by reference. I’m not sure what it’s going to do exactly so I’m asking here.
Yes
Java is entirely pass-by/assign-by value. The value being assigned here is a reference to the object. Think of it as an
intthat tells us what slot in memory the object is in.Continuing the
intanalogy:What’s
b‘s value?5, of course, the later assignment of6toahas nothing to do with the value stored inb.And so similarly:
What’s the value of
s? Right! It’s the reference to the connected socket object. The value ins(a reference to the socket) is completely unaffected by your assigning a different value tod.Now, of course, when
dandsare pointing (referring) to the same object, naturally any time that object changes, you can see the change viadors. All thatdandsdo is tell us where the object is, they don’t contain the object at all. They point to the memory that contains the object.Once you grasp that object references are primitives just like
ints and have exactly the same behavior, understanding Java code gets a lot easier.