Implementing the C enum Keyword

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 canhold 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 aninteger in C. But in C++, enumerated types really are distinct types.

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

        int w = Day.SUN; // Java        

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

        enum Test { GRE, GMAT, SAT };        enum Vendor { DEC, HP, SUN };    
See also  Essential Measures for Safeguarding Your Digital Data

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist