跳到主要内容

Java 知识速查表

本页面汇总了 Java 编程中最常用的语法和知识点,方便快速查阅。

数据类型

基本类型

类型大小示例说明
byte1字节10字节
short2字节1000短整型
int4字节100000整数
long8字节100000L长整数
float4字节3.14f单精度浮点
double8字节3.14双精度浮点
char2字节'A', '中'字符
boolean1位true, false布尔值

引用类型

String str = "Hello";
Integer num = 100; // int 的包装类
Double d = 3.14; // double 的包装类
int[] arr = {1, 2, 3}; // 数组

类型转换

// 自动类型转换(小→大)
int i = 100;
double d = i; // 100.0

// 强制类型转换(大→小)
double d = 3.14;
int i = (int) d; // 3

// 字符串转换
String s = String.valueOf(100);
int num = Integer.parseInt("100");
double d = Double.parseDouble("3.14");

// 包装类
Integer.parseInt("100");
Integer.valueOf("100");

字符串

String s = "Hello World";

// 基本信息
s.length() // 11
s.isEmpty() // false
s.isBlank() // false(Java 11+,检查是否全为空白)

// 查找
s.indexOf("o") // 4
s.lastIndexOf("o") // 7
s.contains("World") // true
s.startsWith("Hello") // true
s.endsWith("World") // true

// 截取和分割
s.substring(6) // "World"
s.substring(0, 5) // "Hello"
s.split(" ") // ["Hello", "World"]
s.lines().toList() // 按行分割(Java 11+)

// 修改
s.toUpperCase() // "HELLO WORLD"
s.toLowerCase() // "hello world"
s.replace("World", "Java") // "Hello Java"
s.replaceAll("\\s+", " ") // 正则替换
s.trim() // 去除首尾空白
s.strip() // 去除首尾空白(Java 11+,更智能)
s.repeat(3) // 重复3次(Java 11+)

// 格式化
String.format("姓名: %s, 年龄: %d", "张三", 20)
"%s有%d元".formatted("张三", 100) // Java 15+

// 连接
String.join(",", "a", "b", "c") // "a,b,c"

文本块(Java 15+)

// 多行字符串
String json = """
{
"name": "张三",
"age": 20
}
""";

数组

// 创建
int[] arr1 = {1, 2, 3};
int[] arr2 = new int[5];
String[] strs = new String[]{"a", "b", "c"};

// 访问
arr1[0] // 1
arr1.length // 3

// 遍历
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}

for (int num : arr) {
System.out.println(num);
}

// Arrays 工具类
Arrays.toString(arr) // "[1, 2, 3]"
Arrays.sort(arr) // 排序
Arrays.binarySearch(arr, 2) // 二分查找
Arrays.fill(arr, 0) // 填充
Arrays.copyOf(arr, 10) // 复制并扩展
Arrays.equals(arr1, arr2) // 比较
Arrays.stream(arr) // 转为流

集合框架

List

// 创建
List<String> list = new ArrayList<>();
List<String> linked = new LinkedList<>();

// 基本操作
list.add("a");
list.add(0, "b"); // 在索引0处插入
list.get(0); // 获取元素
list.set(0, "c"); // 替换元素
list.remove(0); // 按索引删除
list.remove("a"); // 按值删除
list.contains("a"); // 是否包含
list.indexOf("a"); // 查找索引
list.size();
list.isEmpty();
list.clear();

// 批量操作
list.addAll(anotherList);
list.removeAll(anotherList);
list.retainAll(anotherList); // 交集

// 不可变 List(Java 9+)
List<String> immutable = List.of("a", "b", "c");

Set

// 创建
Set<String> set = new HashSet<>(); // 无序,最快
Set<String> linked = new LinkedHashSet<>(); // 保持插入顺序
Set<String> tree = new TreeSet<>(); // 自然排序

// 基本操作
set.add("a");
set.remove("a");
set.contains("a");
set.size();
set.isEmpty();

// 不可变 Set(Java 9+)
Set<String> immutable = Set.of("a", "b", "c");

Map

// 创建
Map<String, Integer> map = new HashMap<>();
Map<String, Integer> linked = new LinkedHashMap<>();
Map<String, Integer> tree = new TreeMap<>();

// 基本操作
map.put("a", 1);
map.get("a"); // 1
map.getOrDefault("b", 0); // 0
map.containsKey("a");
map.containsValue(1);
map.remove("a");
map.size();
map.isEmpty();

// 遍历
for (String key : map.keySet()) { }
for (Integer value : map.values()) { }
for (Map.Entry<String, Integer> e : map.entrySet()) { }
map.forEach((k, v) -> System.out.println(k + ":" + v));

// Java 8+ 新方法
map.putIfAbsent("a", 1); // 不存在才放入
map.compute("a", (k, v) -> v == null ? 1 : v + 1);
map.merge("a", 1, Integer::sum);
map.getOrDefault("key", 0);

// 不可变 Map(Java 9+)
Map<String, Integer> immutable = Map.of("a", 1, "b", 2);

Queue

Queue<String> queue = new LinkedList<>();
queue.offer("a"); // 入队
queue.poll(); // 出队(空返回null)
queue.peek(); // 查看队首

// 优先队列
Queue<Integer> pq = new PriorityQueue<>();
pq.offer(3);
pq.offer(1);
pq.poll(); // 1(最小的先出)

// 双端队列
Deque<String> deque = new ArrayDeque<>();
deque.addFirst("a");
deque.addLast("b");
deque.removeFirst();
deque.removeLast();

Stream API

List<Integer> list = List.of(1, 2, 3, 4, 5);

// 创建流
list.stream()
list.parallelStream() // 并行流
Arrays.stream(array)
Stream.of(1, 2, 3)
Stream.iterate(0, n -> n + 1) // 无限流
Stream.generate(() -> Math.random()) // 无限流

// 中间操作
.filter(x -> x > 2) // 过滤
.map(x -> x * 2) // 映射
.flatMap(x -> Stream.of(x, x)) // 扁平化
.distinct() // 去重
.sorted() // 排序
.sorted(Comparator.reverseOrder())
.limit(3) // 取前n个
.skip(2) // 跳过前n个
.peek(x -> System.out.println(x)) // 消费但不改变

// 终端操作
.collect(Collectors.toList())
.collect(Collectors.toSet())
.collect(Collectors.toMap(x -> x, x -> x * 2))
.collect(Collectors.groupingBy(x -> x % 2))
.collect(Collectors.joining(","))
.forEach(System.out::println)
.count()
.min(Comparator.naturalOrder())
.max(Comparator.naturalOrder())
.findFirst()
.findAny()
.anyMatch(x -> x > 3)
.allMatch(x -> x > 0)
.noneMatch(x -> x < 0)
.reduce((a, b) -> a + b)
.reduce(0, (a, b) -> a + b)
.toArray()

// 原始类型流
IntStream.range(1, 10) // 1-9
IntStream.rangeClosed(1, 10) // 1-10
list.stream().mapToInt(x -> x).sum()
list.stream().mapToInt(x -> x).average()

控制流

条件判断

if (condition) {
// ...
} else if (condition2) {
// ...
} else {
// ...
}

// 三元运算符
String result = x > 0 ? "正数" : "非正数";

Switch

// 传统 switch
switch (day) {
case 1:
System.out.println("周一");
break;
case 2:
case 3:
System.out.println("周二或周三");
break;
default:
System.out.println("其他");
}

// Switch 表达式(Java 14+)
String result = switch (day) {
case 1 -> "周一";
case 2, 3, 4, 5 -> "工作日";
case 6, 7 -> "周末";
default -> "无效";
};

// 带 yield 的 switch 表达式
int num = switch (s) {
case "one" -> 1;
case "two" -> 2;
default -> {
System.out.println("未知");
yield 0;
}
};

循环

// for 循环
for (int i = 0; i < 10; i++) { }

// 增强 for 循环
for (String s : list) { }

// while 循环
while (condition) { }

// do-while 循环
do { } while (condition);

// 循环控制
break; // 跳出循环
continue; // 跳过本次迭代
return; // 返回方法

面向对象

类定义

public class Person {
// 字段
private String name;
private int age;

// 静态字段
private static int count = 0;

// 构造方法
public Person() {
this("未知", 0);
}

public Person(String name, int age) {
this.name = name;
this.age = age;
count++;
}

// Getter/Setter
public String getName() { return name; }
public void setName(String name) { this.name = name; }

// 实例方法
public void sayHello() {
System.out.println("你好,我是" + name);
}

// 静态方法
public static int getCount() { return count; }

// 重写 toString
@Override
public String toString() {
return "Person{name=" + name + ", age=" + age + "}";
}
}

Record(Java 16+)

// 不可变数据类
public record Person(String name, int age) { }

// 使用
Person p = new Person("张三", 20);
p.name(); // "张三"
p.age(); // 20
p.toString(); // "Person[name=张三, age=20]"

// 带额外方法
public record Point(int x, int y) {
public int sum() {
return x + y;
}
}

Sealed Class(Java 17+)

// 密封类:限制子类
public sealed class Shape permits Circle, Rectangle {
}

public final class Circle extends Shape {
private double radius;
}

public final class Rectangle extends Shape {
private double width, height;
}

继承与多态

public class Student extends Person {
private String school;

public Student(String name, int age, String school) {
super(name, age); // 调用父类构造方法
this.school = school;
}

@Override
public void sayHello() {
super.sayHello(); // 调用父类方法
System.out.println("我在" + school + "上学");
}
}

抽象类与接口

// 抽象类
public abstract class Animal {
protected String name;

public Animal(String name) {
this.name = name;
}

public abstract void speak(); // 抽象方法

public void eat() { // 具体方法
System.out.println(name + "正在吃东西");
}
}

// 接口
public interface Flyable {
void fly();

default void land() { // 默认方法
System.out.println("着陆");
}

static void info() { // 静态方法
System.out.println("飞行接口");
}
}

// 实现接口
public class Bird extends Animal implements Flyable {
public Bird(String name) {
super(name);
}

@Override
public void speak() {
System.out.println("叽叽喳喳");
}

@Override
public void fly() {
System.out.println(name + "在飞");
}
}

异常处理

try {
// 可能抛出异常的代码
} catch (FileNotFoundException e) {
// 处理特定异常
} catch (IOException e) {
// 处理更一般的异常
} catch (Exception e) {
// 处理所有异常
} finally {
// 总是执行(可选)
}

// try-with-resources(自动关闭资源)
try (FileReader fr = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fr)) {
String line = br.readLine();
}

// 抛出异常
public void method() throws IOException {
throw new IOException("文件不存在");
}

// 自定义异常
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}

泛型

// 泛型类
public class Box<T> {
private T value;
public void set(T value) { this.value = value; }
public T get() { return value; }
}

// 泛型方法
public <T> T getFirst(List<T> list) {
return list.isEmpty() ? null : list.get(0);
}

// 泛型接口
public interface Processor<T, R> {
R process(T input);
}

// 通配符
List<?> list; // 任意类型
List<? extends Number> nums; // Number 或其子类
List<? super Integer> ints; // Integer 或其父类

枚举

public enum Day {
MONDAY("周一"),
TUESDAY("周二"),
WEDNESDAY("周三");

private final String name;

Day(String name) {
this.name = name;
}

public String getName() {
return name;
}
}

// 使用
Day day = Day.MONDAY;
day.getName(); // "周一"
Day.values(); // 所有枚举值
Day.valueOf("MONDAY"); // 转换

注解

// 常用内置注解
@Override // 重写方法
@Deprecated // 已过时
@SuppressWarnings("unchecked") // 抑制警告
@FunctionalInterface // 函数式接口

// 自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
String value() default "";
int count() default 0;
}

// 使用
@MyAnnotation(value = "test", count = 1)
public void method() { }

Optional 类

// 创建
Optional<String> opt1 = Optional.of("value"); // 非null
Optional<String> opt2 = Optional.ofNullable(null); // 可为null
Optional<String> opt3 = Optional.empty(); // 空

// 获取值
opt.get(); // 获取值(空则抛异常)
opt.orElse("default"); // 空则返回默认值
opt.orElseGet(() -> "default"); // 空则调用函数获取默认值
opt.orElseThrow(() -> new Exception()); // 空则抛异常

// 判断
opt.isPresent() // 是否有值
opt.isEmpty() // 是否为空(Java 11+)
opt.ifPresent(v -> System.out.println(v));

// 转换
opt.map(String::toUpperCase)
opt.flatMap(v -> Optional.of(v + "!"))
opt.filter(v -> v.length() > 3)

// 流式操作
opt.stream() // 转为 Stream(Java 9+)

并发编程

创建线程

// 继承 Thread
class MyThread extends Thread {
public void run() { /* 任务 */ }
}
new MyThread().start();

// 实现 Runnable
new Thread(() -> System.out.println("任务")).start();

// ExecutorService
ExecutorService executor = Executors.newFixedThreadPool(4);
executor.submit(() -> System.out.println("任务"));
executor.shutdown();

虚拟线程(Java 21+)

// 创建虚拟线程
Thread vt = Thread.ofVirtual().start(() -> {
System.out.println("虚拟线程");
});

// 使用 ExecutorService
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() -> task1());
executor.submit(() -> task2());
}

// 快速创建
Thread.startVirtualThread(() -> {
// I/O 密集型任务
});

同步工具

// synchronized
synchronized (lock) { /* 临界区 */ }

// ReentrantLock
ReentrantLock lock = new ReentrantLock();
lock.lock();
try { /* 临界区 */ }
finally { lock.unlock(); }

// AtomicInteger
AtomicInteger count = new AtomicInteger(0);
count.incrementAndGet(); // +1
count.compareAndSet(0, 1); // CAS

// CountDownLatch
CountDownLatch latch = new CountDownLatch(3);
latch.countDown();
latch.await();

// ConcurrentHashMap
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.putIfAbsent("key", 1);
map.computeIfAbsent("key", k -> 0);

常用工具类

Math

Math.max(1, 2)
Math.min(1, 2)
Math.abs(-5)
Math.pow(2, 3) // 8.0
Math.sqrt(16) // 4.0
Math.round(3.5) // 4
Math.floor(3.9) // 3.0
Math.ceil(3.1) // 4.0
Math.random() // [0, 1)

Objects

Objects.isNull(obj)
Objects.nonNull(obj)
Objects.equals(a, b)
Objects.hash(a, b, c)
Objects.requireNonNull(obj, "不能为空")

日期时间(Java 8+)

// 日期
LocalDate date = LocalDate.now();
LocalDate date = LocalDate.of(2024, 1, 15);
date.plusDays(1);
date.minusMonths(1);

// 时间
LocalTime time = LocalTime.now();
LocalTime time = LocalTime.of(10, 30, 0);

// 日期时间
LocalDateTime datetime = LocalDateTime.now();
datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

// 时间戳
Instant instant = Instant.now();
long epochMilli = instant.toEpochMilli();

// 时间段
Duration d = Duration.between(start, end);
Period p = Period.between(date1, date2);

文件操作(Java 7+ NIO)

import java.nio.file.*;

// 读取文件
List<String> lines = Files.readAllLines(Path.of("file.txt"));
String content = Files.readString(Path.of("file.txt")); // Java 11+

// 写入文件
Files.write(Path.of("file.txt"), "内容".getBytes());
Files.writeString(Path.of("file.txt"), "内容"); // Java 11+

// 复制、移动、删除
Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
Files.move(src, dest);
Files.delete(Path.of("file.txt"));

// 遍历目录
Files.list(Path.of(".")).forEach(System.out::println);
Files.walk(Path.of(".")).forEach(System.out::println); // 递归

常用库

用途
java.util集合、随机数、日期(旧)
java.time日期时间(Java 8+)
java.io输入输出流
java.nio新 IO、文件操作
java.net网络编程
java.util.concurrent并发工具
java.util.stream流式编程
java.util.function函数式接口
java.lang.reflect反射
java.util.regex正则表达式

模式匹配(Java 16+)

// instanceof 模式匹配
if (obj instanceof String s) {
System.out.println(s.length());
}

// switch 模式匹配(Java 21+)
String result = switch (obj) {
case Integer i -> "整数: " + i;
case String s -> "字符串: " + s;
case null -> "null";
default -> "未知";
};

// Record 模式匹配(Java 21+)
if (obj instanceof Person(String name, int age)) {
System.out.println(name + ": " + age);
}

关键字

abstract    continue    for           new          switch
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while

// Java 10+ var
var list = new ArrayList<String>();

常用命令

# 编译
javac Main.java

# 运行
java Main

# 打包 JAR
jar cvf app.jar *.class

# 运行 JAR
java -jar app.jar

# 查看 Java 版本
java -version

# 启用预览特性(新版本)
java --enable-preview --source 21 Main.java