We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 2b549a7 commit 5316c10Copy full SHA for 5316c10
1 file changed
pages/P38 整数类型详解 3.md
@@ -6,4 +6,16 @@
6
- ① 在Java中,多种数据类型混合运算时,各自先转换成容量最大的类型,再做运算 byte a = 100;
7
- int b = 200;
8
- long c = 300L;
9
- - long d = a + b + c;
+ - long d = a + b + c;
10
+- 编译器的小心思
11
+ - 以下程序编译通过:
12
+ - byte x = 10 / 3;
13
+ - 为什么编译通过?这种情况下都是字面量的时候,编译器可以在编译阶段得出结果是3,而3没有超出byte 取值范围。可以直接赋值。
14
+ - 以下程序编译报错:
15
+ - int a = 10; int b = 3; byte x = a / b;
16
+ - 为什么编译失败?这种a和b都是变量的情况下,编译器是无法在编译阶段得出结果的,编译器只能检测到结果是int类型。int类型不能直接赋值给byte类型变量。
17
+ - 怎么解决?要么把x变量声明为int类型,要么强制类型转换,例如:
18
+- int a = 10; int b = 3;byte x = (byte) (a / b) ;
19
+- 这里需要注意的是:注意小括号的添加,如果不添加小括号,例如:
20
+- int a = 10; int b = 3;byte x = (byte) a / b;
21
+- 这样还是编译报错,因为只是将a强转为byte了,b还是int。byte和int混合运算,结果还是int类型。
0 commit comments