• Post Reply Bookmark Topic Watch Topic
  • New Topic

switch statement  RSS feed

 
radhika ayirala
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which line(s) should be removed for this code to compile?
static public void main(String...arg)
{
Byte snake = 5;
final int b;
b=2;
Integer i=5;
switch(snake){
case 128:System.out.println("Shouldn't it freeze in December ?");//1
default:System.out.println("White Christmas?");//2
case b:System.out.println("An Inconvenient truth...");//3
case i:break;//4
}
}

why line4 is wrong.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the expression in the cases in a switch statement must be a compile-time constant, and i is not a compile-time constant.
 
radhika ayirala
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can we apply autoboxing concept here.If we apply that,we can change Integer to int.Then line4 would be valied.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, because i would still not be a compile time constant. You need to make i final, the same as b.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, because it's still not a constant.

Variables that can be used in switch statements need to be final. They also have to be given a variable on the same line as it is declared. That is why b cannot be used. Should it be "final int b = 2" then it could be used.

Well, except that snake is a Byte and therefore only byte constants can be used in this case
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!