The switch-expression uses a String type.
If the switch-expression is null, a NullPointerException is thrown.
The case labels must be String literals.
We cannot use String variables in the case labels.
The following is an example of using a String in a switch statement.
public class Main {
public static void main(String[] args) {
String status = "off";
switch (status) {
case "on":
System.out.println("Turn on");
case "off":
System.out.println("Turn off");
break;
default:
System.out.println("Unknown command");
break;
}
}
}
运行结果如下:
The equals() method of the String class performs a case-sensitive string comparison.
public class Main {
public static void main(String[] args) {
operate("on");
operate("off");
operate("ON");
operate("Nothing");
operate("OFF");
operate("No");
operate("On");
operate("OK");
operate(null);/* w w w . ja va 2 s.com*/
operate("Yes");
}
public static void operate(String status) {
// Check for null
if (status == null) {
System.out.println("status cannot be null.");
return;
}
status = status.toLowerCase();
switch (status) {
case "on":
System.out.println("Turn on");
break;
case "off":
System.out.println("Turn off");
break;
default:
System.out.println("Unknown command");
break;
}
}
}
运行结果如下:
![](/attachments/jimg/qa/ANSWER__9D9C9A2C9B8F686B6FA4.png)