In this example, let’s us see how to compare two enums in Java.
Source Code
1)
package com.beginner.examples;
public enum Week {
SUN,MON,
TUE,WED,
THURS,FIR,
SAT;
}
2)
package com.beginner.examples;
public class CompareEnumExample {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Week dayWeek=Week.TUE;
if(dayWeek==Week.SUN)
{
System.out.println("Sunday");
}
else if(dayWeek==Week.MON)
{
System.out.println("Monday");
}
else if(dayWeek==Week.TUE)
{
System.out.println("Tuesday");
}
else if(dayWeek==Week.WED)
{
System.out.println("Wednesday");
}
else if(dayWeek==Week.THURS)
{
System.out.println("Thursday");
}
else if(dayWeek==Week.FIR)
{
System.out.println("Firday");
}
else {
System.out.println("Saturday");
}
}
}
Output:
Thursday
3)
package com.beginner.examples;
public class CompareEnumExample2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Week day=Week.TUE;
switch (day) {
case SUN:System.out.println("Sunday");break;
case MON:System.out.println("Monday");break;
case TUE:System.out.println("Thursday");break;
case WED:System.out.println("Wednesday");break;
case THURS:System.out.println("Thursday");break;
case FIR:System.out.println("Firday");break;
default:System.out.println("Saturday");
}
}
}
Output:
Thursday