Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the Switch Statement in Java could contain a FINAL Variable as the CASE?

Why the Switch Statement in Java could contain a FINAL Variable as the CASE? ##

In JDK7 as checked by me a value cannot be reassigned to final variable, as shown below. But, Why the final variable "x" can be included in a Switch Statement for a case eventhough value for final variable "x" cannot be reassigned?

Why this can be done eventhough Oracle defines that the Java Compiler takes final variable as the value initialized but not the variable name?http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.4

Please tell me if this is a Technical Error of the Java Compiler or are there Exceptions or Special Use of checking the Case of a Final Variable in a Switch Statement?

class Example{
    public static void main(String args[]){
        final int x=100;
        //x=200;    //error: cannot assign a value to final variable x

        //The below piece of code compiles
        switch(x){
            case 200: System.out.println("200");
            case 300: System.out.println("300");
        }

    }
}
like image 484
DJ Tishan Avatar asked Feb 24 '13 15:02

DJ Tishan


1 Answers

What about this situation?

public class Foo
{
    private final int x;

    public Foo(int x){this.x = x;}

    public void boo()
    {
        switch(x)
        {
            case 200: System.out.println("200");
            case 300: System.out.println("300");
        }
    }
}

or maybe this one:

public static void doSomething(final int x)
{
    switch(x)
    {
        case 200: System.out.println("200");
        case 300: System.out.println("300");
    }
}
like image 198
Eng.Fouad Avatar answered Sep 19 '22 02:09

Eng.Fouad