This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Legal arguments in switch case statements

 
meena
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can someone tell me why this code won't compile
final int a =1;
final int b;
b=2;
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
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
simple rule for switch case:
you can only use constant or final variable as case argument.
 
Deb Sadhukhan
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
atiqur,
b is a final variable
 
heyagosper
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic