Comparing null Character with character throws exception

  • A+
Category:Languages

Why does the following throw a NPE?

Character c = null; if(c == ' ') {      System.out.println("Is space");   }   

Is this some syntactical sugar for c.equals(' ')?


Not exactly. The operation c == ' ' is equivalent to c.charValue() == ' ', so when charValue() is invoked on null, a NullPointerException is thrown.

This is an "unboxing" operation on c, rather than a "boxing" of ' ' followed by an equals() test.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: