Public class test { public static void main (String[] args) Throws classnotfoundexception { // system.out.println (Class.forName (" Java.lang.String "). getClassLoader ()); // system.out.println (Class.forName (" Java.lang.Object "). getClassLoader ()); // string str1 = new String ("123"); // string str2 = new string ("456"); // system.out.println (Str1.getclass () == str2.getclass ()); System.out.println (test1.x); system.out.println ("------------"); system.out.println (test2.x); }}class test1 { public static final int x = 6 / 3; static { System.out.println ("Test1"); }}cLass test2 { public static final int x = new random (). Nextint (+); static { system.out.println ("Test2"); }}
The results of the implementation are as follows:
2
------------
Test2
50
Why?
Static code blocks are executed when the class is initialized, so first understand the initialization time of the class:
– Create an instance of the class
– Access a static variable for a class or interface, or assign a value to the static variable
– Call the static method of the class
– Reflections (e.g. Class.forName ("Com.shengsiyuan.Test"))
– Initializes a subclass of a class
–java Class (Javatest) that is identified as the startup class when the virtual machine is started
Note 2nd, – Access a static variable for a class or interface, or assign a value to the static variable
Test1 and Test2 Add the final keyword, which is why the class is initialized.
Test1 6/3 knows the value at compile time, so x is a static constant, so Test1 is not initialized. and Test2 X is run to know the result. So Test2 will initialize.
If you get rid of the final keyword, all 2 classes will initialize the class, and everything will print. The 2nd is in line.
Time to execute static code blocks such as Java virtual machines