dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: Java Language
Expertise: Beginner
Mar 19, 1997

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


Implementing the C enum Keyword

Question:
I'm porting my C code to Java and would like to know how I would implement the C enum keyword to Java.

Answer:
There is no convenient mechanism for enum in Java. You just list the constants one by one, and you must attach values to them. You also must find a "home" for them, some class to which the constants conceptually belong.

For example,

        enum Weekday { MON, TUE, WED, THU, FRI, SAT, SUN }; // C
        

might turn into

       class Day // Java
       {       public static int MON = 0;
               public static int TUE = 1;
               public static int WED = 2;
               public static int THU = 3;
               public static int FRI = 4;
               public static int SAT = 5;
               public static int SUN = 6;
               // . . .
       }
        

Note that this does not introduce a special type. A variable that can hold weekdays must be defined as an int.

Contrast that with C, where you can define a variable of type Weekday:

        enum Weekday w;
        

Actually, in C, this is just window-dressing. An enumeration is just an integer in C. But in C++, enumerated types really are distinct types.

On the positive side, names are inside the scope of that class. For example, Sunday is

        int w = Day.SUN; // Java
        

(This is completely analogous to enumerations defined inside classes in C++.) This is a good thing because it saves you from embarrassing multiple definitions of enumeration constants, like

        enum Test { GRE, GMAT, SAT };
        enum Vendor { DEC, HP, SUN };
    
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date