Java Switch Statement just like if-else-if ladder statement executes on a statement from multiple conditions. Java Switch Statement Syntax...
Java Switch Statement just like if-else-if ladder statement executes on a statement from multiple conditions.
Java Switch Statement Syntax
[switch(expression ){
case value1: //code to be executed;
break; //optional
case value2: //code to be executed;
break; //optional ...... default: code to be executed if all cases fail to match;
}
]
]
Example:
[
public class JavaSwitchStatementExample { public static void main(String args[]) { int score=30; switch(score) { case 30: System.out.println("Number is 30"); break; case 40: System.out.println("Number is 40"); break; case 50: System.out.println("Number is 50"); break; case 60: System.out.println("Number is 60"); break; default: System.out.println("No match for the number"); } } }
]
Java Switch Statement can be a fall-through
If break keyword is not used,Java Switch Statement becomes a fall-through.
Run below code and compare the result with above.
[
public class JavaSwitchStatementExample { public static void main(String args[]) { int score=40; switch(score) { case 30: System.out.println("Number is 30"); case 40: System.out.println("Number is 40"); case 50: System.out.println("Number is 50"); case 60: System.out.println("Number is 60"); default: System.out.println("No match for the number"); } } }
]
You should note the Different between the two outputs.