Java enumeration class

With enums (short for enumeration) Java offers you as a programmer the possibility to define predefined constants for your variables. This is particularly useful when a variable has only a small number of states that can be named. This can be java enum class example :playing cards (clubs, spades, hearts, diamonds) or the name of the day of the week.

Define a java enum class type

Create a java enum variable

Application example

Define an enum type:

You define a java enum for days of the week using the following syntax:

public enum WeekDay
{
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

WeekDay is the identifier of the enum here. This name will later be used to declare variables of this type. The days of the week MONDAY, TUESDAY, … are the possible values ​​that a variable of the type WeekDay can take. Alternatively, you can choose any other assignment for your java enum variables. For the above example of playing cards, you would use the following syntax:

public enum cards
{
CLUBS, SPADES, HEARTS, DIAMONDS
}

Create a java enum variable:
How to declare a WeekDay variable and assign a value to it.

WeekDay day = WeekDay.MONDAY;

WeekDay is now the key word for the enum type you just created.

System.out.println (day);

If the variable is output on the console, the string “MONDAY” appears on the console.

Application example:
The variable day can also be compared in logical expressions. For example, you can now query the day of the week in a switch construction:

String message = “”;
WeekDay day = WeekDay.FRIDAY;
switch (day)
{
case MONDAY:
case TUESDAY:
case WEDNESDAY:
message = “Head up, the week has just started.”;
break;

case THURSDAY:
case FRIDAY:
message = “The weekend will be here soon!”;
break;

case SATURDAY:
case SUNDAY:
message = “Finally weekend!”;
}
System.out.println (message);

The output of the code changes depending on the state of the day variable.

اترك تعليقاً

لن يتم نشر عنوان بريدك الإلكتروني. الحقول الإلزامية مشار إليها بـ *

جميع الحقوق محفوظة لموقع كيفاش 2024