aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes does switch take a Integer wrapper? 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 "does switch take a Integer wrapper? " Watch "does switch take a Integer wrapper? " New topic
Author

does switch take a Integer wrapper?

Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531


how does this compile? switch can only take primitives(that can be implicitly casted to int) and enum right....
avi sinha
Ranch Hand

Joined: Mar 15, 2009
Posts: 453

have you heard about autoboxing and unboxing .???

avi sinha


SCJP 5.0 SCWCD 5.0
Neha Daga
Ranch Hand

Joined: Oct 30, 2009
Posts: 504
Unlike if-then and if-then-else, the switch statement allows for any number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Classes and Inheritance) and a few special classes that "wrap" certain primitive types: Character, Byte, Short, and Integer (discussed in Simple Data Objects ).


I read it here


SCJP 1.6 96%
Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531
yup...initially i thought it can work that way here..through unboxing...but in K&B it isnt mentioned that wrappers are allowed...nor in moghuls book
avi sinha
Ranch Hand

Joined: Mar 15, 2009
Posts: 453

Ankur kothari wrote:yup...initially i thought it can work that way here..through unboxing...but in K&B it isnt mentioned that wrappers are allowed...nor in moghuls book


you have got it wrong.

note these points

1> wrappers can be used in the switch expression. like switch( i ) where i is an Integer.

2> a wrapper can't be used in the case expression.

avi sinha
satish kumar kandukuri
Greenhorn

Joined: Aug 10, 2005
Posts: 6
Also another thing i got to know is
Case expressions cannot be wrappers as Avi sinha said. It can neither be regular primitive type as well. But we can specify Compile time constants (Initialed Final variables along with declaration) and it cannot be just final variables.

Below one works

....
final int j = 3; //This works as its a compile time constant
switch(i) {
case j: System.out.println("three”"); break;
default: System.out.println("other”"); break;
}


Where as below one doesnot work and it gives compile time error.
final int j;
j = 3;
switch(i) {
case j: System.out.println("three”"); break;
default: System.out.println("other”"); break;
}








Satish Kandukuri.
avi sinha
Ranch Hand

Joined: Mar 15, 2009
Posts: 453

for a variable to be a compile time constant it should be initialized on the same line as that of declaration .

avi sinha
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: does switch take a Integer wrapper?