-10

A programming like this,

static {
  a = 6;
}

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

Raedwald
  • 46,613
  • 43
  • 151
  • 237
meng hang
  • 7
  • 3

3 Answers3

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.
Erik Pragt
  • 13,513
  • 11
  • 58
  • 64
1

Every variable needs a type in Java.

Rápli András
  • 3,869
  • 1
  • 35
  • 55
0

I think somewhere you initialized the variable a

 private static int a;
static {
  a = 6;
  }
Mohsin Shaikh
  • 494
  • 1
  • 4
  • 11