
What is a Switch Case in Java?
The switch statement or switch case in java is a multi-way branch statement. Based on the value of the expression given, different parts of code can be executed quickly. The given expression can be of a primitive data type such as int, char, short, byte, and char. With JDK7, the switch case in java works with the string and wrapper class and enumerated data type (enum in java).
Rules to Remember
certain points to remember while writing a switch case in java.
This is how it works:
// Syntax
switch(expression) { case 1 : //statement break; case 2 : //statement break; default: //statement }
Flow Chart
Program
public static void main(String[] args) { char ch='A'; switch(ch) { case 'a': System.out.println("Vowel"); break; case 'e': System.out.println("Vowel"); break; case 'i': System.out.println("Vowel"); break; case 'o': System.out.println("Vowel"); break; case 'u': System.out.println("Vowel"); break; case 'A': System.out.println("Vowel"); break; case 'E': System.out.println("Vowel"); break; case 'I': System.out.println("Vowel"); break; case 'O': System.out.println("Vowel"); break; case 'U': System.out.println("Vowel"); break; default: System.out.println("Consonant"); } }
output // Vowel
The break Keyword
When Java reaches a break
keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need for more testing.
The default Keyword
The default
keyword specifies some code to run if there is no matching found.
In this article, we have discussed how we can use switch case in java with various examples. With the use of conditional statements it becomes easier to test multiple conditions at once and also generate an optimized solution of rather difficult problem