Tutorial by Examples

Enum can be considered to be syntax sugar for a sealed class that is instantiated only a number of times known at compile-time to define a set of constants. A simple enum to list the different seasons would be declared as follows: public enum Season { WINTER, SPRING, SUMMER, FA...
An enum cannot have a public constructor; however, private constructors are acceptable (constructors for enums are package-private by default): public enum Coin { PENNY(1), NICKEL(5), DIME(10), QUARTER(25); // usual names for US coins // note that the above parentheses and the constructor...
An enum can contain a method, just like any class. To see how this works, we'll declare an enum like this: public enum Direction { NORTH, SOUTH, EAST, WEST; } Let's have a method that returns the enum in the opposite direction: public enum Direction { NORTH, SOUTH, EAST, WEST; ...
This is an enum that is also a callable function that tests String inputs against precompiled regular expression patterns. import java.util.function.Predicate; import java.util.regex.Pattern; enum RegEx implements Predicate<String> { UPPER("[A-Z]+"), LOWER("[a-z]+&quot...
When a method need to accept an "extensible" set of enum values, the programmer can apply polymorphism like on a normal class by creating an interface which will be used anywere where the enums shall be used: public interface ExtensibleEnum { String name(); } This way, any enum t...
Enums can define abstract methods, which each enum member is required to implement. enum Action { DODGE { public boolean execute(Player player) { return player.isAttacking(); } }, ATTACK { public boolean execute(Player player) { re...
Not always the enum name is clear enough to be understood. To document an enum, use standard javadoc: /** * United States coins */ public enum Coins { /** * One-cent coin, commonly known as a penny, * is a unit of currency equaling one-hundredth * of a United Sta...
Each enum class contains an implicit static method named values(). This method returns an array containing all values of that enum. You can use this method to iterate over the values. It is important to note however that this method returns a new array every time it is called. public enum Day { ...
When writing a class with generics in java, it is possible to ensure that the type parameter is an enum. Since all enums extend the Enum class, the following syntax may be used. public class Holder<T extends Enum<T>> { public final T value; public Holder(T init) { t...
Say we have an enum DayOfWeek: enum DayOfWeek { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; } An enum is compiled with a built-in static valueOf() method which can be used to lookup a constant by its name: String dayName = DayOfWeek.SUNDAY.name(); assert dayName.equal...
Enum constants are instantiated when an enum is referenced for the first time. Therefore, that allows to implement Singleton software design pattern with a single-element enum. public enum Attendant { INSTANCE; private Attendant() { // perform some initialization routine ...
In case we want to use enum with more information and not just as constant values, and we want to be able to compare two enums. Consider the following example: public enum Coin { PENNY(1), NICKEL(5), DIME(10), QUARTER(25); private final int value; Coin(int value){ this....
Sometimes you want to convert your enum to a String, there are two ways to do that. Assume we have: public enum Fruit { APPLE, ORANGE, STRAWBERRY, BANANA, LEMON, GRAPE_FRUIT; } So how do we convert something like Fruit.APPLE to "APPLE"? Convert using name() name() is an inte...
In an enum it is possible to define a specific behavior for a particular constant of the enum which overrides the default behavior of the enum, this technique is known as constant specific body. Suppose three piano students - John, Ben and Luke - are defined in an enum named PianoClass, as follows:...
enum Util { /* No instances */; public static int clamp(int min, int max, int i) { return Math.min(Math.max(i, min), max); } // other utility methods... } Just as enum can be used for singletons (1 instance classes), it can be used for utility classes (0 instance...
If your enum class is required to have static fields, keep in mind they are created after the enum values themselves. That means, the following code will result in a NullPointerException: enum Example { ONE(1), TWO(2); static Map<String, Integer> integers = new HashMap<>(); ...
Enums contains only constants and can be compared directly with ==. So, only reference check is needed, no need to use .equals method. Moreover, if .equals used incorrectly, may raise the NullPointerException while that's not the case with == check. enum Day { GOOD, AVERAGE, WORST; } publi...

Page 1 of 1