一、Java 基础语法要点
1.1 数据类型与变量
8 种基本数据类型:
类型 | 大小(字节) | 默认值 | 取值范围 |
---|---|---|---|
byte | 1 | 0 | -128 ~ 127 |
short | 2 | 0 | -32768 ~ 32767 |
int | 4 | 0 | -2³¹ ~ 2³¹-1 |
long | 8 | 0L | -2⁶³ ~ 2⁶³-1 |
float | 4 | 0.0f | ±3.4E38(约 6-7 位有效数字) |
double | 8 | 0.0d | ±1.7E308(15 位有效数字) |
char | 2 | '\u0000' | 0 ~ 65535 |
boolean | 未明确定义 | false | true/false |
示例代码:
int age = 25;
double price = 99.95;
char grade = 'A';
boolean isStudent = true;
// 自动类型转换
double total = price * age; // int自动转换为double
// 强制类型转换
int discount = (int) (price * 0.8); // 可能丢失精度
变量作用域:
public class ScopeExample {
static int classVar = 0; // 类变量
int instanceVar = 0; // 实例变量
public void method() {
int localVar = 0; // 局部变量
if (true) {
int blockVar = 0; // 块级变量
}
// blockVar无法在此处访问
}
}
1.2 流程控制结构
三种核心结构:
- 顺序结构:代码逐行执行
- 分支结构:
if-else
、switch-case
- 循环结构:
for
、while
、do-while
代码示例:
// if-else判断成绩
int score = 85;
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 60) {
System.out.println("合格");
} else {
System.out.println("不及格");
}
// switch-case示例 (Java 14+)
String day = "MONDAY";
switch (day) {
case "MONDAY", "FRIDAY", "SUNDAY" -> System.out.println(6);
case "TUESDAY" -> System.out.println(7);
case "THURSDAY", "SATURDAY" -> System.out.println(8);
case "WEDNESDAY" -> System.out.println(9);
}
// for循环计算阶乘
int n = 5, result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
System.out.println("5! = " + result);
// 增强for循环
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.print(num + " ");
}
二、面向对象编程(OOP)
2.1 类与对象
类的定义:
public class Person {
// 成员变量
private String name;
private int age;
// 构造方法
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 方法
public void introduce() {
System.out.println("我叫" + name + ",今年" + age + "岁");
}
// Getter和Setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
对象使用:
Person p = new Person("张三", 25);
p.introduce(); // 输出: 我叫张三,今年25岁
p.setName("李四");
System.out.println(p.getName()); // 输出: 李四
2.2 三大特性
特性 | 定义 | 代码示例 |
---|---|---|
封装 | 隐藏实现细节,提供访问接口 | 使用private 字段 +getter/setter |
继承 | 子类继承父类特征和行为 | class Student extends Person |
多态 | 同一操作作用于不同对象产生不同结果 | 方法重写 + 父类引用指向子类对象 |
多态示例:
// 父类
class Animal {
public void speak() {
System.out.println("动物发出声音");
}
}
// 子类
class Dog extends Animal {
@Override
public void speak() {
System.out.println("汪汪汪");
}
}
class Cat extends Animal {
@Override
public void speak() {
System.out.println("喵喵喵");
}
}
// 测试多态
public static void main(String[] args) {
Animal dog = new Dog();
Animal cat = new Cat();
dog.speak(); // 输出: 汪汪汪
cat.speak(); // 输出: 喵喵喵
}
抽象类与接口:
// 抽象类
abstract class Shape {
abstract double area(); // 抽象方法
}
// 接口 (Java 8+)
interface Drawable {
default void draw() { // 默认方法
System.out.println("绘制图形");
}
}
// 实现类
class Circle extends Shape implements Drawable {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
三、异常处理机制
3.1 异常体系
3.2 处理方式
try-catch-finally:
try {
FileInputStream fis = new FileInputStream("test.txt");
// 读取文件
} catch (FileNotFoundException e) {
System.out.println("文件未找到: " + e.getMessage());
} catch (IOException e) {
System.out.println("读取文件失败: " + e.getMessage());
} finally {
System.out.println("资源清理完成");
}
try-with-resources(Java 7+):
try (FileInputStream fis = new FileInputStream("test.txt")) {
// 自动关闭资源
} catch (IOException e) {
e.printStackTrace();
}
自定义异常:
class AgeException extends Exception {
public AgeException(String message) {
super(message);
}
}
class Person {
private int age;
public void setAge(int age) throws AgeException {
if (age < 0 || age > 150) {
throw new AgeException("年龄无效: " + age);
}
this.age = age;
}
}
// 使用自定义异常
public static void main(String[] args) {
Person p = new Person();
try {
p.setAge(-5);
} catch (AgeException e) {
System.out.println(e.getMessage()); // 输出: 年龄无效: -5
}
}
四、集合框架(Collection Framework)
4.1 核心接口
接口 | 特点 | 实现类 |
---|---|---|
List | 有序可重复 | ArrayList、LinkedList |
Set | 无序唯一 | HashSet、TreeSet |
Map | 键值对存储 | HashMap、TreeMap |
Queue | 队列 / FIFO | LinkedList、PriorityQueue |
ArrayList 示例:
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple"); // 允许重复
System.out.println(fruits.get(0)); // 输出: Apple
System.out.println(fruits.size()); // 输出: 3
// 遍历列表
for (String fruit : fruits) {
System.out.println(fruit);
}
// Lambda表达式遍历
fruits.forEach(fruit -> System.out.println(fruit));
Map 示例:
Map<String, Integer> scores = new HashMap<>();
scores.put("张三", 85);
scores.put("李四", 90);
scores.put("王五", 78);
System.out.println(scores.get("李四")); // 输出: 90
// 遍历Map
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Stream API遍历
scores.forEach((name, score) -> System.out.println(name + ": " + score));
五、IO 流体系
5.1 流分类
分类维度 | 类型 | 典型类 |
---|---|---|
数据方向 | 输入流 / 输出流 | InputStream/OutputStream |
数据类型 | 字节流 / 字符流 | FileReader/FileWriter |
功能 | 节点流 / 处理流 | BufferedReader/BufferedWriter |
文件复制示例:
try (FileInputStream fis = new FileInputStream("src.txt");
FileOutputStream fos = new FileOutputStream("dest.txt")) {
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
System.out.println("文件复制成功");
} catch (IOException e) {
e.printStackTrace();
}
字符流示例:
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
六、多线程编程
6.1 线程创建方式
继承 Thread 类:
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("线程1: " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 启动线程
new MyThread().start();
实现 Runnable 接口:
Runnable task = () -> {
for (int i = 0; i < 5; i++) {
System.out.println("线程2: " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
// 启动线程
new Thread(task).start();
实现 Callable 接口(带返回值):
Callable<Integer> task = () -> {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
return sum;
};
FutureTask<Integer> futureTask = new FutureTask<>(task);
new Thread(futureTask).start();
// 获取结果
try {
Integer result = futureTask.get();
System.out.println("计算结果: " + result);
} catch (Exception e) {
e.printStackTrace();
}
6.2 线程同步
synchronized 示例:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
// 使用线程池执行多线程任务
ExecutorService executor = Executors.newFixedThreadPool(2);
Counter counter = new Counter();
for (int i = 0; i < 1000; i++) {
executor.submit(counter::increment);
}
executor.shutdown();
while (!executor.isTerminated()) {}
System.out.println("最终计数: " + counter.getCount()); // 正确输出: 1000
Lock 接口示例:
class Counter {
private int count = 0;
private final Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
return count;
}
}
七、Java 新特性(Java 8+)
7.1 Lambda 表达式
// 传统方式
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("传统方式创建线程");
}
};
// Lambda方式
Runnable r2 = () -> System.out.println("Lambda方式创建线程");
// 集合排序
List<String> names = Arrays.asList("Tom", "Jerry", "Spike");
names.sort((a, b) -> a.compareTo(b));
7.2 Stream API
List<String> names = Arrays.asList("Tom", "Jerry", "Spike", "Tyke");
// 过滤长度大于3的名字并转换为大写
List<String> result = names.stream()
.filter(name -> name.length() > 3)
.map(String::toUpperCase)
.collect(Collectors.toList());
// 输出: [JERRY, SPIKE, TYKE]
System.out.println(result);
// 并行流处理
long count = names.parallelStream()
.filter(name -> name.startsWith("T"))
.count();
// 输出: 2
System.out.println(count);
7.3 Optional 类
String str = null;
Optional<String> optional = Optional.ofNullable(str);
// 安全获取值
String result = optional.orElse("default");
System.out.println(result); // 输出: default
// 链式处理
optional.ifPresent(s -> System.out.println("值存在: " + s));
// 转换值
Optional<Integer> length = optional.map(String::length);
7.4 接口默认方法与静态方法
interface MyInterface {
// 默认方法
default void defaultMethod() {
System.out.println("默认方法实现");
}
// 静态方法
static void staticMethod() {
System.out.println("静态方法实现");
}
}
八、常见问题解答
8.1 == 与 equals 区别?
- ==:比较对象内存地址(基本类型比较值)
- equals:默认比较地址,可重写为值比较(如 String 类)
示例:
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2); // false (地址不同)
System.out.println(s1.equals(s2)); // true (值相同)
8.2 String 是否可变?
- String:不可变(内部使用 final char [])
- StringBuilder:可变,非线程安全
- StringBuffer:可变,线程安全
性能对比:
// StringBuilder性能更好(单线程环境)
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i);
}
8.3 接口与抽象类区别?
特性 | 接口 | 抽象类 |
---|---|---|
方法实现 | Java 8 + 支持默认方法 | 可以有具体方法 |
变量类型 | 默认 public static final | 任意类型变量 |
继承 | 多继承 | 单继承 |
设计目的 | 定义行为规范 | 抽取公共代码 |
8.4 深拷贝与浅拷贝
- 浅拷贝:复制对象及其引用,但不复制引用的对象
- 深拷贝:完全复制对象及其所有引用的对象
示例:
// 浅拷贝
class Point implements Cloneable {
private int x;
private int y;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
// 深拷贝
class Person implements Cloneable {
private String name;
private Address address; // 引用类型
@Override
protected Object clone() throws CloneNotSupportedException {
Person clone = (Person) super.clone();
clone.address = (Address) address.clone(); // 递归克隆引用对象
return clone;
}
}
8.5 HashMap 与 Hashtable 区别
特性 | HashMap | Hashtable |
---|---|---|
线程安全性 | 非线程安全 | 线程安全 |
空键值支持 | 允许一个 null 键和多个 null 值 | 不允许 null 键值 |
性能 | 高 | 低(同步开销) |
继承类 | 继承 AbstractMap | 继承 Dictionary |
九、Java 开发工具与环境
9.1 JDK、JRE 和 JVM
- JVM:Java 虚拟机,执行字节码
- JRE:Java 运行环境,包含 JVM 和核心类库
- JDK:Java 开发工具包,包含 JRE 和开发工具
9.2 常用开发工具
- Eclipse:开源集成开发环境
- IntelliJ IDEA:功能强大的商业 IDE
- VS Code:轻量级编辑器,配合 Java 扩展
- Maven:项目构建和依赖管理工具
- Gradle:现代化构建工具,支持多语言
9.3 环境配置示例(Windows)
- 下载并安装 JDK
- 配置环境变量:
- JAVA_HOME: JDK 安装目录
- PATH: 添加 % JAVA_HOME%\bin
- CLASSPATH: .;%JAVA_HOME%\lib
9.4 第一个 Java 程序
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
编译和运行:
javac HelloWorld.java
java HelloWorld
十、Java 进阶学习资源
10.1 推荐书籍
- 《Effective Java》
- 《Java 核心技术 卷 I/II》
- 《深入理解 Java 虚拟机》
- 《Java 并发编程实战》
10.2 在线学习平台
- Oracle 官方文档
- LeetCode(算法练习)
- HackerRank(编程挑战)
- Coursera(Java 相关课程)
10.3 社区与论坛
- Stack Overflow(技术问答)
- GitHub(开源项目学习)
- 掘金(技术文章分享)
- 开源中国(国内技术社区)
结语
掌握 Java 基础是成为优秀开发者的必经之路。建议学习路径:
- 夯实基础:理解 OOP、集合、异常处理等核心概念
- 动手实践:完成至少 5000 行代码练习
- 深入原理:研究 JVM 内存模型、GC 机制
- 紧跟发展:学习 Stream API、模块化等新特性
学习建议:
- 多做练习题和项目实战
- 参与开源项目,学习优秀代码
- 定期阅读技术博客和书籍
- 参加技术交流活动和会议
希望本文对你的 Java 学习有所帮助!如有疑问欢迎在评论区交流讨论!