Friday, 9 October 2015

name and values method of enum

name method of enum

Enum name() is a static method which can be used to return the name (String) of enum.


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

public class EnumTest {
      public static void main(String[] args) {
            String day1 = Day.MONDAY.name();
            System.out.println(day1);
      }
}

Output: MONDAY

values method of enum

enum.values() method which returns all enum instances.


public class EnumTest {
      private enum Currency {
            PENNY("1 rs"), NICKLE("5 rs"), DIME("10 rs"), QUARTER("25 rs");

            private String value;
            private Currency(String brand) {
                  this.value = brand;
            }

            @Override
            public String toString() {
                  return value;
            }
      }

      public static void main(String args[]) {

            Currency[] currencies = Currency.values();

            // enum name using name method
            // enum to String using toString() method
            for (Currency currency : currencies) {
                  System.out.printf("[ Currency : %s,
                             Value : %s ]%n",currency.name(),currency);
            }
      }
}
Output:
[ Currency : PENNY, Value : 1 rs ]
[ Currency : NICKLE, Value : 5 rs ]
[ Currency : DIME, Value : 10 rs ]
[ Currency : QUARTER, Value : 25 rs ]

7 comments:

Related Posts Plugin for WordPress, Blogger...