• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What can go in a case-switch statement

 
Wilson Mui
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I read that only constants, can go in a switch statement, and therefore static class variables can't. But does that mean ints that are in a interface can, since by default variables in an interface are final static variables, even if they are not declared so.
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this
class Test
{
static int a=1;
public static void main(String args[])
{
switch(a)
{
case 0:
System.out.println("No Match");
break;
case 1:
System.out.println("Match Found");
break;
}
}
}
I read that only constants, can go in a switch statement, and therefore static class variables can't.
Classes can not be static.
[ April 23, 2003: Message edited by: Anupam Sinha ]
 
Wilson Mui
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess I worded it poorly...let me try again.
I think this is how everything works, and I would like somebody to correct me if I am wrong.
In the switch(X) statement
"X" can by anything that will fit into an int. such as char, byte, short, or int.
for the Case part, I read that it has to be either a int literal or something that can fit into an int (literal)...so if X was a char for instance, you can have
case ('a'): and that might actually run, same with byte, and short. But also besides literals I heard you can also have a variable in the case statement, but only if that variable is a final variable...that leads me to my second derivative. If that is the case, and member variables of an interface are by default static ints...then does that mean all member variables of an interface can be used in the case statement. I did a little test and it appears that way. But I am just looking to confirm.
 
Wilson Mui
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes I have, I am in the process, and I think everything I wrote, as far as I can tell is true. So I guess at this point, if anybody can contradict me, please let me know. Otherwise I'm going to swallow my own tripe.
 
Roger Chung-Wee
Ranch Hand
Posts: 1683
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah, that's about right. Here's an example. Note how case j-1: is valid because it can be evaluated compile time.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic