Languages

Java enum valueOf uppercase or lowercase - does it matter when I use enum value of?

2 points
Asked by:
RomanaLittle
458

Does the size of letter matters when I use enum valueOf() method?

For example:

enum CODE_STATUS {
    FETCHED,
    SENT
}

Can I use lowercase letters like "sent" when I use:

CODE_STATUS status = CODE_STATUS.valueOf("sent");

Or do I need to use exatch match?

1 answer
3 points
Answered by:
RomanaLittle
458

Exact match is required (example 1), if not then we will get exception (example 2).

Example 1

public class EnumValueOfExample1 {

    enum CODE_STATUS {
        FETCHED,
        SENT
    }

    public static void main(String[] args) {

        // ok by exactly matching the enum letters
        CODE_STATUS status = CODE_STATUS.valueOf("SENT");
        System.out.println(status);
    }
}

Output:

SENT

Example 2 - exception

public class EnumValueOfExample2 {

    enum CODE_STATUS {
        FETCHED,
        SENT
    }

    public static void main(String[] args) {

        // Exception in thread "main" java.lang.IllegalArgumentException:
        // No enum constant
        // examples.EnumValueOfExample.CODE_STATUS.sent
        CODE_STATUS statusByLowercase = CODE_STATUS.valueOf("sent");
        System.out.println(statusByLowercase);
    }
}
Exception in thread "main" java.lang.IllegalArgumentException: 
No enum constant examples.EnumValueOfExample2.CODE_STATUS.sent
    at java.lang.Enum.valueOf(Enum.java:238)
    at examples.EnumValueOfExample2$CODE_STATUS.valueOf(EnumValueOfExample2.java:5)
    at examples.EnumValueOfExample2.main(EnumValueOfExample2.java:15)

Reference

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join