⬅ Previous Topic
Java else KeywordNext Topic ⮕
Java extends Keyword⬅ Previous Topic
Java else KeywordNext Topic ⮕
Java extends Keywordenum
Keyword in JavaIn Java, the enum
keyword is used to define a set of named constants. Unlike regular constants, enums are more powerful and type-safe. They're ideal when you want to represent a fixed set of values like days of the week, directions, or states in a process.
enum
Instead of Constants?Java enums offer several advantages over traditional constants (e.g., public static final int
):
values()
and valueOf()
.enum
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
You can use enums just like any other class:
public class EnumExample {
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
}
public static void main(String[] args) {
Day today = Day.WEDNESDAY;
if (today == Day.WEDNESDAY) {
System.out.println("It's midweek!");
}
}
}
It's midweek!
switch
StatementEnums pair beautifully with switch
statements:
public class EnumSwitchExample {
enum Direction {
NORTH, SOUTH, EAST, WEST
}
public static void main(String[] args) {
Direction dir = Direction.EAST;
switch (dir) {
case NORTH:
System.out.println("Heading North");
break;
case SOUTH:
System.out.println("Going South");
break;
case EAST:
System.out.println("Turning East");
break;
case WEST:
System.out.println("Moving West");
break;
}
}
}
Turning East
Enums aren't just about values. You can attach fields and methods too:
public class EnumAdvanced {
enum Planet {
EARTH(5.97), MARS(0.642), JUPITER(1898);
private double mass; // in 10^24 kg
Planet(double mass) {
this.mass = mass;
}
public double getMass() {
return mass;
}
}
public static void main(String[] args) {
for (Planet p : Planet.values()) {
System.out.println(p + " has mass " + p.getMass() + " x10^24 kg");
}
}
}
EARTH has mass 5.97 x10^24 kg
MARS has mass 0.642 x10^24 kg
JUPITER has mass 1898.0 x10^24 kg
values()
— Returns an array of all enum constants.valueOf(String)
— Converts a string to the corresponding enum constant.ordinal()
— Returns the position of the enum constant.enum Color {
RED, GREEN, BLUE
}
public class EnumMethods {
public static void main(String[] args) {
Color c = Color.valueOf("GREEN");
System.out.println(c); // Output: GREEN
System.out.println(c.ordinal()); // Output: 1
for (Color color : Color.values()) {
System.out.println(color);
}
}
}
GREEN
1
RED
GREEN
BLUE
⬅ Previous Topic
Java else KeywordNext Topic ⮕
Java extends KeywordYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.