Example & Tutorial understanding programming in easy ways.

Can we use String in switch case?

In this section we using Strings in Switch case, we are accepting a String command from console, and passing it to our execute method, which is like a remote control, execute the command given. If you look at the code, we have used String variables in switch as well as case. They don't have to be upper case, but they are case sensitive, and that's why keeping them in one case, preferably upper case is good for maintenance.

note: before java1.7 it is not possible, but in java1.7 it is possible use string in switch case.

example:

import java.util.Scanner;

public class stringtest{

public static void main(String args[] ) {

Scanner scnr = new Scanner(System.in);

while(true) {

System.out.println("Please enter day : ");

String command = scnr.nextLine();

// command = command.toUpperCase();

execute(day);}}

public static void execute(String day) {

switch (day) {

case "monday":

System.out.println("monday ...");

break;

case "tuesday":

System.out.println("tuesday ...");

break;

case "wednusday":

System.out.println("wednusday...");

break;

case "thursday":

System.out.println("thursday...");

break;

case "friday":

System.out.println("friday ...");

break;

case "saturday":

System.out.println("saturday ..");

case "sunday":

System.out.println("sunday ...");

System.exit(0);

break;

default :

System.out.println("Unknown day"); }}}


  

Read More →