enum in switch statement

      No Comments on enum in switch statement




enum concept was introduced in java 1.5 . from 1.5 version in Java, switch statements were allowed to use enums.

MONTHS.java

package com.masterjavatutorial;

public enum MONTHS {
	 
    JAN,FEB,MAR,APR,MAY;

}

Test.java

package com.masterjavatutorial;

public class Test {

	public static void main(String args[]) {

		printMonth(MONTHS.APR);
		printMonth(MONTHS.MAR);
		printMonth(MONTHS.FEB);
		printMonth(MONTHS.JAN);
		
	}

	public static void printMonth(MONTHS whichMonth) {
	    switch (whichMonth) {
		case JAN:
			System.out.println("January Month");
			break;
		case FEB:
			System.out.println("February Month");
			break;
		case MAR:
			System.out.println("March Month");
			break;
		case APR:
			System.out.println("April Month");
			break;
		default:
			System.out.println("Other Month");
			break;

	   }
	}
}

Output of the above program is as below:

April Month
March Month
February Month
January Month

What if null is passed as an argument in switch statement??

switch(null){….} // This will give NullPointer Exception in Java.
So, in switch statement, value must be not null.