Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a static field with a NULL object in Java

Tags:

java

The following simple code snippet is working fine and is accessing a static field with a null object.

final class TestNull
{
    public static int field=100;

    public TestNull temp()
    {
        return(null);
    }
}

public class Main
{
    public static void main(String[] args)
    {
        System.out.println(new TestNull().temp().field);
    }
}

In the above code, the statement System.out.println(new TestNull().temp().field); in which the static field field is being associated with a NULL objectnew TestNull().temp(), still it is returning a correct value of it which is 100 instead of throwing a null pointer exception in Java! Why?

like image 597
Bhavesh Avatar asked Nov 07 '11 20:11

Bhavesh


People also ask

What is a static field in Java?

The use of a static field means that each object does not need to know about the other objects to get a unique id. This could be useful if you wanted to know the order in which the Item objects were created. What Is a Static Constant? Static constants are exactly like static fields except that their values cannot be changed.

Is it possible to access static fields from an object?

Static fields and methods are not belong to a specific object, but to a class, so you should access them from the class, and not from an object: This answered it for me; your answer was short at the same time concise. Amazing! @Binyamin Sharet I know this was an older question but your comment helped me through my project. Thank you!

What is a null object in Java?

In object-oriented programming, we deal very frequently with null objects. A null object refers to an object without any reference or an object defined with neutral/null functionality/behavior. These null objects need to be checked to ensure that they are not null while accessing any member or invoking any methods.

How do you handle null variables in Java?

Generally, null variables, references and collections are tricky to handle in Java code. They are not only hard to identify but also complex to deal with. As a matter of fact, any miss in dealing with null cannot be identified at compile time and results in a NullPointerException at runtime.


2 Answers

As opposed to regular member variables, static variables belong to the class and not to the instances of the class. The reason it works is thus simply because you don't need an instance in order to access a static field.

In fact I'd say it would me more surprising if accessing a static field could ever throw a NullPointerException.

If you're curious, here's the bytecode looks for your program:

// Create TestNull object
3: new             #3; //class TestNull
6: dup
7: invokespecial   #4; //Method TestNull."<init>":()V

// Invoke the temp method
10: invokevirtual   #5; //Method TestNull.temp:()LTestNull;

// Discard the result of the call to temp.
13: pop

// Load the content of the static field.
14: getstatic       #6; //Field TestNull.field:I

This is described in the Java Language Specification, Section 15.11.1: Field Access Using a Primary. They even provide an example:

The following example demonstrates that a null reference may be used to access a class (static) variable without causing an exception:

class Test {
        static String mountain = "Chocorua";
        static Test favorite(){
                System.out.print("Mount ");
                return null;
        }
        public static void main(String[] args) {
                System.out.println(favorite().mountain);
        }
}

It compiles, executes, and prints:

Mount Chocorua

like image 84
aioobe Avatar answered Sep 17 '22 11:09

aioobe


Static variables are shared among every object of a class. So while the actual object reference you are returning is null (In C++: TestNull* temp = null;), you have an object of type TestNull which Java can use to find static values of that class.

Remember in Java objects are really pointers. Pointers have a type. From that type Java can discern certain information, even if its pointing to null.

like image 34
onit Avatar answered Sep 19 '22 11:09

onit