tags:

views:

92

answers:

4

Consider this code:

public class Main {


 static String s = "-";

 public static void main (String [] args){

     go();
     System.out.println(s);

     Main m = new Main();
 }
 {go();}

 static {go();}
 static void go(){s+="s";}
}

Its output is:

-ss

the instance init block is never called, why?

+3  A: 

It is called - AFTER you've printed s. Instance initializers are called when instances are created.

ChssPly76
If you're all just going to say the same thing, up-vote the person that said it first and then just add a comment.Add another "System.out.println(s);" to the very end of your "main" block and you'll see "-sss" as the output.
Brent Nash
+1  A: 

It is called. However it is called after the call to println because you create the first instance of Main of that. If you move the call to println to the end of main, you'll see three s.

sepp2k
A: 

It is called, but after you print to the console. You aren't making an instance of it until after printing.

ColinD
A: 

As the others have pointed out, the instance init block is called, but it doesnt affect the output of your System.out.println statement, because it is called in conjunction with the invocation of the instance of your class: Main m = new Main();

One thing you could do when trying to debug these cases is to dump a thread stack at the invocation point:

static void go() {
    new Exception().printStackTrace(System.out);
        s += "s";
}

This will allow you to see all the times that the go method is called, and by using the same print stream as your println in your main method, you can see the stacks in relation to the output of your s var.

In my version, the result looks like this:

java.lang.Exception
    at Main.go(Main.java:29)
    at Main.<clinit>(Main.java:25)
java.lang.Exception
    at Main.go(Main.java:29)
    at Main.main(Main.java:14)
-ss
java.lang.Exception
    at Main.go(Main.java:29)
    at Main.<init>(Main.java:21)
    at Main.main(Main.java:17)
akf