Java 7 Switch String Support

Java 7 switch String support should have been added long way back! It was first requested 17 years ago!!

Until the previous version it supported variables and expressions which resolved into int, byte, short or char only. But now with the addition of String support, it will surely save a lot of complex if-else structures and improve the overall code readability.

Here is a self explanatory example of Switch with Strings in action:

We simply accept the String input and print the corresponding matching case.

Around The World Flights - Promo Code WORLD15
package com.quicklyjava;

import java.util.Scanner;

public class Java7SwitchDemo {

	 * @param args
	public static void main(String[] args) {
				.println(" Aristotle\n Plato\n Socrates\n Gandhi\nEnter you favourite philosopher:\n ");
		Scanner sc = new Scanner(;
		String philosopher = sc.nextLine();
		switch (philosopher.toUpperCase()) {

		case "ARISTOTLE":
					.println("A friend to all is a friend to none.\n - Aristotle");
		case "PLATO":
			System.out.println("Love is a serious mental disease.\n - Plato");
		case "SOCRATES":
					.println("The only true wisdom is in knowing you know nothing.\n - Socrates ");
		case "GANDHI":
					.println("An eye for an eye only ends up making the whole world blind.\n - Gandhi");
			System.out.println("No qoute for you.");



Output for Java 7 Switch String Support Example

java 7 switch string

Please note that you might face issues running this code in eclipse if it is not Java 7 compliant. You can refer to this post for adding Java 7 compliance to Eclipse.

You can download the eclipse project of the code explained in this tutorial: (3K)

Leave a Reply