Java 基本数据类型
Java 是强类型语言,变量必须先声明类型再使用。基本类型是语言内置的最小数据单元,共 8 种;字符串、数组、对象等都属于引用类型。
8 种基本类型与取值范围表
整数:byte/short/int/long,浮点:float/double,字符:char,布尔:boolean。各类型大小、取值范围与默认值如下:
| 类型 | 位数 | 取值范围 | 默认值 |
|---|---|---|---|
| byte | 8 | -128 ~ 127 | 0 |
| short | 16 | -32768 ~ 32767 | 0 |
| int | 32 | -2147483648 ~ 2147483647 | 0 |
| long | 64 | -9223372036854775808 ~ 9223372036854775807 | 0L |
| float | 32 | 约 ±3.4E+38(约 7 位有效数字) | 0.0f |
| double | 64 | 约 ±1.8E+308(约 15 位有效数字) | 0.0d |
| char | 16 | 0 ~ 65535(Unicode 字符) | '\u0000' |
| boolean | 1 | true 或 false | false |
默认值是成员变量未赋值时的初始值;局部变量没有默认值,必须手动初始化。
字面量写法
整数默认按 int 处理,超出范围加 L;小数默认是 double,想要 float 要加 F:
public class LiteralDemo {
public static void main(String[] args) {
long big = 10000000000L; // 超 int 范围,必须加 L
float f = 3.14F; // 加 F 才是 float
char c = 'A';
boolean ok = true;
System.out.println(big + "," + f + "," + c + "," + ok);
}
}
// 输出:10000000000,3.14,A,true
自动类型转换
小范围转大范围自动完成,顺序为 byte→short→int→long→float→double:
public class AutoConvert {
public static void main(String[] args) {
int i = 100;
long l = i; // int 自动转 long
double d = l; // long 自动转 double
System.out.println(d); // 输出:100.0
}
}
强制转换、溢出与精度丢失
大转小必须强制转换,可能溢出或丢失精度;浮点小数本身也有误差:
public class CastDemo {
public static void main(String[] args) {
double d = 9.8;
int i = (int) d; // 强转,小数被截断
System.out.println(i); // 输出:9
int big = 300;
byte b = (byte) big; // 300 超出 byte 范围
System.out.println(b); // 输出:44(溢出截断)
double a = 0.1 + 0.2; // 0.1 + 0.2 并不等于 0.3
System.out.println(a); // 输出:0.30000000000000004
}
}
金额等敏感计算不要使用 double,应改用 BigDecimal。
包装类转换简介
每种基本类型都有对应包装类,常用 Integer.parseInt / toString 完成字符串互转:
public class WrapDemo {
public static void main(String[] args) {
int n = Integer.parseInt("123"); // 字符串转 int
double d = Double.parseDouble("3.5");
String s = Integer.toString(456); // int 转字符串
System.out.println(n + d); // 输出:126.5
System.out.println(s); // 输出:456
}
}
8 种基本类型各司其职:整数选 int/long、小数选 double、字符 char、布尔 boolean;牢记取值范围、默认值与「小转大自动、大转小强转」两条规则,能避开大量隐藏 Bug。