Java数据类型
一、基本数据类型
八种基本数据类型
整型:byte/short/int/long
浮点型:float/double
字符型:char
布尔型:boolean
二、引用数据类型
类:class
接口:interface
数组:array
类型转换
前提:讨论的不包含boolean型,java中不会等于0/1.
一、自动类型转换
超过范围,编译不通过
低字节向高字节会自动转换:
byte --> short --> int --> long --> float --> double
byte, short, char三者运算为int(也包括同种类型之间运算)
二、强制类型转换
高位截断,可能会损失精度
public class VariableTest3 {
public static void main(String[] args) {
double d1 = 150.12;
int i1 = (int)d1;
System.out.println(i1);
int i2 = 128;
byte b1 = (byte) i2;
System.out.println(b1); // 输出-128
}
}
可能的错误
public class VariableTest4 {
public static void main(String[] args) {
// 过大的整数,整数默认为int型,超出范围
long l1 = 12333333333; // 编译不通过
long l2 = 12333333333L;
// 浮点默认为double型
float f1 = 12.13; // 编译不通过
float f2 = 12.13f;
byte b = 12;
byte b1 = b + 1; // 编译不通过
float f3 = b + 12.3; // 编译不通过
}
}