In J2SE 5.0 Java introduced typesafe enumerations called “Enum” or simply “enums”. They are used to create multiple constants with a single given name.
Prior to Java 5.0, you had to use static final int constants to create a list of enumerated variables as following example.
public static final int GENDER_MALE = 0;public static final in GENDER_FEMALE = 1;
enum WeekDays { MON, TUE, WED, THU, FRI, SAT, SUN }
MovieTypes m1 = MovieTypes.HORROR;MovieTypes m2 = MovieTypes.ACTION;
If you want to print enum variable you can print directly or you can call methods available to all enums in java.
System.out.println(m1); System.out.println(m1.name());System.out.println(m1.toString());
or you can print any of the variable directly with the enum name
System.out.println(MovieTypes.ACTION);System.out.println(MovieTypes.HORROR);
If you want to iterate all the enum variables then you can use static method values() which is available in all enums in java and return an array of enum type
for(MovieTypes m: MovieTypes.values()){ System.out.println(m); }As I said above enums in java are Comparable so you can compare two enum type variables as follows:
Enum type variable can also be used with switch statement to test its value with multiple cases
You should used enums in java every time you need a fixed set of constants or you want to restrict a variable to hold predefined set of constant values defined in enum. You should also use them where you have some predefined set of values you want to user to input in your program such as menu choices.
Name: *
Email: *
Website:
Comments: