自动类型转换

ygcDiary / 2023-08-09 / 原文

自动类型转换

java可以从低精度自动转换到高精度

  1. byte——short——int——long——float——double
  2. char——int——long——float——double
public class AutoConvert{
	public static void main(String[] args) {
		int num = 'a';
		double d = 80;
		System.out.println(num);
		System.out.println(d);
	}
}

运行截图

image-20230809102031447

强制类型转换

public class ForceConvert{
	public static void main(String[] args) {
		/*强制类型转换会导致精度损失,使用时应当注意*/
		int i = (int)1.9;
		System.out.println(i);//1
		int x = (int)(10*1.9*1.2+5)//只对最近的操作数有效
	}
}

注意事项

  1. 多种数据类型混合运算时,系统首先自动将所有数据转换成容量最大的那个数据类型,在进行计算

  2. 精度大的赋给精度小的会报错

  3. (byte,short) 和char不可以发生自动转换

  4. byte short char三者之间可以相互运算,在计算时首先转换成int类型

  5. Boolean 类型不会参与类型的自动转换

  6. 自动提升:有最大类型,结果是最大类型

public class AutoConvertDetail{
	public static void main(String[] args) {
		int n1 = 10;
		// flota = n1 + 1.1 //此处错误,因为系统把等号右边转为double类型,但double不可以转换为float
		double d1 = n1 +1.1
		float d2 = n1 +1.1F

		// 精度大的赋给精度小的会报错
		// (byte,short) 和char不可以发生自动转换
		byte b1 = 10;//正确,赋值时在byte类型的范围里内不报错
		byte b2 = n1;//错误同上
		char c1 = b1;//byte 不可以转换为char
		short s = b1 //short 不可以转换为char类型
        //byte short char三者之间可以相互运算,在计算时首先转换成int类型
		byte b3 = 1;
		short s2 = 1;
		char c3 = 'a';
		int num = b3 + s2 + c3;
	}
}