Nead clarification for following code:
StringBuilder sample = new StringBuilder();
StringBuilder referToSample = sample;
referToSample.append(\"B\");
System.
In a nutshell: You assign null to a reference variable, not to an object.
In one example you change the state of an object that is referred to by two reference variables. When this occurs, both reference variables will reflect the change.
In another example, you change the reference assigned to one variable, but this has no effect on the object itself, and so the second variable, which still refers to the original object, will not notice any change in object state.
So as to your specific "rules":
if two objects referring to same object then if we change any value then it will also reflect to other because both are pointing to same memory reference.
Again, you refer to changing the state of the one object that both variables refer to.
So why is that rule not applying here? If I assign null to referToSample then sample should also be null and it should throw nullPointerException but it is not throwing, why?
Again, you change the reference of one variable which has absolutely no effect on the reference of the other variable.
These are two completely different actions and will result in two completely different results.