Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

What is the best way to use the values stored in an Enum as String literals? For example:

public enum Modes {

    some-really-long-string,

    mode1,

    mode2,

    mode3

}

Then later I could use Mode.mode1 to return its string representation as mode1. Without having to keep calling Mode.mode1.toString().

1 Answer

0 votes
by (46k points)

You can not. I believe you have FOUR choices here. All four attempt a resolution but with a slightly modified method...

Method One: Try the built-in name() on an enum. This is fine if you don't require any special identifying format.

    String name = Modes.mode1.name(); // Returns 

the name of this enum constant, specifically as stated in its enum statement.

Method Two: add overriding features to your enums if you require more direction

public enum Modes {

    mode1 ("Fancy Mode 1"),

    mode2 ("Fancy Mode 2"),

    mode3 ("Fancy Mode 3");

    private final String name;       

    private Modes(String s) {

        name = s;

    }

    public boolean equalsName(String otherName) {

        // (otherName == null) 

check is not required because name.equals(null) returns false 

        return name.equals(otherName);

    }

    public String toString() {

       return this.name;

    }

}

  • Method Three: Try static finals rather of enums:

public final class Modes {

    public static final String MODE_1 = "Fancy Mode 1";

    public static final String MODE_2 = "Fancy Mode 2";

    public static final String MODE_3 = "Fancy Mode 3";

    private Modes() { }

}

  • Method Four: interfaces hold each field public, static and final:

public interface Modes {

    String MODE_1 = "Fancy Mode 1";

    String MODE_2 = "Fancy Mode 2";

    String MODE_3 = "Fancy Mode 3";  

}

Related questions

0 votes
1 answer
asked Nov 25, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 24, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Nov 23, 2019 in Java by Anvi (10.2k points)

Browse Categories

...