What is switch statment?
- The switch keyword in Java is used to execute one block of code among many alternatives.
Syntax :
switch(expression){
case value1:
//code
break;
case value2:
//code
break;
...
...
default:
//default statment
}
- 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.
Which data types are supported in switch case expression?
- byte, short, int, char, String (since Java 7)
Not allowed:
- long,float,double,boolean
is it mandatory to use default statement in switch case in java?
- default is NOT mandatory in a Java switch. It is optional. We use it to handle unexpected values.
Why break statement is used?
- The break statement is used to terminate the switch-case statement. If break is not used, all the cases after the matching case are also executed.
What is fall-through in switch?
- Fall-through happens when a case block does not end with break, so execution continues into the next case block.
Can we have duplicate case values?
- No. Compiler error(duplicate case label).
Can we use expressions in case labels?
- No. Compiler error(constant expression required).
Example :
public class Sample {
public static void main(String[] args)
{
char grade = 'B';
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
break;
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
}
}
What is the syntax of Switch case supported in java 12 and above?
- arrow (->) syntax.
- No need to add break statement to each case statement.
Example:
int mark = 50;
switch (mark) {
case 90 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6 -> "Saturday";
case 7 -> "Sunday";
default -> "Faile";
};
System.out.println(dayName);
// Output: Wednesday
How to write multiple statement in a case block?
int day = 1;
switch (day) {
case 1:
System.out.println("Monday");
System.out.println("Start of week");
System.out.println("Go to work");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}
Java 12:
case 1 -> {
System.out.println("Monday");
System.out.println("Start of week");
}
How to write mutiple cases with same statement?
switch(day) {
case 1:
case 7:
System.out.println("Holiday");
System.out.println("Enjoy!");
break;
}
Java 12:
case 1, 7 -> System.out.println("Weekend");
Top comments (0)