-10

A programming like this,

static {
  a = 6;
}

Why the element "a" does not need a type?

3
  • 9
    'a' does need a type. The type of a must be declared above the static block or else it will fail to compile. Commented Aug 4, 2013 at 8:28
  • 1
    This itself won't compile. Commented Aug 4, 2013 at 8:28
  • This is the best reference I found on this topic. Commented Aug 4, 2013 at 8:37

3 Answers 3

10

This is not a declaration of a variable, this is the assignment of a variable. The type of 'a' is defined somewhere else. So, this code itself won't compile, you'll need a variable declaration like:

class X {
     private static int a;

     static {
         a = 6;
     }
}

As an answer to the comment below, this is the initializion sequence:

  1. Static statements/static blocks are executed.
  2. Instance variables are assigned default values
  3. Instance variables are initialized if the instance variable is assigned a compile time constant. Otherwise, it will be done with Item 5 (instance variables and instance initializers will be done together from the top to the bottom, in the order they are defined).
  4. constructor runs
  5. Instance initialization block(s) run after all the call(s) to super has(have) been completed but before the rest of the constructor is executed.
  6. Rest of the constructor is executed.
Sign up to request clarification or add additional context in comments.

3 Comments

Does that static run before constructor?
Checkout Chapter 12.4 for an answer for that: docs.oracle.com/javase/specs/jls/se7/html/jls-12.html
I've updated my example with a more extended answer source
1

Every variable needs a type in Java.

Comments

0

I think somewhere you initialized the variable a

 private static int a;
static {
  a = 6;
  }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.