The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Legal arguments in switch case statements Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Legal arguments in switch case statements" Watch "Legal arguments in switch case statements" New topic

Legal arguments in switch case statements


Joined: Mar 30, 2004
Posts: 1
can someone tell me why this code won't compile
final int a =1;
final int b;
int x=0;
switch(x) {
case a;
case b; -------compiler error
the book says that case b; this line will give compiler error.
Why is that?
will b=2 not happen at compile time? My understanding was that primitives get their values at compile time and objects at run time..
Please help
atiqur rahman

Joined: Aug 30, 2003
Posts: 10
simple rule for switch case:
you can only use constant or final variable as case argument.
Deb Sadhukhan
Ranch Hand

Joined: Nov 05, 2003
Posts: 67
b is a final variable

Joined: Mar 31, 2004
Posts: 1
I think the answer can be summed up as follows:
a) switch statements, along with their case clauses, are evaluated at compile time.
b) constant expressions such as final variables are evaluated at compile time (so a declaration like "final int b = 2;" makes the constant value of b available to the compiled switch code)
c) assignments that are NOT made when a constant is declared (ie, in the same statement, as above) are made at run-time. So a statement like "final int b; b = 2;" does not expose the value of b to the compiled switch code.
I'm not sure why the compiler doesn't complain about an uninitialised variable in this case... for example:
case a: statement;
case b: x = b;
//No uninitialized variable error, just the constant required error.
I think it is because the precompiler checks for a constant value referenced by b before compiling the rest of the code.

Hope that helps.
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
men man and heyagosper,
Welcome to JavaRanch!
We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy.
Thanks Pardner! Hope to see you 'round the Ranch!

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: Legal arguments in switch case statements
It's not a secret anymore!