Java 5: Enum types

  Java Features     Java 5     Java 7     Java 8  
Java 5 features
 Enhanced for Loop |   Varargs |   Static import |   Autoboxing and unboxing |   Enum types |   Generics |   Annotations |   By date 

The enum type is a new feature in Java 5. Whenever you have a fixed set of constants you can use the enum type. An example is the seasons of
the year, the days of the week and the planets of the solar system. We use the uppercase letters for the names of an enum type’s fields, because they are constants.

For more info click here to read Oracle’s explanation.

Example 1: Enum types code

What is the output of the following code?

Season.java

public enum Season
{
  SPRING, SUMMER, AUTUMN, WINTER
}

Test.java

 
public class Test
{
  Season season;
  
  public Test(Season season)
  {
    this.season = season;
  }
  public void info()
  {
    switch(season)
    {
      case SPRING:
        System.out.println("Spring");
        break;
      case SUMMER:
        System.out.println("Summer");
        break;
      case AUTUMN:
        System.out.println("Autumn");
        break;
      case WINTER:
        System.out.println("Winter");
        break;
      default:
        System.out.println("Invalid.");
        break;
    }
  }
  public static void main(String[] args)
  {
    Test season = new Test(Season.SPRING);
    season.info();
  }
}
Author: Sar Maroof

Answer explanation

The output of this program is: Spring.





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

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