Java Switch Statement Example
Java Switch Statement in one way or the other is similar to Java If-else Statement .One condition is executed from several statements.
Java Switch Statement Syntax :
switch(expresssion statement){
case 1: value
//code that will be executed if true value is returned:
break;
case 2: value
//code that will be executed if true value is returned:
break;
.....................
default:
//this code is executed if all the conditions fails:
}
Java Switch Statement Example:
/**
*
* @author acer
*/
public class SwitchStatement {
public static void main(String[] args) {
int score=70;
switch(score)
{
case 90:
System.out.println("Student score grade A in maths");
break;
case 80:
System.out.println("Student score grade B in maths");
break;
case 70:
System.out.println("Student score grade C in maths");
break;
case 60:
System.out.println("Student score grade D in maths");
break;
default:
System.out.println("Student score grade E in maths");
}
If break keyword is not used,Java Switch Statement becomes a fall through.
What it means by Java Switch Statement fall through?
Java fall through statements means that if the first conditions returns true,other statements that follow are executed.
Execute below code and see the results:
/**
*
* @author acer
*/
public class SwitchStatement {
public static void main(String[] args) {
int score=80;
switch(score)
{
case 90:
System.out.println("Student score grade A in maths");
case 80:
System.out.println("Student score grade B in maths");
case 70:
System.out.println("Student score grade C in maths");
case 60:
System.out.println("Student score grade D in maths");
default:
System.out.println("Student score grade E in maths");
}
}
}
Output
/**
Student score grade B in maths
Student score grade C in maths
Student score grade D in maths
Student score grade E in maths