Java Enums (short for enumerated types) are a type of data type that consists of a fixed set of predefined constants or values. Each of these values represents a distinct and specific member of the enum type. In Java, enums are defined using the enum
keyword.
Here is an example of how to define an enum in Java:
public enum Season { SPRING, SUMMER, FALL, WINTER }
In this example, the Season
enum has four values: SPRING
, SUMMER
, FALL
, and WINTER
. You can use these values in your code just like any other variable:
Season currentSeason = Season.SPRING;
Enums in Java are useful when you need to represent a fixed set of values that don’t change. They can help make your code more readable and self-documenting by using descriptive names for values. Enums can also be used in switch statements, which can make your code more concise and easier to read.
Points to remember for Java Enum:
Here are some important points to remember when working with Java Enums:
- Enums are a type of data type in Java that represent a fixed set of predefined values.
- Enums are defined using the
enum
keyword in Java. - Each value in an enum is an instance of the enum type.
- Enums can have constructors, methods, and instance variables just like any other Java class.
- Enums can be used in switch statements, which can make your code more concise and easier to read.
- The
values()
method of an enum returns an array of all the values in the enum. - You can access the name of an enum value using the
name()
method, and you can get the ordinal (position) of an enum value using theordinal()
method. - Enums can be used in Java annotations.
- Enums can implement interfaces in Java.
- It’s common to use all capital letters for the names of values in an enum to distinguish them from regular variables.
Simple Example of Java Enum:
Sure, here is a simple example of a Java enum:
public enum DayOfWeek { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
In this example, we’ve defined an enum named DayOfWeek
with seven values representing the days of the week. Each value is simply a named constant of the DayOfWeek
type.
We can use this enum in our code like this:
public class Main { public static void main(String[] args) { DayOfWeek today = DayOfWeek.MONDAY; System.out.println("Today is " + today); System.out.println("Tomorrow is " + DayOfWeek.TUESDAY); } }
In this example, we’ve declared a variable named today
of type DayOfWeek
and initialized it to the MONDAY
value. We’ve then used the println()
method to output the current day and the next day using the TUESDAY
value directly. The output of this code would be:
Today is MONDAY Tomorrow is TUESDAY
This is just a simple example, but enums can be used for many purposes in Java to represent a fixed set of related values.
What is the purpose of the values() method in the enum?
The values()
method in Java enums is a built-in method that returns an array of all the values defined in the enum. It is a convenient way to iterate over all the values of an enum, or to perform operations on all the values.
Here’s an example of how you might use the values()
method to loop through all the values of an enum:
public enum Fruit { APPLE, BANANA, ORANGE, PINEAPPLE } public class Main { public static void main(String[] args) { for (Fruit fruit : Fruit.values()) { System.out.println(fruit); } } }
In this example, we’ve defined an enum named Fruit
with four values representing different types of fruit. We’ve then used the values()
method in a for
loop to iterate over all the values of the Fruit
enum and print them out to the console.
The output of this code would be:
APPLE BANANA ORANGE PINEAPPLE
Note that the values()
method returns an array of the enum type, so you can use it to perform operations on all the values of the enum, such as sorting them, filtering them, or passing them as arguments to a method.
What is the purpose of the valueOf() method in the enum?
The valueOf()
method in Java enums is a built-in method that is used to convert a string into an enum constant. It is the opposite of the name()
method, which returns the name of an enum constant as a string.
Here’s an example of how you might use the valueOf()
method to convert a string into an enum constant:
public enum DayOfWeek { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } public class Main { public static void main(String[] args) { String input = "MONDAY"; DayOfWeek day = DayOfWeek.valueOf(input); System.out.println(day); } }
In this example, we’ve defined an enum named DayOfWeek
with seven values representing the days of the week. We’ve then used the valueOf()
method to convert the string “MONDAY” into the MONDAY
enum constant, and assigned it to a variable named day
. We’ve then used the println()
method to output the value of day
.
The output of this code would be:
MONDAY
It’s important to note that the valueOf()
method is case-sensitive and will throw an IllegalArgumentException
if the specified string does not match any of the enum constants. To avoid this, you should always use the name of the enum constant exactly as it is defined in the enum, including its case.
Defining Java Enum:
In Java, you can define an enum using the enum
keyword, followed by a list of comma-separated values, as shown in the following example:
public enum DayOfWeek { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
In this example, we’ve defined an enum named DayOfWeek
with seven values representing the days of the week. Each value is simply a named constant of the DayOfWeek
type.
Enums can also have constructors, methods, and instance variables just like any other Java class. Here’s an example of how you might define an enum with a constructor:
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), JUPITER(1.9e+27, 7.1492e7), SATURN(5.688e+26, 6.0268e7), URANUS(8.686e+25, 2.5559e7), NEPTUNE(1.024e+26, 2.4746e7); private final double mass; // in kilograms private final double radius; // in meters Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } public double getMass() { return mass; } public double getRadius() { return radius; } public double surfaceGravity() { return G * mass / (radius * radius); } private static final double G = 6.67300E-11; // universal gravitational constant }
In this example, we’ve defined an enum named Planet
with eight values representing the planets in our solar system. Each value has two instance variables: mass
and radius
, which are set by a constructor that takes these values as parameters. The enum also has methods for getting the mass, radius, and surface gravity of each planet. Finally, the enum has a private static constant G
, which is the universal gravitational constant.
Enums are a useful way to define a fixed set of related values in your Java code. They can make your code more readable and easier to maintain by ensuring that the values you use are always consistent and well-defined.
Java Enum Example: Defined outside class
In Java, you can define an enum outside of a class, just like you can define a class outside of a class. Here’s an example of how you might define an enum outside of a class:
enum Color { RED, GREEN, BLUE } public class Main { public static void main(String[] args) { Color c1 = Color.RED; Color c2 = Color.GREEN; Color c3 = Color.BLUE; System.out.println(c1); System.out.println(c2); System.out.println(c3); } }
In this example, we’ve defined an enum named Color
with three values representing the primary colors. We’ve then defined a Main
class with a main()
method that creates three instances of the Color
enum and prints them to the console.
When you define an enum outside of a class, it’s still a type that you can use in your code just like any other class or interface. You can import it using a static import statement, just like you would with a class or interface, and you can use it to declare variables, create instances, and pass values between methods.
Defining an enum outside of a class can be useful if you have a set of related values that are used throughout your code, but that don’t necessarily belong to any particular class or interface. It can also make your code more modular and easier to maintain by separating your values into distinct, well-defined types.
Java Enum Example: Defined inside class:
In Java, you can also define an enum inside of a class. Here’s an example of how you might define an enum inside of a class:
public class Main { enum Color { RED, GREEN, BLUE } public static void main(String[] args) { Color c1 = Color.RED; Color c2 = Color.GREEN; Color c3 = Color.BLUE; System.out.println(c1); System.out.println(c2); System.out.println(c3); } }
In this example, we’ve defined an enum named Color
inside of the Main
class. We’ve then defined a main()
method that creates three instances of the Color
enum and prints them to the console.
When you define an enum inside of a class, it’s still a type that you can use in your code just like any other class or interface. However, it’s only accessible within the scope of the enclosing class, so you can’t use it outside of that class. If you want to use the enum in another class, you’ll need to either define it outside of a class or make the enclosing class public and import it from another class.
Defining an enum inside of a class can be useful if you have a set of related values that are only used within that class, and that you don’t want to expose to other parts of your code. It can also help you organize your code by keeping related values together in a single class.
Java Enum Example: main method inside Enum
In Java, it’s not possible to define a main()
method inside an enum, as the main()
method is a special method that must be defined inside a class.
However, you can define methods inside an enum, including a factory method that creates instances of the enum based on some input. Here’s an example:
enum Color { RED, GREEN, BLUE; public static Color fromString(String value) { for (Color color : Color.values()) { if (color.name().equalsIgnoreCase(value)) { return color; } } throw new IllegalArgumentException("Invalid color value: " + value); } } public class Main { public static void main(String[] args) { Color c1 = Color.RED; Color c2 = Color.fromString("green"); System.out.println(c1); System.out.println(c2); } }
In this example, we’ve defined an enum named Color
with three values representing the primary colors. We’ve also defined a static fromString()
method that takes a String
argument and returns an instance of the Color
enum that matches the string. We’ve then defined a Main
class with a main()
method that creates two instances of the Color
enum using both the enum values and the factory method.
When you define a method inside an enum, it becomes a member of that enum and can be called using the dot notation, just like any other member of the enum. This can be useful for adding behavior to your enums or for creating factory methods that create instances of the enum based on some input.
Initializing specific values to the enum constants:
In Java, you can initialize specific values to the constants of an enum using a constructor. Here’s an example:
enum Color { RED("FF0000"), GREEN("00FF00"), BLUE("0000FF"); private final String hexCode; private Color(String hexCode) { this.hexCode = hexCode; } public String getHexCode() { return hexCode; } } public class Main { public static void main(String[] args) { Color c1 = Color.RED; Color c2 = Color.GREEN; Color c3 = Color.BLUE; System.out.println(c1.getHexCode()); System.out.println(c2.getHexCode()); System.out.println(c3.getHexCode()); } }
In this example, we’ve defined an enum named Color
with three values representing the primary colors. We’ve also defined a constructor that takes a String
argument and assigns it to the hexCode
field of each enum constant. We’ve then defined a getHexCode()
method that returns the hexCode
value of each constant.
When you initialize specific values to the constants of an enum, you can access them using methods or fields defined within the enum. This can be useful for associating data with each constant, such as color values or other attributes.
Note that if you define a constructor for an enum, you must use that constructor to initialize each constant of the enum. You can’t use the default constructor or any other constructor to create instances of the enum.
Example of specifying initial value to the enum constants:
Here’s an example of specifying initial values to the constants of an enum using a constructor:
public enum Size { SMALL("S", 18, 28), MEDIUM("M", 20, 30), LARGE("L", 22, 32), XLARGE("XL", 24, 34); private final String sizeCode; private final int width; private final int length; private Size(String sizeCode, int width, int length) { this.sizeCode = sizeCode; this.width = width; this.length = length; } public String getSizeCode() { return sizeCode; } public int getWidth() { return width; } public int getLength() { return length; } }
In this example, we’ve defined an enum named Size
with four values representing different clothing sizes. Each constant of the enum has a sizeCode
, width
, and length
associated with it, which are initialized using a constructor.
When you create an instance of the Size
enum, you can access the initial values using the methods defined within the enum, such as getSizeCode()
, getWidth()
, and getLength()
. Here’s an example of how you might use the Size
enum:
public class Main { public static void main(String[] args) { Size s1 = Size.SMALL; Size s2 = Size.MEDIUM; System.out.println(s1.getSizeCode() + ": " + s1.getWidth() + " x " + s1.getLength()); System.out.println(s2.getSizeCode() + ": " + s2.getWidth() + " x " + s2.getLength()); } }
In this example, we’ve created two instances of the Size
enum (s1
and s2
) and printed their sizeCode
, width
, and length
values to the console.
Specifying initial values to the constants of an enum using a constructor can be useful for associating data with each constant, such as size values, color values, or other attributes. It can also help make your code more readable and maintainable by giving each constant a meaningful name and set of associated values.
Internal code generated by the compiler for the above example of enum type:
When you define an enum type in Java, the compiler generates several pieces of internal code to support the enum’s behavior. Here’s an overview of what the compiler does for the example enum type Size
:
- The compiler creates a class named
Size
that extends theEnum
class. This class is generated automatically and contains the constants, constructors, and methods that you define in your enum type. - The compiler generates a private constructor for the
Size
class that takes one or more arguments, depending on how you initialize your enum constants. This constructor is used to create instances of theSize
class, which represent the constants of the enum type. - The compiler generates a static initialization block for the
Size
class that initializes the constants of the enum type. This block is executed when theSize
class is loaded into memory, and it creates instances of theSize
class for each constant defined in the enum type. - The compiler generates a
values()
method for theSize
class that returns an array of all the constants defined in the enum type. This method can be used to iterate over the constants of the enum type or to perform other operations on them. - The compiler generates a
valueOf()
method for theSize
class that takes aString
argument and returns the constant with the specified name. This method is used to convertString
values to enum constants, such as when parsing user input or reading data from a file. - The compiler generates a
toString()
method for theSize
class that returns aString
representation of the constant. By default, this method returns the name of the constant, but you can override it to provide a custom string representation.
These are just some of the internal code elements that the compiler generates for enum types in Java. By automating much of the boilerplate code involved in defining enums, the compiler makes it easier to create and use enum types in your Java programs.
Java Enum in a switch statement:
In Java, you can use an enum type in a switch statement to perform different actions based on the value of the enum. Here’s an example:
public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; } public class Main { public static void main(String[] args) { Day day = Day.MONDAY; switch (day) { case MONDAY: System.out.println("It's Monday!"); break; case TUESDAY: System.out.println("It's Tuesday!"); break; case WEDNESDAY: System.out.println("It's Wednesday!"); break; case THURSDAY: System.out.println("It's Thursday!"); break; case FRIDAY: System.out.println("It's Friday!"); break; case SATURDAY: case SUNDAY: System.out.println("It's the weekend!"); break; default: System.out.println("Invalid day!"); } } }
In this example, we have an enum type named Day
with seven values representing the days of the week. We then use a switch statement to perform different actions based on the value of the day
variable, which is set to Day.MONDAY
. If day
is equal to Day.MONDAY
, we print “It’s Monday!” to the console. Similarly, if day
is equal to any of the other days of the week, we print a corresponding message. If day
is equal to Day.SATURDAY
or Day.SUNDAY
, we print “It’s the weekend!” instead.
Note that we’ve used the break
keyword to terminate each case block in the switch statement. This is necessary to prevent the program from falling through to the next case block and executing it as well. If we didn’t include break
statements, the program would print multiple messages instead of just one.
Using an enum type in a switch statement can make your code more readable and maintainable, since it allows you to group related actions together based on the value of the enum. It can also help catch errors at compile-time, since the compiler will generate an error if you try to use an invalid enum value in a switch statement.