What is the advantage of using an Enum class to compare something. What is the disadvantage of :
public static final String TRUE = "true";
public static final String FALSE = "false";
public void method1(){
if(TRUE.equals(inputString)){
//do some logic
}
else if(FALSE.equals(inputString)){
//do some other logic
}
}
Why is it recommended to use Enum instead of String in the example?
One important reason is that with the
enum, you know the value is eitherTRUEorFALSE; it can’t be anything else. But theStringcan have any value at all, so you have to check for that. This makes code both simpler and easier to understand.Another is that you can compare
enumelements with==, but you have to use a relatively slowequals()call to compareStringobjects.