Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this code DOES NOT return a NullPointerException?

public class Main
{
   public static void main(String []ar)
   {
      A m = new A();
      System.out.println(m.getNull().getValue());
   }
}

class A
{
   A getNull()
   {
      return null;
   }

   static int getValue()
   {
      return 1;
   }
}

I came across this question in an SCJP book. The code prints out 1 instead of an NPE as would be expected. Could somebody please explain the reason for the same?

like image 567
Vrushank Avatar asked Apr 10 '12 11:04

Vrushank


1 Answers

Basically you're calling a static method as if it were an instance method. That just gets resolved to a static method call, so it's as if you'd written:

A m = new A();
m.getNull();
System.out.println(A.getValue());

IMO the fact that your code is legal at all is a design flaw in Java. It allows you to write very misleading code, with Thread.sleep as an example I always use:

Thread thread = new Thread(someRunnable);
thread.start();
thread.sleep(1000);

Which thread does that send to sleep? The current one, "of course"...

like image 57
Jon Skeet Avatar answered Oct 10 '22 23:10

Jon Skeet