Java Enumerations - enum

This is an intermediate tutorial. Feel free to skip it, if you're just starting out. But come back to it after you've finished the section on creating your own clases.

An enumeration is like a collection of constants. For example, you may want a collection of the days of the week, the points on a compass, a collection of programming languages. You set them up like this:

enum WorkingWeekDays {

MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;

}

enum Compass {

NORTH, EAST, SOUTH, WEST;

}

enum ProgrammingLanguages {

JAVA, PYTHON, PHP;

}

So you start with the keyword enum. After a space, you need to come up with a name for your enumeration. In the code above, the enumerations are called WorkingWeekDays, Compass, and ProgrammingLanguages. Next, you need two curly brackets. The constant names you want to use go between the two curly brackets. Each name is separated by a comma. By convention, your constant names should be in uppercase. Notice, also, that the constant names end in a semicolon.

You can set up your enumeration either outside or inside of a class (above the class line where the main method is, or inside of it, for example). You'd use it like this:

ProgrammingLanguages lang = ProgrammingLanguages. JAVA;

if (lang == ProgrammingLanguages.JAVA) {

System.out.println("You chose Java");

} else if (lang == ProgrammingLanguages.PYTHON) {

System.out.println("You chose Python");

} else if (lang == ProgrammingLanguages.PHP) {

System.out.println("You chose PHP");

}

So you start with setting up a variable of type ProgrammingLanguages, or whatever you called your enumeration. You can then test for each value inside of an if statement.

Better, though, is to use a switch statement to check for each value, as your code will be more readable:

switch (lang) {

case JAVA:

System.out.println("You chose Java");
break;

case PYTHON:

System.out.println("You chose Python");
break;

case PHP:

System.out.println("You chose PHP");
break;

default:

break;

}

 

Enumeration Values

One thing to notice, however, is that you can't get at an enumerations value like this. That's because they don't have any. This creates a problem if we want to pass a value to a method. As an example, suppose we want to call a method that gets a random string of alphanumerical characters. We want various options for the random string: the string could be all in lowercase, all uppercase, numbers only, etc. We could do it with a switch statement inside of a method:

String getRandomString(int options) {

switch (options) {

case 0:

//GET RANDOM STRING LOWER HERE
break;

case 1:

//GET RANDOM STRING UPPER HERE
break;

case 2:

//GET RANDOM STRING LOWER AND UPPER HERE
break;

case 3:

//GET RANDOM STRING NUMBERS ONLY HERE
break;

case 4:

//GET RANDOM STRING ALL CHARACTERS HERE
break;

default:

break;

}

return some_value;

}

We'd want to pass a number over to this getRandomString method for the switch statement:

String randomString = getRandomString(2);

The 2 here means we want option 2, which is for a random string of lower and uppercase letters. But the 2 here makes the code unreadable. It would be better if we could say something like:

String randomString = getRandomString(enum-name.LOWERUPPER);

If, under the hood, LOWERUPPER has a value of 2 then this is much better than entering a raw number.

To get your enumerations to hold values, you can add those values after your constant names. Like this:

LOWERCASE(0),
UPPERCASE(1),

The value goes between round brackets. You can add a space, if you think it will make your code easier to read:

LOWERCASE (0),
UPPERCASE (1),

But this just sets up the enumeration with values. It doesn't get them back out for you. So we still can't do something like this:

String randomString = getRandomString(enum-name.LOWERUPPER);

To get a number back out, you make use of the fact that Java enumerations can also take a constructor (enumerations are really classes, behind the scenes). Let's see how.
Suppose we set up an enumeration for our character options:

enum CharacterOptions {

LOWERCASE (0),
UPPERCASE (1),
LOWERUPPER( 2),
NUMBERSONLY (3),
CHARSANDNUMBERS (4);

}

Inside of the final curly brackets of your enumeration, but after the semicolon, set up a public variable:

public final int val;

Now add the constructor:

private CharacterOptions(int enumVal) {

this.val = enumVal;

}

So the whole of the enumeration looks like this:

enum CharacterOptions {

LOWERCASE (0),
UPPERCASE (1),
LOWERUPPER( 2),
NUMBERSONLY (3),
CHARSANDNUMBERS (4);

public final int val;

private CharacterOptions(int enumVal) {

this.val = enumVal;

}

}

When you type a value from your list, LOWERCASE for example, the value for that item is placed inside of your variable between the round brackets of the constructor (enumVal, in this case). So, a value of 0 will end up in enumVal, if you select LOWERCASE. This value then ends up inside of the val variable. The value inside of the val variable is the one you're getting. Now can we do this?

To get at the value and hand it over to a method, you start with the name of your enumeration. Type a dot and you should see Netbeans display a list of your enumerations:

Select the one you want from the list and you'll have something like this:

String myRandomString = getRandomString(CharacterOptions .LOWER);

This will still get you an error, though. You have to add val on the end, the name of the variable you set up inside of the enumeration, that public final one:

String myRandomString = getRandomString(CharacterOptions .LOWER.val);

Now it's good to go. The value of the LOWERCASE option, the ones between the round brackets after the enumeration names, that value will be grabbed and passed to your method.

Although this is all a bit complicated, the code is easier to read and use. After all, what does a value of 2 mean? It's difficult to guess, unless you're the one who wrote the code. Even then, you'll probably forget if you come back to it a few months down the line. It's much better if you can just type a meaningful word instead a vague number.

A fuller program that uses enumerations can be found here (you need both files):

Java Code to get a random string - main method

Java Code to get a random string - Class

The program gets a random string of text that you can use as a file name or password. Study the program, and the comments.

The next lesson is another inetrmediate lesson and tales a closer look at how to generate random numbers in Java. If you want to skip this tougher lesson, you can move on the error handling.

<-- Inheritance | Java Random Numbers -->

Java Error Handling -->

Back to the Java Contents Page

All Home and Learn Courses