Java – Set Default Value for Enum Fields

This post shows you how to set a default value for Enum fields in Java. To do this, we need to pass values to the constructor. Let’s take a look into two examples shown right below.
 

Example 1

UserType.java
package com.bytenota;

public enum UserType {
    
    ADMIN("User is administrator"),
    MODE("User is moderator"),
    GUEST("User is guest");
    
    private final String description;

    UserType(String description) {
        this.description = description;
    }
    
    public String getDescription() {
        return description;
    }
}

In the above code, we have created UserType enum as an example, it contains a list of user types and we set the default description for these enum fields.


 

Example 2

Here is another example showing how to set two default values to enum fields.

Animal.java
package com.bytenota;

public enum Animal {
    
    DOG("LuLu", 3),
    CAT("MiMi", 1),
    RABBIT("Bunny", 2);
    
    private final String name;
    private final int age;

    Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getInfo() {
        return String.format("My name is %s, I'm %d", name, age);
    }
}

Run example:

RunExample.java
package com.bytenota;

public class RunExample {
    
    public static void main(String[] args) {
        String dog = Animal.DOG.getInfo();
        System.out.println(dog);
        
        String cat = Animal.CAT.getInfo();
        System.out.println(cat);
        
        String rabbit = Animal.RABBIT.getInfo();
        System.out.println(rabbit);
    }
}

Output:

My name is LuLu, I'm 3
My name is MiMi, I'm 1
My name is Bunny, I'm 2

guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Modric
Modric
5 years ago

Thanks!!! your blog is awesome.

1
0
Would love your thoughts, please comment.x
()
x