+3 votes
57 views
in Tips & Tricks by (242k points)
reopened
Java enums - this is how it works

1 Answer

+4 votes
by (1.6m points)
 
Best answer

Define an enum type
Create an enum variable
Application example

Java enums are variable types with fixed value options. They are used for legibility and the logical structure of your code..

image image

With enums (short for enumeration, in German: Aufzählung), Java offers you, the programmer, the option of defining predefined constants for your variables. This is particularly useful when a variable only has a small number of states that can be named. This can be, for example, playing cards (clubs, spades, hearts, diamonds) or the name of the day of the week.

Define an enum type

You define an enum for weekdays with the following syntax: WeekDay is the identifier of the enum . This name will later also 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 assume. Alternatively, you can also choose any other assignment for your variables. For the playing cards example above, you would use the following syntax:

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




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

Create an enum variable

How to declare a variable of type WeekDay and assign it a value.

WeekDay day = WeekDay.MONDAY;


WeekDay
is now the keyword for the enum type we just created . If the variable is output on the console in this way, the string " MONDAY " appears on the console.

System.out.println(day);

Application example

The day variable can also be compared in logical expressions. For example, you can now query the day of the week in a switch construction: The output of the code changes depending on the state of the day variable.

String message = "";

WeekDay day = WeekDay.FRIDAY;
switch(day)
{
case MONDAY:
case TUESDAY:
case WEDNESDAY:

message = "Kopf hoch, die Woche hat gerade erst angefangen."
;
break;

case THURSDAY:
case FRIDAY:
message = "Bald ist das Wochenende da!"
;
break;

case SATURDAY:
case SUNDAY:
message = "Endlich Wochenende!";
}
System.out.println(message);


...