-2
     Double d1 = null;
     Double d2 = null;
     System.out.println(d1+d2);//throw NullPointerException
     String s1 = null;
     String s2 = null;
     System.out.println(s1+s2);//doesn't throw any exception prints nullnull

Since both Double and String are of type Object then why Double types throw exception??

chirag soni
  • 936
  • 10
  • 20

1 Answers1

2

Just to elaborate on @Seelenvirtuose's comment.

The + operator on two expressions of type Double is interpreted as mathematical addition. So it tries to extract the numerical value from the objects and add them together. Since the variables in this case are holding null instead of objects, you get a NullPointerException.

The + operator on two expressions of type String is interpreted as concatenation. There are rules about how you deal with null in a concatenation: it's transformed into the string "null". So that operation can be performed without an error.

khelwood
  • 55,782
  • 14
  • 81
  • 108