I was trying something, and I came across this interesting scenario. I just wanted to understand what is the major difference in these two snippets.
Initially, I took two sets, initialized one and assigned the reference to other. When I cleared set A, I noticed that Set B size changed to zero as well
Set<String> A = new HashSet<String>(); A.add("hello"); A.add("HEY"); A.add("hey"); Set<String > B = A; System.out.println("initial sizes :" + A.size() + " " + B.size()); A.clear(); System.out.println("final sizes :" + A.size() + " " + B.size()); The output of this was something like this :
initial sizes :3 3 final sizes :0 0 Now, I tried to depict the same behavior for objects as follows:
Object a1 = new Object(); Object b1 = a1; System.out.println("initial sizes :" + b1.toString() + " " + a1.toString()); a1 = null; System.out.println("initial sizes :" + b1.toString() + " " + a1); The output for this was something like :
initial sizes :java.lang.Object@54182d86 java.lang.Object@54182d86 initial sizes :java.lang.Object@54182d86 null What is the exact difference here, I was expecting to get a NullPointerException when i tried to print b1.toString()

Objectin the code snippet - Have a look at thisA.clear()modifies the internal state of the object referred to by the referenceA.a1 = nullmodifies the reference stored ina1, not the object it refers to.