+ 2

I need an explanation for code below

How is code compiled in this way,and why.Can someone explain it pls how is the output :s1s2main public class Program { static{ System.out.println ("s1"); } public static void main(String[] args) { System.out.println ("main"); } static{ System.out.println ("s2"); } }

28th Jan 2022, 8:10 AM
Samir Krasnic
Samir Krasnic - avatar
2 Respuestas
+ 2
Samir Krasnic static { } This is known as static block which execute before the main method. So s1s2main
28th Jan 2022, 8:45 AM
A͢J
A͢J - avatar
+ 2
static {} blocks are part of class and they executed by class initialisation - before main() in order how they are present in source code. it is useful for fields initiaize. block can be also non-static and then it is executed by object creation
28th Jan 2022, 8:49 AM
zemiak