Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

comments welcome to clearify...

 
Manoj Globeop
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ,

Manoj.
 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

RED.equals(RED);

and not like this

RED.equals("RED");

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...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic