Top community members

Many years me and my friends we were volunteers on my university doing programming classes for young people.

I got main conclusion: Young people are awesome, especially students, because they always bring new and fresh ideas :)
* I loved to do it but my time is limited

  I decided to create something that will help millions of students

Now I am here

co-founder

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

2 points
Asked by:
JustMike
3364

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
3364

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

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more