Reputation: 5136
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.
Upvotes: 3
Views: 1142
Reputation: 21
As you are initializing and declaring it separately you are getting that error, do it at the same time and it work
Upvotes: 0
Reputation: 626
final variables can't be re-evaluated again runtime, If you want to use switch case you can't do like (b+c) in case clause, instead of this do use this one,
void add() {
final int a = 30;
final int b = 10;
final int c;
c = 20;
final int cmp=b+c;
switch (a) {
case cmp:
System.out.println("In case b+c");
break;
default:
break;
}
}
Now this will work fine for you,
Upvotes: -1
Reputation: 3356
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){}
Upvotes: 2
Reputation: 328785
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.
Upvotes: 10