aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in Rules Roundup switch int only (enum works) 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 "Doubt in Rules Roundup switch int only (enum works)" Watch "Doubt in Rules Roundup switch int only (enum works)" New topic
Author

Doubt in Rules Roundup switch int only (enum works)

Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 688

You can not only switch on an int or a compatible type (byte or short) but you can now switch on an enumerated type created with the enum keyword.



Kaydell

[ June 07, 2007: Message edited by: Kaydell Leavitt ]
[ June 07, 2007: Message edited by: Kaydell Leavitt ]
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
I agree!




Thanks,


cmbhatt
Cor Takken
Ranch Hand

Joined: May 21, 2007
Posts: 58
My guess is that the switch uses the Enum.ordinal() method to get to an int value under the covers. That makes the Enum value an int value and thus valid for the switch-function.

But I might be wrong....

Cor


SCJP 1.5
Dolphins are grey, but they dream in colour.
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 688


My guess is that the switch uses the Enum.ordinal() method to get to an int value under the covers.


You may be able to convert an Enum to an int, but an Enum is really an instance of a subclass of Enum. An Enum is not compatible with an int and that's a good thing so that you don't accidentally pass an int constant where it isn't appropriate. With enum values, if you try to pass them as parameters where an int is required, you get a compile-time error.

Kaydell
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 688

I believe that you can switch on the following types:

byte, short, int, char, and enum

Kaydell
Sergio Tridente
Ranch Hand

Joined: Mar 22, 2007
Posts: 329



It does not compile!


SCJP 1.4 (88%) - SCJP 5.0 Upgrade (93%) - SCWCD 1.4 (97%) - SCBCD 5.0 (98%)
Amit Ghorpade
Bartender

Joined: Jun 06, 2007
Posts: 2712
    
    5

Hi,
even i have learnt this new thing that Enum works with switch
so far even i thought that only int compatible types work with switch.

Thanks


SCJP, SCWCD.
|Asking Good Questions|
Cor Takken
Ranch Hand

Joined: May 21, 2007
Posts: 58
Originally posted by Sergio Tridente:


It does not compile!


Try

Cor
[ June 12, 2007: Message edited by: Cor Takken ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt in Rules Roundup switch int only (enum works)
 
Similar Threads
hi
How Can I Try Linux?
Java Round-Up game
How do I get the AUTOINCREMENT value?
In Eclipse, how can I hide empty packages?