Java Enums

Enum Example

public enum Level {
    HIGH,
    MEDIUM,
    LOW
}

Enums in if Statements

Level level = ...  //assign some Level constant to it

if( level == Level.HIGH) {

} else if( level == Level.MEDIUM) {

} else if( level == Level.LOW) {

}

Enum Iteration

for (Level level : Level.values()) {
    System.out.println(level);
}

Enum Fields

public enum Level {
    HIGH  (3),  //calls constructor with value 3
    MEDIUM(2),  //calls constructor with value 2
    LOW   (1)   //calls constructor with value 1
    ; // semicolon needed when fields / methods follow


    private final int levelCode;

    private Level(int levelCode) {
        this.levelCode = levelCode;
    }
}

Enum Methods

public enum Level {
    HIGH  (3),  //calls constructor with value 3
    MEDIUM(2),  //calls constructor with value 2
    LOW   (1)   //calls constructor with value 1
    ; // semicolon needed when fields / methods follow


    private final int levelCode;

    Level(int levelCode) {
        this.levelCode = levelCode;
    }
    
    public int getLevelCode() {
        return this.levelCode;
    }
    
}

References
http://tutorials.jenkov.com/java/enums.html
https://www.mkyong.com/java/java-enum-example/

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.