Strange code in Java Static Initialization Blocks

On going through JLS 8.3.2.3 I was unable to understand the following code.

class Z {
static { i = j + 2; }
static int i, j;
static { j = 4; }
}

      

The code results in an error Cannot reference a field before it is defined

But if I change the code to

class Z {
static { i = 2; }
static int i, j;
static { j = 4; }
}

      

The code is compiled. But in both cases, the variable definition is after the initialization block. What is the secret of this?

+3


source to share


3 answers


You can assign a value before your declaration - you simply cannot read it. So this fails too:

static { System.out.println(j + 2); }
static int j;

      

While this is ok:

static { j = 5; }
static int j;

      



One of four conditions in section 8.3.2.3 for illegal use:

  • Usage is not on the left side of the assignment.

(The double negatives in this section make my head ache, but I think it's important!)

To be honest, this part of the spec is one of the worst I've seen - it's really unclear. But the result is that you can assign, but not read :)

+8


source


Actually its compiler basics,

assignment operators are executed from right to left.

eg, i=2;

this means 2 is assigned to i and 2 is constant so there is no need to declare it



On the other hand, if we write

i=j+2;

      

it will compile j first and then assign it to i, so it throws an error since j is not defined yet.

+1


source


In i = j + 2;

you are using a variable j

that is initialized in another static block.

You have to put everything, in just one static block, the initialization j

and the expression in order to compile the code. This code works:

public class Z {

    static int i, j;
    static { j = 4; 
            i = j + 2; }

}

      

David

0


source







All Articles