JavaSE之 常用 API 详解(附代码示例)
在 Java 开发中,API(Application Programming Interface)是提高开发效率的核心工具。本文整理了日常开发中最常用的 10大类API,包含核心功能、使用场景、代码示例,适合新手入门学习与开发参考。
一、Math 类:数学运算工具类
1. Math 类核心特点
- 概述:Java 提供的数学运算工具类,无需创建对象即可使用。
- 核心特点:
- 构造方法私有(无法通过
new
创建对象);
- 所有成员方法均为静态方法(直接通过
Math.方法名()
调用)。
2. Math 类常用方法
方法声明 |
功能描述 |
static int abs(int a) |
求参数的绝对值 |
static double ceil(double a) |
向上取整(如 10.1 → 11.0) |
static double floor(double a) |
向下取整(如 10.9 → 10.0) |
static long round(double a) |
四舍五入(如 10.5 → 11,10.4 → 10) |
static int max(int a, int b) |
求两个数的较大值 |
static int min(int a, int b) |
求两个数的较小值 |
3. 代码示例
package com.code.day14;
public class Day14Math {
public static void main(String[] args) {
System.out.println(Math.abs(-10));
System.out.println(Math.abs(10));
System.out.println(Math.ceil(10.1));
System.out.println(Math.ceil(-5.2));
System.out.println(Math.floor(10.4));
System.out.println(Math.floor(-5.2));
System.out.println(Math.round(10.4));
System.out.println(Math.round(10.5));
System.out.println(Math.round(-5.2));
System.out.println(Math.round(-5.5));
System.out.println(Math.max(10, 20));
System.out.println(Math.min(10, 20));
}
}
二、BigInteger 类:超大整数处理类
1. BigInteger 类核心场景
- 问题背景:
long
是 Java 中能表示的最大基本整数类型(范围:-9223372036854775808
~ 9223372036854775807
),当需要处理超过 long
范围的整数时,需使用 BigInteger
。
- 核心作用:处理任意大小的整数,无精度损失。
2. BigInteger 类常用方法
构造方法/方法声明 |
功能描述 |
BigInteger(String val) |
构造方法:将字符串格式的整数转为 BigInteger 对象(val 必须是整数格式,如 “123456”) |
BigInteger add(BigInteger val) |
加法:返回 this + val 的结果 |
BigInteger subtract(BigInteger val) |
减法:返回 this - val 的结果 |
BigInteger multiply(BigInteger val) |
乘法:返回 this * val 的结果 |
BigInteger divide(BigInteger val) |
除法:返回 this / val 的结果(需确保能整除,否则抛异常) |
三、BigDecimal 类:高精度小数处理类
1. BigDecimal 类核心场景
- 问题背景:
double
和 float
是浮点型,直接运算会出现精度损失(如 0.1 + 0.2 = 0.30000000000000004
),BigDecimal
可解决此问题。
- 核心作用:处理高精度小数运算,避免精度损失。
2. BigDecimal 类常用方法
构造方法/方法声明 |
功能描述 |
BigDecimal(String val) |
构造方法:推荐使用,避免精度损失(如 new BigDecimal("0.1") ) |
static BigDecimal valueOf(double val) |
静态方法:将 double 转为 BigDecimal(内部处理了精度问题,也推荐使用) |
BigDecimal add(BigDecimal val) |
加法:返回 this + val 的结果 |
BigDecimal subtract(BigDecimal val) |
减法:返回 this - val 的结果 |
BigDecimal multiply(BigDecimal val) |
乘法:返回 this * val 的结果 |
BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) |
除法:指定保留小数位数(scale)和舍入模式(roundingMode),避免除不尽异常 |
3. 关键说明:除法舍入模式
舍入模式(RoundingMode 枚举) |
功能描述 |
RoundingMode.UP |
向上取整(如 1.234 保留 2 位 → 1.24) |
RoundingMode.DOWN |
向下取整(如 1.239 保留 2 位 → 1.23) |
RoundingMode.HALF_UP |
四舍五入(如 1.235 保留 2 位 → 1.24) |
4. 代码示例
package com.code.day14;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Day14BigDecimal {
public static void main(String[] args) {
BigDecimal b1 = BigDecimal.valueOf(3.55);
BigDecimal b2 = BigDecimal.valueOf(2.12);
BigDecimal add = b1.add(b2);
System.out.println("加法结果:" + add);
BigDecimal subtract = b1.subtract(b2);
System.out.println("减法结果:" + subtract);
BigDecimal multiply = b1.multiply(b2);
System.out.println("乘法结果:" + multiply);
BigDecimal divide = b1.divide(b2, 2, RoundingMode.HALF_UP);
System.out.println("除法结果:" + divide);
}
}
四、Date 类:日期时间表示类
1. Date 类核心特点
- 概述:表示特定的瞬间,精确到毫秒。
- 关键常识:
- 时间原点:1970年1月1日0时0分0秒(UTC时区);
- 北京时区:东8区,比时间原点快8小时;
- 1秒 = 1000毫秒。
2. Date 类常用方法
构造方法/方法声明 |
功能描述 |
Date() |
构造方法:创建表示当前系统时间的 Date 对象 |
Date(long time) |
构造方法:创建表示指定毫秒值对应的 Date 对象(time 为从时间原点开始的毫秒数) |
void setTime(long time) |
设置 Date 对象对应的毫秒值 |
long getTime() |
获取 Date 对象对应的毫秒值 |
3. 代码示例
package com.code.day14;
import java.util.Date;
public class Day14Date {
public static void main(String[] args) {
Date date = new Date();
System.out.println("当前时间:" + date);
date.setTime(1000L);
System.out.println("设置后的时间:" + date);
long timeMillis = date.getTime();
System.out.println("对应的毫秒值:" + timeMillis);
}
}
五、Calendar 类:日历操作类
1. Calendar 类核心特点
- 概述:抽象类,用于操作日历字段(年、月、日、时、分、秒等),不能直接
new
对象,需通过静态方法获取实例。
- 关键注意:
- 月份从 0 开始(0 = 1月,1 = 2月,…,11 = 12月);
- 每周从周日开始(0 = 周日,1 = 周一,…,6 = 周六)。
2. Calendar 类常用方法
方法声明 |
功能描述 |
static Calendar getInstance() |
获取 Calendar 实例(默认当前系统时间和时区) |
int get(int field) |
获取指定日历字段的值(field 为 Calendar 静态常量,如 Calendar.YEAR 、Calendar.MONTH ) |
void set(int field, int value) |
设置指定日历字段的值(如 calendar.set(Calendar.YEAR, 2024) ) |
void add(int field, int amount) |
为指定日历字段增减值(amount 为正数则加,负数则减,如 calendar.add(Calendar.MONTH, 1) 表示加1个月) |
Date getTime() |
将 Calendar 对象转为 Date 对象 |
3. 实战场景:判断闰年
package com.code.day14;
import java.util.Calendar;
import java.util.Scanner;
public class Day14CalendarKuoZhan {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个年份:");
int year = scanner.nextInt();
Calendar calendar = Calendar.getInstance();
calendar.set(year, 2, 1);
calendar.add(Calendar.DATE, -1);
int day = calendar.get(Calendar.DATE);
if (day == 29) {
System.out.println(year + "是闰年");
} else {
System.out.println(year + "不是闰年");
}
scanner.close();
}
}
六、SimpleDateFormat 类:日期格式化类
1. SimpleDateFormat 类核心作用
- 概述:
DateFormat
的子类,用于实现 Date 对象与字符串的相互转换。
- 核心功能:
- 格式化(Format):将
Date
对象按指定格式转为字符串;
- 解析(Parse):将符合格式的字符串转为
Date
对象。
2. 关键:日期格式占位符
占位符 |
含义 |
示例 |
yyyy |
4位年份 |
2024 |
MM |
2位月份(01~12) |
09 |
dd |
2位日期(01~31) |
03 |
HH |
24小时制小时(00~23) |
14 |
mm |
2位分钟(00~59) |
30 |
ss |
2位秒(00~59) |
59 |
注意:连接符可自定义(如 -
、/
、年
、月
等),但占位符不可变(如年份必须用 yyyy
,不能用 xxxx
)。
3. 代码示例
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Day14SimpleDateFormat {
public static void main(String[] args) throws ParseException {
Date now = new Date();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdf1.format(now);
System.out.println("格式化后的日期:" + dateStr);
String targetStr = "2019-10-10 10:10:10";
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date targetDate = sdf2.parse(targetStr);
System.out.println("解析后的 Date 对象:" + targetDate);
}
}
七、JDK8 新日期类(LocalDate/LocalDateTime 等)
JDK8 之前的 Date
和 Calendar
存在线程不安全、API 设计混乱等问题,因此新增了 java.time 包,包含 LocalDate
、LocalDateTime
、Period
、Duration
、DateTimeFormatter
等类,解决了旧 API 的缺陷。
1. LocalDate:日期(年月日)
1.1 核心方法
方法声明 |
功能描述 |
static LocalDate now() |
获取当前日期(年月日) |
static LocalDate of(int year, int month, int dayOfMonth) |
创建指定年月日的 LocalDate 对象(月份从 1 开始,无需加 1) |
LocalDate withYear(int year) |
修改年份,返回新对象(不可变类,原对象不变) |
LocalDate withMonth(int month) |
修改月份,返回新对象 |
LocalDate withDayOfMonth(int day) |
修改日期,返回新对象 |
LocalDate plusYears(int years) |
增加年份,返回新对象 |
LocalDate minusYears(int years) |
减少年份,返回新对象 |
1.2 代码示例
package com.code.day14;
import java.time.LocalDate;
public class Day14LocalDate {
public static void main(String[] args) {
LocalDate now = LocalDate.now();
System.out.println("当前日期:" + now);
LocalDate targetDate = LocalDate.of(2020, 10, 10);
System.out.println("指定日期:" + targetDate);
LocalDate modifiedDate = now.withYear(2024).withMonth(10).withDayOfMonth(10);
System.out.println("修改后日期:" + modifiedDate);
LocalDate nextYear = now.plusYears(1);
System.out.println("明年今日:" + nextYear);
}
}
2. LocalDateTime:日期时间(年月日时分秒)
2.1 核心方法
方法声明 |
功能描述 |
static LocalDateTime now() |
获取当前日期时间 |
static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second) |
创建指定年月日时分秒的 LocalDateTime 对象(月份从1开始) |
LocalDateTime plusHours(int hours) |
增加小时,返回新对象 |
LocalDateTime minusMinutes(int minutes) |
减少分钟,返回新对象 |
2.2 代码示例
package com.code.day14;
import java.time.LocalDateTime;
public class Day14LocalDateTime {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println("当前日期时间:" + now);
LocalDateTime targetTime = LocalDateTime.of(2020, 10, 10, 10, 10, 10);
System.out.println("指定日期时间:" + targetTime);
LocalDateTime modifiedTime = targetTime.plusHours(2).minusMinutes(30);
System.out.println("修改后时间:" + modifiedTime);
}
}
3. Period & Duration:日期/时间差值计算
3.1 Period:计算日期差值(年月日)
- 核心作用:计算两个
LocalDate
之间的差值,返回年、月、日的具体差值。
- 常用方法:
static Period between(LocalDate start, LocalDate end)
:计算 start
到 end
的日期差(end
需在 start
之后,否则差值为负);
int getYears()
:获取相差的年数;
int getMonths()
:获取相差的月数;
int getDays()
:获取相差的天数。
3.2 Duration:计算时间差值(时分秒毫秒)
- 核心作用:计算两个
LocalDateTime
(或 LocalTime
)之间的差值,返回天、时、分、秒、毫秒的具体差值。
- 常用方法:
static Duration between(Temporal start, Temporal end)
:计算 start
到 end
的时间差;
long toDays()
:转换为相差的天数;
long toHours()
:转换为相差的小时数;
long toMinutes()
:转换为相差的分钟数;
long toMillis()
:转换为相差的毫秒数。
3.3 代码示例
package com.code.day14;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
public class Day14PeriodDuration {
public static void main(String[] args) {
LocalDate date1 = LocalDate.of(2024, 10, 10);
LocalDate date2 = LocalDate.of(2025, 11, 12);
Period period = Period.between(date1, date2);
System.out.println("日期差:" + period.getYears() + "年" + period.getMonths() + "月" + period.getDays() + "天");
LocalDateTime time1 = LocalDateTime.of(2020, 1, 1, 0, 0);
LocalDateTime time2 = LocalDateTime.of(2022, 1, 1, 1, 1);
Duration duration = Duration.between(time1, time2);
System.out.println("时间差:" + duration.toDays() + "天 " + (duration.toHours() % 24) + "小时 " + (duration.toMinutes() % 60) + "分钟");
}
}
4. DateTimeFormatter:日期时间格式化(JDK8+)
- 核心作用:替代 JDK8 之前的
SimpleDateFormat
,线程安全,用于 LocalDate
/LocalDateTime
与字符串的相互转换。
- 常用方法:
static DateTimeFormatter ofPattern(String pattern)
:指定格式创建 DateTimeFormatter
对象(格式占位符与 SimpleDateFormat
一致,如 yyyy-MM-dd HH:mm:ss
);
String format(TemporalAccessor temporal)
:将日期时间对象(如 LocalDateTime
)格式化为字符串;
TemporalAccessor parse(CharSequence text)
:将符合格式的字符串解析为 TemporalAccessor
,再通过 LocalDateTime.from()
转为目标对象。
代码示例
package com.code.day14;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
public class Day14DateTimeFormatter {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.of(2019, 10, 10, 10, 10, 10);
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String timeStr = formatter1.format(now);
System.out.println("格式化结果:" + timeStr);
String targetStr = "2019-10-10 10:10:10";
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
TemporalAccessor temporal = formatter2.parse(targetStr);
LocalDateTime parsedTime = LocalDateTime.from(temporal);
System.out.println("解析结果:" + parsedTime);
LocalDateTime simplifiedParsed = LocalDateTime.parse(targetStr, formatter2);
System.out.println("简化解析结果:" + simplifiedParsed);
}
}
八、System 类:系统工具类
1. System 类核心特点
- 概述:与系统交互的工具类,提供系统级别的操作。
- 核心特点:
- 构造方法私有(无法
new
对象);
- 所有方法均为静态方法(通过
System.方法名()
调用)。
2. System 类常用方法
方法声明 |
功能描述 |
static long currentTimeMillis() |
获取当前系统时间对应的毫秒值(从1970-01-01 00:00:00 UTC开始) |
static void exit(int status) |
退出当前JVM(status=0 表示正常退出,非0表示异常退出) |
static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) |
数组复制(高效原生方法) |
3. 代码示例
package com.code.day14;
import java.util.Date;
public class Day14System {
public static void main(String[] args) {
long currentTime = System.currentTimeMillis();
System.out.println("当前时间毫秒值:" + currentTime);
Date nowDate = new Date(currentTime);
System.out.println("当前时间:" + nowDate);
int[] src = {1, 2, 3, 4, 5};
int[] dest = new int[src.length];
System.arraycopy(src, 0, dest, 0, src.length);
System.out.print("复制后的目标数组:");
for (int num : dest) {
System.out.print(num + " ");
}
}
}
九、Arrays 类:数组工具类
1. Arrays 类核心作用
- 概述:专门用于操作数组的工具类,提供排序、查找、复制、打印等常用功能。
- 核心特点:
2. Arrays 类常用方法
方法声明(以 int 数组为例) |
功能描述 |
static void sort(int[] a) |
对数组进行升序排序(快速排序实现,效率高) |
static String toString(int[] a) |
将数组转为字符串(格式:[元素1, 元素2, ...] ),方便打印 |
static int binarySearch(int[] a, int key) |
二分查找指定元素在数组中的索引(前提:数组已升序排序;未找到返回负数) |
static int[] copyOf(int[] original, int newLength) |
数组复制/扩容:创建新数组,长度为 newLength ,内容从原数组复制(长度不足补默认值,如 int 补 0) |
3. 代码示例
package com.code.day14;
import java.util.Arrays;
public class Day14Arrays {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
System.out.println("arr1 原始值:" + Arrays.toString(arr1));
int[] arr2 = {5, 3, 1, 4, 2};
Arrays.sort(arr2);
System.out.println("arr2 排序后:" + Arrays.toString(arr2));
int[] arr3 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int index = Arrays.binarySearch(arr3, 5);
System.out.println("元素 5 在 arr3 中的索引:" + index);
int noIndex = Arrays.binarySearch(arr3, 11);
System.out.println("元素 11 在 arr3 中的索引:" + noIndex);
int[] arr4 = {1, 2, 3, 4, 5};
int[] newArr = Arrays.copyOf(arr4, arr4.length * 2);
System.out.println("arr4 扩容后:" + Arrays.toString(newArr));
}
}
十、包装类:基本类型与引用类型的桥梁
1. 包装类概述
- 定义:为 8 种基本类型提供对应的 引用类型(包装类),解决“集合只能存储引用类型”“方法参数需引用类型”等问题。
- 基本类型与包装类对应关系:
基本类型 |
包装类 |
byte |
Byte |
short |
Short |
int |
Integer |
long |
Long |
float |
Float |
double |
Double |
char |
Character |
boolean |
Boolean |
2. Integer 类核心使用(以 Integer 为例,其他包装类用法类似)
2.1 构造/创建方式(JDK9+ 推荐)
JDK9 之前的 new Integer(int)
和 new Integer(String)
已过时,推荐使用 静态工厂方法 valueOf()
:
static Integer valueOf(int i)
:将 int
转为 Integer
;
static Integer valueOf(String s)
:将字符串格式的整数转为 Integer
(字符串需为纯数字,否则抛 NumberFormatException
)。
2.2 装箱与拆箱
- 装箱:基本类型 → 包装类(手动:
Integer.valueOf(100)
;自动:Integer i = 100
,编译器自动调用 valueOf()
);
- 拆箱:包装类 → 基本类型(手动:
i.intValue()
;自动:int num = i
,编译器自动调用 intValue()
)。
2.3 关键:Integer 缓存机制(笔试题)
Integer.valueOf()
会缓存 -128 ~ 127 范围内的 Integer
对象,避免重复创建,提升性能:
- 当值在
-128~127
时,多次调用 valueOf()
返回同一个对象(==
比较为 true
);
- 当值超出范围时,每次调用
valueOf()
创建新对象(==
比较为 false
)。
3. 代码示例
package com.code.day14;
public class Day14Integer {
public static void main(String[] args) {
Integer i1 = Integer.valueOf(100);
Integer i2 = Integer.valueOf("100");
System.out.println("i1 = " + i1);
System.out.println("i2 = " + i2);
Integer i3 = 200;
int num = i3;
System.out.println("num = " + (num + 50));
Integer a = 100;
Integer b = 100;
System.out.println("a == b:" + (a == b));
Integer c = 200;
Integer d = 200;
System.out.println("c == d:" + (c == d));
System.out.println("c.equals(d):" + c.equals(d));
}
}
总结
本文整理的 10 大类 API 是 Java 开发的基础工具,涵盖 数学运算、高精度数值、日期时间、系统操作、数组处理、类型转换 等核心场景。建议重点掌握:
- JDK8 新日期类(
LocalDate
/LocalDateTime
/DateTimeFormatter
),替代旧的 Date
/Calendar
;
- 包装类的自动装箱/拆箱与缓存机制(面试高频);
BigDecimal
的高精度运算(金融、电商等场景必备);
Arrays
与 System
类的实用方法(提升开发效率)。
实际开发中,需结合场景选择合适的 API,并注意异常处理(如 BigDecimal
除法、Integer.valueOf(String)
解析),确保代码健壮性。