You can learn Java with me as the Java Programming language is being made easily. It would take a period of minimum three months and maximum 6 months to master Java. I would recommend you to watch all my videos to crack any software interviews that would require Java Programming language as a primary skill.
Methods inside the Java Enum:-
1. values()
2. valueOf(String name)
3. ordinal()
1. values()
=========
This method returns an array containing all of the values inside the enum in the order they have been declared.
enum Color
{
RED,GREEN,ORANGE;
}
Color[] colors=Color.values();//An array will be returned
Example program:-
=================
enum Color
{
RED,GREEN,ORANGE;
}
public class Test{
public static void main(String[] args)
{
Color[] colors =Color.values();
for(Color x:colors){
System.out.println(x);//Retrieving using enhanced for loop
}
}
}
Example:-
enum Color
{
RED("STOP"),GREEN("GO"),ORANGE("SLOW DOWN");
//Variable
String action;
//Constructor
Color(String action)
{
this.action=action;
}
//getter
public String getAction()
{
return action;
}
}
public class Test{
public static void main(String[] args)
{
System.out.println(Color.RED.getAction());
System.out.println(Color.ORANGE.getAction());
System.out.println(Color.GREEN.getAction());
}
}
ordinal() method:-
===============
What is an ordinal() method in java enum?
It is a method which is going to return the oridinal number for the particular enum constant.
It is available inside java.lang.Enum.
It is a non-static method and it can be accessed only with the class object.
It is a final method and it cant be overriden.
Syntax :-
========
public final int ordinal();
Return :-
========
This will return the ordinal number of the java enum.
enum Color
{
GREEN,ORANGE,BLACK,WHITE,RED;
}
public class Test{
public static void main(String[] args)
{
int number=Color.RED.ordinal();
System.out.println(number);//0
}
Please be informed that the ordinal number is the position of constants in the enum declaration.
enum{
A,B,C,D;
}
A 0 ordinal number
B 1 ordinal number
C 2 ordinal number
D 3 ordinal number
3. valuesOf(String name)
=======================
It is going to return the enum constant with the specified name.
Example:-
========
enum Color{
RED,BLUE,GREEN;
}
Color.valueOf("GREEN");
Example:-
========
enum Parts
{
SKIN,MUSCLES,BONES,ORGANS,TISSUE;
}
public class Test{
public static void main(String[] args)
{
System.out.println("The part which gets exposed to the Environment");
Parts[] p=Parts.values();
for(Parts x:p)
{
int or=x.ordinal()+1;//0,1,2,3,4
System.out.println(or+" . "+x);
}
Parts p1=Parts.valueOf("SKIN");
System.out.println("The Answer is "+p1);
}
}