Java Enums

Introduction to Enumerated Data Type in Java

An enumerated data type, also known as an enum, is a special type of data type in Java that allows you to represent a fixed set of constants. Enums are useful for representing things like the days of the week, the months of the year, or the different states of a machine.

To create an enum, you use the `enum` keyword followed by the name of the enum and a list of constants, enclosed in curly braces. For example, the following code defines an enum called `DaysOfWeek` with the following constants:

enum DaysOfWeek {
  MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

Once you have created an enum, you can use it to declare variables and constants. For example, the following code declares a variable called `dayOfWeek` of type `DaysOfWeek`:

DaysOfWeek dayOfWeek;

You can then assign a value to the variable from the set of constants defined in the enum:

dayOfWeek = DaysOfWeek.MONDAY;

Enums are also useful for switch statements. For example, the following code uses a switch statement to print out the day of the week based on the value of the `dayOfWeek` variable:

switch (dayOfWeek) {
  case MONDAY:
    System.out.println("Today is Monday.");
    break;
  case TUESDAY:
    System.out.println("Today is Tuesday.");
    break;
  ...
  case SUNDAY:
    System.out.println("Today is Sunday.");
    break;
  default:
    System.out.println("Invalid day of the week.");
}

Enums are a powerful tool that can help you write more robust and efficient Java code. They are especially useful for representing fixed sets of constants and for use in switch statements.

Here are some other benefits of using enums:

  • They can make your code more readable and maintainable by making it clear what values are valid for a given variable or parameter.
  • They can help to prevent errors by preventing you from assigning invalid values to variables or parameters.
  • They can be used to implement other design patterns, such as state machines and singletons.

If you are working with Java, I encourage you to learn more about enums and how to use them in your code.

Exercises

Code for declaring an enum data type and traversing it


  package testProject;
  public class testProject {
  
    public enum semester {FALL,WINTER,SUMMER,WEEKEND}
    public static void main(String[] args) {		
       
      for(semester s: semester.values())
      {
                 System.out.println(s);
      }
    
    }
  } 

Code for Declaring an enum outside a class


  package testProject;
  enum semester {FALL,WINTER,SUMMER,WEEKEND}
  public class testProject {
    public static void main(String[] args) {		
      for(semester s: semester.values())
      {
                 System.out.println(s);
      }
    }
  }
  
  OUTPUT
  FALL
  WINTER
  SUMMER
  WEEKEND 

Code for demonstrating the use of Use of valueof method - returns an ENUM constant matching the passed String


  package testProject;
  enum semester {FALL,WINTER,SUMMER,WEEKEND};
  public class testProject {
    public static void main(String[] args) {		
      
      System.out.println(semester.valueOf("WINTER"));
    }
  }
  
  Output
  WINTER 

Code for demonstrating the Use of Ordinal Method - returns the index of an ENUM constant


  package testProject;
  enum semester {FALL,WINTER,SUMMER,WEEKEND};
  public class testProject {
    public static void main(String[] args) {		
      
      System.out.println(semester.valueOf("WINTER").ordinal());
    }
  }
  
  output 
  1 

Code for demonstrating the use of Use of compareTo Method .The compareTo() method compares the enum constants based on their ordinal value.


  package testProject;
  public class testProject {
      
    public enum semester {
      FALL,
      WINTER,
      SUMMER,
      WEEKEND;
      
      public void display()
      {
        System.out.println("This is the display method");
      }
      
    }
    public static void main(String[] args) {		
       
      semester s = semester.FALL;
      semester s1 = semester.WINTER;
      System.out.println(s.compareTo(s1));
      
    }
  
  }
  
  output
  -1 

Code for demonstrating the use of toString Method - returns the string representation of a ENUM constant.


  package testProject;
  public class testProject {
      
    public enum semester {
      FALL,
      WINTER,
      SUMMER,
      WEEKEND;
      
      public void display()
      {
        System.out.println("This is the display method");
      }
      
    }
    public static void main(String[] args) {		
       
      String s = semester.FALL.toString();
      System.out.println(s);
      
    }
  }
  
  output 
  FALL    

Code to demonstrate the Use of ENUM with switch case statement in Java.


  package testProject;
  public class testProject {
    public enum semester {FALL,WINTER,SUMMER,WEEKEND};
    public static void main(String[] args) {		
       
      semester s = semester.WINTER;
      
      switch(s)
      {
         case WINTER : 
           System.out.println("This is winter");
           break;
         case SUMMER:
           System.out.println("This is summer");
           break;
          default:
            System.out.println("Invalid Input");
            break;
      }
    }
  } 

Code for demonstrating the use of enum with a constructor .ENUM contains private constructors only


  package testProject;
  public class testProject {
      
    public enum semester {
      FALL,
      WINTER,
      SUMMER,
      WEEKEND;
      
      private semester()
      {
        System.out.println(this.toString());
      }
      
    }
    public static void main(String[] args) {		
       
      semester s = semester.FALL;
      
    }
  
  }
  
  output 
  FALL
  WINTER
  SUMMER
  WEEKEND   

Code for ENUM with a constructor - Passing Parameters to Constructors


  package testProject;
  public class testProject {
      
    public enum semester {
      FALL("June to Decemeber"),
      WINTER("Jan to April"),
      SUMMER("May to June"),
      WEEKEND("Saturday and Sunday");
      
      private String duration;
      
      private semester(String dur)
      {
        this.duration = dur;
      }
      
      public void display_duration()
      {
        System.out.println(this.duration);
      }
      
    }
    public static void main(String[] args) {		
       
      semester s = semester.WINTER;
      s.display_duration();
      
    }
  } 

Code for demonstrating the use of methods in ENUM


  package testProject;
  public class testProject {
      
    public enum semester {
      FALL,
      WINTER,
      SUMMER,
      WEEKEND;
      
      private semester()
      {
        System.out.println(this.toString());
      }
      
      public void display()
      {
        System.out.println("This is the display method");
      }
      
    }
    public static void main(String[] args) {		
       
      semester s = semester.FALL;
      s.display();
      
    }
  
  }
  
  output
  FALL
  WINTER
  SUMMER
  WEEKEND
  This is the display method