Question

I am getting confused with below code I expected that it will give an error or answer will be 10 but it is giving 20 how?

public class test {
    public static void main(String[] args) {
        System.out.println(x);
    }

    static{
        x=10;
    }

    static int x=20;
}
Was it helpful?

Solution

It's specified in section 12.4.2 of the JLS, which gives details of class initialization:

Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.

The variable initializer (x = 20) occurs after the static initializer (the block containing x = 10) in the program text. The value at the end of initialization is therefore 20.

If you swap the order round so that the variable initializer comes first, you'll see 10 instead.

I'd strongly advise you to avoid writing code which relies on textual ordering if possible though.

EDIT: The variable can still be used in the static initializer because it's in scope - just like you can use an instance variable in a method declared earlier than the variable. However, section 8.3.2.3 gives some restrictions on this:

The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:

  • The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.

  • The usage is not on the left hand side of an assignment.

  • The usage is via a simple name.

  • C is the innermost class or interface enclosing the usage.

It is a compile-time error if any of the four requirements above are not met.

So if you change your static initializer to:

static {
    System.out.println(x);
}

then you'll get an error.

Your existing static initializer uses x in a way which does comply with all of the restrictions, however.

OTHER TIPS

in static if a value is changed once then it will be effected through out. So you are getting 20.

if you write this way

public class test {
      static int x=20;

 public static void main(String[] args) {
 System.out.println(x);
            }
static{
x=10;
 }
  }

then it will print 10.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top