Why not NullPointerException?

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
Mamede
Posts: 2
Joined: Wed May 03, 2017 8:25 pm
Contact:

Why not NullPointerException?

Post by Mamede »

Could somebody explains why "null" string is put in result of following line (why not an exception?) :

public class Test{
   int[] ia = new int[1];
   Object oA[]  = new Object[1];
   boolean bool;
   public static void main(String args[]){
      Test test = new Test();
      System.out.println(test.ia[0] + "  " + test.oA[0]+"  "+test.bool);
   }
}

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Why not NullPointerException?

Post by admin »

In general, "accessing" a null reference always causes a NPE to be thrown. And access basically means the use of dot operator on a reference.

But the + operator is a special case. It does not throw a NullPointerException during string concatenation, because it is overloaded in a way that when one operand is a String and another is null reference, then it appends the string "null" instead of calling toString on the null reference. You can think of it as if the + operator checks whether the reference is null or not and if it is null, it appends "null" and if it is not null then it appends the string returned by calling toString on that reference.

This is given here: https://docs.oracle.com/javase/specs/jl ... jls-5.1.11


HTH,
Paul.

Post Reply

Who is online

Users browsing this forum: No registered users and 21 guests