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) {
		System.out
				.println(" Aristotle\n Plato\n Socrates\n Gandhi\nEnter you favourite philosopher:\n ");
		Scanner sc = new Scanner(System.in);
		String philosopher = sc.nextLine();
		System.out.println("\n");
		switch (philosopher.toUpperCase()) {

		case "ARISTOTLE":
			System.out
					.println("A friend to all is a friend to none.\n - Aristotle");
			break;
		case "PLATO":
			System.out.println("Love is a serious mental disease.\n - Plato");
			break;
		case "SOCRATES":
			System.out
					.println("The only true wisdom is in knowing you know nothing.\n - Socrates ");
			break;
		case "GANDHI":
			System.out
					.println("An eye for an eye only ends up making the whole world blind.\n - Gandhi");
			break;
		default:
			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:
Java7SwitchDemo.zip (3K)

Leave a Reply