MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create enum class in Java

In this article we will see the process to create enum class in Java and how its importance in the web application development.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

What is Enum in java?

Enum is a keyword in java and on more detail term Java Enum is type like class and interfaces and can be used to define a set of Enum constants. Enum constants are implicitly static and final and you cannot change their value once created. Enum in Java provides type-safety and can be used inside switch statement like int variables. Since enum is a keyword you cannot use as variable name and since it’s only introduced in JDK 1.5 all your previous code which has enum as variable name will not work and needs to be re-factored.

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.

Listing 1: Creating list of enumerated variables

public static final int GENDER_MALE = 0;
public static final int GENDER_FEMALE = 1;

Although the above code solves the problem but this pattern of creating enumerated type has some problems such as the above variables are not typesafe since both variables GENDER_MALE and GENDER_FEMALE are just int variables so you can pass in any other int value where one of the above constant gender value is required.

Secondly if you print any of the above variables all you will get is a number such as 0 or 1, since they are just integers. You cannot get information about variables for example what type of gender this number represents.

So java 5.0 enums solve both above problems and in addition they provide many more useful features than their counterparts in other languages. In their simplest form, enums in java have same syntax as C, C++ or C# languages:

Listing 2: Enum syntax in Java

Enum MovieTypes
{
   ACTION,
   HORROR,
   COMEDY
}

Or you can also use single line syntax:

enum WeekDays { MON, TUE, WED, THU, FRI, SAT, SUN }

Every time you create enum in java you are creating a fully-fledged enum type or class and by default they provide basic implementation of all Object class methods. In addition to getting a complete enum type in your code, they are also Comparable and Serializable.

After your enum is created you can declare variables of enum type to store one of the enum predefined variable.

Listing 3: Declaring variable of enum type

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.

Listing 4: Print methods available to enum

System.out.println(m1);    
System.out.println(m1.name());
System.out.println(m1.toString());

Or you can print any of the variables directly with the enum name:

Listing 5: Print 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:

Listing 6: Using the static method values()

MovieTypes[] movies = MovieTypes.values();

for(int i=0 ; i<movies.length ; i++)
{
   System.out.println(movies[i]);
}

You can also use new java foreach loop to iterate enum variables.

Listing 7: Using the for loop

for(MovieTypes m: MovieTypes.values())
{
   System.out.println(m); 
}

As we said above enums in java are Comparable so you can compare two enum type variables as follows:

Listing 8: Comparing two enum type variables

MovieTypes m1 = MovieTypes.HORROR;
MovieTypes m2 = MovieTypes.HORROR;
MovieTypes m3 = MovieTypes.ACTION;

System.out.println(m1.equals(m2));
System.out.println(m1.equals(m3));

Enum type variable can also be used with switch statement to test its value with multiple cases.

Listing 9: Using the switch statement

MovieTypes m = MovieTypes.ACTION;

switch(m)
{
   case COMEDY:
      System.out.println(m); break;
   case HORROR:
      System.out.println(m); break;
   case ACTION:
       System.out.println(m); break;
}

You should use 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.

Listing 10: Creation of a Java 5 Enum with the actual values read in from a property file:

public enum MyEnum {
TOP(.05, 70),
MIDDLE(.15, 20);
BOTTOM(.25, 10);
private static final Map ENUMS = new HashMap();

private double bracketPercentage;
private int ratioPercentage;

static {
for (MyEnumbracketType : values()) {
ENUMS.put(bracketType.getBracketPercentage(), bracketType);
}
}

private MyEnum(double bracketPercentage, int ratioPercentage) {
this.bracketPercentage = bracketPercentage;
this.ratioPercentage = ratioPercentage;
}

public double getBracketPercentage() {
return bracketPercentage;
}

public int getRatioPercentage() {
return ratioPercentage;
}
}

Rather than "hard code" those values, we need to read them from a property file. The point of enums is that they are fixed things, so in your case you only have top, middle and bottom.

public enum Brackets { TOP, MIDDLE, BOTTOM }

Then you have a utility class or context to get the percentages and ratio for a bracket in that context. This allows you for example to compare things when those ratios change.

Listing 11: Comparing after ratios change

class TaxContext {
public TaxContext(Date date) {
// load the correct ratio for the specified years
}
public int getBracketRatio(Bracket bracket) {
switch(bracket) {
case TOP:
return ...;
// etc
}
}
}

The solution is to make the parameters in the constructor mutable objects, so that you can change them. But you can never increase / decrease the number of members to the enum or change the name/ordinal of the enum, these are entirely fixed (because that's the definition of an enum).

Listing 12: Playing with the parameters

public class EnumExperiment {
public static class Holder {
int a ;
Holder (int a) { this.a = a; }
public void setValue(int b) { a = b; }
public String toString() { return String.valueOf(a); }
}
public enum Experiments { A(new Holder(1)), B(new Holder(2));
public Holder a;
Experiments(Holder a) {
this.a = a;
}
public void setValue(int b) {
a.setValue(b);
}
public Holder getValue() { return a; }

}
public static void main(String[] a) {
System.out.println(Experiments.A.getValue());
System.out.println(Experiments.B.getValue());
Experiments.A.setValue(3);
Experiments.B.setValue(4);
System.out.println(Experiments.A.getValue());
System.out.println(Experiments.B.getValue());
}
}

Now, we will see the full source code of this article.

Listing 13: Full source code

class TaxContext {
public TaxContext(Date date) {
// load the correct ratio for the specified years
}
public int getBracketRatio(Bracket bracket) {
switch(bracket) {
case TOP:
return ...;
// etc
}
}
}

public class EnumExperiment {
public static class Holder {
int a ;
Holder (int a) { this.a = a; }

public void setValue(int b) { a = b; }
public String toString() { return String.valueOf(a); }
}
public enum Experiments { A(new Holder(1)), B(new Holder(2));
public Holder a;
Experiments(Holder a) {
this.a = a;
}
public void setValue(int b) {
a.setValue(b);
}
public Holder getValue() { return a; }

}
public static void main(String[] a) {
System.out.println(Experiments.A.getValue());
System.out.println(Experiments.B.getValue());
Experiments.A.setValue(3);
Experiments.B.setValue(4);
System.out.println(Experiments.A.getValue());
System.out.println(Experiments.B.getValue());
}
}

Conclusion

We saw today the process to create enum class in java and how it's importance in the web application development.



Software Developer from India. I hold Master in Computer Applications Degree and is well versed with programming languages such as Java, .Net, C and C++ and possess good working knowledge on Mobile Platforms as well.

What did you think of this post?

Did you like the post?

Help us to keep publishing good contents like this.

SUPPORT US

funded

remaining

[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login