Java 基础知识全面梳理:从语法到核心机制

一、Java 语言概述

Java 是由 Sun Microsystems(现 Oracle)于 1995 年发布的面向对象编程语言,其核心理念是 **”Write Once, Run Anywhere”**。

核心特性

  • 跨平台:通过 JVM 实现平台无关性
  • 面向对象:封装、继承、多态
  • 自动内存管理:垃圾回收机制(GC)
  • 强类型语言:编译期类型检查
  • 多线程支持:内置线程机制

Java 平台体系

1
2
3
4
5
6
7
8
9
┌─────────────────────────┐
│ Java 应用程序 │
├─────────────────────────┤
│ Java API(类库) │
├─────────────────────────┤
│ JVM(虚拟机) │
├─────────────────────────┤
│ 操作系统 │
└─────────────────────────┘
  • JVM:Java Virtual Machine,执行字节码的虚拟机
  • JRE:Java Runtime Environment = JVM + 核心类库
  • JDK:Java Development Kit = JRE + 开发工具(javac、javadoc 等)

二、数据类型

基本数据类型(8 种)

类型 大小 范围 默认值
byte 1字节 -128 ~ 127 0
short 2字节 -32768 ~ 32767 0
int 4字节 -2^31 ~ 2^31-1 0
long 8字节 -2^63 ~ 2^63-1 0L
float 4字节 IEEE 754 0.0f
double 8字节 IEEE 754 0.0d
char 2字节 Unicode
boolean - true/false false

引用数据类型

  • 类(Class)StringInteger、自定义类
  • 接口(Interface)
  • 数组(Array)

类型转换

1
2
3
4
5
6
7
8
9
10
11
12
// 自动类型转换(小 → 大)
int i = 100;
long l = i; // int → long
double d = i; // int → double

// 强制类型转换(大 → 小,可能丢失精度)
double d = 3.14;
int i = (int) d; // i = 3

// 包装类与自动装箱拆箱
Integer num = 100; // 自动装箱 int → Integer
int n = num; // 自动拆箱 Integer → int

三、面向对象

类与对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Person {
// 成员变量
private String name;
private int age;

// 构造方法
public Person(String name, int age) {
this.name = name;
this.age = age;
}

// 成员方法
public void sayHello() {
System.out.println("Hello, I'm " + name);
}

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

三大特性

封装

1
2
3
4
5
6
7
8
9
10
11
12
13
public class BankAccount {
private double balance; // 私有字段

public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}

public double getBalance() {
return balance;
}
}

继承

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Animal {
protected String name;

public void eat() {
System.out.println(name + " is eating");
}
}

public class Dog extends Animal {
public void bark() {
System.out.println(name + " is barking");
}
}

多态

1
2
3
4
// 编译时看左边,运行时看右边
Animal animal = new Dog();
animal.eat(); // 调用 Dog 的 eat(如果重写)
// animal.bark(); // 编译错误,Animal 类型看不到 bark 方法

抽象类与接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 抽象类
public abstract class Shape {
abstract double area(); // 抽象方法

public void display() { // 普通方法
System.out.println("Area: " + area());
}
}

// 接口(Java 8+)
public interface Drawable {
void draw(); // 抽象方法
default void resize() { } // 默认方法
static void info() { } // 静态方法
}

抽象类 vs 接口

特性 抽象类 接口
实例化 不能 不能
构造方法
成员变量 可以有 只能 public static final
方法 抽象 + 普通 抽象 + default + static
继承 单继承 多实现

四、String 深入

String 的不可变性

1
2
3
4
5
6
7
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");

s1 == s2 // true (字符串常量池,同一对象)
s1 == s3 // false (堆中不同对象)
s1.equals(s3) // true (值相等)

StringBuilder vs StringBuffer

1
2
3
4
5
6
7
8
// StringBuilder - 非线程安全,性能高
StringBuilder sb = new StringBuilder();
sb.append("hello").append(" ").append("world");
String result = sb.toString();

// StringBuffer - 线程安全,性能略低
StringBuffer buf = new StringBuffer();
buf.append("hello");
特性 String StringBuilder StringBuffer
可变性 不可变 可变 可变
线程安全 是(不可变)
性能 拼接慢 较快

五、集合框架

体系结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Collection
├── List(有序,可重复)
│ ├── ArrayList - 数组实现,查询快
│ ├── LinkedList - 链表实现,增删快
│ └── Vector - 线程安全的 ArrayList
├── Set(无序,不重复)
│ ├── HashSet - 哈希表实现
│ ├── LinkedHashSet- 有序哈希表
│ └── TreeSet - 红黑树,有序
└── Queue(队列)
├── LinkedList
├── PriorityQueue
└── ArrayDeque

Map(键值对)
├── HashMap - 哈希表,最常用
├── LinkedHashMap - 有序哈希表
├── TreeMap - 红黑树,按 key 排序
├── ConcurrentHashMap- 线程安全
└── Hashtable - 线程安全(旧)

常用操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// ArrayList
List<String> list = new ArrayList<>();
list.add("a");
list.add(0, "b"); // 指定位置插入
list.get(0); // 获取
list.remove(0); // 删除
list.size(); // 大小

// HashMap
Map<String, Integer> map = new HashMap<>();
map.put("key", 1);
map.get("key"); // 1
map.getOrDefault("k2", 0); // 0
map.containsKey("key"); // true
map.remove("key");

// 遍历
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

// Java 8 Stream
list.stream()
.filter(s -> s.length() > 3)
.map(String::toUpperCase)
.collect(Collectors.toList());

HashMap 底层原理

  • 数据结构:数组 + 链表 + 红黑树(Java 8+)
  • 扩容:默认初始容量 16,负载因子 0.75,扩容为 2 倍
  • 链表转红黑树:链表长度 >= 8 且数组长度 >= 64
  • key 的 hashCode 和 equals:必须同时重写

六、异常处理

异常体系

1
2
3
4
5
6
7
8
9
10
11
12
Throwable
├── Error(不可恢复)
│ ├── OutOfMemoryError
│ └── StackOverflowError
└── Exception
├── RuntimeException(非受检异常)
│ ├── NullPointerException
│ ├── ArrayIndexOutOfBoundsException
│ └── ClassCastException
└── 受检异常
├── IOException
└── SQLException

异常处理语法

1
2
3
4
5
6
7
8
9
10
11
12
13
try {
// 可能抛出异常的代码
int result = 10 / 0;
} catch (ArithmeticException e) {
// 处理特定异常
System.out.println("算术异常: " + e.getMessage());
} catch (Exception e) {
// 处理其他异常
e.printStackTrace();
} finally {
// 无论是否异常都会执行
// 通常用于释放资源
}

try-with-resources(Java 7+)

1
2
3
4
5
6
// 自动关闭实现 AutoCloseable 的资源
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}

自定义异常

1
2
3
4
5
6
7
8
public class BusinessException extends RuntimeException {
private int code;

public BusinessException(int code, String message) {
super(message);
this.code = code;
}
}

七、泛型

泛型类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Result<T> {
private int code;
private String message;
private T data;

public Result(int code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
}

// 使用
Result<User> result = new Result<>(200, "success", user);
Result<List<String>> result2 = new Result<>(200, "ok", list);

泛型方法

1
2
3
public static <T> T getFirst(List<T> list) {
return list.isEmpty() ? null : list.get(0);
}

泛型通配符

1
2
3
4
5
6
7
8
// <?> 无界通配符
public void printList(List<?> list) { }

// <? extends T> 上界通配符(只读)
public double sum(List<? extends Number> list) { }

// <? super T> 下界通配符(只写)
public void addNumbers(List<? super Integer> list) { }

八、IO 与 NIO

传统 IO

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 字节流
FileInputStream fis = new FileInputStream("file.txt");
FileOutputStream fos = new FileOutputStream("copy.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}

// 字符流
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

NIO(Java 7+)

1
2
3
4
5
6
7
8
9
10
// Files 工具类
Path path = Paths.get("/tmp/file.txt");
List<String> lines = Files.readAllLines(path);
Files.write(path, lines);
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);

// 遍历目录
Files.walk(Paths.get("/tmp"))
.filter(Files::isRegularFile)
.forEach(System.out::println);

九、多线程

创建线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 方式1:继承 Thread
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running");
}
}

// 方式2:实现 Runnable
Runnable task = () -> System.out.println("Runnable running");
new Thread(task).start();

// 方式3:实现 Callable(有返回值)
Callable<Integer> callable = () -> {
Thread.sleep(1000);
return 42;
};
FutureTask<Integer> future = new FutureTask<>(callable);
new Thread(future).start();
Integer result = future.get(); // 阻塞等待结果

线程池

1
2
3
4
5
6
7
8
9
10
11
// 推荐使用 ThreadPoolExecutor
ThreadPoolExecutor executor = new ThreadPoolExecutor(
5, // 核心线程数
10, // 最大线程数
60, TimeUnit.SECONDS, // 空闲线程存活时间
new LinkedBlockingQueue<>(100), // 任务队列
new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
);

executor.submit(() -> System.out.println("Task executed"));
executor.shutdown();

synchronized 与 Lock

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// synchronized
public synchronized void increment() {
count++;
}

// ReentrantLock
private final Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}

十、Java 8 新特性

Lambda 表达式

1
2
3
4
5
6
7
8
9
// 无参
Runnable r = () -> System.out.println("hello");

// 有参
Comparator<String> comp = (a, b) -> a.length() - b.length();

// 方法引用
list.forEach(System.out::println);
list.stream().map(String::toUpperCase);

Stream API

1
2
3
4
5
6
7
8
9
10
11
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");

List<String> result = names.stream()
.filter(name -> name.length() > 3) // 过滤
.map(String::toUpperCase) // 转换
.sorted() // 排序
.collect(Collectors.toList()); // 收集

// 聚合操作
int sum = IntStream.rangeClosed(1, 100).sum();
Optional<String> max = names.stream().max(Comparator.comparingInt(String::length));

Optional

1
2
3
4
5
6
7
8
9
10
11
12
Optional<String> opt = Optional.ofNullable(getName());

// 安全取值
String name = opt.orElse("default");
String name2 = opt.orElseGet(() -> computeDefault());
String name3 = opt.orElseThrow(() -> new RuntimeException("name is null"));

// 链式调用
String result = Optional.ofNullable(user)
.map(User::getAddress)
.map(Address::getCity)
.orElse("unknown");

总结

Java 基础知识是构建所有 Java 技术栈的根基。面向对象思想、集合框架、异常处理、多线程和 Java 8 新特性是日常开发中最常接触的内容。建议通过实际编码加深理解,多读源码,逐步建立完整的 Java 知识体系。

🔥 0 打卡天