2

Possible Duplicate:
Static fields on a null reference in Java

I am new to Java. I know if any object point to and if we try to perform any operation on that object, a Nullpointer exception is thrown by JVM. But in my case there is no Nullpointer exception please help me ?. Below is my code

public class Employee
{

     public static String empName = "John"

     public static void main(String args[])
     {
           Employee emp = new Employee();    
           emp = null;
           System.out.println(emp.empName);
      }   
}

It prints John as output even emp object is pointion to null. But I am expecting a nullpointer exception.

Community
  • 1
  • 1

3 Answers3

5

because field is static.
In your case emp.empName equals to Employee.empName

Ilya
  • 29,135
  • 19
  • 110
  • 158
3

Since you are accessing a static variable, so you will not get NPE if your reference is referencing null. This is because static fields are bound to class rather than any instance.

So, for static variable: -

Employee emp = null;
emp.empName;  // This is evaluated as `Employee.empName;`

So, only the reference type is used. Regardless of whether that reference is pointing to null, or any subclass object.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0

As empName is static the call would be Employee.empName in the byte code, Thus no NPE:

original Code: System.out.println(emp.empName);

Byte code: GETSTATIC java/lang/System.out : Ljava/io/PrintStream; GETSTATIC oops/Employee.empName : Ljava/lang/String;

PermGenError
  • 45,977
  • 8
  • 87
  • 106