Languages

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

2 points
Asked by:
JustMike
3593

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 answers
3 points
Answered by:
JustMike
3593

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
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join