• Post Reply Bookmark Topic Watch Topic
  • New Topic

weird java code  RSS feed

 
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) Why does this code compile ?
2) Why does it give NPE on line 3 ?

 
Ranch Hand
Posts: 614
9
BSD Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code will not compile

1. Starting curly brace is missing in methodOfA() method.
2. You are trying to call a non static method from a static method.
 
Ranch Hand
Posts: 57
3
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even if you did get it to compile by fixing the errors Tapas pointed out, methodOfA will ALWAYS return null, because you're basically evaluating this:


It will always return null, because true always evaluates - which will trigger the NullPointerException when the code executes.
 
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tim Harris wrote: methodOfA will ALWAYS return null

No, this method will always throw NullPointerException because it tries to unbox null value.
 
Lucian Whiteman
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tapas Chand wrote:This code will not compile

1. Starting curly brace is missing in methodOfA() method.
2. You are trying to call a non static method from a static method.



So I misses one curly bracket. No big deal:



At runtime it gives NPE. Why ?
 
Tim Harris
Ranch Hand
Posts: 57
3
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paweł Baczyński wrote:
Tim Harris wrote: methodOfA will ALWAYS return null

No, this method will always throw NullPointerException because it tries to unbox null value.


Whoops, you are indeed correct.

If you were to try my example code in Eclipse, it would tell you that it cannot convert a null to int - in the given example, it's being boxed inside the expression, so it sneaks past the compiler.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!