Java Enum equals

In this chapter you will learn:

  1. How to use Java Enum equals
  2. Example - Compare for equality an enumeration constant with any other object

Description

You can compare for equality an enumeration constant with any other object by using equals(). Those two objects will only be equal if they both refer to the same constant, within the same enumeration.

Example

Compare for equality an enumeration constant with any other object.


enum Direction {//  www  .j  a  v  a2  s  .c  o  m
  East, South, West, North
}

public class Main {
  public static void main(String args[]) {
    Direction ap = Direction.West;
    Direction ap2 = Direction.South;
    Direction ap3 = Direction.West;

    if (ap.equals(ap2)){
      System.out.println("Error!");
    }
      
    if (ap.equals(ap3)){
      System.out.println(ap + " equals " + ap3);
    }
      
    if (ap == ap3){
      System.out.println(ap + " == " + ap3);
    }
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Java Enum Behaviour
  2. Assign a different behavior to each constant
Home »
  Java Tutorial »
    Java Langauge »
      Java Enum
Java Enum type
Java Enum values() / valueOf() Methods
Java Enum as Class
Java Enum Inherit Enum
Java Enum compareTo
Java Enum equals
Java Enum Behaviour