自动类型转换

自动类型转换

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)//只对最近的操作数有效
	}
}

字符串转换

public class StringToBasic{
	public static void main(String[] args) {
		/*基本数据类型转换字符串类型*/
		int n1 = 100;
		float f = 1.1;
		double d1 = 1.1;
		String s1 = n1 + "";
		String s2 = f + "";
		String s3 = d1 + "";


		/*字符串转换基本数据类型*/
		//使用封装类parse函数实现转换
		String s5 = "123";
		int num = Integer.parseInt(s5);

		//把字符串转换成char类型,含义是指取出字符串的第一个字符
		System.out.println(s5.charAt(0));
	}
}

注意事项

  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;
	}
}
posted @ 2023-08-10 10:37  小Y的开发笔记  阅读(24)  评论(0)    收藏  举报