Page 253 - PowerPoint Presentation
P. 253
CAVITE STATE UNIVERSITY
TRECE MARTIRES CITY CAMPUS
Department of Information Technology DCIT 111 - Advanced Programming
Java Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like
if-else-if ladder statement. The switch statement works with any data type like int, char, string
and more.
In other words, the switch statement tests the equality of a variable against multiple
values.
//Syntax
switch (expression) {
case value1:
// code to be executed
break; public class SwitchExample {
case value2: public static void main(String[] args) {
// code to be executed
break; int num=20;
.. char a= ‘A’;
default: string h= “Hello”;
// code to execut if all cases are not
matched switch (num) { // can be change to a or h.
} case 10:
System.out.println(“The number is 10”);
break;
NOTE: case 20:
System.out.println(“The number is 20”);
If char is used as the data type in break;
switch statement, we should add
single apostrophe (‘ ‘ ) . case 30:
System.out.println(“The number is 30”);
Example: break;
switch (variable_name):
case ‘A’ or ‘+’ :
System……… default:
break; System.out.println(“Invalid”);
break;
If string is used as the data type in }
switch statement, we should add }
double apostrophe (“ “). }
Example:
switch(variable_name):
case “String”:
System…..
break;
29