How to Use Strings in a Java Switch Statement

By Barry A. Burd

An int value inside a switch statement works in any version of Java, old or new. (For that matter, char values and a few other kinds of values have worked in Java’s switch statements ever since Java was a brand-new language.)

Starting with Java 7, you can set it up so that the case to be executed in a switch statement depends on the value of a particular string. The code below illustrates the use of strings in switch statements.

string in switch statements
Running the code.

This code illustrates a switch statement with a string.

import static java.lang.System.out;

import java.util.Scanner;

 

public class SwitchIt7 {

 

public static void main(String args[]) {

Scanner keyboard = new Scanner(System.in);

out.print("Which verse (one, two or three)? ");

String verse = keyboard.next();

 

switch (verse) {

case "one":

out.println("That's because he has no brain.");

break;

case "two":

out.println("That's because he is a pain.");

break;

case "three":

out.println("'Cause this is the last refrain.");

break;

default:

out.println("No such verse. Please try again.");

break;

}

 

out.println("Ohhhhhhhh… .");

 

keyboard.close();

}

}

Get some practice with if statements and switch statements!

Write a program that inputs the name of a month and outputs the number of days in that month. In this first version of the program, assume that February always has 28 days.

Make your code even better! Have the user input a month name, but also have the user input yes or no in response to the question Is it a leap year?