java enum from string code example

Example 1: java get enum from string

public enum Hello {
  A, B, C
};

val = Hello.valueOf("A") // Case sensitive and cannot have spaces in the string
val.equals(Hello.A) // returns true

Example 2: java string enum

package test;

/**
 * @author The Elite Gentleman
 *
 */
public enum Strings {
    STRING_ONE("ONE"),
    STRING_TWO("TWO")
    ;

    private final String text;

    /**
     * @param text
     */
    Strings(final String text) {
        this.text = text;
    }

    /* (non-Javadoc)
     * @see java.lang.Enum#toString()
     */
    @Override
    public String toString() {
        return text;
    }
}

Tags:

Java Example