Switch Statement in Java
Starting from JDK 7, we can use string literals/constants to control switch statements, which is impossible in C/C++. Using a string-based switch is an improvement over the equivalent sequence of using if/else statements.
Important Points:
In Java, the switch statement is used to evaluate an expression and perform different actions based on different possible values of the expression. The expression can be of any data type, including primitive types like int, long, and char.
One of the features of the switch statement in Java is the ability to use a string as the expression to be evaluated. This is called a string in switch case. When using a string in a switch case, each case statement compares the value of the string with a specific string literal. If a match is found, the code block corresponding to that case is executed.
Here's an example of how to use a string in a switch case:
String day = "Monday"; switch (day) { case "Monday": System.out.println("Today is Monday"); break; case "Tuesday": System.out.println("Today is Tuesday"); break; case "Wednesday": System.out.println("Today is Wednesday"); break; default: System.out.println("Today is neither Monday, Tuesday, nor Wednesday"); }
In this example, the value of the string variable day
is compared to the string literals in each case statement. Since day
is equal to "Monday", the code block corresponding to the first case is executed, and the output is "Today is Monday". If the value of day
were "Friday", the code block corresponding to the default
case would be executed instead.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.