1、switch使用示例
从 Java 7 开始,可以在 switch 条件判断语句中使用 String 对象。
String s = "a"; switch (s) { case "a": System.out.println("case is a"); break; case "b": System.out.println("case is b"); break; } //default的用法:在没有匹配到的情况或匹配到的代码块没有break,就会执行default代码。 switch (case) { case "a": System.out.println("case is a"); break; case "b": System.out.println("case is b"); break; default: System.out.println("default"); break; }
2、switch 不支持 long
switch 不支持 long,是因为 switch 的设计初衷是对那些只有少数的几个值进行等值判断,如果值过于复杂,那么还是用 if 比较合适。
// long x = 111;
// switch (x) { // Incompatible types. Found: 'long', required: 'char, byte, short, int, Character, Byte, Short, Integer, String, or an enum'
// case 1:
// System.out.println(111);
// break;
// case 2:
// System.out.println(222);
// break;
// }