Java的基本数据类型 整型:byte、short、int、lang 浮点型:float、double 字符型:char 布尔型:boolean 基本数据类型之间的运算规则: 前提:只讨论七种基本类型之间的运算,除了Boolean类型 1、自动类型提升 当容量小的数据类型变量和容量大的数据类型变量做运算时,结果自动提升为容量大的数据类型。(此时的容量大小指的是表示数的范围的大和小,比如float的容量大于long的容量) byte、char、short --> int --> long --> float --> double 特别的:当byte、char、short三种数据类型的变量之间做运算时,结果为int型。 2、强制类型转换(自动类型提升的逆运算) 需要使用强转符,可能会导致精度损失。
//有精度损失12 double d = 12.9; int i = (int)d; System.out.println(i); //没有精度损失123 long l1 = 123; short s = (short)l1; System.out.println(s); //有精度损失-128 int i1 = 128; byte b = (byte)i1; System.out.println(b);编码情况:
//整型常量:默认类型为int //浮点型常量;默认类型为double byte b = 12; byte b1 = b + 1;//编译失败 float f = b + 12.3;//编译失败String类型变量的使用: 1、String属于引用数据类型 2、声明String类型变量时使用一对双引号 3、String可以和八种基本数据类型变量做运算,并且只能做连接运算 4、运算结果仍为String类型
char c = 'a';//97 A:65 int num = 10; String str = "hello"; System.out.println(c + num + str);//107hello System.out.println(c + str + num);//ahello10 System.out.println(c + (num + str));//a10hello System.out.println(str + num + c);//hello10a