Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is this not throwing a NullPointerException?
    primarykey
    data
    text
    <p>Nead clarification for following code:</p> <pre><code>StringBuilder sample = new StringBuilder(); StringBuilder referToSample = sample; referToSample.append("B"); System.out.println(sample); </code></pre> <p>This will print <code>B</code> so that proves <code>sample</code> and <code>referToSample</code> objects refer to the same memory reference.</p> <pre><code>StringBuilder sample = new StringBuilder(); StringBuilder referToSample = sample; sample.append("A"); referToSample.append("B"); System.out.println(referToSample); </code></pre> <p>This will print <code>AB</code> that also proves the same.</p> <pre><code>StringBuilder sample = new StringBuilder(); StringBuilder referToSample = sample; referToSample = null; referToSample.append("A"); System.out.println(sample); </code></pre> <p>Obviously this will throw <code>NullPointerException</code> because I am trying to call <code>append</code> on a null reference.</p> <pre><code>StringBuilder sample = new StringBuilder(); StringBuilder referToSample = sample; referToSample = null; sample.append("A"); System.out.println(sample); </code></pre> <p>So Here is my question, why is the last code sample not throwing <code>NullPointerException</code> 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 <code>null</code> to referToSample then sample should also be null and it should throw a NullPointerException but it is not throwing one, why?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload