Java Enum When do I need to use it?
what is the Java Enum in java ?
A?Java Enum?is a special Java type used to define collections of constants. More precisely, a Java enum type is a special kind of Java class. An enum can contain constants, methods etc. Java enums were added in Java 5.
what the case i can use Java enum ?
i can use java Enum with Switch statement , and when i want use json object and map it with java class object?
implementation:
how i can create Enum class , look at the following code.
public enum Level {
HIGH,
MEDIUM,
LOW
}
in the above code,?we are create new enum class, and you can see we are replace class or interface keyword to enum keyword to declaration it.
okay but what is the difference between enum and class
each value inside enum is static and final i cant change and i can call by enum name without use object it but i can add new value inside enum .
how i can represent enum value inside class , look at the following example to see what is the difference between them .
public enum Level {
HIGH,
MEDIUM,
LOW
}
public class Level{
public static final HIGH="HIGH";
public static final MEDIUM="MEDIUM";
public static final LOW="LOW";
}
where i can use it
领英推荐
Level level=Level.HIGH; // here we are declration object of Enum
switch (level) {
case HIGH : ...; break;
case MEDIUM : ...; break;
case LOW : ...; break;
}
Level level = Level.LOW // here we are declration object of Enum
if( level == Level.HIGH) {
} else if( level == Level.MEDIUM) {
} else if( level == Level.LOW) {
}
okay how i can iteration in Enum
we can make iteration in enum and make print all value inside it how i can make it ,look at the following example .
for (Level level : Level.values()) {
System.out.println(level);
}
okay the finally about enum how i can print enum as a string or set enum value inside string variable.
we can print enum as a string and we can set inside a string value how i can make it ,look at the following example .?
String levelText = Level.HIGH.toString();
System.out.print(levelText); // HIGH
in the above example we are set the enum value inside string variable and after that i printed it .
conclusion:
in this article i explained about enum and make new enum and make some process to it in the next article i will explain about how i can serialize enum from json and explain why i need do it?