Learn how to convert enum values to int in Java using an enum constructor, getter method, and values() method. Java enums are used to represent a group of named constants.
Code Explanation (Step-by-Step)
- Here enum constants A to Z are declared, and each constant is assigned an integer value.
- To assign values to enum constants, an argument constructor Alphabets(int value) is defined inside the enum.
- The constructor stores the integer value in the value variable.
- The getValue() method is used to return the integer value associated with an enum constant.
- The static getValue(String character) method accepts a character and finds its integer value from the enum.
- The Alphabets.values() method returns an array containing all enum constants and stored in an Alphabets[] array .
- A for-each loop iterates through all enum constants one by one.
- Inside the loop, the entered character is compared with the enum constant using equalsIgnoreCase().
- If a match is found, the corresponding integer value is assigned to the value variable.
- Now, the integer value is returned and displayed as output.
enum Alphabets {
A(1), B(2), C(3), D(4), E(5), F(6), G(7), H(8), I(9),
J(1), K(2), L(3), M(4), N(5), O(6), P(7), Q(8), R(9),
S(1), T(2), U(3), V(4), W(5), X(6), Y(7), Z(8);
private int value;
private Alphabets(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static int getValue(String character) {
Alphabets[] alphabets = Alphabets.values();
int value = 0;
for (Alphabets alphabet : alphabets) {
if (alphabet.name().equalsIgnoreCase(character)) {
value = alphabet.getValue();
}
}
return value;
}
}
public class CharacterToIntFromEnum {
public static void main(String[] args) {
System.out.println(
"Convert character to integer from enum class value is :- "
+ Alphabets.getValue("A")
);
}
}
Output :-
convert character to integer from enum class value is:- 1
What are Enum Constants in Java?
Enum constants are predefined fixed values declared inside an enum. In the Alphabets enum, A, B, C, …, Z are enum constants, and each constant is associated with an integer value through the enum constructor.
enum Alphabets {
A(1), B(2), C(3);
}
Here are some Java-related programs that will help you understand Java concepts better: