How to use Enums with Java

Photo by Marjan Blan on Unsplash

How to use Enums with Java

Using Enums effectively

More description coming soon.




public class MyClass {

     private static final String _name = "Ironman";
     private static final String _from = "Marvel";

    enum HEROS {

    IRONMAN(_name,  _from),
    BATMAN("Batman",       "DC");


    private final String name;
    private final String from;


    private HEROS(String name, String from) {
        this.name = name;
        this.from = from;
    }

    public String getFullName() {
        return name;
    }

    public String getFrom() {
        return from;
    }

    //Get Name by passing a from value
    public static String getNameByFrom(String from) {
        for (HEROS hero : HEROS.values()) {
            if (hero.getFrom().equalsIgnoreCase(from)) {
                return hero.getFullName();
            }
        }
        return _name; // Return default value or throw an exception
    }

    //Get from by passing a Name
    public static String getFromByName(String name) {
        for (HEROS hero : HEROS.values()) {
            if (hero.getFullName().equalsIgnoreCase(name)) {
                return hero.getFrom();
            }
        }
        return _from; // Return default value or throw an exception
    }



}

    public static void main(String args[]) {
    //   for(HEROS hero : HEROS.values()) {
    //         System.out.println(hero.getFullName());
    //     }
    //     System.out.println(HEROS.getNameByFrom("DC1"));
    //     System.out.println(HEROS.getFromByName("BATM1AN"));
    //     System.out.println(HEROS.getNameByFrom(_name));
        System.out.println(HEROS.getFromByName(_from));

    }
}