Table of Contents
Switch case statement in Java language
In this tutorial, we will discuss the concept of the Switch case statement in Java language
In this post, we will learn how to use the switch case statement in java language
- The switch statement is one of the java statement allows a unique variable to be checked for equality against a list of the case value of the same type variable(int, String, char can use anyone )
- Switch case similar if-else statement functioning based Boolean expression.
- Switch statement choose and executes one from multiple conditions, that multiple conditions are called cases
- Any number of the case may use within a switch and every case statement contain a value to compared with switch value. case and case value separated by a colon(case: value)
- End of the switch can have a default statement the default statement can be used for performing a task when becoming false
Switch case Syntax in java
Syntax
switch case Flow diagram in java
How to work switch statements
- The switch statement is evaluated once
- The value of the switch expression is compared with the value of each case.
- When there is a match of the particular case, the associated block of statements is executed.
- When there is not match any cases, the default statement is executed.
Example programs to switch case
Example 2
public class switchnotd{ // start of class
public static void main(String args[]){// start of main method
int age=10; //variable Assignment
switch(age){ //swich expression
case 10: //if statement is true this case executed
System.out.println(“10”); //if false go to next case
case 20: //if statement is true this case executed
System.out.println(“20”);//if false go to next case
case 30: //if statement is true this case executed
System.out.println(“30”);//if false go to next case
default:System.out.println(“age not match”);
// all case are false this statement executed
}
} / end of main method
Example 3
class age{
public static void main (String args[]){
int age=20;
switch(age){
case 10:
System.out.println(“you age is ten”);
break;
case 20:
System.out.println(“you age is twenty”);
break;
case 30:
System.out.println(“you age is thirty”);
break;
case 40:
System.out.println(“you age is forty”);
break;
default:
System.out.println(“i don’t no age”);
break;
}
}
}
Similar post