全面解析Java核心技术体系 · 从零入门到深度掌握
Java作为一种跨平台的面向对象编程语言,其核心特性可归纳为以下五点:
以“Hello World”为例说明Java程序基本结构:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
其中:
• public class HelloWorld:声明公共类,类名与文件名必须严格一致
• public static void main(String[] args):程序入口点,JVM固定调用签名
• System.out.println():标准输出流,用于向控制台打印信息
Java数据类型分为基本类型与引用类型两大类,共八种基本类型:
| 类型分类 | 关键字 | 字节数 | 取值范围 | 默认值 |
|---|---|---|---|---|
| 整数型 | byte | 1 | -128 ~ 127 | 0 |
| 整数型 | short | 2 | -32768 ~ 32767 | 0 |
| 整数型 | int | 4 | -2³¹ ~ 2³¹-1 | 0 |
| 整数型 | long | 8 | -2⁶³ ~ 2⁶³-1 | 0L |
| 浮点型 | float | 4 | ±3.402823e+38 | 0.0f |
| 浮点型 | double | 8 | ±1.797693e+308 | 0.0d |
| 字符型 | char | 2 | Unicode字符集 | \u0000 |
| 布尔型 | boolean | 1 | true / false | false |
特别注意以下易混淆点:
int a = 5; long b = a + 3L;中a参与运算时提升为longdouble d = 3.14; int i = (int)d; //结果为3+运算符用于字符串时执行拼接:"值为:" + 42结果为"值为:42"Java流程控制语句可分为三类:
运算符优先级关键点:
经典案例:判断闰年条件(能被4整除但不能被100整除,或能被400整除)
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
studentScore、MAX_VALUE反例:int 123abc(数字开头)、String class(关键字)均为非法命名
==与equals()区别:
==比较基本类型值,比较引用类型时比较内存地址equals()比较对象内容(需重写实现)i = i++陷阱:后置++先返回原值再自增,导致i值不变0.1 + 0.2 == 0.3结果为false正确比较字符串:if("Java".equals(lang))可避免空指针异常
Integer.MAX_VALUE + 1结果为负数(-2147483648),发生整数溢出// 安全计算阶乘(示例)
long factorial(int n) {
if (n < 0) throw new IllegalArgumentException();
long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
if (result < 0) throw new ArithmeticException("Overflow!");
}
return result;
}
Java面向对象三大特征实现原理:
封装示例:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
setAge(age); // 使用setter验证
}
public String getName() { return name; }
public void setName(String name) {
if (name != null && !name.isEmpty()) {
this.name = name;
}
}
public int getAge() { return age; }
public void setAge(int age) {
if (age >= 0 && age <= 150) {
this.age = age;
}
}
}
| 对比维度 | 接口(interface) | 抽象类(abstract class) |
|---|---|---|
| 声明关键字 | interface | abstract class |
| 成员变量 | public static final | 可有各种修饰符 |
| 方法类型 | public abstract(JDK8+默认/静态方法) | 可含具体实现方法 |
| 继承/实现 | 类可实现多个接口 | 类只能继承一个抽象类 |
| 构造方法 | 无 | 有(供子类调用) |
| 设计目的 | 行为规范 | 代码复用与模板 |
典型应用场景:
设计原则:
子类对象赋值给父类引用变量:
Animal animal = new Dog(); // Dog是Animal子类
此时animal只能访问Animal类定义的方法,但实际调用的是Dog类重写的方法
方法表(vtable)机制确保多态正确性
解决方案:向下转型(需instanceof检查)
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
dog.bark(); // 调用子类特有方法
}
Java集合框架分为两大体系:
核心接口关系图:
Collection
├── List
│ ├── ArrayList(数组实现,随机访问快)
│ ├── LinkedList(链表实现,增删快)
│ └── Vector(线程安全)
└── Set
├── HashSet(哈希表实现)
├── LinkedHashSet(LinkedHashMap实现)
└── TreeSet(红黑树实现)
Map
├── HashMap(数组+链表+红黑树)
├── LinkedHashMap(双向链表维护顺序)
├── Hashtable(线程安全)
└── TreeMap(红黑树实现)
| 集合类型 | 底层结构 | 线程安全 | 允许null | 典型场景 |
|---|---|---|---|---|
| ArrayList | 动态数组 | 否 | 允许 | 频繁随机访问 |
| LinkedList | 双向链表 | 否 | 允许 | 频繁插入删除 |
| HashSet | HashMap键 | 否 | 一个null | 快速查找去重 |
| TreeSet | TreeMap键 | 否 | 不允许 | 有序集合 |
| HashMap | 数组+链表+红黑树 | 否 | 允许 | 通用映射存储 |
| ConcurrentHashMap | CAS+synchronized | 是 | 不允许 | 高并发映射 |
ArrayList与LinkedList性能对比:
编译器转换为迭代器遍历:
for (String s : list) {
System.out.println(s);
}
// 等价于:
Iterator it = list.iterator();
while (it.hasNext()) {
String s = it.next();
System.out.println(s);
}
不能用于修改集合(删除/添加元素)
使用迭代器的remove方法:
Iterator it = list.iterator();
while (it.hasNext()) {
if (it.next().equals("Java")) {
it.remove(); // 安全删除
}
}
Java 8+可使用removeIf:
list.removeIf("Java"::equals);
在遍历中直接调用集合remove方法会抛出ConcurrentModificationException:
for (String s : list) {
if (s.equals("Java")) {
list.remove(s); // 抛出异常!
}
}
解决方案:
Java异常体系以Throwable为根:
典型异常继承树:
Throwable
├── Error
│ ├── OutOfMemoryError
│ └── StackOverflowError
└── Exception
├── RuntimeException
│ ├── NullPointerException
│ ├── ArrayIndexOutOfBoundsException
│ └── IllegalArgumentException
└── IOException
├── FileNotFoundException
└── EOFException
try-catch-finally使用规范:
资源自动关闭(try-with-resources):
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
return br.readLine();
} catch (IOException e) {
logger.error("读取文件失败", e);
}
错误示例:
try {
riskyOperation();
} catch (Exception e) {
// 空实现!
}
危害:掩盖问题,难以定位故障
正确做法:
保留原始异常信息:
try {
// 低层操作
} catch (SQLException e) {
throw new DataAccessException("数据库操作失败", e);
}
堆栈信息包含完整异常链,便于调试
finally中异常覆盖try异常:
try {
throw new RuntimeException("原始异常");
} finally {
throw new RuntimeException("finally异常"); // 覆盖原异常!
}
解决方案:使用Suppressed异常(Java7+)
try (Resource r = new Resource()) {
throw new RuntimeException("主异常");
} catch (Exception e) {
e.addSuppressed(new RuntimeException("附加异常"));
}
Java IO流按方向分为:
按处理单位分为:
典型流继承体系:
InputStream
├── FileInputStream
├── BufferedInputStream
└── ByteArrayInputStream
Reader
├── FileReader
├── BufferedReader
└── StringReader
缓冲流提升IO性能:
try (BufferedReader br = new BufferedReader(
new FileReader("input.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
转换流实现字节-字符转换:
new InputStreamReader(inputStream, StandardCharsets.UTF_8)
示例:非阻塞服务器核心逻辑
Selector selector = Selector.open();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
ssc.register(selector, SelectionKey.OP_ACCEPT);
try (RandomAccessFile file = new RandomAccessFile("data.bin", "rw")) {
FileChannel channel = file.getChannel();
MappedByteBuffer buffer = channel.map(
FileChannel.MapMode.READ_WRITE, 0, 1024);
buffer.put((byte) 'A');
}
创建线程方式:
线程状态转换:
典型线程创建示例:
Thread thread = new Thread(() -> {
System.out.println("执行中...");
}, "Worker-1");
thread.start();
synchronized关键字:
可见性保证:
死锁必要条件:
预防策略:
常见拒绝策略:
示例:定时任务
ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(2);
scheduler.scheduleAtFixedRate(
() -> System.out.println("执行中..."),
0, 5, TimeUnit.SECONDS);
ForkJoinPool pool = new ForkJoinPool();
int result = pool.invoke(new SumTask(array, 0, array.length));
JVM运行时数据区:
内存溢出常见场景:
对象存活判定:
垃圾回收算法:
常见垃圾收集器:
| 收集器 | 适用区域 | 特点 |
|---|---|---|
| Serial | 新生代 | 单线程,简单高效 |
| ParNew | 新生代 | Serial多线程版本 |
| Parallel Scavenge | 新生代 | 关注吞吐量 |
| Serial Old | 老年代 | Serial单线程老年代版本 |
| Parallel Old | 老年代 | Parallel Scavenge老年代版本 |
| CMS | 老年代 | 低停顿,并发收集 |
| G1 | 整堆 | 面向服务端,可预测停顿 |
启用GC日志:
-Xlog:gc*:file=gc.log:time,uptime:filecount=5,filesize=10m
关键指标:
典型配置(8GB内存服务器):
-Xms4g -Xmx4g -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m
生成堆快照:
jmap -dump:format=b,file=heap.hprof <pid>
JDK安装与版本选择:
验证安装:
java -version
javac -version
| 工具 | 依赖管理 | 构建速度 | 配置复杂度 | 适用场景 |
|---|---|---|---|---|
| Maven | 中央仓库 | 中 | 低 | 传统企业项目 |
| Gradle | 灵活仓库 | 高 | 中 | 大型多模块项目 |
| Ant | 手动管理 | 高 | 高 | 简单项目/脚本 |
Gradle优势:
典型build.gradle配置:
plugins {
id 'java'
id 'application'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter:3.0.0'
testImplementation 'org.junit.jupiter:junit-jupiter:5.9.0'
}
==比较基本类型时比较值,比较引用类型时比较内存地址;equals()默认行为与==相同,但String等类已重写该方法用于比较内容。
经典陷阱:Integer缓存范围[-128,127]
Integer a = 127;
Integer b = 127;
System.out.println(a == b); // true(缓存对象)
System.out.println(a.equals(b)); // true
Integer c = 128;
Integer d = 128;
System.out.println(c == d); // false(新对象)
System.out.println(c.equals(d)); // true
现代开发推荐:
性能对比(10000次拼接):
最佳实践:频繁字符串操作使用StringBuilder
推荐学习资源: