When you call changeObject2CLEAR
passby.changeObject2CLEAR(map);
you are passing a map instance.
in changeObject2CLEAR method
public Map<Integer, String> changeObject2CLEAR (Map<Integer, String> m) { m.clear(); return m; }
you execute .clear() on the same map instance, although in the method it is called m .
As an exercise in understanding, notice that the next method will do the same.
public void changeObject2CLEAR (Map<Integer, String> m) { m.clear(); }
Note that you do not need to return Map<Integer, String> m , since the map that you have access to is the same instance of the object that is passed wherever the method is called.
EDIT: why m = null; behaves like pass-by-value, but m.clear() behave like passing by reference?
When you assign a null value to m , you change the link from the previous instance of the map object to a new null memory location.
When you call the .clear() method of an .clear() object m , you call the method on the same object that is in the memory location referenced by map , therefore, you modify the map object.
source share