Skip to content

Java 速记表

基础语法

Hello World

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

输入输出

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        // 输出
        System.out.println("Hello, World!");
        System.out.print("Without newline");
        System.out.printf("Name: %s, Age: %d%n", "Alice", 25);
        // 输入
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        System.out.print("Enter your age: ");
        int age = scanner.nextInt();
        System.out.println("Hello, " + name);
        scanner.close();
    }
}

注释

// 单行注释
/* 多行注释
   可以换行 */
/**
 * JavaDoc 文档注释
 * @param name 参数说明
 * @return 返回值说明
 */

变量与常量

声明方式

int num = 10;
String name = "Alice";
final double PI = 3.14;
// Java 10+ var 类型推导
var message = "Hello";
var count = 100;

作用域

public class Example {
    static int classVar = 0;  // 类变量
    int instanceVar = 0;      // 实例变量
    public void method() {
        int localVar = 0;     // 局部变量
        if (true) {
            int blockVar = 0; // 块作用域
        }
    }
}

数据类型

基本类型

// 整数
byte b = 127;           // 8-bit
short s = 32767;        // 16-bit
int i = 2147483647;     // 32-bit
long l = 9223372036854775807L;  // 64-bit
// 浮点数
float f = 3.14f;        // 32-bit
double d = 3.14159;     // 64-bit
// 其他
boolean bool = true;
char c = 'A';           // 16-bit Unicode

引用类型

String str = "hello";
Integer num = 100;
int[] arr = {1, 2, 3};
List<String> list = new ArrayList<>();

类型转换

// 自动转换(小到大)
int i = 100;
double d = i;
// 强制转换
double d = 3.14;
int i = (int) d;
// 包装类转换
String str = String.valueOf(42);
int num = Integer.parseInt("42");

泛型

List<String> list = new ArrayList<>();
Map<String, Integer> map = new HashMap<>();
// 泛型类
class Box<T> {
    private T value;
    public void set(T value) { this.value = value; }
    public T get() { return value; }
}

运算符

算术运算符

+  -  *  /  %    // 加减乘除取模
++  --           // 自增自减

比较运算符

==  !=           // 相等、不等
>  <  >=  <=     // 大小比较
instanceof       // 类型检查

逻辑运算符

&&  ||  !        // 逻辑与、或、非
&  |             // 位逻辑与、或

位运算符

&  |  ^  ~       // 按位与、或、异或、非
<<  >>  >>>      // 左移、右移、无符号右移

赋值运算符

=  +=  -=  *=  /=  %=
&=  |=  ^=  <<=  >>=  >>>=

三元运算符

int max = (a > b) ? a : b;
String result = (valid) ? "yes" : "no";

字符串

创建字符串

String str = "hello";
String str2 = new String("world");
String str3 = String.format("Age: %d", 25);

字符串方法

str.length()
str.charAt(0)
str.indexOf("sub")
str.contains("sub")
str.startsWith("pre")
str.endsWith("suf")
str.substring(0, 5)
str.split(" ")
str.replace("old", "new")
str.toLowerCase()
str.toUpperCase()
str.trim()
str.strip()  // Java 11+
str.isEmpty()
str.isBlank()  // Java 11+

字符串拼接

// + 运算符
String result = "Hello" + " " + "World";
// concat()
String result = str1.concat(str2);
// String.join()
String result = String.join("-", "a", "b", "c");
// StringBuilder
StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" ").append("World");
String result = sb.toString();

文本块

Java 15+

String html = """
    <html>
        <body>
            <p>Hello</p>
        </body>
    </html>
    """;

集合数据结构

List

List<String> list = new ArrayList<>();
List<Integer> nums = Arrays.asList(1, 2, 3);
List<String> immutable = List.of("a", "b", "c");
list.add("item");
list.add(0, "first");
list.remove("item");
list.remove(0);
list.set(0, "new");
list.get(0);
list.size();
list.isEmpty();
list.contains("item");
list.clear();

Set

Set<String> set = new HashSet<>();
Set<Integer> ordered = new LinkedHashSet<>();
Set<String> sorted = new TreeSet<>();
set.add("item");
set.remove("item");
set.contains("item");
set.size();
set.isEmpty();

Map

Map<String, Integer> map = new HashMap<>();
Map<String, String> ordered = new LinkedHashMap<>();
map.put("key", 100);
map.get("key");
map.getOrDefault("key", 0);
map.remove("key");
map.containsKey("key");
map.containsValue(100);
map.size();
map.isEmpty();
map.keySet();
map.values();
map.entrySet();

Queue & Deque

Queue<Integer> queue = new LinkedList<>();
queue.offer(1);
queue.poll();
queue.peek();
Deque<Integer> deque = new ArrayDeque<>();
deque.offerFirst(1);
deque.offerLast(2);
deque.pollFirst();
deque.pollLast();

控制流

if / else

if (condition) {
    // 执行
} else if (otherCondition) {
    // 执行
} else {
    // 执行
}

switch

// 传统 switch
switch (day) {
    case MONDAY:
    case FRIDAY:
        System.out.println("Working");
        break;
    case SATURDAY:
    case SUNDAY:
        System.out.println("Weekend");
        break;
    default:
        System.out.println("Midweek");
}
// Switch 表达式 (Java 14+)
String result = switch (day) {
    case MONDAY, FRIDAY -> "Working";
    case SATURDAY, SUNDAY -> "Weekend";
    default -> "Midweek";
};

for 循环

// 传统 for
for (int i = 0; i < 10; i++) {
    System.out.println(i);
}
// 增强 for (for-each)
for (String item : list) {
    System.out.println(item);
}

while 循环

while (condition) {
    // 执行
}
do {
    // 至少执行一次
} while (condition);

跳转语句

break;       // 退出循环
continue;    // 跳过本次
return value; // 返回值

函数

方法定义

public int add(int a, int b) {
    return a + b;
}
public static void main(String[] args) {
    System.out.println("Hello");
}
// 可变参数
public int sum(int... nums) {
    int total = 0;
    for (int n : nums) total += n;
    return total;
}

Lambda 表达式

Java 8+

(a, b) -> a + b
x -> x * x
() -> System.out.println("Hello")
(String s) -> { return s.length(); }

方法引用

Java 8+

// 静态方法引用
Integer::parseInt
// 实例方法引用
String::toUpperCase
list::add
// 构造器引用
ArrayList::new

Stream API

创建 Stream

list.stream()
Stream.of(1, 2, 3)
Arrays.stream(array)
Stream.empty()
Stream.generate(() -> Math.random())
Stream.iterate(0, n -> n + 1)

中间操作

stream.filter(x -> x > 0)
stream.map(x -> x * 2)
stream.flatMap(list -> list.stream())
stream.distinct()
stream.sorted()
stream.limit(10)
stream.skip(5)
stream.peek(System.out::println)

终端操作

stream.forEach(System.out::println)
stream.toList()  // Java 16+
stream.collect(Collectors.toList())
stream.reduce(0, Integer::sum)
stream.count()
stream.anyMatch(x -> x > 10)
stream.allMatch(x -> x > 0)
stream.noneMatch(x -> x < 0)
stream.findFirst()
stream.findAny()

面向对象

类定义

public class Person {
    private String name;
    protected int age;
    public final String id;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
        this.id = UUID.randomUUID().toString();
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

Record

Java 16+ 不可变数据类

public record Person(String name, int age) {
    // 自动生成 constructor, getters, equals, hashCode, toString
    // 自定义方法
    public String greet() {
        return "Hello, " + name;
    }
}
Person p = new Person("Alice", 25);
System.out.println(p.name());

继承

public class Student extends Person {
    private String major;
    public Student(String name, int age, String major) {
        super(name, age);
        this.major = major;
    }
    @Override
    public String greet() {
        return "Hi, I'm " + getName();
    }
}

接口

public interface Drawable {
    void draw();
    // 默认方法 (Java 8+)
    default void display() {
        System.out.println("Displaying");
    }
    // 静态方法
    static void info() {
        System.out.println("Drawable interface");
    }
}

抽象类

public abstract class Shape {
    protected String color;
    public abstract double area();
    public void setColor(String color) {
        this.color = color;
    }
}

Sealed Classes

Java 17+

public sealed class Shape 
    permits Circle, Rectangle, Triangle {
}
public final class Circle extends Shape {}
public final class Rectangle extends Shape {}
public final class Triangle extends Shape {}

错误处理

try-catch-finally

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.err.println("Error: " + e.getMessage());
    e.printStackTrace();
} catch (Exception e) {
    System.err.println("Unexpected: " + e);
} finally {
    // 总是执行
    System.out.println("Cleanup");
}

try-with-resources

Java 7+ 自动关闭资源

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line = br.readLine();
} catch (IOException e) {
    e.printStackTrace();
}

异常类型

// Checked Exceptions
IOException
SQLException
ClassNotFoundException
// Unchecked Exceptions
NullPointerException
IllegalArgumentException
IndexOutOfBoundsException
ArithmeticException

抛出异常

public void validate(String input) throws IllegalArgumentException {
    if (input == null) {
        throw new IllegalArgumentException("Input cannot be null");
    }
}
// 自定义异常
public class ValidationException extends Exception {
    public ValidationException(String message) {
        super(message);
    }
}

文件操作

读取文件

// Java 11+
String content = Files.readString(Path.of("file.txt"));
List<String> lines = Files.readAllLines(Path.of("file.txt"));
// 传统方式
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
}

写入文件

// Java 11+
Files.writeString(Path.of("file.txt"), "content");
// 写入多行
List<String> lines = Arrays.asList("line1", "line2");
Files.write(Path.of("file.txt"), lines);
// 传统方式
try (BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt"))) {
    bw.write("Hello\n");
}

路径操作

Path path = Paths.get("dir", "file.txt");
path.getFileName();
path.getParent();
path.toAbsolutePath();
Files.exists(path);
Files.isDirectory(path);
Files.createDirectories(path);

并发编程

线程

// 继承 Thread
class MyThread extends Thread {
    public void run() {
        System.out.println("Running");
    }
}
new MyThread().start();
// 实现 Runnable
new Thread(() -> {
    System.out.println("Running");
}).start();

ExecutorService

ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
    System.out.println("Task running");
});
executor.shutdown();

CompletableFuture

Java 8+

CompletableFuture.supplyAsync(() -> {
    return "result";
}).thenApply(result -> {
    return result.toUpperCase();
}).thenAccept(result -> {
    System.out.println(result);
});

同步

// synchronized 方法
public synchronized void method() {}
// synchronized 块
synchronized (this) {
    // 临界区
}
// Lock
Lock lock = new ReentrantLock();
lock.lock();
try {
    // 临界区
} finally {
    lock.unlock();
}

最佳实践

代码风格

// 使用 final 修饰不变量
final int MAX = 100;
// 使用 var 简化代码 (Java 10+)
var list = new ArrayList<String>();
// 使用 Optional 避免 null
Optional<String> opt = Optional.ofNullable(value);
// 使用 Stream API
list.stream()
    .filter(s -> s.length() > 3)
    .collect(Collectors.toList());

性能优化

// 使用 StringBuilder 拼接字符串
StringBuilder sb = new StringBuilder();
for (String s : list) {
    sb.append(s);
}
// 使用合适的集合
ArrayList - 随机访问快
LinkedList - 插入删除快
HashSet - 快速查找
TreeSet - 有序集合

常见陷阱

// == vs equals
"a" == "a"       // 比较引用
"a".equals("a")  // 比较值
// Integer 缓存 (-128 to 127)
Integer a = 127;
Integer b = 127;
a == b  // true
Integer x = 128;
Integer y = 128;
x == y  // false

工具链

构建工具

# Maven
mvn clean install
mvn test
mvn package
# Gradle
gradle build
gradle test
gradle run

依赖管理

<!-- Maven pom.xml -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>3.2.0</version>
</dependency>
// Gradle build.gradle
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web:3.2.0'
}

测试框架

// JUnit 5
@Test
void testAdd() {
    assertEquals(5, calculator.add(2, 3));
}
// Mockito
@Mock
private UserService userService;