December 29, 2020 Here's a quick summary of how to work with enums in Java using enums.
A type that can combine multiple constants into one. Handles data that cannot be changed later because it is a constant. The ennum type has the advantage that multiple constants can be grouped together.
The ~~ enum type has the advantage of making switch statements easier to handle. ~~ → Since the branch is completed when the instance of enum is acquired, it is good to give the process and value that you want to branch with the switch to the enum itself.
The enum type is described as follows.
Basic writing
enum enum{Enumerator 1,Enumerator 2,・ ・ ・};
//When retrieving an enum
Enumeration name.Data you want to get
Sample code
public class Sample {
public static void main(String[] args) {
//Get Name and output only Tanaka data in it
Name name = Name.Tanaka;
System.out.println(name);
}
//Define enum Name
protected enum Name {
Tanaka,
Sato,
Kimura
};
}
Execution result
Tanaka
public class Sample {
public static void main(String[] args) {
Name name = Name.Tanaka;
switch(name) {
case Tanaka:
System.out.println("Tanaka");
break;
case Sato:
System.out.println("Sato");
break;
case Kimura:
System.out.println("Kimura");
break;
}
}
protected enum Name {
Tanaka,
Sato,
Kimura
};
}
Execution result
Tanaka
[For beginners] Explain Java Enum types! Introducing basic methods! How to use enums with enum in Java [for beginners]
Recommended Posts