What is enumeration string in java

enum in java

The enum in java is a special type of data types like Class and Interface. A Java enum is used to define collections of constants. It is also known as enumeration java. By the use of an enum, we can define a group of constants with all possible values at compile time. We can change the number of constants later and it doesn’t fit all time. Enum was introduced in JDK 1.5.

For example, we can use of enum in java to store the days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY). Because we know all the possible values at compile time. As per the naming conventions of the enum, all constants should be in capital letters.

Important points about enum

1. It is special data that is used to define a set of constants and the value of the constant defined at compile time.

2. All the constants of the enum are by default static and final. So, we can’t change the value of the constant. As constants are static so they are accessible by enum name.

3. A enum can have methods, constructors, and fields.

4. Java enums extend the Enum class that exists in java.lang package. The Enum class is an abstract class that implements a Comparable interface and serialize interface.

5. A enum can implements interfaces but can’t extend the class because it already internally extending the Enum class.

6. A enum can have numeric or string data constants.

How to create an enum

To create an enum we have to use an enum keyword like class keyword. It is the way to in java define enum.

enum in java

accessModifier, we can provide access modifiers according to to use like default, and public.
enum, it is a predefined keyword.
enumName, which is the name of the enum to declare.
constant, We can have any number of constants.
methods, We can have any number of methods.

Java enum example

Here you can see the enum keyword that is used in place of class or interface . The enum keyword indicates to the compiler that this type of definition is an enum.

How to use of enum

Suppose we have an enum Week that contains some constants. You can access any constant by using the enum name because all constants are static. Here is the syntax to access the constant.

You can refer to the constants in the enum above like this:

Week constantFromEnum = Week.MONDAY;
enum Week < SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; >public class EnumExample < public static void main(String arg[]) < // Getting a constant Week constantFromEnum = Week.MONDAY; System.out.println(constantFromEnum); >>

How to create Java enum methods and java enum constructor

We can create methods and constructors in an enum and use those methods to operate the constants of Enum.

Let’s see an example with a constructor and method. Here we are creating constants with an int code. So, we must provide a constructor that can take a parameter of int type otherwise compiler shows an error. This constructor internally involving by the compiler to set the code in constructors. Here we are creating a method that will return the code of each constant.

enum Week < SUNDAY(1), MONDAY(2), TUESDAY(3), WEDNESDAY(4), THURSDAY(5), FRIDAY(6), SATURDAY(7); private final int code; // Compiler internally invokes it to assign value Week(int code) < this.code = code; >public int getCode() < return code; >> public class EnumExample < public static void main(String arg[]) < // Getting a constant Week constantFromEnum = Week.MONDAY; System.out.println(constantFromEnum); System.out.println(constantFromEnum.getCode()); >>

How to use String in Java enum string value

We can use any type of value in enum constants. Let’s see the example with a string value.

enum Week < SUNDAY(1, "First day"), MONDAY(2, "Second day"), TUESDAY(3, "Third day"), WEDNESDAY(4, "Fourth day"), THURSDAY(5, "Fifth day"), FRIDAY(6, "Sixth day"), SATURDAY(7, "Seventh day"); private final int intCode; private final String stringCode; // Compiler internally invokes it to assign value Week(int intCode, String stringCode) < this.intCode = intCode; this.stringCode = stringCode; >public int getIntCode() < return intCode; >public String getStringCode() < return stringCode; >> public class EnumExample < public static void main(String arg[]) < // Getting a constant Week constantFromEnum = Week.MONDAY; System.out.println(constantFromEnum); System.out.println(constantFromEnum.getIntCode()); System.out.println(constantFromEnum.getStringCode()); >>

Methods of enum

Java enum class provides some predefined methods that are used to operate the values of an enum. Here we will discuss the most common method of the enum class.

Читайте также:  Сетчатый питон интересные факты

compareTo() method

The compareTo() method is used to compare the constants of an enum. It compares the constant based on ordinal values.

enum Week < SUNDAY(1, "First day"), MONDAY(2, "Second day"), TUESDAY(3, "Third day"), WEDNESDAY(4, "Fourth day"), THURSDAY(5, "Fifth day"), FRIDAY(6, "Sixth day"), SATURDAY(7, "Seventh day"); private final int intCode; private final String stringCode; // Compiler internally invokes it to assign value Week(int intCode, String stringCode) < this.intCode = intCode; this.stringCode = stringCode; >public int getIntCode() < return intCode; >public String getStringCode() < return stringCode; >> public class EnumExample < public static void main(String arg[]) < System.out.println(Week.SUNDAY.compareTo(Week.MONDAY)); >>

toString() method

The toString() method converts the name of an enum to a string.

enum Week < SUNDAY(1, "First day"), MONDAY(2, "Second day"), TUESDAY(3, "Third day"), WEDNESDAY(4, "Fourth day"), THURSDAY(5, "Fifth day"), FRIDAY(6, "Sixth day"), SATURDAY(7, "Seventh day"); private final int intCode; private final String stringCode; // Compiler internally invokes it to assign value Week(int intCode, String stringCode) < this.intCode = intCode; this.stringCode = stringCode; >public int getIntCode() < return intCode; >public String getStringCode() < return stringCode; >> public class EnumExample < public static void main(String arg[]) < System.out.println(Week.SUNDAY.toString()); >>

Java enum valueof() method

The valueOf() method is a static method in the enum class and it is used to obtain an instance of the enum class for a given String value.

enum Week < SUNDAY(1, "First day"), MONDAY(2, "Second day"), TUESDAY(3, "Third day"), WEDNESDAY(4, "Fourth day"), THURSDAY(5, "Fifth day"), FRIDAY(6, "Sixth day"), SATURDAY(7, "Seventh day"); private final int intCode; private final String stringCode; // Compiler internally invokes it to assign value Week(int intCode, String stringCode) < this.intCode = intCode; this.stringCode = stringCode; >public int getIntCode() < return intCode; >public String getStringCode() < return stringCode; >> public class EnumExample < public static void main(String arg[]) < Week week = Week.valueOf("SUNDAY"); System.out.println(week); >>

2 thoughts on “enum in java”

This is some good stuff. It took me a while to locate this blog but it was worth the time. I noticed this article was buried in yahoo and not the number one spot. This internet site has a ton of decent stuff and it does not deserve to be burried in the searches like that. By the way I am going to save this web site to my favorites. Log in to Reply

Читайте также:  Rendering thread exception java

Great article. I was checking continuously to this web site and Im really inspired! Very helpful information, especially the second sentences. I really need this kind of knowledge. I used to be seeking this kind of information for a period. Thankx and best wishes. Log in to Reply

Leave a Comment Cancel reply

You must be logged in to post a comment.

  • Basics Of Java
    • What is JAVA language
    • JAVA features/advantage
    • How to run Java program
    • Difference between JRE, JDK and JVM
    • Java Virtual Machine(JVM) & JVM Architecture
    • Variables in Java
      • Local Variable Type Inference (Java var)
      • Java control statements
        • if statement in Java
        • Switch statement Java
        • class and object in Java
        • Constructor Overloading in Java
        • Constructor chaining in java
        • Multiple inheritance using interface in java
        • Method overloading in Java
        • Method overriding in Java
        • Abstract class in java
        • Interface in java
          • Multiple inheritance using interface in java
          • Java import package
          • final variable in Java
          • final method in java
          • final class in Java
          • Static variable in java
          • Static method in java
          • Static block in java
          • Static class in java
          • Thread life cycle in java
          • Thread scheduler in java
          • Java Thread Sleep
          • join() method in java
          • yield() method in java
          • wait() method in Java
          • notify() method in Java
          • Thread class in java
          • Daemon thread in java
          • Callable and Future in java
          • What is immutable String in java
          • What is a mutable string
          • String concatenation
          • String comparison in Java
          • Substring in Java
          • Convert string to int
          • String Replace in Java
          • Substring in Java
          • String constructor in java
          • string methods in java
          • try and catch java block
          • finally block in java
          • throw and throws keyword in java
          • Chained exception in java
          • User defined exception in java
          • Java try with resource
          • ArrayList in java
            • Java ArrayList methods
            • How to add the element in ArrayList
            • How to replace element in an ArrayList?
            • How to remove element from arraylist java
            • How to access ArrayList in java
            • How to get index of object in arraylist java
            • How to Iterate list in java
            • How to achieve Java sort ArrayList
            • How to get java sublist from ArrayList
            • How to Convert list to array in java
            • How to convert array to list java
            • How to remove duplicates from ArrayList in java
            • Difference between ArrayList and array
            • Difference between ArrayList and LinkedList
            • Java linked list methods
            • How to do LinkedList insertion?
            • How to perform deletion in linked list
            • How to get the element from LinkedList
            • Traverse a linked list java
            • Searching in linked list
            • How to convert linked list to array in java
            • How to remove duplicates from linked list
            • How to perform linked list sorting
            • Difference between ArrayList and LinkedList
            • How to add element in HashSet?
            • How to remove elements from HashSet?
            • TreeSet internal working
            • TreeSet Methods in Java
            • Internal working of HashMap
            • HashMap method in java
            • How to add an object in HashMap by HashMap put() method
            • How to get values from hashmap in java example
            • How to remove the element by Java HashMap remove() method
            • How to replace the value by HashMap replace() method
            • How to check the map contains key by hashmap containskey() method
            • How to get java map keyset by hashmap keyset() method
            • How to get java map entryset by java entryset() method
            • How to iterate hashmap in java
            • TreeMap(Comparator comp)
            • Treemap methods
            • Generic types in Java
            • Advantages of generics in java
            • toString() method in Java
            • equals() method in java
            • Java hashCode() method
            • clone() method in java
            • finalize() method in java
            • getclass() method in java
            • wait() method in Java
            • notify() method in Java
            • Garbage collector in java
            • finalize() method in java
            • equals() method in java
            • Java hashCode() method
            • Comparable java interface
            • Comparator interface
            • Difference between comparable and comparator
            • Why Comparable and Comparator are useful?
            • comparator() method in java
            • functional interface in java 8
            • Predicate in java 8
              • Why predicate in java 8
              • Why consumer in java 8
              • How lambda expression works in java
              • Java 8 lambda expression example
              • Why Lambda expression use functional interface only
              • Lambda expression with the return statement
              • Java stream operations in java
              • Intermediate operation in Java 8
              • Terminal operations in java 8
              • Short circuit operations in Java 8
              • Lazy evaluation of stream
              • Converting stream to collections and Arrays
              • Java 9 module
              • try with resource improvement
              • Optional Class Improvements
              • Private methods in interface
              • Factory Methods for Immutable List, Set, Map and Map.Entry
              • Jshell java 9
              • Java CompletableFuture API Improvements
              • Local Variable Type Inference (Java var)
              • Java 11 String New Methods

              Content copy is strictly prohibited. Copyright © by JavaGoal 2022. Designed & Developed By Finalrope Soft Solutions Pvt. Ltd.

              Источник

              Java Enum with Strings

              In this guide to Java enum with string values, learn to create enum using strings, iterate over all enum values, get enum value and perform a reverse lookup to find an enum by string parameter.

              We should always create enum when we have a fixed set of related constants. Enums are inherently singleton, so they provide better performance.

              1. Creating Enum with Strings

              Java program to create an enum with strings. The given enum contains deployment environments and their respective URLs. URLs are passed to the enum constructor for each enum constant.

              public enum Environment < PROD("https://prod.domain.com:1088/"), SIT("https://sit.domain.com:2019/"), CIT("https://cit.domain.com:8080/"), DEV("https://dev.domain.com:21323/"); private String url; Environment(String envUrl) < this.url = envUrl; >public String getUrl() < return url; >>

              2. Iterating over Enum Constants

              To iterate over enum list, use values() method on enum type which returns all enum constants in an array.

              //Get all enums for(Environment env : Environment.values())
              PROD :: https://prod.domain.com:1088/ SIT :: https://sit.domain.com:2019/ CIT :: https://cit.domain.com:8080/ DEV :: https://dev.domain.com:21323/

              To get a single enum value (e.g., get production URL from enum constant), use the getUrl() method that we created.

              String prodUrl = Environment.PROD.getUrl(); System.out.println(prodUrl);

              If we want to get enum constant using its name, then we should use valueOf() method.

              Environment sitUrl = Environment.valueOf("SIT"); System.out.println(sitUrl.getUrl());

              5. Reverse Lookup – Get Enum Name from Value

              We will often have the value of enum with us, and we will need to get the enum name by its value. This is achieved using a reverse lookup.

              enum Environment < PROD("https://prod.domain.com:1088/"), SIT("https://sit.domain.com:2019/"), CIT("https://cit.domain.com:8080/"), DEV("https://dev.domain.com:21323/"); private String url; Environment(String envUrl) < this.url = envUrl; >public String getUrl() < return url; >//****** Reverse Lookup ************// public static Optional get(String url) < return Arrays.stream(Environment.values()) .filter(env ->env.url.equals(url)) .findFirst(); > >

              To use the reverse lookup in the application code, use enum.get() method.

              String url = "https://sit.domain.com:2019/"; Optional env = Environment.get(url); System.out.println(env.get());

              Источник

Оцените статью