Java 7: Using strings in switch statements

  Java Features     Java 5     Java 7     Java 8  
Java 7 features
 Binary literals |   Strings in switch statements |   Catching multiple exceptions |   Try with resources |   Type inference |   Underscores in numeric literals |   By date 

This is a simple feature in JSE7, which allows to pass a String to switch statements. That was not allowed in earlier Java versions. Let’s see how it works!

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

Example 1: The seasons in a switch statement

What is the output of the following code?

public class Season
  public static void main(String[] args)
    /* we pass the string season 
     * to the switch statement
    String season = "Summer";
      case "Spring":
        System.out.print("Is Spring");
      case "Summer":
        System.out.print("Is Summer");
      case "Autumn":
        System.out.print("Is Autumn");
      case "Winter":
        System.out.print("Is Winter");
        System.out.print("Invalid: " + season);

Author: Sar Maroof

Answer explanation

This code is simple as any other switch code in Java, but the only different is that this program passes String (“Summer”) instead of int or char to the switch statement.

The correct answer is: Is Summer

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