Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
25 views

Enum in Java

enum data type in c language

Uploaded by

rajput.patial
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Enum in Java

enum data type in c language

Uploaded by

rajput.patial
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

enum in Java

Last Updated : 05 Sep, 2024



In Java,Enumerations or Java Enum serve the purpose of representing a


group of named constants in a programming language. Java Enums are used
when we know all possible values at compile time, such as choices on a
menu, rounding modes, command-line flags, etc.

What is Enumeration or Enum in Java?

A Java enumeration is a class type. Although we don’t need to instantiate an


enum using new, it has the same capabilities as other classes. This fact
makes Java enumeration a very powerful tool. Just like classes, you can give
them constructors, add instance variables and methods, and even implement
interfaces.

Enum Example:

The 4 suits in a deck of playing cards may be 4 enumerators named Club,


Diamond, Heart, and Spade, belonging to an enumerated type named Suit.
Other examples include natural enumerated types (like the planets, days of
the week, colors, directions, etc.).

One thing to keep in mind is that, unlike classes, enumerations neither inherit
other classes nor can get extended(i.e become superclass). We can also add
variables, methods, and constructors to it. The main objective of an enum is to
define our own data types(Enumerated Data Types).

Declaration of enum in Java

Enum declaration can be done outside a class or inside a class but not inside
a method.

1. Declaration outside the class

Java
// A simple enum example where enum is declared
// outside any class (Note enum keyword instead of
// class keyword)
enum Color {
RED,
GREEN,
BLUE;
}

public class Test {


// Driver method
public static void main(String[] args) {
Color c1 = Color.RED;
System.out.println(c1);
}
}

Output
RED

2. Declaration inside a class


Java
// enum declaration inside a class.
public class Test {
enum Color {
RED,
GREEN,
BLUE;
}

// Driver method
public static void main(String[] args) {
Color c1 = Color.RED;
System.out.println(c1);
}
}

Output
RED

● The first line inside the enum should be a list of constants and then
other things like methods, variables, and constructors.
● According to Java naming conventions, it is recommended that we
name constant with all capital letters

Properties of Enum in Java

There are certain properties followed by Enum as mentioned below:

● Class Type: Every enum is internally implemented using the Class


type.
● Enum Constants: Each enum constant represents an object of type
enum.
● Switch Statements: Enum types can be used in switch statements.
● Implicit Modifiers: Every enum constant is implicitly public static
final. Since it is static, it can be accessed using the enum name.
Since it is final, enums cannot be extended.
● Main Method: Enums can declare a main() method, allowing direct
invocation from the command line.

Below is the implementation of the above properties:

Java
// A Java program to demonstrate working on enum
// in a switch case (Filename Test.java)

import java.util.Scanner;

// An Enum class
enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
}

// Driver class that contains an object of "day" and


// main().
public class Test {
Day day;

// Constructor
public Test(Day day) {
this.day = day;
}

// Prints a line about Day using switch


public void dayIsLike() {
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;
}
}

// Driver method
public static void main(String[] args) {
String str = "MONDAY";
Test t1 = new Test(Day.valueOf(str));
t1.dayIsLike();
}
}

Output
Mondays are bad.

Java Enum Programs

1. Main Function Inside Enum

Enums can have a main function, allowing them to be invoked directly from the
command line.

Below is the implementation of the above property:


Java
// A Java program to demonstrate that we can have
// main() inside enum class.

public enum Color {


RED,
GREEN,
BLUE;

// Driver method
public static void main(String[] args) {
Color c1 = Color.RED;
System.out.println(c1);
}
}

Output

RED

The above program will not run on online compiler. To run this program, save
it as Color.java and use the java command to compile and execute.

2. Loop through Enum

We can iterate over the Enum using the values() method, which returns an
array of enum constants.

Below is the implementation of the loop through Enum:

Java
// Java Program to Print all the values
// inside the enum using for loop
import java.io.*;

// Enum Declared
enum Color {
RED,
GREEN,
BLUE;
}

// Driver Class
class GFG {

// Main Function
public static void main(String[] args) {
// Iterating over all the values in
// enum using for loop
for (Color var_1 : Color.values()) {
System.out.println(var_1);
}
}
}

Output
RED
GREEN
BLUE

3. Enum in a Switch Statement

Enums can be used in switch statements to handle different cases based on


the enum constants.

Java
// Java Program to implement
// Enum in a Switch Statement
import java.io.*;

// Driver Class
class GFG {
// Enum Declared
enum Color {
RED,
GREEN,
BLUE,
YELLOW;
}

// Main Function
public static void main(String[] args) {
Color var_1 = Color.YELLOW;

// Switch case with Enum


switch (var_1) {
case RED:
System.out.println("Red color observed");
break;
case GREEN:
System.out.println("Green color observed");
break;
case BLUE:
System.out.println("Blue color observed");
break;
default:
System.out.println("Other color observed");
}
}
}

Output
Other color observed

Enum and Inheritance


● All enums implicitly extend java.lang.Enum class. As a class can
only extend one parent in Java, an enum cannot extend anything
else.
● toString() method is overridden in java.lang.Enum class, which
returns enum constant name.
● enum can implement many interfaces.

Enum and Constructor

● Enums can contain constructors, which are called separately for


each enum constant at the time of enum class loading.
● We can’t create enum objects explicitly and hence we can’t invoke
the enum constructor directly.

Enum and Methods

Enums can have both concrete and abstract methods. If an enum class has
an abstract method, each enum constant must implement it.

Java
// Java program to demonstrate that enums can have
// constructor and concrete methods.

// An enum (Note enum keyword in place of class keyword)


enum Color {
RED,
GREEN,
BLUE;

// Enum constructor called separately for each


// constant
private Color() {
System.out.println("Constructor called for : " + this.toString());
}
public void colorInfo() {
System.out.println("Universal Color");
}
}

public class Test {


// Driver method
public static void main(String[] args) {
Color c1 = Color.RED;
System.out.println(c1);
c1.colorInfo();
}
}

Output
Constructor called for : RED
Constructor called for : GREEN
Constructor called for : BLUE
RED
Universal Color

Note: While the set of constants in a Java enum is fixed at runtime and
cannot be changed dynamically, you can modify the source code of the enum
to add or remove constants and then recompile the application to reflect these
changes.

Creating a Class with Enum Member

When combined with classes, enum can serve as powerful tool for organising
program.

Java
/*package whatever //do not write package name here */

import java.io.*;

enum Day {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}

public class EnumTest {


// Enum member variable
Day day;

// constructor which takes enum value


public EnumTest(Day day) { this.day = day; }

// method to execute action as per enum value


public void tellItLikeItIs()
{
switch (day) {
case MONDAY:
System.out.println("Mondays are tough");
break;
case TUESDAY:
System.out.println("Tuesday are better");
break;
case WEDNESDAY:
System.out.println("Wednesday are okay");
break;
case THURSDAY:
System.out.println("Thursdays are hopeful");
break;
case FRIDAY:
System.out.println("Fridays are exciting");
break;
case SATURDAY:
System.out.println("Saturdays are relaxing");
break;
case SUNDAY:
System.out.println("Sunday are for rest");
break;
default:
System.out.println("Everyday are good");
break;
}
}

public static void main(String[] args)


{
EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs();

EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);


thirdDay.tellItLikeItIs();

EnumTest fifthDay = new EnumTest(Day.FRIDAY);


fifthDay.tellItLikeItIs();

EnumTest sixthDay = new EnumTest(Day.SATURDAY);


sixthDay.tellItLikeItIs();

EnumTest seventhDay = new EnumTest(Day.SUNDAY);


seventhDay.tellItLikeItIs();
}
}

Output
Mondays are tough
Wednesday are okay
Fridays are exciting
Saturdays are relaxing
Sunday are for rest

The EnumTest class in above code is created with member of type Day. It has
constructor which takes Day enum as an argument and assigns it.

The class has method tellItLikeItIs(), which prints message based on value of
day.
The main method includes objects of EnumTest using different Day enum
values and calling tellItLikeItIs() method on each.

NOTE: In the main method new is used when creating instances of EnumTest
because EnumTest is a regular Java class not enum itself. So, the new
keyword is used to create new instance of EnumTest class, and passing enum
value to its constructor.

You might also like