Java 基础核心技术笔记 - 从入门到精通
本文系统梳理 Java 核心技术体系,涵盖环境搭建、基本语法、面向对象、异常处理等关键知识点,适合初学者快速入门和开发者系统复习。
一、Java 概述与环境搭建
1.1 JDK 与 JRE 的区别
- JDK (Java Development Kit): Java 开发工具包,包含 JRE + 开发工具(javac, java, javadoc 等)
- JRE (Java Runtime Environment): Java 运行环境,包含 JVM + 核心类库
- JVM (Java Virtual Machine): Java 虚拟机,负责字节码执行
开发关系: JDK ⊃ JRE ⊃ JVM
1.2 环境变量配置
# Linux/Mac 配置 ~/.bashrc 或 ~/.zshrc
export JAVA_HOME=/usr/lib/jvm/jdk-17
export PATH=$JAVA_HOME/bin:$PATH
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
# Windows 系统环境变量
# JAVA_HOME: C:\Program Files\Java\jdk-17
# Path: %JAVA_HOME%\bin
# CLASSPATH: .;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar
验证安装:
java -version
javac -version
1.3 第一个 Hello World
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
编译与运行:
javac HelloWorld.java # 编译生成 HelloWorld.class
java HelloWorld # 运行程序
1.4 常用开发工具
| 工具 | 特点 | 适用场景 |
|---|---|---|
| IntelliJ IDEA | 功能强大、智能提示好 | 企业开发、大型项目 |
| Eclipse | 开源免费、插件丰富 | 学习、中小型项目 |
| VS Code | 轻量级、启动快 | 快速编辑、脚本编写 |
二、基本语法
2.1 标识符与关键字
标识符规则:
- 由字母、数字、下划线、$ 组成
- 不能以数字开头
- 不能使用 Java 关键字
- 区分大小写
常用关键字: public, class, static, void, int, if, for, return, new 等
2.2 变量与数据类型
8 种基本数据类型:
| 类型 | 关键字 | 字节 | 取值范围 |
|---|---|---|---|
| 字节型 | byte | 1 | -128 ~ 127 |
| 短整型 | short | 2 | -32768 ~ 32767 |
| 整型 | int | 4 | -2³¹ ~ 2³¹-1 |
| 长整型 | long | 8 | -2⁶³ ~ 2⁶³-1 |
| 浮点型 | float | 4 | 单精度 |
| 双精度 | double | 8 | 双精度 |
| 字符型 | char | 2 | Unicode 字符 |
| 布尔型 | boolean | 1 | true/false |
引用类型: String, 数组,类,接口等
// 变量定义示例
int age = 25;
double salary = 5000.50;
char grade = 'A';
boolean isActive = true;
String name = "Java";
2.3 类型转换
自动类型转换(小→大):
int a = 10;
long b = a; // int → long,自动转换
double c = a; // int → double,自动转换
强制类型转换(大→小):
double x = 9.78;
int y = (int)x; // double → int,结果为 9(截断小数部分)
2.4 运算符
算术运算符: +, -, *, /, %, ++, --
关系运算符: ==, !=, >, <, >=, <=
逻辑运算符: &&, ||, !
位运算符: &, |, ^, ~, <<, >>, >>>
赋值运算符: =, +=, -=, *=, /=, %=
2.5 注释规范
// 单行注释
/*
* 多行注释
*/
/**
* Javadoc 文档注释
* @author 寒呀
* @version 1.0
*/
三、流程控制
3.1 条件语句
if-else 结构:
int score = 85;
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 60) {
System.out.println("及格");
} else {
System.out.println("不及格");
}
switch 语句:
int day = 3;
switch (day) {
case 1:
System.out.println("星期一");
break;
case 2:
System.out.println("星期二");
break;
default:
System.out.println("其他");
}
3.2 循环结构
for 循环:
for (int i = 0; i < 5; i++) {
System.out.println("第" + i + "次循环");
}
while 循环:
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
do-while 循环:
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
3.3 跳转语句
- break: 跳出循环或 switch
- continue: 跳过本次循环,继续下一次
- return: 返回方法结果
四、数组与字符串
4.1 数组定义与遍历
// 静态初始化
int[] arr1 = {1, 2, 3, 4, 5};
// 动态初始化
int[] arr2 = new int[5];
// 遍历数组
for (int i = 0; i < arr1.length; i++) {
System.out.println(arr1[i]);
}
// 增强 for 循环
for (int num : arr1) {
System.out.println(num);
}
4.2 二维数组
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// 遍历二维数组
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
4.3 String 类常用方法
String str = "Hello, Java!";
str.length(); // 获取长度:12
str.charAt(0); // 获取字符:'H'
str.substring(0, 5); // 截取子串:"Hello"
str.indexOf("Java"); // 查找位置:7
str.replace("Java", "World"); // 替换:"Hello, World!"
str.split(","); // 分割:["Hello", " Java!"]
str.trim(); // 去除首尾空格
str.toUpperCase(); // 转大写:"HELLO, JAVA!"
str.toLowerCase(); // 转小写:"hello, java!"
4.4 StringBuilder 与 StringBuffer
// StringBuilder(非线程安全,性能高)
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String result = sb.toString();
// StringBuffer(线程安全,性能略低)
StringBuffer sbf = new StringBuffer();
sbf.append("Thread Safe");
五、面向对象编程
5.1 类与对象
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;
}
}
// 创建对象
Person p = new Person("张三", 25);
p.sayHello();
5.2 三大特性
封装: 隐藏内部实现,提供公共访问接口
private String name; // 私有化成员变量
public String getName() { // 提供公共访问方法
return name;
}
继承: 子类继承父类的属性和方法
public class Student extends Person {
private String studentId;
public Student(String name, int age, String studentId) {
super(name, age); // 调用父类构造器
this.studentId = studentId;
}
}
多态: 同一操作作用于不同对象产生不同行为
Person p = new Student("李四", 20, "S001"); // 父类引用指向子类对象
p.sayHello(); // 执行子类重写的方法
5.3 常用关键字
this: 指向当前对象
public Person(String name) {
this.name = name; // 区分成员变量和局部变量
}
super: 指向父类对象
public Student(String name, int age) {
super(name, age); // 调用父类构造器
}
static: 静态修饰符,属于类而非对象
public static int count = 0; // 静态变量
public static void print() { // 静态方法
System.out.println("Hello");
}
final: 最终修饰符
final int MAX_VALUE = 100; // 常量
final class FinalClass {} // 不能被继承
final void finalMethod() {} // 不能被重写
六、异常处理
6.1 Throwable 体系
Throwable
├── Error(严重错误,不可恢复)
└── Exception(异常,可处理)
├── RuntimeException(运行时异常)
└── 其他 Exception(编译时异常)
6.2 try-catch-finally
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("最终都会执行");
}
6.3 throw 与 throws
// throw: 手动抛出异常
if (age < 0) {
throw new IllegalArgumentException("年龄不能为负");
}
// throws: 声明方法可能抛出的异常
public void readFile() throws IOException {
// 可能抛出 IOException 的代码
}
6.4 自定义异常
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
// 使用自定义异常
public void validate(int age) throws MyException {
if (age < 0) {
throw new MyException("年龄无效");
}
}
七、常用 API
7.1 包装类
| 基本类型 | 包装类 |
|---|---|
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
// 自动装箱与拆箱
Integer a = 10; // 自动装箱
int b = a; // 自动拆箱
// 类型转换
String str = "123";
int num = Integer.parseInt(str);
String str2 = String.valueOf(num);
7.2 Math 类
Math.abs(-10); // 绝对值:10
Math.sqrt(16); // 平方根:4.0
Math.pow(2, 3); // 幂运算:8.0
Math.random(); // 随机数:[0, 1)
Math.round(3.6); // 四舍五入:4
Math.max(10, 20); // 最大值:20
Math.min(10, 20); // 最小值:10
7.3 Date 与 Calendar
// Date
Date now = new Date();
long time = now.getTime(); // 毫秒值
// SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdf.format(now);
// Calendar
Calendar cal = Calendar.getInstance();
cal.set(2026, 3, 14); // 注意:月份从 0 开始
int year = cal.get(Calendar.YEAR);
7.4 正则表达式
String regex = "^\\d{3}-\\d{8}$"; // 匹配电话号码
String tel = "010-12345678";
boolean matches = tel.matches(regex);
// 常用正则
// 邮箱:^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$
// 手机号:^1[3-9]\\d{9}$
// 身份证:^[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[\\dXx]$
总结
Java 作为一门成熟的面向对象编程语言,具有跨平台、安全性高、生态丰富等优势。掌握以上基础知识后,建议进一步学习:
- 集合框架(List, Set, Map)
- IO 流与序列化
- 多线程与并发
- 网络编程
- 反射与注解
- JVM 原理与调优
作者: 寒呀
发布于: 2026-04-14
博客: 运维笔记
备案号: 陕 ICP 备 20240429 号 -2