![]() | |
|
In Java SE 7 and later, you can use a String
object in the switch statement's
expression. The following code example, StringSwitch
, displays the color RGB based
on the value of the String named color:
public class StringSwitch { public static void main(String[] args) { String color = "black"; switch (color) { case "white": System.out.print(color + " RGB: ffffff"); break; case "black": System.out.print(color + " RGB: 000000"); break; default: System.out.print(color + " RGB: UNKNOWN"); break; } } }
The output from this code is:
black RGB: 000000
The String
in the switch expression is compared with the expressions associated with
each case label as if the String.equals(...)
method were being used. Two things to
keep in mind:
Check for null
before the switch:
public class StringSwitchNull { public static void main(String[] args) { String color = null; switch (color) { case "white": System.out.print(color + " RGB: ffffff"); break; case "black": System.out.print(color + " RGB: 000000"); break; default: System.out.print(color + " RGB: UNKNOWN"); break; } } }
result:
Exception in thread "main" java.lang.NullPointerException at c1.s1.StringSwitchNull.main(StringSwitchNull.java:9) Java Result: 1
Check for different case letters before the switch:
public class StringSwitchCase { public static void main(String[] args) { String color = "BlAcK"; switch (color) { case "white": System.out.print(color + " RGB: ffffff"); break; case "black": System.out.print(color + " RGB: 000000"); break; default: System.out.print(color + " RGB: UNKNOWN"); break; } } }
result:
BlAcK RGB: UNKNOWN
![]() ![]() ![]() |