《疯狂JAVA讲义》之十一——Java基本数据类型之二

xiaoxiao2021-02-27  1.1K+

看代码,小例子更清晰。

package com.huateng.mjq.chapter3; /** * java 自动类型转换的路径如下:所有左侧的类型可以自动转换为右侧的类型而不需要强制显式类型转换也不会产生精度丢失 * char * | * | * \/ * byte ---> short ----> int ---->long ---->float ----> double * * 如果希望把右侧的类型转换为左侧的类型,则会发生精度丢失 * @author Administrator * */ public class PrimitiveType_6 { public static void main(String [] args) { test3(); } public static void test1() { int a =6; float f = a; System.out.println(f); byte b =9; //byte 并不能自动转换为char类型 //char c = b; double d = b; System.out.println(d); } /** * 字符串与任何基本类型做连接操作——+ 都会自动转换为字符串类型 */ public static void test2() { System.out.println("Hello"+3+4); System.out.println(3+4+"Hello"); } public static void test3() { int iValue = 233; //byte 表示范围-128---127,所以整型223强制转换为byte,肯定会发生精度丢失; //具体会怎样截断:整数在计算机中以补码形式存在,最左边一位(最高位)为符号位 //截断时对补码保留低位,舍弃高位 //233用补码表示为00000...00011101001(一共32位) //截断时保留低八位11101001,最高位为1(代表符号为负),所以该补码11101001表示的数的原码为:最低位-1,符号位不变,全部取反 //10010111 -23 byte bValue = (byte) iValue; double dValue = 3.98; //将一个浮点数强制转换为整数,将直接节点浮点数的小数部分,保留整数部分。结果为:3 int tol = (int) dValue; System.out.println(tol); } } package com.huateng.mjq.chapter3; /** * 在java的算术表达式中,当表达式中包含多个基本类型的值时,表达式的数据类型会自动提升,提升规则如下: * 1.所有的byte,short,char类型将会自动提升为int型,final变量除外。 * 2.整个算术表达式的类型自动提升到与表达式中最高等级操作数同样的类型;操作数的等级排列如上例中所示。 * @author Administrator * */ public class PrimitiveType_7 { public static void main(String [] args) { test1(); } public static void test1() { byte a =12,b=13; final byte c = 14,d = 15; //如果不进行强制类型转换则无法通过编译,因为表达式类型自动提升,右侧 a + b 后的结果为int类型 byte e = (byte) (a + b); System.out.println(e); //final类型除外,不会自动提升。 byte f = c + d; //c + d 不会自动提升,但是h为int类型,整个表达式类型自动提升为int类型,所有g如果为byte类型,则需强制类型转换 int h = 2; int g = c + d + h; System.out.println(g); } }

转载请注明原文地址: https://www.6miu.com/read-8.html

最新回复(0)