浮点型数据
-
浮点型包括:
float 4个字节 double 8个字节 float是单精度,double是双精度,double更精准,比如说: 10.0 / 3 如果采用float来存储的话结果可能是: 3.33333 10.0 / 3 如果采用double来存储的话结果可能是:3.3333333333
-
注意:任意一个浮点型都比整数型空间大。
long类型占用8个字节。 float类型占用4个字节。 float容量 > long容量 java中规定,任何一个浮点型数据默认被当作double来处理。如果想让这个浮点型字面量被当作float类型来处理,那么请在字面量后面加F/f。
数据类型总结
- 八种基本数据类型中,除boolean类型不能转换,剩下七种类型之间都可以进行转换;
- 如果整数型字面量没有超出byte,short,char的取值范围,可以直接将其赋值给byte,short,char类型的变量;
- 小容量向大容量转换称为自己类型转换,容量从小到大的排序为:byte<short(char)<int<long<float<double,其中short和char都占用两个字节,但是char可以表示更大的正整数;
- 大容量转换成小容量,称为强制类型转换,编写时必须添加“强制类型转换符”,但运行时可能出现精度损失,谨慎使用;
- byte,short,char类型混合运算时,先各自转换成int类型再做运算;
- 多种数据类型混合运算,各自先转换成大容量最大的那一种再做运算
练习:
public class TypeTransferTest{
public static void main(String[] args){
//编译报错,因为1000已经超出范围了
byte b1 = 1000;
//可以
byte b2 = 20;
//可以
byte s = 1000;
//可以
int c = 1000;
//可以
long d = c;
//编译报错
int e = d;
//可以
int f = 10/3;
//可以
long g = 10;
//编译报错
int h = g/3;
//可以
long m = g/3;
//编译报错
byte x = (byte)g/3;
//可以
short y =(short)(g/3);
//可以
short i = 10;
//可以
byte j = 5;
//编译报错
short k = i + j;
//可以
int n = i + j;
//可以
char cc = 'a';
System.out.println(cc);//a
System.out.println((byte)cc);//97
//cc会先自动转换成int类型,再做运算
int o = cc + 100;
System.out.println(o);//197
}
}