基本数据类型转换规则

第一条:八种基本数据类型中,除 boolan 类型不能转换,剩下七种类型之间都可以进行转换;

第二条:如果整数型字面量没有超出 byte,short,char 的取值范围,可以直接将其赋值给byte,short,char 类型的变量;

第三条:小容量向大容量转换称为自动类型转换,容量从小到大的排序为:byte < short(char) < int < long < float < double,其中 short和 char都占用两个字节,但是char可以表示更大的正整数;

第四条:大容量转换成小容量,称为强制类型转换,编写时必须添加”强制类型转换符”,但运行时可能出现精度损失,谨慎使用;

第五条: byte,short,char 类型混合运算时,先各自转换成 int 类型再做运算;

第六条:多种数据类型混合运算,各自先转换成容量最大的那一种再做运算;

所有的笔试题都超不出以上的6条规则。

案例


public class TypeTransferTest{
	public static void main(String[] args){
	// 编译报错,因为1000已经超出范围了
	byte b1 = 1000;
	// 可以
	byte b2 = 20;
	// 可以
	short s = 1000;
	// 可以
	int c = 1000;
	// 可以
	long d = c;
	// 编译报错
	int e = d;
	// 可以
	int f = 10 / 3;
	// 可以
	long g = 10;
	// 编译报错
	int h = g / 3;
	// 可以
	long m = g / 3;
	// 编译报错
	byte x = (byte)g / 3;
	// 可以
	short y = (short)(g / 3) ;
	// 可以
	short i = 10;
	// 可以
	byte j = 5;
	// 编译报错
	short k = i + j;
	// 可以
	int n = i + j;
	// 可以
	char cc = 'a';
	System.out.println(cc); // a
	System.out.println((byte)cc); // 97
	// cc 会先自动转换成int类型,再做运算
	int o = cc + 100;
	System.out.println(o); // 197
	}
}
Windows PowerShell
版权所有(C) Microsoft Corporation。保留所有权利。
安装最新的 PowerShell,了解新功能和改进!https://aka.ms/PSWindows
PS D:JavaProjects2-JavaSEchapter04> javac .TypeTransferTest.java
.TypeTransferTest.java:4: 错误: 不兼容的类型: 从int转换到byte可能会有损失
        byte b1 = 1000;
                  ^
.TypeTransferTest.java:14: 错误: 不兼容的类型: 从long转换到int可能会有损失
        int e = d;
                ^
.TypeTransferTest.java:20: 错误: 不兼容的类型: 从long转换到int可能会有损失
        int h = g / 3;
                  ^
.TypeTransferTest.java:24: 错误: 不兼容的类型: 从int转换到byte可能会有损失
        byte x = (byte)g / 3;
                         ^
.TypeTransferTest.java:32: 错误: 不兼容的类型: 从int转换到short可能会有损失
        short k = i + j;
                    ^
5 个错误

发表评论