2

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?

2 Answers 2

5

One important reason is that with the enum, you know the value is either TRUE or FALSE; it can't be anything else. But the String can 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 enum elements with ==, but you have to use a relatively slow equals() call to compare String objects.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Can you also tell me if there is any other use of ENUM except for == comparison?
You can also use Enums in switch statements, unlike strings (for JREs < 1.7).
Enums are objects. They have methods. You can add your own methods. You can define custom implementations for specific instances of your enum.
2

Resons why you should use enums:

  • Enums are strong typed
  • Comparing enums is faster, you can use == instead equals()
  • Enums can implement interfaces, methods and functions. For example enum for various metric systems Metric.EUCLID.distance(Point a, Point b));
  • There is bunch of convenience methods out of the box - MyEnum[] all = MyEnum.values(); MyEnum.valueOf("ENUM_NAME");
  • You can use them in a switch statement since Java 5, String since Java 7.
  • IMO It makes code a bit more readable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.