一、JDK9的JShell简单使用
/* 使用方法: cmd中输入jshell; 可以直接写输出语句 jshell->System.out.println("Hello,World!"); Hello,World! jshell->int a = 10; a ==> 10; jshell-> int b = 20; b ==> 20; jshell->int result = a * b; result ==> 200 jshell->System.out.println("结果是:" + result); 结果是:200; jshell-> exit // 错误退出 jshell-> /exit // 正确退出 再见 */
二、编译器的两点优化
/* 对于bute/short/char三种类型来说,如果右侧赋值的数值没有超过范围, 那么javac编译器将会自动隐含的为我们补上一个(byte)(short)(char). 1、如果没有超过左侧的范围,编译器补上强转。 2、如果右侧超过了左侧饭费,那么直接编译器报错。 */ public class Demo12Notice{ public static void main(String[] args){ // 右侧确实是一个int数字,但是没有超过左侧的范围,就是正确的 // int -->byte,不是自动类型转换 byte num1 = 30; // 右侧没有超过左侧的范围 System.out.println(num1); // 30 // byte num2 = 128; // 右侧超过了左侧的范围 // int -->char,没有超过范围 // 编译器将会自动补上一个隐含的(char) char zifu = /*(char)*/65; System.out.println(zifu); // A } }
/* 在给变量进行赋值的时候,如果右侧的表达式当中全都是常量,没有任何变量, 那么编译器javac将会直接将若干个常量表达式计算得到结果。 short result = 5 + 8; // 等号右边全都是常量,没有过任何变量参与运算 编译之后,得到的.class字节码文件当中相当于【直接就是】: short result = 13; 右侧的常量结果数值,没有超过左侧范围,所以正确。 这称为"编译器的常量优化"。 但是注意:一旦表达式当中有变量参与,那么就不能进行这种优化了。 */ public class Demo13Notice{ public static void main(String[] args){ short num1 = 10; // 正确写法,右侧没有超过左侧的范围。 short a = 5; short b = 8; // short + short --> int + int --> int // short result = a + b; // 错误写法!左侧需要是int类型 // 右侧不用变量,而是采用常量,而且只有两个常量,没有别人 short result = 5 + 8; System.out.println(result); // short result2 = 5 + a + 8; // 18 变量不能使用编译器优化 } }