Java enum example

Some of the Java enum examples, and how to use it, nothing special, just for self-reference.

Note
Consider the Enum type if your program consists of a fixed set of constants, like seasons of the year, operations calculator, user status and etc.

1. Basic Enum

UserStatus.java

public enum UserStatus {
    PENDING,
    ACTIVE,
    INACTIVE,
    DELETED;
}
Test.java

public class Test {

    public static void main(String[] args) {

		//ACTIVE
        System.out.println(UserStatus.ACTIVE);

    }

}

2. Enum + Instance field

WhoisRIR.java

public enum WhoisRIR {
    ARIN("whois.arin.net"),
    RIPE("whois.ripe.net"),
    APNIC("whois.apnic.net"),
    AFRINIC("whois.afrinic.net"),
    LACNIC("whois.lacnic.net"),
    JPNIC("whois.nic.ad.jp"),
    KRNIC("whois.nic.or.kr"),
    CNNIC("ipwhois.cnnic.cn"),
    UNKNOWN("");

    private String url;

    WhoisRIR(String url) {
        this.url = url;
    }

    public String url() {
        return url;
    }
}
Test.java

public class Test {

    public static void main(String[] args) {

		//whois.arin.net
        System.out.println(WhoisRIR.ARIN.url());

    }

}

3. Enum + Method + Some logic

Operation.java

public enum Operation {
    PLUS,
    MINUS,
    TIMES,
    DIVIDE;

    double calculate(double x, double y) {
        switch (this) {
            case PLUS:
                return x + y;
            case MINUS:
                return x - y;
            case TIMES:
                return x * y;
            case DIVIDE:
                return x / y;
            default:
                throw new AssertionError("Unknown operations " + this);
        }
    }

}
Test.java

public class Test {

    public static void main(String[] args) {

        double result = Operation.PLUS.calculate(1, 2);
        System.out.println(result); //3.0

    }

}

4. How to use Enum

4.1 To loop a Enum object.


public class Test {

    public static void main(String[] args) {

        for (UserStatus status : UserStatus.values()) {
            System.out.println(status);
        }

    }

}

Output

PENDING
ACTIVE
INACTIVE
DELETED

4.2 To compare the Enum values, use == operator.


public class Test {

    public static void main(String[] args) {

        WhoisRIR rir = WhoisRIR.APNIC;

        if(rir == WhoisRIR.APNIC) {
            System.out.println("This is APNIC : " + rir.url());
        }

    }

}

Output

This is APNIC : whois.apnic.net

4.3 Switch case.


public class Test {

    public static void main(String[] args) {

        WhoisRIR rir = WhoisRIR.RIPE;

        switch (rir) {
            case ARIN:
                System.out.println("This is ARIN");
                break;
            case APNIC:
                System.out.println("This is APNIC");
                break;
            case RIPE:
                System.out.println("This is RIPE");
                break;
            default:
                throw new AssertionError("Unknown RIR " + rir);

        }

    }
}

Output

This is RIPE

4.2 Convert a String to Enum object.


public class Test {

    public static void main(String[] args) {

		//enum valueOf + uppercase
        Operation op = Operation.valueOf("times".toUpperCase());
        System.out.println(op.calculate(10, 3));

    }
}

Output

30.0

Done.

References

  1. Oracle Doc – Enum Types
  2. Stackoverflow : Comparing Java enum members: == or equals()
  3. Java – Convert String to Enum object
  4. Java – Compare Enum value

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Narya
Guest
Narya

First of all, thank you for posting these example.It helped me to understand how I can use ‘ENUM’ in an application.
However, doing more practice on Enum , I noticed that – I get Compile time error when I declare constructor before declaring Enum constants.

Could you please justify why did it happen ?

Kalyan
Guest
Kalyan

Java requires that the constants be defined first, prior to any fields or methods. Also, when there are fields and methods, the list of enum constants must end with a semicolon.
ref: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

trackback
10 Tech Stories To Read This Week – October 23 Edition » iRomin

[…] Java Enum Example: An interesting way to use Enums, take a look. […]

Karthik Marupeddi
Guest
Karthik Marupeddi

Thank you.

????? ????
Guest
????? ????

thanks

Navneet
Guest
Navneet

Hi Mkyong, Your article is very helpful to me.

Navneet
Guest
Navneet

Thanks to mkyong. You explained it very well.

jiangjian
Guest
jiangjian

thanks, your article is so clear to me.

oliver
Guest
oliver

This website is very helpful to me.Thanks!

tianvo
Guest
tianvo

Thx,it’s clear to understand,your site is so usefull!
since i found it few days ago i always come here.

tamil
Guest
tamil

cant understand above explanation

tamil
Guest
tamil

i cant understand clearly above example

evilsniper
Guest
evilsniper

This website is very helpful to me.Thanks!

Subrat
Guest
Subrat

good example.

Terry Le
Guest
Terry Le

Short sample for more effective

sa
Guest
sa

Nice one,simple and concise. Thanks.

Pankaj
Guest
Pankaj

I have written a tutorial for Java Enum, please have a look and let me know your thoughts.

http://www.journaldev.com/716/java-enum-examples-with-benefits-and-class-usage

Jairo Sanches
Guest
Jairo Sanches

Thanks, excelent example.