• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

switch statement

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 22855
132
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic