[java] How to convert enum value to int?

I have a function which return a type int. However, I only have a value of the TAX enumeration.

How can I cast the TAX enumeration value to an int?

public enum TAX {
    NOTAX(0),SALESTAX(10),IMPORTEDTAX(5);

    private int value;
    private TAX(int value){
        this.value = value;
    }
}

TAX var = TAX.NOTAX; // This value will differ

public int getTaxValue()
{
  // what do do here?
  // return (int)var;
}

This question is related to java enums

The answer is


Maybe it's better to use a String representation than an integer, because the String is still valid if values are added to the enum. You can use the enum's name() method to convert the enum value to a String an the enum's valueOf() method to create an enum representation from the String again. The following example shows how to convert the enum value to String and back (ValueType is an enum):

ValueType expected = ValueType.FLOAT;
String value = expected.name();

System.out.println("Name value: " + value);

ValueType actual = ValueType.valueOf(value);

if(expected.equals(actual)) System.out.println("Values are equal");

I prefer this:

public enum Color {

   White,

   Green,

   Blue,

   Purple,

   Orange,

   Red
}

then:

//cast enum to int
int color = Color.Blue.ordinal();

If you want the value you are assigning in the constructor, you need to add a method in the enum definition to return that value.

If you want a unique number that represent the enum value, you can use ordinal().


A somewhat different approach (at least on Android) is to use the IntDef annotation to combine a set of int constants

@IntDef({NOTAX, SALESTAX, IMPORTEDTAX})
@interface TAX {}
int NOTAX = 0;
int SALESTAX = 10;
int IMPORTEDTAX = 5;

Use as function parameter:

void computeTax(@TAX int taxPercentage){...} 

or in a variable declaration:

@TAX int currentTax = IMPORTEDTAX;

Sometime some C# approach makes the life easier in Java world..:

class XLINK {
static final short PAYLOAD = 102, ACK = 103, PAYLOAD_AND_ACK = 104;
}
//Now is trivial to use it like a C# enum:
int rcv = XLINK.ACK;

public enum Tax {

NONE(1), SALES(2), IMPORT(3);

private final int value;
    private Tax(int value) {
        this.value = value;
    }

    public String toString() {
        return Integer.toString(value);
    }
}

class Test {
    System.out.println(Tax.NONE);    //Just an example.
}