Java supports pass by value (always works on a copy) but when you pass a user defined object then it changes the actual object (kind of pass by reference but no pointer changes), which I understand but why the changeObject2CLEAR method below is actually changing the value of the object ? Instead it has to work on the copy?
import java.util.HashMap; import java.util.Map; public class PassBy { class CustomBean { public CustomBean() { } private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return id + ", " + name; } } public Map<Integer, String> changeObject2NULL (Map<Integer, String> m) { m = null; return m; } public Map<Integer, String> changeObject2CLEAR (Map<Integer, String> m) { m.clear(); return m; } public CustomBean changeCustomObject (CustomBean _e) { _e.setId(_e.getId() + 1); return _e; } public static void main(String[] args) { PassBy passby = new PassBy(); Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "value"); CustomBean bean = passby.new CustomBean(); bean.setId(1); bean.setName("arun"); // Initial Value System.out.println(map.toString()); System.out.println(bean.toString()); System.out.println("-------------------------"); // Pass by value works fine passby.changeObject2NULL(map); passby.changeCustomObject(bean); // Custom object value changes since we pass as the object reference but Map remains with actual value System.out.println(map.toString()); System.out.println(bean.toString()); System.out.println("-------------------------"); // Testing Pass by value - CANT UNDERSTAND why it changed the object since it has to be pass-by-value and not by ref in this case ?? // Why setting to null not chainging the value but clear does ? passby.changeObject2CLEAR(map); System.out.println(map.toString()); } }
changeObject2NULL(Map<Integer, String> m)contains its own local variablemwhich happens to be also method parameter. When you use this method likechangeObject2NULL(map)mcopies information about which objectmapholds (this address is value ofmapvariable). So when you callm.clear()it invokesclearmethod on same object whichmapholds so you are able to see new state of that object viamap. When you callm = nullyou simply change which objectmholds tonull; this doesn't affectmapnor object it is referring to.