• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

flow controls

 
Hasitha Randika
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A{
final static int x2 = 7;
final static Integer x4 = 8;
public static void main(String ar[])throws Exception{
Integer x1 = 5;
String s ="a";
if(x1 < 9)
s += "b";
switch(x1){ //can we use a variable which is not assign as final
case 5: s += "c";
case x2: s += "d";
case x4: s += "e"; //error why?
}
System.out.println(s);
}
}
in the above syntax case4:s+="e" gives a compile error.how come?

and here in the switch condition it uses a variable.can we use a variable which is not assign as final
 
Vassili Vladimir
Ranch Hand
Posts: 1585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

The reference itself is final, but not its state. Meaning, x4 can not refer to another object in the heap, but this does not mean that its value can not change.

Best of luck ...
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15369
40
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The values you use in case statements in a switch block must be compile-time constants.

In the code above, x4 is not a compile-time constant. As Vassili says, the value of x4 itself is constant (it's always referring to the same object), but in principle the value of the object could change.

(Actually, the value of an Integer object never changes, because wrapper classes like Integer are immutable. But the Java compiler doesn't know that, so it's still illegal).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic