Java enum Strings
What is Java enums?
Java enums, short for enumerations, are a special type of class that defines a fixed set of constants. These constants are fixed values that are known at compile-time, and are typically used to represent a fixed set of options, such as a set of predefined values for a variable.
Enums have some utility methods such as values(), valueOf() and name().
To know more about Java enum in java read the complete article.
Java enum strings:
Java enums are a special type of class that defines a fixed number of constants. One of the ways to use enums is to associate a string value with each enum constant.
- In the example I provided earlier, the Color enum is defined with three constants: RED, GREEN, and BLUE. Each constant has an associated string value that represents the hex code for that color.
- The enum also has a constructor that takes a string and assigns it to the hexCode field, and a getter method getHexCode() that returns the hex code of the color.
Let’s look at a Java enum where the Java enum strings is used to perform an operation on the given code.
Example 1 : Java enum string
public enum Color { RED("#ff0000"), GREEN("#00ff00"), BLUE("#0000ff"); private String hexCode; Color(String hexCode) { this.hexCode = hexCode; } public String getHexCode() { return hexCode; } } public class Main { public static void main(String[] args) { Color color = Color.RED; System.out.println("Hex code of color: " + color.getHexCode()); //compare color with string if(color == Color.RED) { System.out.println("Color is Red"); } } }
Output
Hex code of color: #ff0000 Color is Red
Example 2 : Java enum strings
public enum Fruit { APPLE("red"), BANANA("yellow"), ORANGE("orange"); private String color; Fruit(String color) { this.color = color; } public String getColor() { return color; } } public class Main { public static void main(String[] args) { Fruit fruit = Fruit.APPLE; System.out.println("Color of fruit: " + fruit.getColor()); //compare fruit with string if(fruit.toString().equals("APPLE")) { System.out.println("Fruit is Apple"); } } }
Output
Color of fruit: red Fruit is Apple
Example 3: Java enum strings
public enum Shape { CIRCLE("Circle"), SQUARE("Square"), TRIANGLE("Triangle"); private String name; Shape(String name) { this.name = name; } public String getName() { return name; } } public class Main { public static void main(String[] args) { Shape shape = Shape.CIRCLE; System.out.println("Name of shape: " + shape.getName()); } }
Output
Name of shape: Circle
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment