Java Tutorials Series - Enum types

We will be learning about Enum in Java, how they can be implemented and what is the usage of Enum in Java in this tutorial. Consider there is a variable and it can have limited values in it, in that case we can make good use of Enum.

Enum Types in Java

Syntax of creating Enum in Java is similar to that of creating classes or interfaces in Java. by now, we already know that Enum contains the set of fixed values that can be used by a variable. It may or may not be in any order.

Before learning Enum, let's look at one of the code below -

Existing code in Java without the usage of enum -

public class App {

public static final int CAT = 0;
public static final int DOG = 1;
public static final MOUSE =2;

public static void main(String[] Args) {

int animal = CAT;

switch(animal)
{
case DOG :
    System.out.println("This is a DOG");
    break;
case CAT :
   System.out.println("This is CAT");
   break;
}
}
}

Can you see the highlighted text above? That is where we can implement the enum, animal can take either cat, dog and mouse, that is inevitable. Let's look at same code implementation with the help of enum in Java.

Implementation of enum in the same code -

Creating enum -
public enum Animal {
          CAT,DOG, MOUSE;
}

public class App {
public static void main(String[] Args) {

Animal  animal = Animal.CAT;

switch(animal)
{
case DOG :
    System.out.println("This is a DOG");
    break;
case CAT :
   System.out.println("This is CAT");
   break;
}
}
}


  • enum can also have a constructor and methods.
  • Whatever is passed in enum are objects and not to be considered as Strings.
That's all that needs to be covered for basics of enums, we needn't to cover the advance concepts of enum because that is not being used by developers.

Happy Learning and Happy Sharing!

Comments

Popular posts from this blog

Azure Tutorials Series - Azure Networking

Testing in CI/CD

Azure Tutorials Series - IaaS vs PaaS vs SaaS