Switch Statement: Ma'Am Cheng

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 9

SWITCH STATEMENT

MA’AM CHENG
switch (expression) {
The switch statement
case value1:
allows us to execute a // code
block of code among many break;

alternatives. case value2:


// code
break;
The syntax of the switch
statement in Java is: ...
...

default:
// default statements
}
How does the switch-case statement work?

The expression is evaluated once and compared with the


values of each case.

If expression matches with value1, the code of case


value1 are executed. Similarly, the code of case value2 is
executed if expression matches with value2.
If there is no match, the code of the default case is
executed.
// Java Program to check the size // match the value of week
// using the switch...case statement case 44:
size = "Large";
class Main { break;
public static void main(String[] args) {
case 48:
int number = 44; size = "Extra Large";
String size; break;

// switch statement to check size default:


switch (number) { size = "Unknown";
break;
case 29:
size = "Small"; }
break; System.out.println("Size: " + size);
}
case 42: }
size = "Medium";
break;
class Main {
public static void main(String[] args) {
Break statement in Java switch...case
int expression = 2;

// switch statement to check size


switch (expression) {
...
case 1:
case 29:
System.out.println("Case 1");
size = "Small";
break;
// matching case
...
case 2:
The break statem
System.out.println("Case 2");

case 3:
System.out.println("Case 3");

default:
System.out.println("Default case");
}
}
}
Output

Case 2
Case 3
Default case
Default case in class Main {

Java switch-case public static void main(String[] args) {

int expression = 9;
The switch statement
also includes an optional switch(expression) {
default case. It is case 2:
executed when the System.out.println("Small Size");
break;
expression doesn't match
any of the cases case 3:
System.out.println("Large Size");
break;

// default case
default:
System.out.println("Unknown Size");
}
}
}
Reference :
https://www.programiz.com/java-programming/switch-
statement

You might also like