jvm - Accessing an uninitialised static field in Java -


i'm indebted this answer idea.

the following code compiles, shouldn't. uses value of x before it's been initialised. if remove staticassign. qualifier 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 machine, consistently prints 0. if change type of x string, consistently prints null.

the question is: print 0 or null, or might access uninitialised memory , print out else?

and if code gets through compiler, why isn't picked jvm?

is there way nasty things based on this?

it has been initialized. variables in global scope initialized automatically. variables of object type initialized null primitive int initialized 0. variable declared not in global scope must initialized ie. declared in method. problem declaring final telling compiler must explicitly initialized. adding x=5 bypassing compiler error saying must explicitly initialized. when access before line @ run-time initialized 0 other primitive int type variable in global scope.


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -