数据精度
数据精度指的是数值的取值范围,具体如下:
数据类型 | 关键字 | 内存占用 | 取值范围 |
---|---|---|---|
字节型 | byte | 1个字节 | -128~127 |
短整型 | short | 2个字节 | -32768~32767 |
整型 | int(默认) | 4个字节 | -231~231-1 |
长整型 | long | 8个字节 | -263~263-1 |
单精度浮点数 | float | 4个字节 | 1.4013E-45~3.4028E+38 |
双精度浮点数 | double(默认) | 8个字节 | 4.9E-324~1.7977E+308 |
字符型 | char | 2个字节 | 0~65535 |
布尔类型 | boolean | 1个字节 | true,false |
自动类型转换
首先看一个例子:
public class demo1{
public static void main(String[] args){
int i=1;
byte b=2;
byte j=i+b;
System.out.println(j);
}
}
运行结果为:
可以看到,运行报错显示不兼容的类型,从int转换到byte有损失。这句话告诉我们j原本的数据类型为int,后来因为将c定义为了byte类型,因此发生了精度丢失。那么为什么int类型与byte类型相加结果会是int类型呢?看下面原理图:
byte类型内存占有1个字节,在和int类型运算时会提升为int类型,自动补充3个字节,
因此计算后的结果仍是int类型。这就是自动类型转换。
因此上述问题中,j在运算后数值类型自动转换为了int,在被定义为byte后数据的范围变小了,就可能会丢失数据精度。因此将j的数据类型改为int:
public class demo1{
public static void main(String[] args){
int i=1;
byte b=2;
int j=i+b;
System.out.println(j);
}
}
运行结果:
同理,当int类型与double类型运算时,int数据类型将会自动提升为double类型。即由范围小的类型向范围大的类型转换。
byte、short、char‐‐>int‐‐>long‐‐>float‐‐>double
下面介绍两种特殊情况:
整型与浮点型类型转换
public class demo2{
public static void main(String[] args){
int i=1;
float b=20.0f;
int j=i+b;
System.out.println(j);
}
}
运行结果:
出现这种情况的原因是浮点型存在小数点,因此做数学运算时,如果转换为int类型,则必然会出现丢失精度的问题。因此需将j的类型定义为浮点型:
public class demo2{
public static void main(String[] args){
int i=1;
float b=20.0f;
float j=i+b;
System.out.println(j);
}
}
运行结果:
char类型与int类型
public class demo3{
public static void main(String[] args){
char i='a';
byte b=1;
byte j=i+b;
System.out.println(j);
}
}
运行结果:
char类型与其他类型不同,char类型与整型做数据运算,会将char提升为int,在做运算。
public class demo3{
public static void main(String[] args){
char i='a';
byte b=1;
int j=i+b;
System.out.println(j);
}
}
运行结果:
强制类型转换
public class demo4{
public static void main(String[] args){
int a=1.1;
System.out.println(a);
}
}
若想输出int类型但是不报错,则需要用到强制类型转换:
public class demo4{
public static void main(String[] args){
int a=(int)1.1;
System.out.println(a);
}
}