开篇概览:Java 核心类库体系
Java 标准库(Java Standard Library)提供了大量开箱即用的类和接口,覆盖字符串处理、日期时间、数学运算、系统操作、对象基础等核心功能。掌握这些核心 API,可大幅提升开发效率,避免重复造轮子。
本章重点介绍以下核心类库:
- 字符串处理:
String(不可变)、StringBuilder(单线程高效)、StringBuffer(线程安全); - 日期时间 API:传统
Date/Calendar(已过时) vs 现代LocalDateTime系列(Java 8+ 推荐); - 数学工具:
Math(数学函数)、Random(随机数); - 系统操作:
System(标准输入输出、属性、垃圾回收); - 包装类:
Integer、Double等,支持自动装箱/拆箱; - Object 类:所有类的根类,提供
equals、hashCode、toString等基础方法。
一、字符串处理:String、StringBuilder、StringBuffer
1.1 String(不可变字符串)
- 特点:内容不可变,每次修改都生成新对象;
- 适用场景:字符串内容不频繁变化(如配置、常量);
- 线程安全:是(因不可变)。
示例:String 基本操作
public class StringDemo {
public static void main(String[] args) {
// 创建字符串
String str1 = "Hello";
String str2 = new String("World");
// 字符串拼接(+ 操作符底层使用 StringBuilder)
String result = str1 + " " + str2;
System.out.println("拼接结果: " + result); // Hello World
// 常用方法
System.out.println("长度: " + result.length()); // 11
System.out.println("转大写: " + result.toUpperCase()); // HELLO WORLD
System.out.println("是否包含 'Hello': " + result.contains("Hello")); // true
System.out.println("子串: " + result.substring(6)); // World
// 字符串比较:必须用 equals(),不能用 ==
String s1 = "Java";
String s2 = new String("Java");
System.out.println("s1 == s2: " + (s1 == s2)); // false(引用不同)
System.out.println("s1.equals(s2): " + s1.equals(s2)); // true(内容相同)
}
}
⚠️ 注意:频繁拼接字符串(如循环中)应避免使用
String +,性能极低。
1.2 StringBuilder(可变、非线程安全)
- 特点:内容可变,内部使用字符数组动态扩容;
- 适用场景:单线程下大量字符串拼接;
- 性能:远高于
String拼接。
示例:StringBuilder 高效拼接
public class StringBuilderDemo {
public static void main(String[] args) {
// 创建 StringBuilder 对象
StringBuilder sb = new StringBuilder();
// 循环拼接(高效)
for (int i = 1; i <= 5; i++) {
sb.append("第").append(i).append("项, ");
}
// 转为 String
String result = sb.toString();
System.out.println("拼接结果: " + result); // 第1项, 第2项, 第3项, 第4项, 第5项,
// 其他操作
sb.insert(0, "【开头】"); // 在开头插入
sb.delete(sb.length() - 2, sb.length()); // 删除末尾逗号和空格
System.out.println("处理后: " + sb.toString());
}
}
1.3 StringBuffer(可变、线程安全)
- 特点:与
StringBuilder功能相同,但方法加synchronized; - 适用场景:多线程环境下的字符串拼接(极少使用,因性能低);
- 性能:低于
StringBuilder。
✅ 选择建议:
- 单线程 →
StringBuilder;- 多线程 → 优先考虑其他同步方案,而非
StringBuffer。
二、日期时间 API
2.1 传统 API(已过时,不推荐)
java.util.Date:表示时间戳,但方法设计混乱;java.util.Calendar:可修改日期,但线程不安全、API 复杂。
示例:传统 API(仅作了解)
import java.util.*;
public class OldDateDemo {
public static void main(String[] args) {
// Date 表示当前时间
Date now = new Date();
System.out.println("当前时间(Date): " + now);
// Calendar 用于操作日期
Calendar cal = Calendar.getInstance();
cal.set(2023, Calendar.DECEMBER, 25); // 设置日期(月份从0开始!)
Date christmas = cal.getTime();
System.out.println("圣诞节: " + christmas);
// 获取年份(注意:YEAR 返回的是当前年份 - 1900)
int year = cal.get(Calendar.YEAR);
System.out.println("年份: " + year); // 2023
}
}
❌ 问题:
Date可变(线程不安全);- 月份从 0 开始(易错);
- 无时区、格式化复杂。
2.2 现代 API(Java 8+ 推荐)
- 包:
java.time - 核心类:
LocalDate:仅日期(年-月-日);LocalTime:仅时间(时:分:秒.纳秒);LocalDateTime:日期+时间;ZonedDateTime:带时区的日期时间;DateTimeFormatter:格式化与解析。
示例:现代日期时间 API
import java.time.*;
import java.time.format.DateTimeFormatter;
public class NewDateTimeDemo {
public static void main(String[] args) {
// 1. 获取当前日期时间
LocalDate today = LocalDate.now();
LocalTime now = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
System.out.println("当前日期: " + today); // 2024-06-15
System.out.println("当前时间: " + now); // 14:30:45.123
System.out.println("当前日期时间: " + dateTime); // 2024-06-15T14:30:45.123
// 2. 创建指定日期时间
LocalDate birthday = LocalDate.of(1990, 5, 20);
LocalDateTime meeting = LocalDateTime.of(2024, 7, 1, 9, 0, 0);
System.out.println("生日: " + birthday); // 1990-05-20
System.out.println("会议时间: " + meeting); // 2024-07-01T09:00
// 3. 日期计算
LocalDate nextWeek = today.plusWeeks(1);
LocalDate lastMonth = today.minusMonths(1);
System.out.println("下周: " + nextWeek);
System.out.println("上个月: " + lastMonth);
// 4. 格式化输出(使用预定义或自定义格式)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
String formatted = dateTime.format(formatter);
System.out.println("格式化后: " + formatted); // 2024年06月15日 14:30:45
// 5. 解析字符串为日期时间
String dateStr = "2024-08-15 10:00:00";
LocalDateTime parsed = LocalDateTime.parse(dateStr,
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println("解析结果: " + parsed); // 2024-08-15T10:00
}
}
✅ 现代 API 优势:
- 不可变(线程安全);
- 清晰的 API 设计;
- 内置格式化支持;
- 无月份从0开始的陷阱。
三、数学相关:Math 与 Random
3.1 Math 类(工具类,全静态方法)
示例:常用数学函数
public class MathDemo {
public static void main(String[] args) {
// 绝对值
System.out.println("绝对值: " + Math.abs(-10)); // 10
// 幂运算
System.out.println("2的3次方: " + Math.pow(2, 3)); // 8.0
// 平方根
System.out.println("16的平方根: " + Math.sqrt(16)); // 4.0
// 最大值/最小值
System.out.println("最大值: " + Math.max(5, 10)); // 10
// 向上/向下取整
System.out.println("向上取整: " + Math.ceil(3.2)); // 4.0
System.out.println("向下取整: " + Math.floor(3.8)); // 3.0
// 四舍五入
System.out.println("四舍五入: " + Math.round(3.6)); // 4
// 随机数 [0.0, 1.0)
System.out.println("随机数: " + Math.random());
}
}
3.2 Random 类(生成随机数)
示例:生成各种随机数
import java.util.Random;
public class RandomDemo {
public static void main(String[] args) {
Random rand = new Random();
// 生成 int 范围随机数
int randomInt = rand.nextInt(100); // [0, 100)
System.out.println("0-99 的随机整数: " + randomInt);
// 生成指定范围整数 [min, max)
int min = 10, max = 20;
int rangeInt = rand.nextInt(max - min) + min;
System.out.println("10-19 的随机整数: " + rangeInt);
// 生成 boolean
System.out.println("随机布尔值: " + rand.nextBoolean());
// 生成 double
System.out.println("随机小数 [0.0, 1.0): " + rand.nextDouble());
}
}
💡 安全随机数:若需加密级随机数,使用
java.security.SecureRandom。
四、系统相关:System 类
核心功能:
System.out/System.err:标准输出/错误流;System.in:标准输入流;System.getProperty():获取系统属性;System.currentTimeMillis():获取当前时间戳(毫秒);System.gc():建议 JVM 执行垃圾回收(不保证立即执行)。
示例:System 类常用操作
import java.util.Scanner;
public class SystemDemo {
public static void main(String[] args) {
// 1. 获取系统属性
String osName = System.getProperty("os.name");
String javaVersion = System.getProperty("java.version");
// 获取当前工作目录
String userDir = System.getProperty("user.dir");
System.out.println("操作系统: " + osName);
System.out.println("Java 版本: " + javaVersion);
System.out.println("当前工作目录: " + userDir);
// 2. 获取当前时间戳(常用于性能测试)
long start = System.currentTimeMillis();
// 模拟耗时操作
try { Thread.sleep(100); } catch (InterruptedException e) {}
long end = System.currentTimeMillis();
System.out.println("耗时: " + (end - start) + " 毫秒");
// 3. 标准输入(配合 Scanner)
System.out.print("请输入您的姓名: ");
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
System.out.println("您好, " + name + "!");
// 4. 建议垃圾回收(一般不需要手动调用)
System.gc();
}
}
五、包装类与自动装箱/拆箱
5.1 包装类(Wrapper Classes)
| 基本类型 | 包装类 |
|---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
5.2 自动装箱(Autoboxing)与拆箱(Unboxing)
- 装箱:基本类型 → 包装类(如
int→Integer); - 拆箱:包装类 → 基本类型(如
Integer→int); - JVM 自动完成,简化代码。
示例:自动装箱与拆箱
public class WrapperDemo {
public static void main(String[] args) {
// 自动装箱:int → Integer
Integer num1 = 100; // 等价于 Integer.valueOf(100)
// 自动拆箱:Integer → int
int num2 = num1; // 等价于 num1.intValue()
// 在集合中使用(集合只能存对象)
java.util.List<Integer> list = new java.util.ArrayList<>();
list.add(200); // 自动装箱
int first = list.get(0); // 自动拆箱
// 注意:null 值拆箱会抛出 NullPointerException
Integer nullNum = null;
// int x = nullNum; // ❌ 运行时抛出 NullPointerException
// 缓存机制:-128 ~ 127 的 Integer 对象被缓存
Integer a = 127;
Integer b = 127;
System.out.println("a == b (127): " + (a == b)); // true(同一对象)
Integer c = 128;
Integer d = 128;
System.out.println("c == d (128): " + (c == d)); // false(不同对象)
}
}
⚠️ 注意:
- 避免在循环中频繁装箱/拆箱(性能损耗);
==比较包装类时,仅在缓存范围内可能为true,应使用equals()。
六、Object 类:所有类的根
所有 Java 类隐式继承自 java.lang.Object,因此具备以下方法:
| 方法 | 说明 |
|---|---|
toString() | 返回对象的字符串表示(建议重写) |
equals(Object obj) | 判断两对象是否“相等”(建议重写) |
hashCode() | 返回哈希码(若重写 equals,必须重写 hashCode) |
getClass() | 获取运行时类 |
clone() | 创建并返回对象副本(需实现 Cloneable) |
finalize() | 对象被回收前调用(已废弃,Java 9+) |
示例:重写 Object 方法
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 重写 toString():便于打印对象
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
// 重写 equals():按 name 和 age 判断相等
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return age == person.age && name.equals(person.name);
}
// 重写 hashCode():保证 equals 相等的对象 hashCode 相同
@Override
public int hashCode() {
return name.hashCode() * 31 + age;
}
}
public class ObjectDemo {
public static void main(String[] args) {
Person p1 = new Person("张三", 25);
Person p2 = new Person("张三", 25);
System.out.println("p1: " + p1); // 调用 toString()
System.out.println("p1.equals(p2): " + p1.equals(p2)); // true
System.out.println("p1.hashCode() == p2.hashCode(): " + (p1.hashCode() == p2.hashCode())); // true
}
}
✅ 重写原则:
equals()必须满足:自反性、对称性、传递性、一致性;hashCode():相等对象必须有相同哈希码,不相等对象尽量不同。
七、总结
| 类库类别 | 核心类 | 推荐用法 |
|---|---|---|
| 字符串 | String / StringBuilder | 不变用 String,拼接用 StringBuilder |
| 日期时间 | LocalDateTime 系列 | 全面替代 Date/Calendar |
| 数学 | Math / Random | 基础计算与随机数生成 |
| 系统 | System | 获取属性、时间戳、IO 流 |
| 包装类 | Integer 等 | 集合存储、自动装箱/拆箱 |
| Object | Object | 重写 toString/equals/hashCode |
📌 最佳实践:
- 日期时间永远使用
java.time包;- 字符串拼接避免循环中用
+;- 重写
equals时必须重写hashCode;- 包装类比较使用
equals()而非==。
掌握这些核心 API,是编写高效、健壮、可维护 Java 代码的基础。
1485

被折叠的 条评论
为什么被折叠?



