Table of contents
Switch Keyword:
The switch
is one of the alternatives for the many if.....else
conditions. Instead of using many if-else
statements we case use the switch
statements.
The main use of the switch
statement It selects one of many code blocks
to be executed.
//syntax for the java switch statement
switch(expression) {
case a:
// code block
break;
case b:
// code block
break;
default:
// code block
}
Important points :
The
switch
statement can be evaluated one time only.The value of the expression is compared with the values of each
case.
If any match is found with the
case
then the specificcode block
will be executed.If we use the
switch
statement, we need to provide thedefault case
value as well.
Switch
Example:
public class Main{
public static void main(String[] args){
int number = 4;
switch(number){
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("You have given an invalid entry");
}
}
}
Output:
Break Keyword:
The break
is the keyword that can help helpful for breaking out of the switch
statement.
The main use of this break
keyword is, it will stop the execution of more code
and case
testing inside the block.
If a job is done, then the next step is to break
from the switch
. There is no need for extra testing.
public class Main{
public static void main(String[] args){
int age = 18;
switch(age){
case 18:
System.out.println("Your Minor");
break;
case 19:
System.out.println("You are Major");
break;
default:
System.out.println("--Invalid--");
}
}
}
Output:
Default Keyword:
default
is a keyword that is used in the Switch statements.
We need to provide the default case because even if all the switch cases
fail then the default
case code block gets executed.
public class Main{
public static void main(String[] args){
int age = 24;
switch(age){
case 18:
System.out.println("Your Minor");
break;
case 19:
System.out.println("You are Major");
break;
default: //here age is 24 and which is not matched with any case
System.out.println("Age is above 25");
}
}
}