enum Planet{ MERCURY(1), VENUS(2), EARTH(3), MARS(4), JUPITER(5), SATURN(6), URANUS(7), NEPTUNE(8), PLUTO(9); int number; Planet(int number){ this.number = number; } } public class Main { public static void main(String[] args) { //enum = enumerated (ordered listing of items in a collection) //grouping of constants that behave similarly to objects Planet myPlanet = Planet.PLUTO; canILiveHere(myPlanet); } static void canILiveHere(Planet myPlanet){ switch(myPlanet) { case EARTH: System.out.println("You can live here :)"); System.out.println("This is planet #"+myPlanet.number); break; default: System.out.println("You can't live here...yet"); System.out.println("This is planet #"+myPlanet.number); break; } } }
Practicing... enum Day { MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6), SUNDAY(7); int number; Day(int number){ this.number = number; } } public class Main { public static void main (String[]args) { Day day = Day.MONDAY; workDay (day); } static void workDay (Day day) { switch (day) { case MONDAY: case TUESDAY: case WEDNESDAY: case THURSDAY: case FRIDAY: System.out.println ("It's a working day."); System.out.println("Day number "+day.number); break; default: System.out.println ("It's weekend!"); System.out.println("Day number "+day.number); break; } } }
package enums.java; enum Fruits{ APPLE(100),MANGO(101),BANANA(102),LEMON(103),KURKURE(104),PUFF(500),PAPER(505); int number; Fruits(int no){ this.number=no; } } public class EnumEration { public static void main(String[] args) { //enum = enumerated (ordered listing of items in a collection) //grouping of constants that behave similarly to objects Fruits myfruit=Fruits.KURKURE; iWilleat(myfruit); } static void iWilleat(Fruits kela) { switch(kela) { case APPLE: System.out.println("I will cut it"); System.out.println("The number is"+kela.number); break; default: System.out.println("I will do any thing rather cutting"); System.out.println("The number is :"+kela.number); break; } } }
I am going through Enums that were introduced in Java 1.5. In Effective Java 2'nd Edition it's mentioned that before Java 1.5 there were int and String enum patterns which were having some deficiencies. I understood the cons of int enum patterns but while going through String enum patterns I got the basic idea but didn't get the deep sense of below statements mentioned under Item30 in Effective Java: This variant, known as the String enum pattern, is even less desirable. While it does provide printable strings for its constants, it can lead to performance problems because it relies on string comparisons. Worse, it can lead naive users to hard-code string constants into client code instead of using field names. If such a hard-coded string constant contains a typographical error, it will escape detection at compile time and result in bugs at runtime. Can anyone help me in understanding what these lines explaining. I would appreciate if it can be explained with some code snippet. Thanks