Java 基础(基本数据类型之间的运算规则)

7种基本数据类型变量间的运算,不包含 boolean 类型。

自动类型提升:

结论:当容量小的数据类型的变量与容量大的数据类型的变量做运算时,结果自动提升为容量大的数据类型。
byte, char, short --> int --> long --> float --> double
注意:此时的容量大小指的是,表示数的范围的大和小,比如:float 容量要大于 long 的容量

class VariableTest2 {
	public static void main(String[] args) {
		byte b1 = 2;
		int  i1 = 129;
		
		int  i2 = b1 + i1;
		long l1 = b1 + i1;

		System.out.println(i2);  // 131
		System.out.println(l1);  // 131
		
		float f1 = b1 + i1;
		System.out.println(f1);  // 131.0
		
		short  s1 = 123;
		double d1 = s1;
		System.out.println(d1);  // 123.0

                char c1 = 'a';
		int i3 = 10;
		int i4 = c1 + i3;
		System.out.println(i4);   // 107
	}
}

强制类型转换:自动类型提升运算的逆运算

  1. 需要使用强转符:()
  2. 强制类型转换,可能导致精度损失
class VariableTest3 {
	public static void main(String[] args) {
		double d1 = 12.9;
		
		// 精度损失
		int i1 = (int)d1;
		System.out.println(i1);   // 12
		
		// 精度正常
		long l1 = 123;
		short s2 = (short)l1;
		System.out.println(s2);   // 123
		
		// 精度损失
		int i2 = 128;
		byte b = (byte)i2;
		System.out.println(b);    // -128
	}
}
class StringTest{
	public static void main(String[] args){
		String str1 = "123";
		int num1 = Integer.parseInt(str1);
		System.out.println(num1);  // 123
	}
}
class ReviewTest {
	public static void main(String[] args){
		char c1 = 'a';
		char c2 = 97;
		
		System.out.println(c1);     //a 
		System.out.println(c2);     //a

		char c3 = 65;
		//char c4 = '65';           编译失败
		char c5 = '6';
		System.out.println(c3);   
		
		int i1 = (int)c5;
		System.out.println(i1);     //54
	}
}
posted @ 2020-12-21 16:18  klvchen  阅读(231)  评论(0编辑  收藏  举报