Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java classes and static blocks

Tags:

java

static

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?

like image 407
Shashank Agarwal Avatar asked Jul 22 '14 18:07

Shashank Agarwal


People also ask

Can we have static block in a class in Java?

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.

What is the use of static block in Java?

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.

Can class have 2 static blocks?

Yes. It is possible to define multiple static blocks in a java class.

How many static blocks can be present in a class?

A class definition should have only one static block {} .


2 Answers

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.

like image 136
rgettman Avatar answered Oct 13 '22 13:10

rgettman


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.

like image 43
betteroutthanin Avatar answered Oct 13 '22 14:10

betteroutthanin