Enum in Java

Enum in Java :

  • Enum in java is a data type that contains fixed set of constants.
  • The java enum constants are static and final implicitly.
  • Java Enums can be thought of as classes that have fixed set of constants.

Remember for Enum

  • enum improves type safety
  • Constant
public static final String MALE = "M";
public static final String FEMALE = "F";
private String g = "G Force?"; // What is g?
private String gender = "Male";
  • Enum
public enum Gender {
    MALE, FEMALE
}
private Gender g = "G Force?"; // Compile error!!
private Gender gender = "Male"; // Compile error!!
 
private Gender maleInstance = Gender.MALE;
private Gender femaleInstance = Gender.FEMALE;
  • enum can be easily used in switch
switch (gender) {
    case MALE:
        // do sthg
        break;
    case FEMALE:
        // do other thg
        break;
}
  • enum can be traversed
  • enum can have fields, constructors and methods
class EnumExample4 {
    enum Season {
        WINTER(5), SPRING(10), SUMMER(15), FALL(20);

        private int value;

        private Season(int value) {
            this.value = value;
        }
    }

    public static void main(String args[]) {
        for (Season s : Season.values())
            System.out.println(s + " " + s.value);
    }
}
  • enum may implement many interfaces but cannot extend any class because it internally extends Enum class
  • Enum can list all possible options
public Gender[] getOptions() {
    return Gender.values();
}
  • Enum compare
String gender;
if (gender == Gender.FEMALE) {
 // Single instance means we are comparing the references
}

if (Gender.FEMALE.equal(gender)) {
 // Of course this also works
}

Enum Switch Statement

class EnumWeekName {
    enum Day {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}

    public static void main(String args[]) {
        Day day = Day.MONDAY;

        switch (day) {
            case SUNDAY:
                System.out.println("sunday");
                break;
            case MONDAY:
                System.out.println("monday");
                break;
            default:
                System.out.println("other day");
        }
    }
}

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in