Home

How to Use Strings in a Java Switch Statement

|
|  Updated:  
2017-05-04 11:13:43
|   From The Book:  
Java Essentials For Dummies
Explore Book
Buy On Amazon
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: