class Hello12 { static int b = 10; static { b = 100; } } class sample { public static void main(String args[]) { System.out.println(Hello12.b); } }
On running above code the output comes as 100 because when I called Hello class, static block is executed first setting the value of b to 100 and displaying it. But when i write this code:
class Hello12 { static { b = 100; } static int b = 10; } class sample { public static void main(String args[]) { System.out.println(Hello12.b); } }
Here the output comes as 10. I am expecting answer as 100 because once the static block is executed it gave b the value as 100. so when in main(), I called Hello.b it should have referred to b (=100). How is the memory allocated to b in both the codes?
Unlike C++, Java supports a special block, called a static block (also called static clause) that can be used for static initialization of a class.
Java Programming for Complete Stranger static keyword can be used to create a block to be used to initialize static variables. This static block executes when classloader loads the class. A static block is invoked before main() method. You can verify the same using.
Yes. It is possible to define multiple static blocks in a java class.
A class definition should have only one static block {} .
In the "Detailed Initialization Procedure" for classes, Section 12.4.2 of the JLS states:
Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
This means that it's as if the first example was:
b = 10; b = 100;
And the second example was:
b = 100; b = 10;
The last assignment "wins", explaining your output.
Static blocks and static variables are initialized in the order in which they appear in the source. If your code is:
class Hello12 { static int b = 10; static { b = 100; } }
The result is 100.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With