Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in Rules Roundup switch int only (enum works)

 
Kaydell Leavitt
Ranch Hand
Posts: 690
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree!




Thanks,
 
Cor Takken
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Kaydell Leavitt
Ranch Hand
Posts: 690
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 690
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe that you can switch on the following types:

byte, short, int, char, and enum

Kaydell
 
Sergio Tridente
Ranch Hand
Posts: 329
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


It does not compile!
 
Amit Ghorpade
Bartender
Posts: 2854
10
Fedora Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Cor Takken
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sergio Tridente:


It does not compile!


Try

Cor
[ June 12, 2007: Message edited by: Cor Takken ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic