3

The code 1:

       public class StaticBlockExample1
      {
        static {  value = 20;  }

        static int value = 10;
        public static void main(String[] args) {

              System.out.println(" Value = " + value);
        }
    }

output of StaticBlockExample1 is 10

The code 2:

  public class StaticBlockExample2 
      {
        static int value = 10;
        static {    value = 20;     }   

        public static void main(String[] args)
           {
            System.out.println(" Value = " + value);
           }
      }

output of StaticBlockExample2 is 20.

Am confused with outputs of the above examples. is there any significance to declare static variable before or after static block?

3 Answers 3

14

Yes, the static block and the static field initializations are executed in the order in which they are found in the input file.

Sign up to request clarification or add additional context in comments.

Comments

1

The most important is order of your inicializations. - 1st case - 10 is defined as second

static int value = 10;

and in 2nd case , block is second

  static {
            value = 20;
        }  

Comments

1

order of initialization is different

first: you define static block before variable declaration

second: you define static block after variable declaration

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.