Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A final constant not accepted in switch case

I would like to know the difference between the 2 declarations inside a method add() as in below.

final int c;
c = 20;

and

final int c = 20;

I think that both are final variables for which, I cannot reassign any new values. Here is the method that is treating the above declarations differently.

void add() {
        final int a = 30;
        final int b = 10;
        final int c;
        c = 20;

        switch (a) {
        case b + c:
            System.out.println("In case b+c");
            break;

        default:
            break;
        }

    }

The above method doesn't compile at all, complaining that

constant expression required case b+c

If the variable c is declared and initialized in one line, like final int c = 30;. It works.

like image 747
srk Avatar asked Dec 29 '25 23:12

srk


2 Answers

The JLS #4.12.4 defines constant variables as (emphasis mine):

A variable of primitive type or type String, that is final and initialized with a compile-time constant expression, is called a constant variable.

In your case, final int c = 20; is a constant variable but final int c; c = 20; is not.

like image 79
assylias Avatar answered Jan 01 '26 12:01

assylias


Java compiler replaces a final identifier with its value if it is declared & initialized in a single(same) statement, otherwise identifier is kept as it is and initialized by jvm at run time for blank final variable. You can see this by opening class file. switch statement permits final, but not a blank, variable to be used as a case value.

final int a = 20; // concrete final variable
switch(a){}
#=> gets changed by compiler as the following:--
switch(20){}

final int a; // blank final variable
a = 20;
switch(a){}
#=> compiler leave it for jvm to initialize 
switch(a){}
like image 37
Alok Anand Avatar answered Jan 01 '26 13:01

Alok Anand