wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes A switch-case statement question 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 "A switch-case statement question" Watch "A switch-case statement question" New topic
Author

A switch-case statement question

Amelia Ma
Ranch Hand

Joined: Nov 09, 2009
Posts: 33
What will be the result of attempting to compile and run the following program?

Correct answer is that the code will fail to compile. Because the value of the case label iFour is not a constant expression.
I totally don't understand. Isn't iFour is a compile time constant and become 4 through unboxing?
This problem come from "A Programmer's Guide to Java SCJP Certification", Chapter 6.2, page 215.
Thanks.


Hi, this is Fat Louie. Please feel free to contact me at goFatLouie@yahoo.com
rohan yadav
Ranch Hand

Joined: Oct 13, 2009
Posts: 156
Try this:


Wrapping takes place at runtime(Integer to int), and you require compile time constants for switch case.


Sage of The Monstrous Toad of Mount Myoboku
Rein de Boer
Greenhorn

Joined: Jul 12, 2009
Posts: 15
To add to the previous post, iFour is a reference variable (to object type Integer), not a value type. So therefore not usable in a case.
Amelia Ma
Ranch Hand

Joined: Nov 09, 2009
Posts: 33
Rein de Boer wrote:To add to the previous post, iFour is a reference variable (to object type Integer), not a value type. So therefore not usable in a case.


so all wrapper classes (Integer Character Short Byte) can't be in the case expression, right?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18520
    
  40

Amelia Ma wrote:I totally don't understand. Isn't iFour is a compile time constant and become 4 through unboxing?


As a side note to this topic... compile time constants require that the type be a primative or a string. The Java Language Specification currently doesn't support any other type as a compile time constant.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: A switch-case statement question
 
Similar Threads
problem in switch case
Wrapper Classes for Switch
Switch And Primitive Wrappers
final variables
overload method in boxing/unboxing