Comparing enum in Java: use == or equals()?
Hi everyone! I started learning Java not long ago and came across a question about enum. When I compare two enum variables, I see that I can use both the == operator and the equals() method. Both options work in my code, but I don't understand which one is correct and why.
Here's an example code that confuses me:
```java
public enum Color {
RED, GREEN, BLUE
}
public class Main {
public static void main(String[] args) {
Color c1 = Color.RED;
Color c2 = Color.RED;
Color c3 = Color.GREEN;
// Comparison using ==
System.out.println(c1 == c2); // true
System.out.println(c1 == c3); // false
// Comparison using equals()
System.out.println(c1.equals(c2)); // true
System.out
No answers yet.
Log in to leave an answer
Blogs