Java隐式类型转换和强制类型转换

一、强制类型转换

char 和 整型之间的类型转换

 1 char a7 = 'a';
 2 System.out.println(a7);
 3 
 4 System.out.println( (int)a7 );
 5 System.out.println( (byte)a7 );
 6 System.out.println( (short)a7 );
 7 
 8 int b1 = 101;
 9 System.out.println( (char)b1 );
10 System.out.println( (char)(b1 + 1) );

输出:

a
97
97
97
e
f

下面这段代码会把 26 个小写字母对应的 int 值打印出来

1 char[] chs = {
2             'a','b','c','d','e','f','g','h','i','j','k','l','m',
3             'n','o','p','q','r','s','t','u','v','w','x','y','z'};
4 
5 for (int i = 0; i < chs.length; i++) {
6     System.out.println( (int)chs[i] );
7 }

二、隐式类型转换

这是一个很经典的题目,先看代码:

1 short a = 1;
2 short b = 2;
3 
4 short c = a + b;

答案是第4行代码出现编译错误:“可能损失精度”

原因:在进行 a + b 操作时,会把结果的类型“隐式”提升为 int 类型,此时再使用 short 类型的 c 变量引用时,就会出现“损失精度”

可以把 a + b 的结果强制转换为 short 类型,但是可能导致数值精度发生错误。也就是说可以解决编译期的错误,但是可能在运行期出现BUG

1 short a = 1;
2 short b = 2;
3 
4 // short c = (a + b);
5 short c = (short)(a + b);

还可以使用 int 或者 long 类型变量接收返回值

1 short a = 1;
2 short b = 2;
3 
4 int c = (a + b);
原文地址:https://www.cnblogs.com/xugf/p/7795305.html