Explain Codes LogoExplain Codes Logo

How to convert enum value to int?

java
enum-int-conversion
java-best-practices
enum-usage
Alex KataevbyAlex Kataev·Aug 31, 2024
TLDR

You can convert an enum to an int in Java using the ordinal() function, which returns a zero-based index of the enum constant.

Here's a simplistic example:

enum Day { MONDAY, TUESDAY, WEDNESDAY; // Who likes Mondays? ordinal: 0, 1, 2 } int dayIndex = Day.MONDAY.ordinal(); // This will give you "0" aka Monday which promises a long week!

Warning: The ordinal() method returns the declaration order. If you shuffle the enum's constants, their corresponding ordinal values change too, turning the whole system into a chaotic dancing session, and possibly breaking something.

Beyond the ordinal(): custom int for enums

Not all scenarios call for ordinal values — maybe you want custom integer values tied to your enum constants? This is how you could do that:

public enum TaxCode { EXEMPT(0), // Tax? No, thank you! STANDARD(10), // The regular guest. REDUCED(5); // Guess who's on a diet. private final int taxValue; TaxCode(int taxValue) { this.taxValue = taxValue; } public int getTaxValue() { return taxValue; } } int tax = TaxCode.EXEMPT.getTaxValue(); // gives '0', and not '10' or '5'.

Here the .ordinal() would create a Pandora's box, incorrectly mapping REDUCED to 2 instead of 5. We tackled it with getTaxValue() that fetches the right integer.

Looking at enum-int conversion alternates

Scenario: computation needed

When calculation or logic are involved, a switch-case can come handy.

public int getTaxValue(TaxCode taxCode) { switch (taxCode) { case EXEMPT: return 0; // "Free bird" case STANDARD: return 10; // "Eh, a regular Joe" case REDUCED: return 5; // "Half price, double excitement" default: throw new IllegalArgumentException("Unknown TaxCode"); // "Tax invasion? Unacceptable!" } }

Scenario: enums aren't fitting well

When an enum is more of a square peg for a round hole, consider a static class with public final fields. This follows C# enum's suit of explicitly linking each name to an integer.

public class TaxCode { public static final int EXEMPT = 0; // The one who slips away public static final int STANDARD = 10; // The staple diet public static final int REDUCED = 5; // Size doesn't matter // Usage int taxValue = TaxCode.EXEMPT; }

Crossing the 'i's and dotting the 't's

The order of constancy

If your code leans heavily on ordinal(), remember to chisel those enum orders in stone. or, at the very least, write them in bold letters for your future self or the next coders.

The growth of enums

For dynamic enums that might acquire more constants, it's better to tie them to explicit integers or to bind them with a custom getter method. This makes future expansion less chaotic and intentions more transparent.

Enum vs int

In Java, enums are an overhead compared to ints since they're essentially classes, but they shine in providing type safety, a clear context, and better code readability.