7 ms·
Java passes objects by value, not by reference. Try implementing swap(Object a, Object b) in Java, and you will see it is by Val not by ref
by andy0x2a 8y ago
Java passes objects by value, not by reference.
Try implementing swap(Object a, Object b) in Java, and you will see it is by Val not by ref
- scott_s 8y agoJava passes references to objects by value. That is, in Java, a variable for a heap-allocated object is a reference to that object. When you pass that variable to a method, the method gets a copy of that reference. So if the method makes changes to the object itself, that is visible outside of the method, but if it makes changes to its own copy of the reference (say, makes it point to a different object), that's not visible outside of the method. I still consider this behavior "passing by reference" since it passes around references/pointers to objects, and does not incur an object copy.
- foldr 8y agoExpanding on the sibling, Java is a pass by value language which is commonly mistakenly thought to be pass by reference. (That's probably the mistake you think I'm making.) It is not, however, possible to pass objects by value in Java.