Enum ordinal() in Java

ordinal(): This method is available in java.lang.Enum class of Java.

Syntax:

int java.lang.Enum.ordinal()

This method returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).

Parameters: NA

Returns: the ordinal of this enumeration constant.

Exceptions: NA

Approach

Java

enum Colour {
    RED, GREEN, GRAY, ORANGE
}

public class Enumordinal {
    public static void main(String[] args) {

        System.out.println(Colour.GRAY.ordinal());
    }
}

Output:

2


Enum name() in Java

name(): This method is available in java.lang.Enum class of Java.

Syntax:

String java.lang.Enum.name()

This method returns the name of this enum constant, exactly as declared in its enum declaration.

Parameters: NA

Returns: the name of this enum constant.

Exceptions: NA

Approach

Java

enum Colour {
    RED, GREEN, GRAY, ORANGE
}

public class Enumname {
    public static void main(String[] args) {

        System.out.println(Colour.RED.name());
    }
}

Output:

RED


Enum hashCode() in Java

hashCode(): This method is available in java.lang.Enum class of Java.

Syntax:

int java.lang.Enum.hashCode()

This method returns a hash code for this enum constant.

Parameters: NA

Returns: a hash code for this enum constant.

Exceptions: NA

Approach

Java

enum Colour {
    RED, GREEN, GRAY, ORANGE
}

public class EnumhashCode {
    public static void main(String[] args) {

        System.out.println(Colour.RED.hashCode());
    }
}

Output:

405662939


Enum getClass() in Java

getClass(): This method is available in java.lang.Object class of Java.

Syntax:

Class<? extends Colour> java.lang.Object.getClass()

This method returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.

Parameters: NA

Returns: The Class object that represents the runtime class of this object.

Exceptions: NA

Approach

Java

enum Colour {
    RED, GREEN, GRAY, ORANGE
}

public class EnumgetClass {
    public static void main(String[] args) {

        System.out.println(Colour.RED.getClass());
    }
}

Output:

class com.example.Enum.Colour