Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behavior - Does java perform compile time optimization here?

Tags:

java

static

Please see this piece of code:

class Ideone
{
    static int value = 3;

    Ideone getIdeone()
    {
        System.out.println("getIdeone() called");
        return null;
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        Ideone ideone = new Ideone();
        System.out.println(ideone.getIdeone().value);
    }
}

Output:

getIdeone() called

3

Ideone link here

As you must have observed, I am making call to getIdeone() which returns null and then fetching value from the null object.

What is going on here? Does compiler perform some compile-time optimization and fetches value directly from the class, reason being it is static?

like image 201
Green goblin Avatar asked Aug 27 '26 07:08

Green goblin


1 Answers

Because value is a static field, you don't need an instance to access it, so null will suffice. It is indeed taken directly from the class.

The compiler warns you about this already:

The static field Ideone.value should be accessed in a static way


As a bonus exercise, look what happens when subclasses are involved. The code at the bottom will give this output:

getIdeone() in Test called

3

(so not 5), even though (at runtime) the getIdeone() is expected to return a Test. This is because the compiler already turned this into a call to the static field of Ideone - it doesn't matter what happens at runtime.

public class Ideone {
    static final int value = 3;

    Ideone getIdeone() {
        System.out.println("getIdeone() called");
        return null;
    }

    public static void main(String[] args) throws java.lang.Exception {
        Ideone ideone = new Ideone().new Test();
        System.out.println(ideone.getIdeone().value);
    }

    class Test extends Ideone {
        static final int value = 5;

        @Override
        Test getIdeone() {
            System.out.println("getIdeone() in Test called");
            return null;
        }
    }
}
like image 100
Glorfindel Avatar answered Aug 28 '26 23:08

Glorfindel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!