Enum – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Sat, 25 Nov 2023 13:14:04 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Enum – Java2Blog https://java2blog.com 32 32 Java enum with String https://java2blog.com/java-enum-string/?utm_source=rss&utm_medium=rss&utm_campaign=java-enum-string https://java2blog.com/java-enum-string/#respond Fri, 08 Jun 2018 07:44:22 +0000 https://java2blog.com/?p=5681 In this quick tutorial, how to create String constants using enum, convert String to enum etc.
You can go though complete enum tutorial here.

Let’s create java enum String constants.

Create java enum String

package org.arpit.java2blog;

public enum Weekdays {

    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY
}

That’s pretty simple.

Access enum by name

You can simply use . operator to access enum but if you have string as enum name, then use of method.

package org.arpit.java2blog;

public class JavaEnumStringMain {

    public static void main(String[] args) {
        // You can simply use . operator
        Weekdays wd=Weekdays.TUESDAY;
        System.out.println("Week day:"+wd.name());

        // If you have String as "TUESDAY", you can use valueOf method
        Weekdays wdVal=Weekdays.valueOf("TUESDAY");
        System.out.println("Week day:"+wdVal.name());

    }

}

Output:

Week day:TUESDAY
Week day:TUESDAY

Please note that valueOf method takes the String argument as case sensitive.

package org.arpit.java2blog;

public class JavaEnumStringMain {

    public static void main(String[] args) {

        Weekdays wdVal=Weekdays.valueOf("TUesDAY");
        System.out.println("Week day:"+wdVal.name());
    }
}

Output:

Exception in thread “main” java.lang.IllegalArgumentException: No enum constant org.arpit.java2blog.Weekdays.TUesDAY
at java.base/java.lang.Enum.valueOf(Enum.java:240)
at org.arpit.java2blog.Weekdays.valueOf(Weekdays.java:1)
at org.arpit.java2blog.JavaEnumStringMain.main(JavaEnumStringMain.java:7)

Iteratve over all values of Enum with String constansts

You can simply iterate over all String constants using values method.

package org.arpit.java2blog;

public class JavaEnumStringMain {

    public static void main(String[] args) {

        for(Weekdays wd:Weekdays.values())
        {
            System.out.println(wd.name());
        }
    }
}

Output:

MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY

Let’s give an index to each week days with 1 to 5.You can simply change above enum as below.

package org.arpit.java2blog;

public enum Weekdays {

    MONDAY(1),
    TUESDAY(2),
    WEDNESDAY(3),
    THURSDAY(4),
    FRIDAY(5);

    private int index;

    Weekdays(int index)
    {
        this.index=index;
    }
    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

}

Access the index of any weekdays

package org.arpit.java2blog;

public class JavaEnumStringMain {

    public static void main(String[] args) {

        int index=Weekdays.THURSDAY.getIndex();
        System.out.println("Index of Thrusday is: "+index);
    }
}

Output:

Index of Thrusday is: 4

That’s all about Java enum String.

]]>
https://java2blog.com/java-enum-string/feed/ 0
Java Enum tutorial with examples https://java2blog.com/java-enum/?utm_source=rss&utm_medium=rss&utm_campaign=java-enum https://java2blog.com/java-enum/#respond Wed, 02 Sep 2015 18:25:00 +0000 http://www.java2blog.com/?p=325
Java Enum is special data type which represents list of constants values. It is a special type of java class.  It can contain constant, methods and constructors  etc.
Lets see example to understand better
Let’s say we get three types of issues which require different SLA to get it fixed. Usually they are level 1,level 2 and level 3 severity. So it will represent in term of enums as follows.
Public enum Severity

(Level_1,
Level_2,
Level_3
)
Here

Serverity  level= Severity. Level_1;
level variable is type of Serverity which is enum type. You can assign only 3 values (Level_1,Level_2 and Level_3) to it.If you assign any other value, it will give you compile time error.Enum in java are type safe and has its own name space

Now you must be wondering why you can’t use class over here,  why you require special data type called enum.
Lets understand it with the help of example:
Create enum as SeverityEnum.java
package org.arpit.java2blog.corejava;

public enum SeverityEnum
{
LEVEL_1,
LEVEL_2,
LEVEL_3;
}
Create class as SeverityClass.java
package org.arpit.java2blog.corejava;

public class SeverityClass {
public static final String LEVEL_1="LEVEL_1";
public static final String LEVEL_2="LEVEL_2";
public static final String LEVEL_3="LEVEL_3";

}

Create issue.java. It will use above enum and class.

package org.arpit.java2blog.corejava;

public class Issue {

 String issueName;

 public Issue(String issueName) {
  super();
  this.issueName = issueName;
 }
 public String getIssueName() {
  return issueName;
 }
 public void setIssueName(String issueName) {
  this.issueName = issueName;
 }

 public void resolveIssueEnum(SeverityEnum level)
 {
  System.out.println("Resolving "+issueName+ " of "+level.name());
 }

 public void resolveIssueClass(String level)
 {
  System.out.println("Resolving "+issueName+ " of "+level);
 }

}

Create EnumMain.java .

package org.arpit.java2blog.corejava;

public class EnumMain {

 public static void main(String args[])
 {
  Issue a=new Issue("Server is down");
  Issue b=new Issue("UI is not formatted properly");

  System.out.println("Resolving issues:");
  System.out.println("*****************");

  a.resolveIssueClass(SeverityClass.LEVEL_2);

  // You are able to pass "LEVEL_5" also here, but LEVEL_5 is not defined as Severity at all
  // So this is considered to be invalid value, but you still can pass it if you use class
  b.resolveIssueClass("LEVEL_5");

  // b.resolveIssueEnum("LEVEL_5");  // Compilation error

  // You can pass only fixed values with this which is our requirement here
  // So enum ensures type safety
  a.resolveIssueEnum(SeverityEnum.LEVEL_2);
 }
}

When you run above program, you will get following output:

Resolving issues:
*****************
Resolving Server is down of LEVEL_2
Resolving UI is not formatted properly of LEVEL_5
Resolving Server is down of LEVEL_2

The main  reason for it is type safety . You won’t be able to put any other value with enums but if you use class instead of enum, it may be more error prone as you may assign invalid value to it.

Lets understand more about Enum.

package org.arpit.java2blog.corejava;

public class Issue {

 String issueName;

 public Issue(String issueName) {
  super();
  this.issueName = issueName;
 }
 public String getIssueName() {
  return issueName;
 }
 public void setIssueName(String issueName) {
  this.issueName = issueName;
 }

 public static void main(String[] args)
 {
        Severity level=Severity.LEVEL_2;
        System.out.println(level.name());
 }

}

We can see structure of enum using a debug point.
put debug point at line 21 and right click on project->debug as->java application. Program will stop execution at line 21 then right click on level then select watch.You will be able to see structure as below.
Java Enum structure

So it has many methods and two of them are :
name() : it returns you enum constant. For above enum level, its value is LEVEL_2.
ordinal() : It returns you position in enum declaration. This method is not generally used by programmers, it is used mostly in enum based data structures such as EnumSet.Constructor:
protected Enum(String name, int ordinal)
This is only constructor present by default in enum. This can not be called by program. This is called internally when you declare the enum.I am summarising important points on enum based on their nature.

Constructor:

  • Enum can have constructors and can be overloaded.
  • Enum constructor can never be invoked directly, it will be implicitly called when enum is initialized.
  • You also can provide value to enum constants but you need to create member variable and constructor for that

Methods:

  • You can declare methods in enum.
  • You can also declare abstract methods in enum and while declaring constants,  you need to override it.
Java Enum example with description

Declaration :

    • You can not create instance of enum with new operation as it does not support public constructor and it make sense too as you want fixed values in Enum. If new operator would have been allowed, then you might able to add more values.
// compilation error
Serverity level=new Severity();
    • Enum constants are implicitly static and final.  You can not change its value after creation.
    • You can not extend any other class to enums as enum implicitly extends Enum class and java does not allow multiple inheritance.

You can not extends any other class in enum

    • Enum can be defined inside or outside of a class but can not be defined in method.
    • Enum declared outside class can not be declared as static,  abstract,  private,  protected or final.
    • Enum can implement an interface.

Enum interface example

  • Semi colon declared at the end of enum is optional.

Comparison and Switch case:

  • You can compare values of enum using ‘==’  operator.
  • You can use enum in switch case too.

Example:

create Enum class named Severity.java

package org.arpit.java2blog.corejava;

public enum Severity {

 LEVEL_1(1) {
  @Override
  public String getDescription() {
   return "SLA: 2 hours";
  }
 },
 LEVEL_2(2) {
  @Override
  public String getDescription() {
   return "SLA: 8 hours";
  }
 },
 LEVEL_3(3) {
  @Override
  public String getDescription() {
   return "SLA: 1 day";
  }
 };

 int level;
 Severity(int level)
 {
  this.level=level;
 }

 public int getLevel()
 {
  return level;
 }

 public abstract String getDescription();
}

Create issue.java which will used above enum class.

package org.arpit.java2blog.corejava;

public class Issue {

 String issueName;
 Severity issueLevel;

 public Issue(String issueName,Severity level) {
  super();
  this.issueName = issueName;
  this.issueLevel=level;
 }
 public String getIssueName() {
  return issueName;
 }
 public void setIssueName(String issueName) {
  this.issueName = issueName;
 }

 public Severity getIssueLevel() {
  return issueLevel;
 }
 public void setIssueLevel(Severity level) {
  this.issueLevel = level;
 }
 public void resolveIssueUsingSwitch()
 {

  switch(issueLevel)
  {
  case LEVEL_1:
   System.out.println("Resolving level 1 issue");
   break;
  case LEVEL_2:
   System.out.println("Resolving level 2 issue");
   break;
  case LEVEL_3:
   System.out.println("Resolving level 3 issue");
   break;
  }

 }

 public void resolveIssueUsingIfElse()
 {
  if(issueLevel==Severity.LEVEL_1)
  {
   System.out.println("Resolving level 1 issue");
  }
  else if(issueLevel==Severity.LEVEL_2)
  {
   System.out.println("Resolving level 2 issue");
  }
  else if(issueLevel==Severity.LEVEL_3)
  {
   System.out.println("Resolving level 3 issue");
  }
 }

}

create enumMain.java to run the code:

package org.arpit.java2blog.corejava;

public class EnumMain {

 public static void main(String args[])
 {
  Issue a=new Issue("Server is down",Severity.LEVEL_1);
  Issue b=new Issue("UI is not formatted properly",Severity.LEVEL_3);

  System.out.println("*****************");
  System.out.println("Resolving issues:");

  // Using if else
  a.resolveIssueUsingIfElse();

  // Using switch case
  b.resolveIssueUsingSwitch();

  System.out.println("*****************");
  System.out.println("valueOf method example");
  // converting string to Enum using valueOf Method
  Severity level2=Enum.valueOf(Severity.class,"LEVEL_2");
  System.out.println(level2.name()+" -"+level2.getDescription());

  // values for getting all enum values
  System.out.println("*****************");
  System.out.println("values method example");
  for (Severity level:Severity.values()) {
   System.out.println(level.name()+" - "+level.getDescription());
  }

 }
}

When you run above code, you will get following output:

*****************
Resolving issues:
Resolving level 1 issue
Resolving level 3 issue
*****************
valueOf method example
LEVEL_2 -SLA: 8 hours
*****************
values method example
LEVEL_1 - SLA: 2 hours
LEVEL_2 - SLA: 8 hours
LEVEL_3 - SLA: 1 day

Please go through  core java interview questions for more interview questions.

]]>
https://java2blog.com/java-enum/feed/ 0