also read:- Boolean datatype in java
Switch statement syntax:-
switch(expression)
{
case value1:
statement;
break; //break the execution and goes outside of switch.
case value2:
statement;
break;
.
.
.
default: //Goes to default value
statement;
}
The data type of expression inside switch keyword must be same as the value part of case.Break statement is used to stop the execution in every case.When the value inside the expression does not match with any of case value then it goes inside default part and execute that statement.If we do not use break statement then that case will continue to execute.
So it’s necessary to use break to avoid infinite execution situation.
There is one example below through which you will get better idea of switch in java.
Problem:-Execute a java program using switch statement
Code–>>
import java.util.Scanner;
class sw{
public static void main(String args[])
{
Scanner temp=new Scanner(System.in);
int i;
i=temp.nextInt();
System.out.println(“Enter your number”);
switch(i)
{
case 1:
System.out.println(“Java is so easy”);
break;
case 2:
System.out.println(“Java is neither easy nor hard”);
break;
case 3:
System.out.println(“Java is so hard”);
break;
default:
System.out.println(“No comments for java”);
}
}
}
Output:-
2
Java is neither easy nor hard.
Logic:-
First we have imported one java library file named Scanner for getting value from user.We have created object temp of scanner file.Through temp we have initialised variable i using nextInt() statement.There are three case values having integer data type.Depending upon the value of i inside switch statement, particular statement executed within that case.If value does not match then it goes inside default part.Here we have initialised value i to 2. so it goes towards case 2 and then prints the statement.There is break keyword after it,so it goes outside of switch after first execution and ends the program.