top of page

Java Programming Help

Public·1 member

Java Programming Help: Can I add a function to enums in Java - Codersarts

Yes, you can add as many function you wish .


A Java Enum is a special Java class that define group of constants which is unchangeable variables, like final variables. An enum can contain constants, methods etc. Java enums were added in Java 5.


To create an enum, use the enum keyword and separate the constants with a comma.


Note that they should be in uppercase letters:


Example 1: enum for movie RATING


enum RATING {
         GENERAL,
         PARENTGUIDANCE,
         MATURE
}

Example 2: enum for mathematical Operator

enum OPERATOR {
        ADD,
        SUBTRACT,
        MULTIPLY,
        DIVIDE
}

Example 2: enum for Week days

enum WEEKDAYS {
        SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
        }

You can access enum constants with the dot syntax:

RATING rating = RATING.GENERAL;
OPERATOR opt = OPERATOR.ADD;
WEEKDAYS weekdays = WEEKDAYS.SUNDAY;
System.out.println(rating);
System.out.println(opt);
System.out.println(weekdays);

Output:

GENERAL
ADD
SUNDAY


How to use enum in if Statement


RATING rating = RATING.GENERAL;

if( rating == RATING.GENERAL) {    
   System.out.println("This film is allowed for all age group");

} else if( rating == RATING.PARENTGUIDANCE) {
         System.out.println("This film is allowed for ages 12 and above");


} else if( rating == RATING.MATURE) {
    System.out.println("This film is allowed for ages 16 and  above");

}

How can we define Enum inside a Class


public class MyClass { 
  enum WEEKDAYS { 
                  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
                  THURSDAY, FRIDAY, SATURDAY;
                }

 public static void main(String[] args) { 
    WEEKDAYS weekdays = WEEKDAYS.SUNDAY; 
    System.out.println(weekdays); 
  } 
}

How to use Enum in a Switch Statement




enum RATING { GENERAL, PARENTGUIDANCE, MATURE }

public class MyClass { 
    public static void main(String[] args) {
    RATING rating = RATING.GENERAL; 

   switch(rating) {
      case GENERAL:
          System.out.println("For all age group"); 
          break;
          
      case PARENTGUIDANCE:
            System.out.println("For ages 12 and above"); 
            break;
            
      case MATURE:
          System.out.println("For ages 16 and  above"); 
          break;
         
    }
  }
}

Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time.



52 Views
bottom of page