Appearance
Java 速记表
基础语法
Hello World & 注释
// Hello Worldpublic class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); }}// 单行注释/* 多行注释 可以换行 *//** * JavaDoc 文档注释 * @param name 参数说明 * @return 返回值说明 */输入输出
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(); }}变量与常量
声明方式
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-bitshort s = 32767; // 16-bitint i = 2147483647; // 32-bitlong l = 9223372036854775807L; // 64-bit// 浮点数float f = 3.14f; // 32-bitdouble 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");// StringBuilderStringBuilder 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
// 传统 switchswitch (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 循环
// 传统 forfor (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 + bx -> x * x() -> System.out.println("Hello")(String s) -> { return s.length(); }方法引用
Java 8+
// 静态方法引用Integer::parseInt// 实例方法引用String::toUpperCaselist::add// 构造器引用ArrayList::newStream 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 ExceptionsIOExceptionSQLExceptionClassNotFoundException// Unchecked ExceptionsNullPointerExceptionIllegalArgumentExceptionIndexOutOfBoundsExceptionArithmeticException抛出异常
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);并发编程
线程
// 继承 Threadclass MyThread extends Thread { public void run() { System.out.println("Running"); }}new MyThread().start();// 实现 Runnablenew 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) { // 临界区}// LockLock lock = new ReentrantLock();lock.lock();try { // 临界区} finally { lock.unlock();}最佳实践
代码风格
// 使用 final 修饰不变量final int MAX = 100;// 使用 var 简化代码 (Java 10+)var list = new ArrayList<String>();// 使用 Optional 避免 nullOptional<String> opt = Optional.ofNullable(value);// 使用 Stream APIlist.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 // trueInteger x = 128;Integer y = 128;x == y // false工具链
构建工具
# Mavenmvn clean installmvn testmvn package# Gradlegradle buildgradle testgradle run依赖管理
<!-- Maven pom.xml --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>3.2.0</version></dependency>// Gradle build.gradledependencies { implementation 'org.springframework.boot:spring-boot-starter-web:3.2.0'}测试框架
// JUnit 5@Testvoid testAdd() { assertEquals(5, calculator.add(2, 3));}// Mockito@Mockprivate UserService userService;