TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVA

Java Enum Examples

Use enums to store constants and improve compiler checking. Pass enums to methods.
Enum. This stores a list of values. Each value is given a name. We use enums, and their values, throughout a program. We identify concepts and clarify code.
Magic constants. We use these values to store magic constants. Suppose a program uses the value 1 to mean Medium. An enum can represent this.
A program. I show an enum called Importance. The enum has 3 constants: Low, Medium and High. We create a variable of Importance type and initialize it to Medium.

Then: In the if-statement, we test the values of Importance. For Low, we display 1. For Medium and High, we display 2 or 3.

If

Result: It matches Importance.Medium, so the value 2 is written to the console. We use System.out.println for this function.

Console
Java program that uses enum public class Program { enum Importance { Low, Medium, High } public static void main(String[] args) { // Create an Importance variable. Importance i = Importance.Medium; // Test the Importance. if (i == Importance.Low) { System.out.println("1"); } else if (i == Importance.Medium) { System.out.println("2"); } else if (i == Importance.High) { System.out.println("3"); } } } Output 2
Method, switch. We pass an enum to a method: it is received by the name of the enum type, Size. And we use a switch on an enum value. We must specify only the "unqualified" constants.

Qualified: Sometimes we use qualified constants, which include the enum type. An example of this syntax is "Size.Small."

Unqualified: In a switch, though, we must use unqualified constants. An example of this form is "Small."

Switch
Java program that uses method, switch public class Program { enum Size { Small, Medium, Large } static void test(Size size) { // Switch on the enum value. switch (size) { case Small: System.out.println("?"); return; case Medium: System.out.println("Is medium size"); return; case Large: System.out.println("!"); return; } } public static void main(String[] args) { // Call method and pass enum value to it. test(Size.Medium); } } Output Is medium size
Qualified case error. If we try to add a qualified case label to a switch, such as Size.Small, we get an error. This is a compile-time error. We can use it to improve program quality.

Tip: With unqualified enum constants in a switch, we reduce code size and make code easier to read.

Qualified case label error The qualified case label Program.Size.Small must be replaced with the unqualified enum constant Small
Null. An enum can be null. When an enum (like Color in this program) is a field of a class, it is by default set to null. It is not initialized to a value in the enum. It has no value.

Tip: We demonstrate a null-initialized static field here. A static field is just like an instance one, except it is tied to no instance.

Static
Java program that shows null enum public class Program { enum Color { Default, Red, Green, Blue } static Color c; public static void main(String[] args) { // An enum field is null by default. if (c == null) { System.out.println("Is null!"); } // We can assign a null enum variable to a value. c = Color.Red; System.out.println(c); } } Output Is null! Red
Array, enums. As with a class, we can create an array of enums. Here, I create a three-element array of Language enums. I use the Language.Java (a good choice) enum and a "null" constant.Array
Java program that uses enum array public class Program { enum Language { Java, Python, Ruby } public static void main(String[] args) { // ... Create a three-element array. Language[] lang = new Language[3]; lang[0] = Language.Java; lang[1] = null; lang[2] = Language.Python; System.out.println(lang[0]); } } Output Java
ArrayList, enums. An enum type can be used just like a class. In an ArrayList, for example, we can use the enum as the element type—and then loop over individual enums.ArrayList

Note: An enum can be used as a key type in a HashMap, but the customized EnumMap is faster for this situation.

Java program that uses ArrayList, enums import java.util.ArrayList; public class Program { enum Density { Low, Medium, High } public static void main(String[] args) { // Add enums to an ArrayList. ArrayList<Density> list = new ArrayList<>(); list.add(Density.Medium); list.add(Density.High); // ... Display enums. for (Density value : list) { System.out.println(value); } } } Output Medium High
Name, ordinal. An enum provides the name() and ordinal() methods. The result of name() is the same as toString: it returns a string with the unqualified enum name (like "Image").

Ordinal: This returns the enum value's index within the enum. The first entry has an ordinal of 0 and the second has an ordinal of 1.

Java program that uses name, ordinal enum DataCode { Image, Text, Combination } public class Program { static void test(DataCode code) { // Write name and ordinal of these enums. System.out.println(code.name()); System.out.println(code.ordinal()); } public static void main(String[] args) { // Call the test method. test(DataCode.Image); test(DataCode.Text); test(DataCode.Combination); } } Output Image 0 Text 1 Combination 2
EnumMap. Sometimes we need to do lookups based on enum values. With an EnumMap, this operation is optimized. In constant time we can look up values based on enum keys.EnumMap
Enums are useful throughout Java programs. They identify concepts and behaviors—such as an object's Importance. They also store magic constants, like numeric codes and values.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf