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)? ");

<strong> String verse = keyboard.next();</strong>

switch (<strong>verse</strong>) {

case <strong>"one"</strong>:

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

break;

case <strong>"two"</strong>:

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

break;

case <strong>"three"</strong>:

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?

About This Article

This article is from the book:

About the book author:

Dr. Barry Burd holds an M.S. in Computer Science from Rutgers University and a Ph.D. in Mathematics from the University of Illinois. Barry is also the author of Beginning Programming with Java For Dummies, Java for Android For Dummies, and Flutter For Dummies.

This article can be found in the category: