Java 数据类型与变量
数据类型分类
Java 的数据类型分为两大类:
- 基本数据类型(Primitive Types):8 种基本类型
- 引用数据类型(Reference Types):类、接口、数组等
数据类型
├── 基本数据类型(8种)
│ ├── 整数类型:byte, short, int, long
│ ├── 浮点类型:float, double
│ ├── 字符类型:char
│ └── 布尔类型:boolean
└── 引用数据类型
├── 类(Class)
├── 接口(Interface)
├── 数组(Array)
└── 枚举(Enum)
基本数据类型
整数类型
public class IntegerTypes {
public static void main(String[] args) {
// byte: 8 位,范围 -128 到 127
// 占用内存:1 字节
byte b1 = 127; // 最大值
byte b2 = -128; // 最小值
// byte b3 = 128; // 错误:超出范围
// short: 16 位,范围 -32768 到 32767
// 占用内存:2 字节
short s1 = 32767; // 最大值
short s2 = -32768; // 最小值
// int: 32 位,范围 -2^31 到 2^31-1
// 占用内存:4 字节(最常用)
int i1 = 2147483647; // 最大值
int i2 = -2147483648; // 最小值
// long: 64 位,范围 -2^63 到 2^63-1
// 占用内存:8 字节,需要加 L 或 l 后缀
long l1 = 9223372036854775807L; // 最大值
long l2 = -9223372036854775808L; // 最小值
// 不同进制的表示
int decimal = 100; // 十进制:100
int binary = 0b1100100; // 二进制:100(Java 7+)
int octal = 0144; // 八进制:100
int hex = 0x64; // 十六进制:100
System.out.println("十进制:" + decimal);
System.out.println("二进制:" + binary);
System.out.println("八进制:" + octal);
System.out.println("十六进制:" + hex);
}
}浮点数类型
public class FloatTypes {
public static void main(String[] args) {
// float: 32 位,单精度浮点数
// 占用内存:4 字节
// 精度:约 7 位有效数字
// 必须加 f 或 F 后缀
float f1 = 3.14f;
float f2 = 3.14F;
float f3 = 1.23e4f; // 科学计数法:12300.0
// double: 64 位,双精度浮点数(默认类型)
// 占用内存:8 字节
// 精度:约 15-17 位有效数字
double d1 = 3.141592653589793;
double d2 = 1.23e4; // 科学计数法:12300.0
double d3 = 1.23e-4; // 科学计数法:0.000123
// 浮点数精度问题
double d4 = 0.1 + 0.2;
System.out.println(d4); // 输出:0.30000000000000004(精度问题)
// 使用 BigDecimal 解决精度问题(后续会学到)
}
}字符类型
public class CharType {
public static void main(String[] args) {
// char: 16 位 Unicode 字符
// 占用内存:2 字节
// 范围:'\u0000' 到 '\uffff'(0 到 65535)
// 字符字面量
char c1 = 'A'; // 单个字符
char c2 = '中'; // 中文字符
char c3 = '\u0041'; // Unicode 编码:'A'
char c4 = 65; // ASCII 码:'A'
// 转义字符
char newline = '\n'; // 换行符
char tab = '\t'; // 制表符
char quote = '\''; // 单引号
char doubleQuote = '\"'; // 双引号
char backslash = '\\'; // 反斜杠
char carriageReturn = '\r'; // 回车符
// 字符运算
char ch = 'A';
int code = ch; // 字符转整数(Unicode 码)
char next = (char)(ch + 1); // 'B'
System.out.println("字符:" + ch);
System.out.println("Unicode 码:" + code);
System.out.println("下一个字符:" + next);
}
}布尔类型
public class BooleanType {
public static void main(String[] args) {
// boolean: 只有 true 和 false 两个值
// 占用内存:JVM 规范未定义,通常为 1 字节
// 不能与整数类型转换(与 C/C++ 不同)
boolean isTrue = true;
boolean isFalse = false;
boolean isActive = true;
// 布尔运算
boolean result1 = isTrue && isFalse; // false(逻辑与)
boolean result2 = isTrue || isFalse; // true(逻辑或)
boolean result3 = !isTrue; // false(逻辑非)
// 不能这样写(Java 不允许)
// boolean b = 1; // 错误
// int i = true; // 错误
System.out.println("isTrue: " + isTrue);
System.out.println("result1: " + result1);
System.out.println("result2: " + result2);
System.out.println("result3: " + result3);
}
}基本数据类型总结
| 类型 | 大小 | 范围 | 默认值 | 说明 |
|---|---|---|---|---|
| byte | 1 字节 | -128 到 127 | 0 | 最小整数类型 |
| short | 2 字节 | -32768 到 32767 | 0 | 短整数 |
| int | 4 字节 | -2^31 到 2^31-1 | 0 | 最常用 |
| long | 8 字节 | -2^63 到 2^63-1 | 0L | 长整数,需加 L |
| float | 4 字节 | 约 ±3.4e38 | 0.0f | 单精度,需加 f |
| double | 8 字节 | 约 ±1.7e308 | 0.0 | 双精度,默认 |
| char | 2 字节 | ’\u0000’ 到 ‘\uffff' | '\u0000’ | Unicode 字符 |
| boolean | 未定义 | true/false | false | 布尔值 |
类型转换
自动类型转换(隐式转换)
public class AutoConversion {
public static void main(String[] args) {
// 小类型自动转换为大类型(不会丢失数据)
// 整数类型:byte -> short -> int -> long
byte b = 10;
short s = b; // byte 自动转换为 short
int i = s; // short 自动转换为 int
long l = i; // int 自动转换为 long
// 浮点类型:float -> double
float f = 3.14f;
double d = f; // float 自动转换为 double
// char -> int
char c = 'A';
int code = c; // char 自动转换为 int(Unicode 码)
// int -> float 或 double
int num = 100;
float f2 = num; // int 自动转换为 float
double d2 = num; // int 自动转换为 double
System.out.println("b: " + b);
System.out.println("s: " + s);
System.out.println("i: " + i);
System.out.println("l: " + l);
}
}强制类型转换(显式转换)
public class ExplicitConversion {
public static void main(String[] args) {
// 大类型转换为小类型需要强制转换(可能丢失数据)
// int -> byte
int i = 100;
byte b = (byte) i; // 强制转换为 byte
System.out.println("b: " + b); // 输出:100
// 注意:超出范围会导致溢出
int large = 300;
byte small = (byte) large;
System.out.println("small: " + small); // 输出:44(溢出)
// double -> int(丢失小数部分)
double d = 3.14;
int num = (int) d;
System.out.println("num: " + num); // 输出:3
// double -> float
double d2 = 3.141592653589793;
float f = (float) d2;
System.out.println("f: " + f); // 精度损失
// int -> char
int code = 65;
char ch = (char) code;
System.out.println("ch: " + ch); // 输出:'A'
}
}类型提升
public class TypePromotion {
public static void main(String[] args) {
// 表达式中的类型提升规则
// 1. byte、short、char 在运算时自动提升为 int
byte b1 = 10;
byte b2 = 20;
// byte sum = b1 + b2; // 错误:需要强制转换
int sum = b1 + b2; // 正确:自动提升为 int
byte sum2 = (byte)(b1 + b2); // 正确:强制转换
// 2. 如果有一个操作数是 long,结果提升为 long
int i = 10;
long l = 20L;
long result = i + l; // 结果类型为 long
// 3. 如果有一个操作数是 float,结果提升为 float
int num = 10;
float f = 3.14f;
float result2 = num + f; // 结果类型为 float
// 4. 如果有一个操作数是 double,结果提升为 double
float f2 = 3.14f;
double d = 2.5;
double result3 = f2 + d; // 结果类型为 double
System.out.println("sum: " + sum);
System.out.println("result: " + result);
System.out.println("result2: " + result2);
System.out.println("result3: " + result3);
}
}变量
变量声明
public class VariableDeclaration {
public static void main(String[] args) {
// 方式1:先声明,后赋值
int age;
age = 18;
// 方式2:声明时直接赋值(推荐)
int score = 100;
// 方式3:声明多个同类型变量
int a = 1, b = 2, c = 3;
// 方式4:使用 var 关键字(Java 10+,类型推断)
var name = "张三"; // 推断为 String
var count = 10; // 推断为 int
var price = 99.9; // 推断为 double
System.out.println("age: " + age);
System.out.println("score: " + score);
System.out.println("name: " + name);
}
}变量作用域
public class VariableScope {
// 类成员变量(实例变量)
private int instanceVar = 10;
// 类静态变量(类变量)
private static int staticVar = 20;
public void method() {
// 局部变量
int localVar = 30;
// 代码块变量
{
int blockVar = 40;
System.out.println("blockVar: " + blockVar); // 可以访问
System.out.println("localVar: " + localVar); // 可以访问
}
// System.out.println(blockVar); // 错误:超出作用域
System.out.println("localVar: " + localVar);
System.out.println("instanceVar: " + instanceVar);
System.out.println("staticVar: " + staticVar);
}
public static void staticMethod() {
// 静态方法中不能直接访问实例变量
// System.out.println(instanceVar); // 错误
System.out.println("staticVar: " + staticVar); // 可以访问
}
}变量命名规范
public class NamingConvention {
// 类成员变量:小驼峰命名
private String userName;
private int userAge;
// 常量:全大写,单词间用下划线
public static final int MAX_SIZE = 100;
public static final String DEFAULT_NAME = "guest";
public void method() {
// 局部变量:小驼峰命名
String firstName = "张";
String lastName = "三";
// 布尔变量:通常以 is、has、can 开头
boolean isActive = true;
boolean hasPermission = false;
boolean canEdit = true;
// 临时变量:可以使用简短名称
int i, j, k; // 循环变量
String temp; // 临时变量
}
}常量
final 关键字
public class Constants {
// 类常量:使用 final static
public static final int MAX_SIZE = 100;
public static final String DEFAULT_NAME = "guest";
public static final double PI = 3.14159;
// 实例常量:使用 final
private final int id;
public Constants(int id) {
this.id = id; // 必须在构造函数中初始化
}
public void method() {
// 局部常量:使用 final
final int localConstant = 50;
// localConstant = 60; // 错误:不能重新赋值
// final 修饰引用类型
final StringBuilder sb = new StringBuilder("Hello");
// sb = new StringBuilder("World"); // 错误:不能重新赋值
sb.append(" World"); // 正确:可以修改对象内容
System.out.println("MAX_SIZE: " + MAX_SIZE);
System.out.println("id: " + id);
System.out.println("sb: " + sb);
}
}包装类(Wrapper Classes)
public class WrapperClasses {
public static void main(String[] args) {
// 基本数据类型对应的包装类
// byte -> Byte
// short -> Short
// int -> Integer
// long -> Long
// float -> Float
// double -> Double
// char -> Character
// boolean -> Boolean
// 自动装箱(Autoboxing):基本类型自动转换为包装类
Integer i1 = 10; // 自动装箱,等价于 Integer.valueOf(10)
// 自动拆箱(Unboxing):包装类自动转换为基本类型
int i2 = i1; // 自动拆箱,等价于 i1.intValue()
// 手动装箱和拆箱
Integer i3 = Integer.valueOf(100); // 手动装箱
int i4 = i3.intValue(); // 手动拆箱
// 包装类的常用方法
String str = "123";
int num = Integer.parseInt(str); // 字符串转整数
String str2 = Integer.toString(123); // 整数转字符串
// 比较(注意:包装类使用 equals 比较值)
Integer a = 100;
Integer b = 100;
System.out.println(a == b); // true(-128 到 127 之间会缓存)
System.out.println(a.equals(b)); // true
Integer c = 200;
Integer d = 200;
System.out.println(c == d); // false(超出缓存范围)
System.out.println(c.equals(d)); // true
}
}总结
Java 数据类型包括:
- 8 种基本类型:byte、short、int、long、float、double、char、boolean
- 引用类型:类、接口、数组等
- 类型转换:自动转换和强制转换
- 变量:声明、作用域、命名规范
- 常量:使用 final 关键字
- 包装类:基本类型的对象表示
理解数据类型是编写 Java 程序的基础。
相关链接: