强制转换: (类型)变量名 高 -- 低;(可以理解成低版本系统不能用高版本的软件,需要降低软件版本)
自动转换 : 低到高(可以理解成高版本系统能用低版本的)
int i = -129;
byte b = (byte) i;
System.out.println(i);
System.out.println(b);//128已经溢出了,所以成了负值
/*窗口输出如下
128
-128
*/
/*
注意点:
1. 不能对布尔值进行转换
2. 不能把对象类型转换成为不相干的类型
3. 在把高容量到低容量时,强制转换
4. 转换的时候可能存在内存溢出,或者精度问题!
*/
向整数位取整
System.out.println((int)23.7);
System.out.println((int)-45.53f);
/*窗口输出如下
23
-45
*/
低到高自动转换
char c = ‘a‘;
int d = c+1;
System.out.println(d);
System.out.println((char)d);
/*窗口输出如下
98
b
*/
操作比较大的数的时候,注意溢出问题;
int money = 10_0000_0000;
int years = 20;
int total = money*years;//-1474836480,计算的时候溢出了
long total2 = money*years;//默认是int,转换之前已经存在问题了?
long total3 = money*((long)years);//先把一个数转换成long
long total4 = ((long) money)*years;//先把一个数转换成long
System.out.println(total);
System.out.println("=======================");
System.out.println(total2);
System.out.println("=======================");
System.out.println(total3);
System.out.println("=======================");
System.out.println(total4);
/*窗口输出如下:
-1474836480
=======================
-1474836480
=======================
20000000000
=======================
20000000000
*/
原文:https://www.cnblogs.com/kuang-xlin/p/14729405.html