Tolga Karahan
Tolga Karahan

Reputation: 69

Using Enum Name to Get Constants

Sometimes I'm confused that whether I should use enum name to get constants defined in enum. What is the difference between code below and when I should use enum name to obtain constants?

switch(accountType) {
    case ZERO_BALANCE:
        break;
    case CREDIT_BALANCE:
        break;
    case DEBIT_BALANCE:
        break;
}

if(accountType == MenuOption.ZERO_BALANCE)
  else if(accountType == MenuOption.CREDIT_BALANCE)
     else if(accountType == MenuOption.DEBIT_BALANCE);

Upvotes: 1

Views: 63

Answers (2)

JB Nizet
JB Nizet

Reputation: 691655

You need the MenuOption. prefix everywhere, unless

  • you have statically imported its constants (which I wouldn't recommend in most cases),
  • or you're referring to the constants in a switch statements as in your first snippet.

Upvotes: 3

Naman
Naman

Reputation: 31868

From the java nutsandbolts(emphasis from me)

Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing. An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.

Upvotes: 3

Related Questions