OnJava8-Examples/control/StringSwitch.java

45 lines
1.1 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// control/StringSwitch.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-06-15 17:47:35 -07:00
public class StringSwitch {
public static void main(String[] args) {
String color = "red";
// Old way: using if-then
if("red".equals(color)) {
2015-11-03 12:00:44 -08:00
System.out.println("RED");
2015-06-15 17:47:35 -07:00
} else if("green".equals(color)) {
2015-11-03 12:00:44 -08:00
System.out.println("GREEN");
2015-06-15 17:47:35 -07:00
} else if("blue".equals(color)) {
2015-11-03 12:00:44 -08:00
System.out.println("BLUE");
2015-06-15 17:47:35 -07:00
} else if("yellow".equals(color)) {
2015-11-03 12:00:44 -08:00
System.out.println("YELLOW");
2015-06-15 17:47:35 -07:00
} else {
2015-11-03 12:00:44 -08:00
System.out.println("Unknown");
2015-06-15 17:47:35 -07:00
}
// New way: Strings in switch
switch(color) {
case "red":
2015-11-03 12:00:44 -08:00
System.out.println("RED");
2015-06-15 17:47:35 -07:00
break;
case "green":
2015-11-03 12:00:44 -08:00
System.out.println("GREEN");
2015-06-15 17:47:35 -07:00
break;
case "blue":
2015-11-03 12:00:44 -08:00
System.out.println("BLUE");
2015-06-15 17:47:35 -07:00
break;
case "yellow":
2015-11-03 12:00:44 -08:00
System.out.println("YELLOW");
2015-06-15 17:47:35 -07:00
break;
default:
2015-11-03 12:00:44 -08:00
System.out.println("Unknown");
2015-06-15 17:47:35 -07:00
break;
}
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
RED
RED
2015-09-07 11:44:36 -06:00
*/