Can we define an enum inside a method in Java?

JavaServer Side ProgrammingProgramming

Enumerations in Java represents a group of named constants, you can create an enumeration using the following syntax −

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

We can an enumeration inside a class. But, we cannot define an enum inside a method. If you try to do so it generates a compile time error saying “enum types must not be local”.

Example

public class EnumExample{
   public void sample() {
      enum Vehicles {
         Activa125, Activa5G, Access125, Vespa, TVSJupiter;
      }
   }
}

Error

EnumExample.java:3: error: enum types must not be local
      enum Vehicles {
      ^
1 error

To use the enum constants inside a method declare the required enum inside a class and use its constants inside a method using the values().

Example

Live Demo

public class EnumerationExample {
   enum Enum {
      Mango, Banana, Orange, Grapes, Thursday, Apple
   }
   public void testMethod(){
      Enum constants[] = Enum.values();
      System.out.println("Value of constants: ");  
      for(Enum d: constants) {
         System.out.println(d);
      }
   }
   public static void main(String args[]) {
      EnumerationExample obj = new EnumerationExample();
      obj.testMethod();      
   }
}

Output

Value of constants:
Mango
Banana
Orange
Grapes
Thursday
Apple
raja
Published on 08-Feb-2021 11:26:09
Advertisements