This piece of code is from the source question Bank ! the Sun Microsystems scjp training they have with mock exams
i would like to know why c.equals("BLUE") does not work and Other.Colors.RED.equals(c) works fine
what's the catch .(The reference did not give me a good clue just one line saying Lines 18 and 20 are correct
here is the code
and here is what it displays
Time is relative so there is no way i can be late.
How can this be possible??? as far as i think "BLUE" will be a String object in the String pool whereas the c is an enum reference variable which will have RED,GREEN,BLUE and YELLOW enum constants. The two cannot be meaningful equivalents at all because enum constants are not a string.
then you can compare
Well one more method is convert your enum constant to a String and then compare. The original code that you had given. change c.equals("Blue"); to c.toString().equals("BLUE");
[ SCJP 6.0 - 90% ] , JSP, Servlets and Learning EJB.
Try out the programs using a TextEditor. Textpad - Java 6 api
Joined: Feb 23, 2007
Sebastian Janisch wrote:I have to correct myself though. A call to the same Enum element will always return the same instance. My bad
Thanks for the clarification. This is what I remember reading when learning about enums and is why == will work with enums.