![]() |
![]() |
Java if statement | |
Java if-else statement | |
Java nested if-else | |
Java else-if ladder | |
Java Switch case statement | |
Java Nested Switch Case | |
Java Ternary/Conditional operator |
Java while loop | |
Java do-while loop | |
Java for loop | |
Java Enhanced loop/for each loop | |
Java Labelled for loop | |
Java Nesting of loops | |
Java Break and Continue |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
Java has a built-in multi way decision statement known as switch statement.
When in our program number of alternatives increases then program becomes difficult to read(Like if else statement). It may confuse to the developer a lot. This is overcome using the switch statement.
Switch case is similar to the if else statement, But the reason for switch case use is that switch knows which case need to be executed. This is not possible in if else statement. If else has to go through all conditions
switch ( test-expression ) { case const_value1: // case 1 statements; break; case const_value2: // case 2 statements; break; . . . case const_value N: // case N statements; break; default: // same as else // default block statements break; }
case
values.default
block statement.Vowel - it is speech sound produced when breath flows out through the mouth without being blocked by the teeth, tongue, or lips. Ex - a,e,i,o,u
Consonant - it is speech sound produced by completely or partly stopping the air being breathed out through the mouth. Ex- except Vowels all others are Consonants.
public class SwitchDemo { public static void main(String[] args) { char mychar = 'i'; String result; switch(mychar) { case 'a': result = "Vowel"; break; case 'e': result = "Vowel"; break; case 'i': result = "Vowel"; break; case 'o': result = "Vowel"; break; case 'u': result = "Vowel"; break; default: result = "Consonant"; break; } System.out.println("Given character is "+result); } }
Output
In above example first of all condition is checked using mychar variable, the compiler searched for the matching case statement in the block of code. if case is matched then result variable is assigned.
We can write the switch case statement in different ways.
We can write above program for checking vowels and consonant as.
public class SwitchNoBreak { public static void main(String[] args) { char mychar = 'u'; String result; switch(mychar) { case 'a': case 'e': case 'i': case 'o': case 'u': result = "Vowel"; break; default: result = "Consonant"; } System.out.println("Given character is "+result); } }
Output