We create Enum classes and write all enum members in Full Uppercase.
public enum Color {
RED,
YELLOW,
BLACK
}
How can we get the values in Capitalization (Writing the first letter of a word in uppercase, and the rest of the letters in lowercase) in java.
Meaning, when I fetch the Value of Color
Enum, I should get as Red
, Yellow
, Black
CodePudding user response:
An enum can be more than just the simple constant as you have it in your snippet. Check out https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html, especially the planet example.
So of course you can override the toString() method and whatever else you need to get your representation running.
CodePudding user response:
If you want to use java enums name() method, you have no choice but to write the values in Capitalization in your code.
If you want to get a «display name» for each color, you can add a String field to your enum, like in the example below:
public enum Color {
RED("Red"),
YELLOW("Yellow"),
BLACK("Black");
String displayName;
Color(String displayName){
this.displayName = displayName;
}
}
Then you can access the capitalized name with RED.displayName
for example.
Last solution, you can manually capitalize the name, with the code below:
String str = RED.name();
String displayName = str.substring(0, 1).toUpperCase() str.substring(1).toLowerCase();