How to convert enum value to int?

Java enum value are use to represent a group of named constant.here we are declare A to Z value and there respective integer value also.for declare this constant value we need to define argumented constructor.

we are created getValue method to pass character.to fetch enum class value we are use values method that store value in array class type.we execute one for loop to fetch array type data in single class value.now from if condition we compare character to enum constant value.

enumerations automatically contain this predefined methods: values( )
public static enum-type[ ] values( )

				
					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;

	public int getValue() {
		return value;
	}

	private Alphabets(int value) {
		this.value = value;
	}

	public static int getValue(String character) {
		Alphabets alphabets[] = Alphabets.values();

		int value = 0;
		for (Alphabets alphabet : alphabets) {
			if (alphabet.toString().equalsIgnoreCase(character)) {
				value = alphabet.value;
			}
		}
		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

Leave a Comment

Your email address will not be published. Required fields are marked *