Java 是 Sun Microsystems(现 Oracle)于 1995 年发布的面向对象编译型语言,核心理念是 "Write Once, Run Anywhere"——代码编译为字节码,由 JVM 在各平台执行。
⚠️ 版本说明:本文以 Java 21 LTS 为基准。部分特性(Record 16+、Sealed Class 17+、Pattern Matching 21+、Virtual Thread 21+)在低版本不可用。
目录
| 章节 | 说明 |
|---|
| 核心特性 | JVM 原理、与其他语言对比 |
| 安装与工具链 | JDK 安装、编译运行、构建工具 |
| 基础语法 | 变量、基本类型、类型转换、运算符 |
| 流程控制 | if、switch、for、while |
| 面向对象 | 类、继承、接口、抽象类、多态 |
| 现代语法特性 | Record、Sealed Class、Pattern Matching、var |
| 常用类库 | String、集合框架、Optional、Stream API |
| 异常处理 | checked/unchecked、try-with-resources |
| 并发 | Thread、线程池、Virtual Thread(21+) |
| 快速参考卡 | 基本类型速查、集合选型、常用修饰符 |
核心特性

JVM 执行模型
Java 源码 (.java)
↓ javac 编译
字节码 (.class)
↓ JVM 解释 + JIT 编译
机器码(平台相关)
| 组件 | 说明 |
|---|
| JDK | Java Development Kit,包含编译器、调试器、JRE |
| JRE | Java Runtime Environment,包含 JVM 和标准库 |
| JVM | Java Virtual Machine,执行字节码的虚拟机 |
| JIT | Just-In-Time 编译器,将热点字节码编译为机器码 |
与其他语言对比
| 维度 | Java | Go | Python |
|---|
| 类型系统 | 静态强类型 | 静态强类型 | 动态强类型 |
| 内存管理 | GC(分代回收) | GC | GC |
| 并发模型 | 线程 / Virtual Thread | goroutine | GIL 限制 |
| 启动速度 | 慢(JVM 预热) | 极快 | 快 |
| 生态 | 极其丰富(Spring 等) | 云原生 | 数据科学 |
| 泛型 | 支持(类型擦除) | 支持(1.18+) | 支持 |
安装与工具链
安装 JDK
# macOS(推荐 Homebrew,安装 OpenJDK)
brew install openjdk@21
# 配置环境变量(写入 ~/.zshrc)
export JAVA_HOME=$(brew --prefix openjdk@21)
export PATH="$JAVA_HOME/bin:$PATH"
# 验证
java -version
javac -version
编译与运行
# 编译
javac Hello.java # 生成 Hello.class
# 运行
java Hello # 不加 .class 后缀
# 单文件程序(Java 11+,无需 javac)
java Hello.java
常用构建工具命令
# Maven
mvn clean package -DskipTests # 打包
mvn test # 运行测试
mvn dependency:tree # 查看依赖树
# Gradle
./gradlew build # 构建
./gradlew test # 运行测试
./gradlew dependencies # 查看依赖树
基础语法
基本类型与包装类
| 基本类型 | 位宽 | 包装类 | 默认值 |
|---|
boolean | — | Boolean | false |
byte | 8 bit | Byte | 0 |
short | 16 bit | Short | 0 |
int | 32 bit | Integer | 0 |
long | 64 bit | Long | 0L |
float | 32 bit | Float | 0.0f |
double | 64 bit | Double | 0.0 |
char | 16 bit | Character | '\u0000' |
// 字面量写法
int million = 1_000_000; // 下划线分隔符(Java 7+)
long bigNum = 9_999_999_999L; // long 需加 L
double pi = 3.14_159_265;
int hex = 0xFF; // 十六进制
int bin = 0b1010_1010; // 二进制(Java 7+)
// 自动装箱 / 拆箱
Integer a = 42; // 自动装箱:Integer.valueOf(42)
int b = a; // 自动拆箱:a.intValue()
// 类型转换
double d = 3.99;
int i = (int) d; // 强制转换,截断小数:3
long l = i; // 隐式宽化转换
变量与常量
// 局部变量(Java 10+ 支持 var 类型推断)
var name = "Alice"; // 推断为 String
var list = new ArrayList<String>();
// 常量:static final
static final int MAX_SIZE = 100;
static final String APP_NAME = "MyApp";
String
String s1 = "Hello";
String s2 = "World";
// 拼接
String greeting = s1 + ", " + s2 + "!";
// 常用方法
System.out.println(s1.length()); // 5
System.out.println(s1.charAt(0)); // H
System.out.println(s1.substring(1, 4)); // ell
System.out.println(s1.toLowerCase()); // hello
System.out.println(s1.trim()); // 去首尾空白
System.out.println(s1.contains("ell")); // true
System.out.println(s1.startsWith("He")); // true
System.out.println(s1.replace("l", "r")); // Herro
System.out.println(String.join(", ", "a", "b", "c")); // a, b, c
// 格式化(Java 15+ 推荐 formatted())
String msg = "name=%s age=%d".formatted("Alice", 30);
// 或
String msg2 = String.format("name=%s age=%d", "Alice", 30);
// 多行文本块(Java 15+)
String json = """
{
"name": "Alice",
"age": 30
}
""";
// 比较(不要用 == 比较内容)
System.out.println("hello".equals("hello")); // true
System.out.println("Hello".equalsIgnoreCase("hello")); // true
// StringBuilder:可变字符串,循环拼接时使用
StringBuilder sb = new StringBuilder();
sb.append("Hello").append(", ").append("World");
System.out.println(sb.toString()); // Hello, World
流程控制
if / switch
// if-else
int score = 85;
String grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else {
grade = "C";
}
// 三元表达式
String label = score >= 60 ? "pass" : "fail";
// switch 表达式(Java 14+,推荐)
String result = switch (score / 10) {
case 10, 9 -> "A";
case 8 -> "B";
case 7 -> "C";
case 6 -> "D";
default -> "F";
};
System.out.println(result); // B
for / while
// 经典 for
for (int i = 0; i < 5; i++) {
System.out.print(i + " "); // 0 1 2 3 4
}
// 增强 for(for-each)
int[] nums = {1, 2, 3, 4, 5};
for (int n : nums) {
System.out.print(n + " ");
}
// while
int n = 1;
while (n < 100) {
n *= 2;
}
System.out.println(n); // 128
// do-while(至少执行一次)
int count = 0;
do {
count++;
} while (count < 3);
System.out.println(count); // 3
面向对象
类与对象
public class Person {
// 字段
private String name;
private int age;
// 构造器
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getter / setter
public String getName() { return name; }
public int getAge() { return age; }
public void setAge(int age) {
if (age >= 0) this.age = age;
}
// toString
@Override
public String toString() {
return "Person{name='%s', age=%d}".formatted(name, age);
}
}
// 使用
Person p = new Person("Alice", 30);
System.out.println(p); // Person{name='Alice', age=30}
System.out.println(p.getName()); // Alice
继承与多态
public abstract class Shape {
public abstract double area();
public void describe() {
System.out.printf("面积: %.2f%n", area());
}
}
public class Circle extends Shape {
private double radius;
public Circle(double radius) { this.radius = radius; }
@Override
public double area() {
return Math.PI * radius * radius;
}
}
public class Rectangle extends Shape {
private double width, height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double area() { return width * height; }
}
// 多态
Shape[] shapes = { new Circle(5), new Rectangle(3, 4) };
for (Shape s : shapes) {
s.describe(); // 运行时调用各自的 area()
}
接口
public interface Drawable {
void draw(); // 抽象方法
default String getType() { // 默认方法(Java 8+)
return "Unknown";
}
static Drawable empty() { // 静态方法(Java 8+)
return () -> System.out.println("(empty)");
}
}
// 函数式接口(只有一个抽象方法)可用 Lambda 实现
Drawable d = () -> System.out.println("drawing...");
d.draw(); // drawing...
现代语法特性
Record(Java 16+)
// Record:不可变数据载体,自动生成构造器、getter、equals、hashCode、toString
public record Point(double x, double y) {
// 可添加自定义方法
public double distance() {
return Math.sqrt(x * x + y * y);
}
}
Point p = new Point(3.0, 4.0);
System.out.println(p); // Point[x=3.0, y=4.0]
System.out.println(p.x()); // 3.0(getter 无 get 前缀)
System.out.println(p.distance()); // 5.0
Sealed Class(Java 17+)
// Sealed:限定可以继承的子类,配合 Pattern Matching 使用
public sealed interface Shape permits Circle, Rectangle, Triangle {}
public record Circle(double radius) implements Shape {}
public record Rectangle(double w, double h) implements Shape {}
public record Triangle(double base, double height) implements Shape {}
Pattern Matching(Java 21+)
// instanceof 模式匹配(Java 16+)
Object obj = "Hello";
if (obj instanceof String s && s.length() > 3) {
System.out.println(s.toUpperCase()); // HELLO
}
// switch 模式匹配(Java 21+)
static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> r.w() * r.h();
case Triangle t -> 0.5 * t.base() * t.height();
};
}
var 类型推断(Java 10+)
var name = "Alice"; // String
var list = new ArrayList<String>(); // ArrayList<String>
var map = new HashMap<String, Integer>(); // HashMap<String, Integer>
// 只能用于局部变量,不能用于字段、方法参数、返回值
常用类库
集合框架
import java.util.*;
// List:有序、可重复
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add(0, "avocado"); // 指定位置插入
list.remove("banana");
System.out.println(list.get(0)); // avocado
System.out.println(list.size()); // 2
Collections.sort(list);
// 不可变 List(Java 9+)
List<String> immutable = List.of("a", "b", "c");
// Map:键值对
Map<String, Integer> map = new HashMap<>();
map.put("Alice", 90);
map.put("Bob", 85);
map.getOrDefault("Charlie", 0); // 0
map.putIfAbsent("Alice", 100); // 已存在则不覆盖
map.forEach((k, v) -> System.out.println(k + ": " + v));
// 不可变 Map(Java 9+)
Map<String, Integer> scores = Map.of("Alice", 90, "Bob", 85);
// Set:无序、唯一
Set<String> set = new HashSet<>(List.of("a", "b", "c", "a"));
System.out.println(set.size()); // 3
// LinkedHashMap:保持插入顺序
// TreeMap:按 key 排序
// LinkedHashSet:保持插入顺序
// TreeSet:自然排序
Stream API(Java 8+)
import java.util.*;
import java.util.stream.*;
List<Integer> nums = List.of(3, 1, 4, 1, 5, 9, 2, 6);
// 过滤 + 映射 + 收集
List<Integer> result = nums.stream()
.filter(n -> n > 3)
.sorted()
.distinct()
.collect(Collectors.toList());
System.out.println(result); // [4, 5, 6, 9]
// 统计
int sum = nums.stream().mapToInt(Integer::intValue).sum();
OptionalInt max = nums.stream().mapToInt(Integer::intValue).max();
System.out.println(sum); // 31
System.out.println(max.getAsInt()); // 9
// 分组
Map<Boolean, List<Integer>> grouped = nums.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println(grouped.get(true)); // [4, 2, 6]
System.out.println(grouped.get(false)); // [3, 1, 1, 5, 9]
// 字符串拼接
String joined = List.of("a", "b", "c").stream()
.collect(Collectors.joining(", ", "[", "]"));
System.out.println(joined); // [a, b, c]
Optional(Java 8+)
import java.util.Optional;
// 避免 NullPointerException
Optional<String> opt = Optional.of("hello");
Optional<String> empty = Optional.empty();
System.out.println(opt.isPresent()); // true
System.out.println(opt.get()); // hello
System.out.println(empty.orElse("default")); // default
System.out.println(empty.orElseGet(() -> "lazy")); // lazy
opt.ifPresent(s -> System.out.println(s.toUpperCase())); // HELLO
// map / flatMap 链式操作
Optional<Integer> len = opt.map(String::length);
System.out.println(len.orElse(0)); // 5
异常处理
// Checked Exception:必须声明或捕获(如 IOException)
// Unchecked Exception:继承 RuntimeException,不强制处理
// 基本结构
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("算术错误: " + e.getMessage());
} catch (Exception e) {
System.out.println("未知错误: " + e.getMessage());
} finally {
System.out.println("finally 一定执行");
}
// try-with-resources(Java 7+):自动关闭实现 AutoCloseable 的资源
import java.io.*;
try (var reader = new BufferedReader(new FileReader("/tmp/test.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("读取失败: " + e.getMessage());
}
// 自定义异常
class AppException extends RuntimeException {
private final String code;
public AppException(String code, String message) {
super(message);
this.code = code;
}
public String getCode() { return code; }
}
// 抛出自定义异常
throw new AppException("INVALID_INPUT", "参数不合法");
并发
Thread 与线程池
import java.util.concurrent.*;
// 方式一:Runnable(无返回值)
Thread t = new Thread(() -> System.out.println("Hello from thread"));
t.start();
// 方式二:Callable(有返回值)+ Future
ExecutorService executor = Executors.newFixedThreadPool(4);
Future<Integer> future = executor.submit(() -> {
Thread.sleep(100);
return 42;
});
System.out.println(future.get()); // 42(阻塞等待结果)
executor.shutdown();
// 线程池类型
Executors.newFixedThreadPool(n); // 固定大小线程池
Executors.newCachedThreadPool(); // 按需创建,空闲回收
Executors.newSingleThreadExecutor(); // 单线程,保证顺序执行
Executors.newScheduledThreadPool(n); // 定时/周期任务
Virtual Thread(Java 21+)
// Virtual Thread:轻量级线程,可创建百万级别,适合 IO 密集型任务
Thread vt = Thread.ofVirtual().start(() ->
System.out.println("Virtual thread: " + Thread.currentThread())
);
vt.join();
// 使用虚拟线程的线程池
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10; i++) {
final int id = i;
executor.submit(() -> System.out.println("task " + id));
}
} // try-with-resources 自动 shutdown
synchronized 与 Lock
import java.util.concurrent.locks.*;
import java.util.concurrent.atomic.*;
// synchronized 方法
public synchronized void increment() {
count++;
}
// ReentrantLock(更灵活)
Lock lock = new ReentrantLock();
lock.lock();
try {
// 临界区
} finally {
lock.unlock(); // 必须在 finally 中释放
}
// 原子类(无锁并发)
AtomicInteger atomicCount = new AtomicInteger(0);
atomicCount.incrementAndGet();
atomicCount.compareAndSet(1, 2); // CAS 操作
快速参考卡
集合选型
| 需求 | 推荐类 |
|---|
| 有序列表,频繁随机访问 | ArrayList |
| 有序列表,频繁增删头尾 | LinkedList |
| 键值对,无序 | HashMap |
| 键值对,保持插入顺序 | LinkedHashMap |
| 键值对,按 key 排序 | TreeMap |
| 唯一值,无序 | HashSet |
| 唯一值,保持插入顺序 | LinkedHashSet |
| 唯一值,自然排序 | TreeSet |
| 线程安全 Map | ConcurrentHashMap |
| 线程安全队列 | LinkedBlockingQueue |
常用修饰符
| 修饰符 | 说明 |
|---|
public | 所有类可访问 |
protected | 同包 + 子类可访问 |
private | 仅本类可访问 |
static | 属于类,不属于实例 |
final | 类不可继承 / 方法不可重写 / 变量不可重赋值 |
abstract | 抽象类或方法,不能实例化 |
synchronized | 方法或代码块加锁 |
volatile | 禁止指令重排,保证可见性 |
transient | 序列化时忽略该字段 |
常用注解
| 注解 | 说明 |
|---|
@Override | 标记重写父类方法,编译器检查 |
@Deprecated | 标记已废弃 |
@SuppressWarnings | 抑制编译器警告 |
@FunctionalInterface | 标记函数式接口 |
@SafeVarargs | 抑制泛型可变参数警告 |
参考资料
评论 (0)