1

As per Wikipedia, the blank final variable is a final variable whose declaration lacks an initializer at the time of definition.

At the same time, the values for switch case statement must be compile-time constant values.

As per above two affirmations, I would expect both of the below code snippets to compile with no problems, however only the first one does:

    final int y = 1;

    switch(1) {
        case y:
    }

and

    final int y;
    y = 1;
    switch(1) {
        case y:
    }

Should have not Java compiler run a flow analysis in second example to ensure that blank final variable is assigned and hence compile the code with no errors?

P.An
  • 355
  • 1
  • 9
  • check this answer https://stackoverflow.com/questions/3827393/java-switch-statement-constant-expression-required-but-it-is-constant#3827424 actually, seems like duplicate of that question – Evgeny Veretennikov Mar 06 '17 at 14:24

2 Answers2

0

The switch case requires a constant expression. In the first example, the compiler replaces the initialization with a constant that is then used in place of all the y variables. The compiler cannot do this in the second case.

BamaPookie
  • 2,560
  • 1
  • 16
  • 21
0

So, you've got error message constant expression required. From JLS 15.28: http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.28 constant expression may be simple name that refer to a constant variable. Again, from JLS http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.12.4 :

A blank final is a final variable whose declaration lacks an initializer.

A constant variable is a final variable of primitive type or type String that is initialized with a constant expression (§15.28). Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9), and definite assignment (§16 (Definite Assignment)).

So, in the first case y is a constant variable, and in the second case it's a blank variable. That's why you can't use it in case.

Evgeny Veretennikov
  • 3,889
  • 2
  • 16
  • 36