Full Stack Web Development Internship Program
- 29k Enrolled Learners
- Weekend/Weekday
- Live Class
The Enumeration in Java is a way of defining a class with fixed and named constants with their respective datatypes using the keyword enum. In this “Java Enum Tutorial” article, we will learn to define Enumeration along with examples for a better understanding.
Java Enums are classes that have a fixed set of constants or variables that do not tend to change. The enumeration in Java is achieved using the keyword enum. The Java enum constants are static and final implicitly. The Enum feature is available since JDK version 1.5.
enum improves type safety at compile-time checking to avoid errors at run-time by avoiding boilerplate code. For example, if you have to select one possibility out of the least number of available options, say,
Job Type: (Contract / Temporary / Permanent)
Then the best option would be using an enum. Because enum can be easily used in the switch. enum can be traversed. enum can have fields, constructors and methods. Hence, it increases compile-time checking and avoids errors due to passing in invalid constants, as you have already documented which values are legal to be used.
Though a class and enum have similar functionality in Java environment, they differ in a few aspects. Let us discuss the differences
Now, to understand enum in a much better way, let us execute some practical examples based on the following.
Defining Enumeration in Java
Enum can be declared either inside a class or outside a class. But, it cannot be declared inside any method. Let’s take a small example to understand its syntax, definition, and declaration.
Syntax:
enum name{constants;}
In this example, we have declared the main() method inside enum
package definition; public class Edureka { enum Level { BAJA, KTM, YAMAHA } public static void main(String[] args) { Level myVar = Level.KTM; System.out.println(myVar); } }
//Ouput
KTM
In this example, the main() method is declared outside of enum.
package definition; enum Color{ BAJAJ, KTM, YAMAHA; } public class Edureka{ public static void main(String[] args){ Bike b1 = Color.YAMAHA; System.out.println(b1); } }
//Output:
Enum used in Switch Case
Enumeration can be used in a switch statement as well. It is important that all the case statements must use constants from the same enum as used by the switch statement. Let us check an example based on this.
Here, we will declare an enum with days of the week as its elements and we shall pass the data in the form of a string to print the data of the matching case.
package switched; enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; } public class Edureka{ Day day; public Edureka(Day day){ this.day = day; } public void dayIsLike(){ switch (day){ case MONDAY: System.out.println("Hi, Today is Monday"); break; case TUESDAY: System.out.println("Hi, Today is Tuesday"); break; case WEDNESDAY: System.out.println("Hi, Today is Wednesday"); break; case THURSDAY: System.out.println("Hi, Today is Thursday"); break; case FRIDAY: System.out.println("Hello, Today is Friday."); break; case SATURDAY: System.out.println("Hi, Today is your Weekend"); break; case SUNDAY: System.out.println("Hi, Today is a Holiday"); break; default: System.out.println("Please enter a valid day."); break; } } public static void main(String[] args){ String str = "MONDAY"; Edureka e1 = new Edureka(Day.valueOf(str)); e1.dayIsLike(); } }
//Output:
Inheritance using enum
Basically, any enum is represented as a class that extends the abstract class java.lang.Enum and has several static members. Therefore, an enum cannot extend any other class or enum there is no multiple inheritances. Let us execute an example to understand it in a better way.
Here, we will inherit the OS based on the phone maker.
package inheritance; import java.util.ArrayList; import java.util.List; public class Edureka { public static void main(String[] args) { List<HTTPMethodConvertible> inherit = new ArrayList<>(); inherit.add(LibraryEnum.FIRST); inherit.add(ClientEnum.google); for (HTTPMethodConvertible element : inherit) { System.out.println(element.getHTTPMethodType()); } } static interface HTTPMethodConvertible { public String getHTTPMethodType(); } static enum LibraryEnum implements HTTPMethodConvertible { FIRST("Google Pixel"), SECOND("Huawei"), THIRD("Apple 11 Pro"); String httpMethodType; LibraryEnum(String phone) { httpMethodType = phone; } public String getHTTPMethodType() { return httpMethodType; } } static enum ClientEnum implements HTTPMethodConvertible { huawei("HongMing OS"), apple("iOS"), google("Android One"); String httpMethodType; ClientEnum(String s) { httpMethodType = s; } public String getHTTPMethodType() { return httpMethodType; } } }
//Output:
Enum with customized values
Enums have their own string values by default, we can also assign some custom values to enums. Let us consider the below example.
enum Traffic { RED(“STOP”), ORANGE(“WAIT”), GREEN(“GO”); }
In the above example, we can see that Traffic enum have three members. Namely,
RED, ORANGE and GREEN with have their own different custom values STOP, WAIT and GO respectively.
Now to use the same type of enum in code we are expected to follow some points that are:
Let us execute a program based on this.
package traffic; enum TrafficSignal { RED("STOP"), GREEN("GO"), ORANGE("WAIT"); private String action; public String getAction() { return this.action; } private TrafficSignal(String action) { this.action = action; } } public class Edureka { public static void main(String args[]) { TrafficSignal[] signals = TrafficSignal.values(); for (TrafficSignal signal : signals) { System.out.println("name : " + signal.name() + " action: " + signal.getAction()); } } }
//Output:
name: RED action: STOP
name: GREEN action: GO
name: ORANGE action: WAIT
Enum in if-else-if statements
Now, let us execute a program based on enum in if-else-if statements. Here, we will find the direction of traversal by passing the values of directions available in the enum.
package Directions; enum Directions { EAST, WEST, NORTH, SOUTH } public class Edureka { public static void main(String args[]) { Directions dir = Directions.NORTH; if (dir == Directions.EAST) { System.out.println("Direction: East"); } else if (dir == Directions.WEST) { System.out.println("Direction: West"); } else if (dir == Directions.NORTH) { System.out.println("Direction: North"); } else { System.out.println("Direction: South"); } } }
//Output:
Different methods used with enum
Values(): When you create an enum, the Java compiler internally adds the values() method. This method returns an array containing all the values of the enum.
//Syntax:
public static enum-type[ ] values()
We will find out the index value of a particular element in an array.
package values; enum Color { RED, GREEN, BLUE; } public class Edureka { public static void main(String[] args) { Color arr[] = Color.values(); for (Color col : arr) { System.out.println(col + " at index " + col.ordinal()); } System.out.println(Color.valueOf("RED")); } }
//Output:
RED at index 0
GREEN at index 1
BLUE at index 2
RED
ValueOf(): This method is used to return the enumeration constant whose value is equal to the string passed as an argument while calling this method.
//Syntax:
public static enum-type valueOf (String str)
Here, we will find the cost of a particular phone based on the input we pass to the string.
package valuesof; enum Mobile { Samsung(1099), Apple(1250), Google(1325); int price; Mobile(int p) { price = p; } int showPrice() { return price; } } public class Edureka { public static void main(String args[]) { System.out.println("CellPhone List:"); for (Mobile m : Mobile.values()) { System.out.println(m + " costs " + m.showPrice() + " dollars"); } Mobile ret; ret = Mobile.valueOf("Samsung"); System.out.println("Selected : " + ret); } }
//Output:
Samsung costs 1099 dollars
Apple costs 1250 dollars
Google costs 1325 dollars
Selected: Samsung
Ordinal(): The Java interpreter adds the ordinal() method internally when it creates an enum. The ordinal() method returns the index of the enum value.
//Syntax:
public final int ordinal()
Here, we will find out the index value of a particular element in an array. and also, the position of the cherry fruit.
Package ordinal; enum Fruits { Apple, Banana, Cherry, Date, Elderberry } enum Vegetables { Carrot, Beetroot, Beans, Tomato, Onion } public class Edureka { public static void main(String[] args) { Fruits[] fru = Fruits.values(); for(Fruits fr : fru){ System.out.println(fr+" : "+fr.ordinal()); } Fruits f1,f2,f3; f1 = Fruits.Apple; f2 = Fruits.Cherry; f3 = Fruits.Apple; if(f2.compareTo(f1) > 0){ System.out.println(f2+" comes after "+f1); } Vegetables v1 = Vegetables.Beetroot; if(f1.equals(v1)){ System.out.println("Incorrect"); } } }
//Output:
Apple : 0
Banana : 1
Cherry : 2
Date : 3
Elderberry : 4
Cherry comes after Apple
We will use enum in Java to create our childhood game, the rock(stone) paper and scissors. The following code explains how.
package Edureka; import java.util.Random; import java.util.Scanner; enum HandSign { SCISSOR, PAPER, STONE } public class SPS { public static void main(String[] args) { Random random = new Random(); boolean gameOver = false; HandSign playerMove = HandSign.SCISSOR; HandSign computerMove; int numTrials = 0; int numComputerWon = 0; int numPlayerWon = 0; int numTie = 0; Scanner in = new Scanner(System.in); System.out.println("nLet us begin...n"); while (!gameOver) { System.out.printf("%nScissor-Paper-Stonen"); boolean validInput; do { System.out.print("nYour turn (Please Enter s for a scissor, p for paper, t for stone, q to quit): n"); char inChar = in.next().toLowerCase().charAt(0); validInput = true; if (inChar == 'q') { gameOver = true; } else if (inChar == 's') { playerMove = HandSign.SCISSOR; } else if (inChar == 'p') { playerMove = HandSign.PAPER; } else if (inChar == 't') { playerMove = HandSign.STONE; } else{ System.out.println("nPlease check the input and try again!n"); validInput = false; } } while (!validInput); if (!gameOver) { int aRandomNumber = random.nextInt(3); if (aRandomNumber == 0) { computerMove = HandSign.SCISSOR; System.out.println("nIt's My turn: SCISSORn"); } else if (aRandomNumber == 0) { computerMove = HandSign.PAPER; System.out.println("nIt's My turn: PAPERn"); } else { computerMove = HandSign.STONE; System.out.println("nIt's My turn: STONEn"); } if (computerMove == playerMove) { System.out.println("nIt's a Tie!n"); ++numTie; } else if (computerMove == HandSign.SCISSOR && playerMove == HandSign.PAPER) { System.out.println("nScissor cuts paper, I won!n"); ++numComputerWon; } else if (computerMove == HandSign.PAPER && playerMove == HandSign.STONE) { System.out.println("nPaper wraps stone, I won!n"); ++numComputerWon; } else if (computerMove == HandSign.STONE && playerMove == HandSign.SCISSOR) { System.out.println("nStone breaks scissor, I won!n"); ++numComputerWon; } else { System.out.println("nCongratulations...! You won!n"); ++numPlayerWon; } ++numTrials; } } System.out.printf("%nThe number of trials: " + numTrials); System.out.printf("I won %d(%.2f%%). You won %d(%.2f%%).%n", numComputerWon, 100.0 * numComputerWon / numTrials, numPlayerWon, 100.0 * numPlayerWon / numTrials); System.out.println("Bye!, Hope you enjoyed..!"); } }
//Output:
Let us begin...
Scissor-Paper-Stone
Your turn (Please Enter s for a scissor, p for paper, t for stone, q to quit):
s
It's My turn: STONE
Stone breaks scissor, I won!
Scissor-Paper-Stone
Your turn (Please Enter s for a scissor, p for paper, t for stone, q to quit):
q
The number of trials: 1I won 1(100.00%). You won 0(0.00%).
Bye!, Hope you enjoyed..!
With this, we come to an end of this Java Enum Tutorial. I hope you have understood the Enum in Java and its implementation through some real-time examples.
Now that you have understood enum basics through this “Java Enum Tutorial” check out the Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification courses are designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.
Got a question for us? Mention it in the comments section of this “Java Enum Tutorial” blog and we will get back to you as soon as possible.
Course Name | Date | Details |
---|---|---|
Java Course Online | Class Starts on 1st March,2025 1st March SAT&SUN (Weekend Batch) | View Details |
edureka.co