Java started supporting Strings in switch statement since Java 7.
Here is an example of using Strings in switch block :
String status = "one";
switch(status) {
case "one":
System.out.println("Choice one"); // Matching case
break;
case "two:
System.out.println("Choice two");
break;
default:
System.out.println("Choice other than one or two");
break;
}
Things to note:
1) The String in the switch expression is compared with the expressions associated with each case label as if the String.equals method was used
2) The expression in switch statement(“status” in above example) must be NOT NULL. Otherwise, it will throw a Null Pointer exception.
3) The values in case(“one”, “two” in above example )should be literal values, not variables.
4) The string comparison in Switch statements is case sensitive.
© 2015 – 2016, https:. All rights reserved. On republishing this post, you must provide link to original post
#