java enum
javaIn Java, an enum
is a special data type that represents a fixed set of values. An enum
is essentially a class that
has
a
fixed set of instances, and each instance represents one of the values that the enum can take.
Here is an example of how to define an enum
in Java:
public enum Color {
RED, GREEN, BLUE
}
This code defines an enum
called Color
with three values: RED
, GREEN
, and BLUE
.
You can use an enum
in your code just like any other data type. For example, you can use it to declare a variable:
Color favoriteColor = Color.GREEN;
You can also use an enum
in a switch
statement:
switch (favoriteColor) {
case RED:
System.out.println("Your favorite color is red.");
break;
case GREEN:
System.out.println("Your favorite color is green.");
break;
case BLUE:
System.out.println("Your favorite color is blue.");
break;
}
An enum
can also have additional properties and methods, just like a regular class. For example, you can define a
toString()
method to return a string representation of an enum
value:
public enum Color {
RED("#FF0000"), GREEN("#00FF00"), BLUE("#0000FF");
private final String hexCode;
private Color(String hexCode) {
this.hexCode = hexCode;
}
public String getHexCode() {
return hexCode;
}
@Override
public String toString() {
return name() + " (" + hexCode + ")";
}
}
This enum
defines a property called hexCode
that represents the hexadecimal code of each color, and a getHexCode()
method that returns the hex code of a color. It also overrides the toString()
method to return a string representation
of a color that includes its name and hex code.
Enums are useful for representing a fixed set of values, such as the days of the week, the months of the year, or a set of predefined options. They can make your code more readable and maintainable by providing a clear and concise way to represent these values.
For more information on enums in Java, you can refer to the Java documentation:
- enum: https://docs.oracle.com/en/java/javase/11/language/enums.html
- EnumSet: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/EnumSet.html
Other Article on Tag java
- - after and before in java date
- - am pm java date format
- - apk minecraft java edition
- - as been blocked by CORS policy Response to preflight request doesn't pass access control check It does not have HTTP ok status
- - bubble sort in java
- - Can I compile and run a spring boot jar from inside another spring boot application
- - convert java date to localdate
- - design patterns in java
- - encrypt by java and decrypt by node
- - exception handling in java