Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing an uninitialised static field in Java

I'm indebted to this answer for the idea.

The following code compiles, but certainly shouldn't. It uses the value of x before it's been initialised. If you remove the StaticAssign. qualifier then it no longer compiles.

public class StaticAssign {

    public static final int x;

    static {
        System.out.println(StaticAssign.x);
        x = 5;
    }

    public static void main(String[] args) {}

}

On my machine, this consistently prints 0. If I change the type of x to String, it consistently prints null.

The question is: will it definitely print 0 or null, or might it access uninitialised memory and print out something else?

And even if this code gets through the compiler, why isn't it picked up by the JVM?

Is there a way to do nasty things based on this?

like image 394
chiastic-security Avatar asked Apr 25 '26 17:04

chiastic-security


1 Answers

It actually has been initialized. Variables in the global scope are initialized automatically. Variables of Object type will be initialized to null primitive like int will be initialized to 0. A variable declared not in the global scope must be initialized ie. declared in a method. Another problem is declaring it as final this is telling the compiler it must be explicitly initialized. So by adding the x=5 you are bypassing the compiler error saying it must be explicitly initialized. When you access it before this line at run-time it is initialized to 0 like any other primitive int type variable in the global scope.

like image 198
brso05 Avatar answered Apr 28 '26 07:04

brso05



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!