Friday, September 11, 2015

Switch in Java 7

In java 7 we got some significant improvement that is worth noting. Before Java 7 it was only possible to check Integer expressions in switch statements but after Java 7 you can use String Object in the expression of a switch statement.

Example:
/**
 * 
 */
package com.blogspot.thinkwithjava;

/**
 * Program to show the use of String comparison in Switch statements
 * 
 * @author RD
 * 
 */
public class SwitchWithString {

 public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
  String typeOfDay;
  switch (dayOfWeekArg) {
  case "Monday":
   typeOfDay = "Start of work week";
   break;
  case "Tuesday":
  case "Wednesday":
  case "Thursday":
   typeOfDay = "Midweek";
   break;
  case "Friday":
   typeOfDay = "End of work week";
   break;
  case "Saturday":
  case "Sunday":
   typeOfDay = "Weekend";
   break;
  default:
   throw new IllegalArgumentException("Invalid day of the week: "
     + dayOfWeekArg);
  }
  return typeOfDay;
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  SwitchWithString sws = new SwitchWithString();

  System.out.println("Monday is a "
    + sws.getTypeOfDayWithSwitchStatement("Monday"));

 }

}

Output is: Monday is a Start of work week


No comments:

Post a Comment

Java garbage collection

In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...