Enum in java



enum used to define the constants variable.You can also define the enum inside the class.


enum cartoons and the class cartoons are Equal.




enum Cartoons
{
      TOM_AND_JERRY,
      AVATAR,
      BEN_TEN;
} 
class Cartoons
{
       static final Cartoons TOM_AND_JERRY = new Cartoons();
       static final Cartoons AVATAR = new Cartoons();
       static final Cartoons BEN_TEN = new Cartoons(); 
}     







Example-1
enum Cartoons                               
{
      TOM_AND_JERRY,AVATAR,BEN_TEN;
}

public class Main
{
      public static void main(String[] args) 
      {
            System.out.print(Cartoons.TOM_AND_JERRY);
      }
}


Output



TOM_AND_JERRY








Example-2
enum Cartoons                               
{
      TOM_AND_JERRY,AVATAR,BEN_TEN;
}

public class Main
{
    public static void main(String[] args) 
    {
          Cartoons c = Cartoons.TOM_AND_JERRY;

          switch(c)
          {
              case TOM_AND_JERRY:

                                  System.out.println("I Love TOM_AND_JERRY");
                                  break;

              case AVATAR:

                                  System.out.println("I Love AVATAR");
                                  break;

              case BEN_TEN:
                                  System.out.println("I Love BEN_TEN");
                                  break;
          }
    }
}


Output



I Love TOM_AND_JERRY







Example-3
enum Cartoons 
{
      TOM_AND_JERRY(10),AVATAR(20),BEN_TEN(30);

      int total_Episodes;

      Cartoons(int t)
      {
            total_Episodes=t;
      }
}

public class Main 
{ 
      public static void main(String[] args) 
      { 
            for(Cartoons myVar : Cartoons.values()) 
            {
                  System.out.println(myVar+" : "+myVar.total_Episodes);
            }
      } 
}



Output



TOM_AND_JERRY : 10
AVATAR : 20
BEN_TEN : 30