09.22. Enum in Java

Enum in Java

  • Eclipse: Oxygen
  • Java: 1.8

Enum is used to define a set of constants in java. Not only constant by it could also call any method, constructor associated with it. Which will be seen further in the tutorial.

We should always use enum when a variable (especially a method parameter) can only take one from a small set of possible values.

Enum is default public static hence we can directly reference variable by Enum Name.

You can define an enum type either independently or as part of a class. The code to define an enum independently is:

This is an example to demonstrate the use of enums in switch-case statements.

Here we have a variable Learning of enum type, which is a collection of five constants COREJAVA, COLLECTIONS, GENERICS, JSPANDSERVLETS, MULTITHREADING.

The variable learn is a type of Learning (that is an enum type). This variable can take any value, out of the possible five values (COREJAVA, COLLECTIONS, GENERICS, JSPANDSERVLETS, MULTITHREADING). In this case, it is set to COREJAVA.

Output

Step 1: learning Core Java

The above concept is explained that enum can be used for more than one purpose, by the assignment of numbers to the enums and then access it by calling the original function.

Output

Step 1 : learning Core Java

0

1

2

3

4

Contributed by Poonam Tomar

 

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments