Exercise:
Write a Java Program to implement switch statement on strings.
Click Here to View the Solution!
public class ImplementSwitch {
public static void main(String[] args) {
String city = "Paris";
switch(city) {
case "London":
System.out.println(city + " is famous for its cultural dynamism.");
break;
case "Paris":
System.out.println(city + " is famous for Eifel Tower .");
break;
case "New York":
System.out.println(city + " is famous for Statue of Liberty.");
break;
default:
System.out.println(city + " not found on record.");
break;
}
}
}
Click Here to View the Output!
Paris is famous for Eifel Tower.
Click Here to View the Explanation!
- This program is used to apply the
switch statement
over the given strings in Java. - Initially, a string variable
city
is initialized ascity = Paris
. - The
switch block
holds multiple case statements each of which specify a distinct string value. - The variable
city
will be given as a parameter to theswitch method
, the value of which will be compared with each case until the same string value is found in a case. - Once, the given string value is found in a case statement, the body of that case is executed and then the break statement stops further program execution.
- In this program, the second case holds the same string value as
city
, hence the code in its body is executed therefore, printingParis is famous for Eifel Tower.
- If neither case matches, the default case is executed.