Final field update in unreachable for loop update section

Tagir Valeev amaembo at gmail.com
Thu Feb 8 02:49:18 UTC 2018


Hello!

Consider two code samples:

public class Sample1 {
  final int x;

  Sample1() {
    for(;;x=1) {
      x=2;
      break;
    }
  }
}

This cannot be compiled via javac 9.0.1:

Sample1.java:6: error: variable x might be assigned in loop
      x=2;
      ^
1 error

The message looks misleading, because if I remove "x=1" assignment,
the compilation goes fine. It's also interesting that if I move x=2
out of the loop, the compilation goes fine as well:

public class Sample2 {
  final int x;

  Sample2() {
    x=2;
    for(;;x=1) {
      break;
    }
  }
}

Though the behavior of the constructor is the same. I feel that
Sample1 should be compilable if Sample2 is compilable. Does
implementation follows spec here or is it a compiler bug?

With best regards,
Tagir Valeev.


More information about the compiler-dev mailing list