Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On static and non-static initializing blocks in Java

Tags:

java

I originally thought that static blocks were for static variables but the compiler allows both A and B to compile and run, what gives?
A

   private static final Map<String,String> m = new HashMap<String,String>();

        {
            m.put("why", "does");
            m.put("this","work");
        }

B

 private static final Map<String,String> m = new HashMap<String,String>();

        static{
               m.put("why", "does");
               m.put("this","work");
             }

Running System.out.println(Main.m.toString()); for A prints

{}

but running the same for B prints out in Yoda-speak

{this=work, why=does}

like image 381
non sequitor Avatar asked Oct 15 '09 20:10

non sequitor


2 Answers

The non static block is executed when an "instance" of the class is created.

Thus

System.out.println(Main.m.toString());

prints nothing because you haven't created an instance.

Try creating an instance first

 Main main = new Main();

and you'll see the same message as B

As you know class variables (declared using static) are in scope when using instance blocks.

See also:

Anonymous Code Blocks In Java

like image 62
OscarRyz Avatar answered Oct 24 '22 12:10

OscarRyz


In A, you have an instance initializer. It will be executed each time you construct a new instance of A.

If multiple threads are constructing A instances, this code would break. And even in a single thread, you normally don't want a single instance to modify state that is shared by every instance. But if you did, this is one way to achieve it.

like image 22
erickson Avatar answered Oct 24 '22 12:10

erickson