一、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):
String、Integer、自定义类
- 接口(Interface)
- 数组(Array)
类型转换
1 2 3 4 5 6 7 8 9 10 11 12
| int i = 100; long l = i; double d = i;
double d = 3.14; int i = (int) d;
Integer num = 100; int n = num;
|
三、面向对象
类与对象
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); }
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();
|
抽象类与接口
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()); } }
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 s1 == s3 s1.equals(s3)
|
StringBuilder vs StringBuffer
1 2 3 4 5 6 7 8
| StringBuilder sb = new StringBuilder(); sb.append("hello").append(" ").append("world"); String result = sb.toString();
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
| List<String> list = new ArrayList<>(); list.add("a"); list.add(0, "b"); list.get(0); list.remove(0); list.size();
Map<String, Integer> map = new HashMap<>(); map.put("key", 1); map.get("key"); map.getOrDefault("k2", 0); map.containsKey("key"); map.remove("key");
for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); }
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
| 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) { }
public double sum(List<? extends Number> list) { }
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
| 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
| class MyThread extends Thread { @Override public void run() { System.out.println("Thread running"); } }
Runnable task = () -> System.out.println("Runnable running"); new Thread(task).start();
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 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
| public synchronized void increment() { count++; }
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 知识体系。