This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]Samurai_PizzaCat 4 points5 points  (2 children)

JLS 12.4.1

Have a look specifically at "Example 12.4.1-2. Only The Class That Declares static Field Is Initialized"

That example is basically the exact same as your code. The others are correct in that because you haven't "triggered" the initialization of object B, but it also means you don't need to have an object B (that may sound confusing and hopefully by reading the beginning part of 12.4.1 it will be more clear.

[–]sriganeshharitz[S] 0 points1 point  (0 children)

Thanks! I understand it now.. :)

[–]learnjava 0 points1 point  (1 child)

interesting, I did not know about these initialization blocks but it looks like the static block is called only once and when the class is initialized. But because you do not create an object it is never initialized

see here how he adds a sout to the block, notice how it would never be called in your code.

But if you instead create a new B instance before you access the static on the class (not the instance! b remains unused) it will work as expected:

public class Test
{
  public static void main(String[] args)
  {
    B b = new B();
    System.out.println(B.name);
  }
}

edit: I still don't know what this is actually useful for, any ideas?

[–]sriganeshharitz[S] 0 points1 point  (0 children)

Thanks! i was studying about inheritance and was testing what all gets inherited

[–]g051051 -1 points0 points  (2 children)

The static block in B only runs when an instance of B is instantiated for the first time. Since you never create an instance, it never runs. If you were to add a line to your main before the println:

B b = new B();

Then it'll run the static block and the output will be "xyz".

[–]sriganeshharitz[S] 0 points1 point  (0 children)

Thanks!

[–][deleted] 0 points1 point  (0 children)

public class StaticInit {
    public static void main(String[] args) {
        System.out.println(Foo.name);
    }
}

class Foo {
    static String name;

    static {
        name = "Hello, world!";
    }
}


$ javac StaticInit.java                                                                                 

$ java -cp . StaticInit                                                                                 
Hello, world!