Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

comments welcome to clearify...  RSS feed

Manoj Globeop
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 ,

Ankit Garg
Posts: 9610
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


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...
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!