How to use static block to initialize default static variables in Java

1 Answer

0 votes
// When the class is loaded, the static block gets executed
 
public class Program {
    static int a;
    static int b;
    static int c;
 
    //static block1 
    static {
        System.out.println("static block 1");
        a = 111;
    }
     
    //static block2
    static {
        System.out.println("static block 2");
        b = 222;
    }
     
    //static block3 
    static {
        System.out.println("static block 3");
        c = 333;
    }
    
    public static void main(String[] s) {
        System.out.println(a + " " + b + " " + c);
    }
}
 
 
 
/*
run:
 
static block 1
static block 2
static block 3
111 222 333
 
*/

 



answered Feb 3, 2024 by avibootz

Related questions

1 answer 128 views
1 answer 207 views
1 answer 204 views
1 answer 201 views
1 answer 208 views
1 answer 178 views
178 views asked Feb 23, 2016 by avibootz
1 answer 189 views
...