Enums, short for "enumerations," are a unique data type in Java that allows a variable to hold a predefined set of constants. They are particularly beneficial for representing a group of related constants in a manner that ensures type safety. Enums are particularly useful when you know all possible
values at compile time, such as days of the week, directions, states, etc.
Understanding Enums
- Definition
and Syntax: Enums are defined using the enum keyword. Each constant defined within an enum is automatically public, static, and final. Here’s a basic example of
an enum:
java
public enum DaysOfWeekEnum { SUN, MON, TUE, WED, THU, FRI, SAT } |
- Usage:
Enums can be used in switch statements, for iteration, and for storing
additional information.
java
public class EnumExample
{ public static void main(String[] args) { Day day = Day.MON; switch (day) { case MON: System.out.println("It's day of Monday!"); break; case FRI: System.out.println("It's day of Friday!"); break; default: System.out.println("It's
some other day."); break; } } } |
- Enum
Methods: Enums can have methods, fields, and constructors. You can
override methods like toString() and add custom methods.
java
public enum DaysOfWeekEnum { SUN, MON, TUE, WED, THU, FRI, SAT; public boolean isWeekend() { return this == SUN || this ==
SAT; } } |
- Custom
Fields and Methods: Enums can have fields and methods. This allows
enums to store additional data.
java
public enum Planet
{ MERCURY(3.303e+23, 2.4397e6), VENUS(4.869e+24, 6.0518e6), EARTH(5.976e+24, 6.37814e6), MARS(6.421e+23, 3.3972e6); private final double massWeight; // in kilograms private final double radiusCircle; // in meters Planet(double massWeight, double radiusCircle) { this.massWeight= massWeight; this.radiusCircle = radiusCircle; } public double massWeight() { return massWeight; } public double radiusCircle() { return radiusCircle; } // Universal gravitational G constant (m³ kg⁻¹ s⁻²) public static final double G = 6.67300E-11; public double surfaceGravity() { return G * massWeight/ (radiusCircle* radiusCircle); } public double surfaceWeight(double
otherMass) { return otherMass * surfaceGravity(); } } |
- Iterating
Over Enums: You can iterate over enum constants using the values()
method.
java
public class EnumIteration
{ public static void main(String[] args) { for (Day day : Day.values()) { System.out.println(day); } } } |
- Enum
with Interfaces: Enums can implement interfaces, which can be useful
for defining behavior shared among constants.
java
public interface
Printable { void print(); } public enum PrinterType
implements Printable { DOT_MATRIX { @Override public void print() { System.out.println("Dot
Matrix Printer"); } }, LASER { @Override public void print() { System.out.println("Laser
Printer"); } }, INKJET { @Override public void print() { System.out.println("Inkjet
Printer"); } } } |
- EnumSet
and EnumMap: Java offers specialized collection classes, EnumSet and EnumMap, specifically designed for use with enums. These classes are optimized for handling enum types efficiently.
java
import
java.util.EnumSet; public class EnumSetExample
{ public static void main(String[] args) { EnumSet<Day> weekend =
EnumSet.of(DaysOfWeekEnumSAT, DaysOfWeekEnum.SUN); for (Day day : weekend) { System.out.println(day); } } } |
Detailed Example
Let’s take a more detailed example to understand enums
deeply.
java
public enum Operation
{ PLUS("+") { public double apply(double x, double
y) { return x + y; } }, MINUS("-") { public double apply(double x, double
y) { return x - y; } }, TIMES("*") { public double apply(double x, double
y) { return x * y; } }, DIVIDE("/") { public double apply(double x, double y) { return
x / y; } }; private final String symbol; Operation(String symbol) { this.symbol = symbol; } @Override public String toString() { return symbol; } public abstract double apply(double x, double
y); } public class EnumExample
{ public static void main(String[] args) { double x = 10.0; double y = 2.0; for (Operation op :
Operation.values()) { System.out.printf("%f %s %f enum data = %f%n", x, op, y, op.apply(x, y)); } } } |
Another example:
public enum
CredentialStatus { SCRAM_SHA_1 { @Override public String getName() { return "ScramSha1"; } }, MONGO_CR { @Override public String getName() { return "MongoCR"; } }, PLAIN { @Override public String getName() { return "Plain"; } }, GSSAPI { @Override public String getName() { return "GSSAPI"; } }, MONGO_X509 { @Override public String getName() { return "MongoX509"; } }, NONE { @Override public String getName() { return "NONE"; } }; /** * * @return getName of Enum class method */ public abstract String getName(); } where you
need to use just call that variable after then you can use Example A:
String scrm = CredentialStatus.SCRAM_SHA_1.getName(); Example B:
String mongoCr = CredentialStatus.MONGO_CR.getName(); |
Enum method example:
public enum
EnumMethod{ SESSION("session",
"AES", "AES/CBC/PKCS5Padding"), TOKEN("token",
"AES","AES/CBC/PKCS5Padding"), CONFIG("mongoservice_config",
"AES","AES/CBC/PKCS5Padding"), SUMMARY("summary",
"AES","AES/CBC/PKCS5Padding"), DOCUMENT("document",
"AES","AES/CBC/PKCS5Padding"); private String transformation; private String role; private String algorithm; private EnumMethod(String role, String
algorithm, String transformation) { this.transformation = transformation; this.role = role; this.algorithm = algorithm; } public String transformation() { return transformation; } public String role() { return role; } public String algorithm() { return algorithm; } } where you
need to use just call that variable after then you can use Example A:
EnumMethod enumMethodSession = EnumMethod.SESSION; Example B:
EnumMethod enumMethodToken = EnumMethod.TOKEN; |
Enum in Switch Case
You can use enums in switch-case statements for clean and
readable code.
java
public class EnumSwitchExample
{ public static void main(String[] args) { Day today = DaysOfWeekEnum.WED; switch (today) { case MON: System.out.println("Mondays
are bad."); break; case FRI: System.out.println("Fridays
are better."); break; case SAT: case SUN: System.out.println("Weekends
are best."); break; default: System.out.println("Midweek
days are so-so."); break; } } } |
Best Practices for Using Enums
- Use
Enums for a Fixed Set of Constants: Enums are ideal for representing
fixed sets of constants, such as days of the week, colors, or operations.
- Add
Methods and Fields as Needed: Enums can have fields, methods, and
constructors to provide additional functionality or store extra data.
- Use
EnumSet and EnumMap: For collections of enum types, prefer EnumSet and
EnumMap for better performance and type safety.
- Override
toString() Method: Customize the toString() method to provide a
meaningful string representation of the enum constants.
- Implement
Interfaces: Enums can implement interfaces to enforce certain
behaviors across all enum constants.
Conclusion
Enums in Java provide a powerful and flexible way to
represent a fixed set of constants. By understanding and utilizing their
features effectively, you can write more readable, maintainable, and type-safe
code. Enums go beyond just being a collection of constants by allowing fields,
methods, and the implementation of interfaces, making them a robust tool in a
Java developer's arsenal.
Java Enums can be thought of as classes that have fixed set
of constants.
- enum
improves type safety
- enum
can be easily used in switch
- enum
can have fields, constructors and methods
- enum
can be traversed
- enum
may implement many interfaces but cannot extend any class because it
internally extends Enum class
For More Java Related information, visit
Ø
Streams
Lambdas Collectors and Functional Interfaces in Java 8
Ø
Java
8 support static method or default method or both in the interface
Ø
Serialization
understanding
Ø
Garbage
Collection Under Standing
Ø
How
work Garbage Collection in Java
Ø Under Standing Of Mutable and Immutable Class
For More sort information, visit:
Ø
Selection
Sort with iteration wise per step
Ø
Bubble
Sort with each iteration how it is work
Ø
Merge
sort of Each step how it is working
Ø
Quick
Sort per iteration what happen
Ø
Sorting
Of a list multiple attribute wise two technique
Ø
Seat
Arrangement in Sorting Order Like 1A-1E, 3C-3G etc
Ø
How
to sort 10 billion numbers
Ø
Merge
Sort simple under standing
For Math information, visit:
Ø
Calculating
the area of a triangle
Ø
The
method for calculating the area of a rectangle in Java
Ø
The value of π =
3.14159 in java [Click
Here]
0 Comments