Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of static final fields in Java

public class Main {
 static final int alex=getc();
 static final int alex1=Integer.parseInt("10");
 static final int alex2=getc();

public static int getc(){
    return alex1;
}

public static void main(String[] args) {
    final Main m = new Main();
    System.out.println(alex+" "+alex1 +" "+alex2);
  } 
}

Can someone tell me why this prints: 0 10 10? I understand that it's a static final variable and its value shouldn't change but it`s a little difficult to understand how the compiler initializes the fields.

like image 533
Alexx Avatar asked May 13 '11 08:05

Alexx


1 Answers

It's an ordering problem. Static fields are initialized in the order that they are encountered, so when you call getc() to inititalize the alex variable, alex1 hasn't been set yet. You need to put initialization of alex1 first, then you'll get the expected result.

like image 182
stevevls Avatar answered Nov 11 '22 01:11

stevevls