我们可以用 javap 命令查看编译的字节码(bytecode)。引用的比较对应 if_acmpeq、if_acmpne 两条指令,其中字母 a 表示 reference,cmp 是比较(comparison),整型的比较会有大于、小于、等于的判断关系,而 reference 的比较只有相等、不等两种。于是,修改成 equals 如下:pub
privatestaticvoidtest(Status status){int result=0;switch(status){caseOPEN:result=1;break;casePROCESS:result=2;break;casePENDING:result=2;break;caseCLOSE:result=3;break;default:thrownewRuntimeException("状态不正确");}System.out.println("result is "+result);} Java 14+ 后可以这样用: 代码语言:...
Javaswitch语句用于从多个条件执行一个语句。它就像if-else-if语句一样。 语法: switch(expression){ case value1: //code to be executed; break; //optional case value2: //code to be executed; break; //optional …… default: // code to be executed if all cases are not matched; } switch语...
字节码如下: Code:0: iconst_31: istore_12: iload_13: tableswitch{//0 to 140:76;1:87;2:153;3:98;4:153;5:109;6:153;7:153;8:153;9:153;10:120;11:153;12:153;13:131;14:142;default:153}76: getstatic #2;//Field java/lang/System.out:Ljava/io/PrintStream;79: ldc #3;//Stri...
Java Copy In this example, we have a switch statement that checks the value of the variableday. Depending on the value, it executes a different code block. Ifdayis 1, it prints ‘Monday’. Ifdayis 2, it prints ‘Tuesday’. In our case,dayis 3, so none of the cases match and not...
这是在Java7中支持switch的表达式为字符串时,编译器针对switch中为字符串的实现方式。当执行case分支时...
还是用JDK自带的javap,看一眼bytecode吧 代码语言:txt AI代码解释 0: iconst_0 1: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 4: astore_1 5: aload_1 6: invokevirtual #3 // Method java/lang/Integer.intValue:()I ...
Java Switch Statement 1. Overview In this tutorial, we’ll learn what theswitchstatement is and how to use it. Theswitchstatement allows us to replace several nestedif-elseconstructs and thus improve the readability of our code. Switchhas evolved over time. New supported types have been added...
SyntaxGet your own Java Server switch(expression){casex:// code blockbreak;casey:// code blockbreak;default:// code block} This is how it works: Theswitchexpression is evaluated once. The value of the expression is compared with the values of eachcase. ...
Code: 根据你键盘录入的字符串,判断是否有满足要求的,如果有就输出。 否则,提示有误。 String s = sc.nextLine(); import java.util.Scanner; class SwitchTest3 { public static void main(String[] args) { //创建键盘录入对象 Scanner sc = new Scanner(System.in); ...