Beginning with JDK 7, we can use a string literal/constant to control a switch statement, which is not possible in C/C++. Using a string-based switch is an improvement over using the equivalent sequence of if/else statements.
- Expensive operation: Switching on strings can be more expensive in term of execution than switching on primitive data types. Therefore, it is best to switch on strings only in cases in which the controlling data is already in string form.
- String should not be NULL: Ensure that the expression in any switch statement is not null while working with strings to prevent a NullPointerException from being thrown at run-time.
- Case Sensitive Comparison: The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive.
- Better than if-else: The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Menu-Driven program using Switch-case in C
- Switch Statement in Java
- Permute a string by changing case
- Sentence Case of a given Camel cased string
- Convert characters of a string to opposite case
- Toggle case of a string using Bitwise Operators
- Why You Should Switch to Kotlin from Java to Develop Android Apps?
- Extract and print words separately from a given Camel Case string
- Lower case to upper case - An interesting fact
- Decision Making in Java (if, if-else, switch, break, continue, jump)
- Case conversion (Lower to Upper and Vice Versa) of a string using BitWise operators in C/C++
- Check whether the given character is in upper case, lower case or non alphabetic character
- Convert a List of String to a comma separated String in Java
- Convert an ArrayList of String to a String array in Java
- Convert a Set of String to a comma separated String in Java
- Collator compare(String, String) method in Java with Example
- Collator equals(String, String) method in Java with Example
- String Literal Vs String Object in Java
- Convert Set of String to Array of String in Java
- Switch Statement in C/C++
Improved By : arjun_dandagi