File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes comments welcome to clearify... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "comments welcome to clearify..." Watch "comments welcome to clearify..." New topic

comments welcome to clearify...

Manoj Globeop

Joined: Nov 09, 2008
Posts: 7
Following question from Sun's pre assessment exam:

1. class UseEnums2{
2. enum Colors{RED,GREEN,BLUE,YELLOW};
3. public static void main(String[] args){
4. for(Colors c : Colors.values()){
5. if(c == Colors.GREEN)
6. System.out.println("green");
7. if(Colors.RED.equals(c))
8. System.out.println("red");
9. if(c == "YELLOW")
10. System.out.println("yellow");
11. if(c.equals("BLUE"))
12. System.out.println("blue");
13. }
14. }
15. }

As i understand at line no. 9 the compilation fails as the 2 object are incomparable(enum and string) and at line no. 11 we are comparing 2 object meaningfully but this condition will always be false.

Could anybody elaborate more on these 2 line no. as whats happening here...
Thanks ,

Ankit Garg

Joined: Aug 03, 2008
Posts: 9466

At line 9, you are actually comparing two unrelated classes. All enums are sub-classes of Enum class. And Enum and String class are not related to each other in any way whatsoever. So it will give you a compilation error. It is just like you are doing this new Integer(10) == "10" where the LHS is an instance of class Integer and RHS is of type String.

In the 11th statement you must read the documentation of Enum class. It states that it will only check if the object passed is same as the enum constant on which it is called. So it will return true if you call it like this


and not like this


Actually you know that they are meaningfully equal (i.e. RED and "RED") but for Java, they are two references of two different types (RED of type Enum and "RED" of type String)... If you have read about equals methods, then they are actually implemented like this

So Enum class also follows this pattern and returns false if the object passed is not of type Enum...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
I agree. Here's the link:
subject: comments welcome to clearify...
It's not a secret anymore!