You are here: Home / Topics / Comparison in Enum example in Java

Comparison in Enum example in Java

Filed under: Java on 2023-09-19 06:56:08

// Program to explain that enum has Ordinal
// number that is used in comparison.

enum  Colour 
{
Red, Green, Blue, Black, White, Orange, Yellow
}

class  EnumDemo4 
{
public static void main(String args[ ])
{
 Colour c1, c2, c3;
 // Obtain all ordinal values using ordinal().
 System.out.println("Colour constants : Ordinal values");
 for(Colour c : Colour.values())
  System.out.println(c + " : " + c.ordinal());
 c1 = Colour.Red;
 c2 = Colour.Green;
 c3 = Colour.Blue;
 
 // Demonstrate compareTo() and equals()
 if(c1.compareTo(c2) < 0)
  System.out.println(c1 + " comes before " + c2);
 
 if(c1.compareTo(c2) > 0)
  System.out.println(c2 + " comes before " + c1);
 
 if(c1.compareTo(c3) == 0)
  System.out.println(c1 + " equals " + c3);

 System.out.println();
 if(c1.equals(c2))
  System.out.println("Error!");
 if(c1.equals(c3))
  System.out.println(c1 + " equals " + c3);
 if(c1 == c3)
  System.out.println(c1 + " == " + c3);
}
}


Output:

Colour constants : Ordinal values
Red : 0
Green : 1
Blue : 2
Black : 3
White : 4
Orange : 5
Yellow : 6
Red comes before Green

About Author:
S
Shyam Dubey     View Profile
I am a good learner. I like posting new questions on this plateform to help other students.