Switch Statement in Java
This is how switch statement works in java
-
switch is used to be tested equally by the list of values in a variable
-
Each value is called a case to be check from a variable expression in the switched
-
break keyword is used to stop the execution of a case block. When Java reaches the break keyword then it means that there’s a match found in a case and the execution stops.
-
default keyword is similar to else when you are using the IF statement. When a value of a variable doesn’t match the value in the case then the default keyword will then execute and stop.
Sample Code
import java.util.Scanner;
/**
*
* @author KENSOFT
*/
public class Switch {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Please choose a letter from A-C: ");
char input = scan.next().charAt(0);
String value = String.valueOf(input);
switch (value){
case "a":
System.out.println("You entered A");
break;
case "b":
System.out.println("You entered B");
break;
case "c":
System.out.println("You entered C");
break;
default:
System.out.println("Out of Scope");
break;
}
}
}
Scanner class in Java is used for obtaining the input value. next() function is used to return the next word in the input as a string and the charAt(0) returns the first character input in that string.
Output
Please choose a letter from A-C: b You entered B



















