Nead clarification for following code:
StringBuilder sample = new StringBuilder();
StringBuilder referToSample = sample;
referToSample.append("B");
System.out.println(sample);
This will print B
so that proves sample
and referToSample
objects refer to the same memory reference.
StringBuilder sample = new StringBuilder();
StringBuilder referToSample = sample;
sample.append("A");
referToSample.append("B");
System.out.println(referToSample);
This will print AB
that also proves the same.
StringBuilder sample = new StringBuilder();
StringBuilder referToSample = sample;
referToSample = null;
referToSample.append("A");
System.out.println(sample);
Obviously this will throw NullPointerException
because I am trying to call append
on a null reference.
StringBuilder sample = new StringBuilder();
StringBuilder referToSample = sample;
referToSample = null;
sample.append("A");
System.out.println(sample);
So Here is my question, why is the last code sample not throwing NullPointerException
because what I see and understand from first two examples is 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. So why is that rule not applying here? If I assign null
to referToSample then sample should also be null and it should throw a NullPointerException but it is not throwing one, why?