my code is:-
class Test
{
static int a = 11;
static
{
System.out.println("Hello static! " + main() + a);
}
public static void main(String[]args)
{
System.out.println("Hello String!");
}
public static char main()
{
System.out.println("Hello char!");
return 'H';
}
}
Output:-
Hello char!
Hello static! H11
Hello String!
Why “Hello char!” is printed before “hello static!”?
Because,
main()method is invoked and executed before the completion of thesysoutstatement printingHello static.Here’s the execution order: –
staticvariableais loaded and initialized to11.staticblock is executed.sysoutstatement there,main()static method is invoked. At this point of timeHello statichas not been printed yet, because thesysoutstatement is not complete.main()method. Because without that the current sysout statement cannot complete.main()method prints"Hello char", and returns'H'.staticblock, insidesysout.sysoutcompletes execution, and prints"Hello static! H11"Note: –
sysoutabove means –System.out.println().