File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Legal arguments in switch case statements" Watch "Legal arguments in switch case statements" New topic
Author

Legal arguments in switch case statements

meena
Greenhorn

Joined: Mar 30, 2004
Posts: 1
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

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
atiqur,
b is a final variable
heyagosper
Greenhorn

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
Sheriff

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: http://aspose.com/file-tools
 
subject: Legal arguments in switch case statements
 
Similar Threads
switch case with final
what is compile time constant in switch case?
switch statement
Case Argument in Switch
Complie time Constant - final int a; a =1 ; IS NOT?!