Difference between enum and constant in java

Enum is a java keyword, we can use it for a variable to be set of predefined constant value.

Before Java 1.5 we used public static final keywords to represent constants. Enum was introduced in Java 1.5 and since then we use it represent constants or string name for a variable. Also Enums are thread safe by default.

public enum StateCities {
    NewYork, 
    SanFrancisco, 
    LosAngeles, 
    Washington, 
    Miami
};

Enum values are static and final by default and cannot be change after once it is created. Also enum can be used in switch statements.

USCity city = StateCities.NewYork;
switch (city) {
case NewYork:
System.out.println("Application started");
break;
case SanFrancisco:
System.out.println("Application failed");
break;
case LosAngeles:
System.out.println("Application completed");
break;
default:
throw new IllegalArgumentException("Invalid City");
}

Enums can implement any interface and override methods.

No extends keyword allows for enum as every enum is internally extends java.lang.Enum class.

Ramesh Kumar S avatar

Posted by

Leave a comment