基本数类型
java中的基本数据类型如下表:
四类八大基本数据类型
数据类型 | 关键字 | 内存 | 取值范围 |
---|---|---|---|
字节型 | byte | 1字节 | -128 - 127 |
短整型 | short | 2字节 | -32768 - 32767 |
整型 | int(默认) | 4字节 | -2^31 - 2^31-1 |
长整型 | long | 8字节 | -2^63 - 2^63-1 |
单精度浮点数 | float | 4字节 | 3.4e-45~1.4e38 |
双精度浮点数 | double(默认) | 8字节 | 4.9e-324~1.8e308 |
字符型 | char | 2字节 | 0 - 65535 |
布尔型 | boolean | 1字节 | true,false |
注意:
1.float内存比long小,但是取值范围比long大;
2.浮点数默认是double,如果使用float,后缀加F或f;
3.整数默认是int,如果使用long,后缀加L
public class DataConversion {
public static void main(String[] args) {
System.out.println(1024); // 默认为int
System.out.println(3.14); // 默认double
long num1 = 10L; // long型整数
System.out.println(num1);
float num2 = 3.14F;
System.out.println(num2);
}
}
数据类型转换
当数据类型不一样时,会发生数据类型转换
自动类型转换
自动类型转换(隐式):代码不需要特殊处理,自动完成,数据范围可以从小转到大,和内存大小没关系。
public class DataConversion {
public static void main(String[] args) {
long num1 = 10; // 自动类型转换,int转为long
System.out.println(num1);
double num2 = 3.14F; // float自定转为double
System.out.println(num2);
float num3 = 10L; // float范围比long大,long自动转为float
System.out.println(num3);
}
}
强制类型转换
强制类型转换(显示):如果直接把范围大的转为范围小的,会报错。这时需要代码进行特殊的格式处理。
格式:范围小的类型 变量名 = (范围小的类型)原本范围大的数据。
注意:
1.强制转换不推荐使用,可能发生精度损失,数据溢出。
2.byte/short/char 这三种类型可以发生数学运算,例如加法,在运算的时候,首先会转为int再计算。
3.boolean不能发生数据类型转换。
/*
强制类型转换
*/
public class DataForceConversion {
public static void main(String[] args) {
int num1 = (int)100L; // 强制转换
System.out.println(num1);
// 当实际数字大小超过数据类型范围,发生数据溢出
int num2 = (int)6000000000L;
System.out.println(num2); // 1705032704,数据发生了改变
// 数据精度损失,比如double -> int
int num3 = (int)3.14;
System.out.println(num3); // 3,小数点丢失
// byte/short/char 这三种类型可以发生数学运算,例如加法,在运算的时候,首先会转为int再计算
char c1 = 'A';
System.out.println(c1 + 1); // 66,c1被转为65进行运算了,其实就是ascii编码
byte b1 = 30;
byte b2 = 20;
int res = b1 + b2; // 因为两个byte相加转为int相加,结果还是int,所以需要用int类型接收
System.out.println(res); // 50
}
}