Browse DevX
Sign up for e-mail newsletters from DevX

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



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Implementing the C enum Keyword

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

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.



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