Java数据类型转换
本文概述
1.数据类型的大小排名
//byte>short>char>int>long>float>double
2.演示小类型转大类型
byte a = 1;
int b = a;
System.out.println("b = " + b);//1
3.演示大转小过程
4. 演示大转小, 内存溢出问题
数据太大, 给到小的类型, 吃不消~ 数据就乱了
public class test {
public static void main(String[] args) {
//3.演示大转小过程
int a = 129;
int a1 = -200;
byte b = (byte) a; //byte能接收范围是: 负128 .正127
System.out.println("b = " + b);//b = -127 结果错误
byte d = (byte) a1; //byte能接收范围是: 负128 .正127
System.out.println("d = " + d);//d = 56 错误
}
}
5.精度丢失问题
public class test {
public static void main(String[] args) {
//精度丢失问题
float a = 1.2345f;
int b = (int) a;
System.out.println("b = " + b);//b = 1 小数全部丢失,因为int是整数类型
}
}
6. byte short char 参与运算会自动转化为int类型
public class test {
public static void main(String[] args) {
//byte short char 参与运算会自动转化为int类型
byte a = 1;
short b = 2;
char c = 'a';
System.out.println(c+a);//98
System.out.println(c+b);//99
//字符本质 是数字 a== 97
}
}
7. 结果的类型会取最高类型
public class test {
public static void main(String[] args) {
//结果的类型会取最高类型
int a = 1;
double b = 2.0;
System.out.println(a + b);//3.0
}
}
8.数字可以用下划线分割, 看的更清楚
public class test {
public static void main(String[] args) {
//数字可以用下划线分割, 看的更清楚
int a = 123_456_789;
System.out.println("a = " + a);//a = 123456789
}
}
9.大额数量运算时, 出现问题
public class test {
public static void main(String[] args) {
//大额数量运算时, 出现问题
//10亿 * 20 = 200亿
int money = 1000_0000_00;
long year = money * 20;
System.out.println("year = " + year);//year = -1474836480
// 这是运算后溢出的, 所以要在运算之前转更高类型
long year_1 = (long) money * 20;
//转化long在money可以, 在20前面也可以, 最终会以最高级别展示
System.out.println("year_1 = " + year_1);
//year_1 = 20000000000
}
}