How to use static block and constructor in Java

1 Answer

0 votes
// When the class is loaded, the static block gets executed once
 
class StaticAndConstructor {
    static int a;

    public StaticAndConstructor() {
        System.out.println("CONSTRUCTOR");
    }
 
    // static block
    static {
        System.out.println("static block");
        a = 111;
    }

    public void show() {
        System.out.println(a);
    }
}

public class Program {
    public static void main(String[] args) {
        StaticAndConstructor sac1 = new StaticAndConstructor();
        StaticAndConstructor sac2 = new StaticAndConstructor();
        StaticAndConstructor sac3 = new StaticAndConstructor();

        sac1.show();
        sac2.show();
        sac3.show();
    }
}
 
 
 
 
/*
run:
 
static block
CONSTRUCTOR
CONSTRUCTOR
CONSTRUCTOR
111
111
111
 
*/

 



answered Feb 3, 2024 by avibootz

Related questions

1 answer 206 views
1 answer 140 views
1 answer 134 views
1 answer 220 views
1 answer 202 views
...