Java编程入门
一、Java简介
1.1 什么是Java
Java是一种跨平台的面向对象编程语言,由Sun Microsystems于1995年推出,现由Oracle公司维护。Java的设计理念是"一次编写,到处运行"(Write Once, Run Anywhere, WORA),通过Java虚拟机(JVM)实现跨平台能力。Java广泛应用于企业级应用开发、移动应用开发(Android)、大数据处理等领域。
1.2 Java的主要特点
跨平台性:通过JVM实现"一次编写,到处运行"
面向对象:封装、继承、多态三大特性
健壮性:强类型检查、异常处理机制、自动内存管理
安全性:字节码验证、安全管理器、沙箱机制
多线程:内置多线程支持,简化并发编程
分布式:支持TCP/IP协议,便于网络编程
动态性:反射机制支持运行时类信息获取和操作
1.3 Java技术体系
Java技术体系由以下核心部分组成:
1.4 Java版本历史与现状
Java自发布以来经历了多个重要版本更新:
1995年:Java 1.0正式发布
2004年:Java 5引入泛型、注解、枚举等重要特性
2014年:Java 8引入Lambda表达式、Stream API、函数式接口
2018年:Java 11成为LTS版本,引入模块化系统
2019年至今:采用6个月发布周期,每年3月和9月发布新版本
当前最新LTS版本:Java 21 (2023年9月发布)
二、Java开发环境搭建
2.1 JDK安装
JDK(Java Development Kit)是Java开发的核心工具包,包含编译器、运行时环境和工具库。
Windows系统安装
访问Oracle官网或Adoptium下载JDK 21 LTS版本
运行安装程序,按照向导完成安装
配置环境变量:
JAVA_HOME: JDK安装路径(如C:\Program Files\Java\jdk-21)
PATH: 添加%JAVA_HOME%\bin和%JAVA_HOME%\jre\bin
Linux系统安装
bash
# Ubuntu/Debian
sudo apt update
sudo apt install openjdk-21-jdk
# CentOS/RHEL
sudo dnf install java-21-openjdk-devel
# 验证安装
java -version
javac -version
macOS系统安装
bash
# 使用Homebrew
brew install openjdk@21
# 配置环境变量
echo 'export JAVA_HOME=$(/usr/libexec/java_home -v 21)' >> ~/.bash_profile
source ~/.bash_profile
2.2 开发工具选择
Java常用开发工具:
IntelliJ IDEA:JetBrains开发的商业IDE,功能强大,插件丰富
社区版(免费):适合基础Java开发
旗舰版(付费):支持Web开发、Spring等框架
Eclipse:开源IDE,插件生态丰富
适合初学者和企业级开发
需要安装相应插件扩展功能
VS Code:轻量级编辑器,通过插件支持Java开发
安装"Extension Pack for Java"插件包
适合轻量级开发和多语言开发场景
2.3 第一个Java程序
创建并运行HelloWorld程序:
java
// HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java World!");
// 打印Java版本信息
System.out.println("Java Version: " + System.getProperty("java.version"));
}
}
编译和运行:
bash
# 编译Java文件
javac HelloWorld.java
# 运行字节码文件
java HelloWorld
三、Java基本语法
3.1 数据类型与变量
Java提供两种数据类型:基本类型和引用类型
变量定义与初始化示例:
java
// 基本类型变量
byte age = 25;
short score = 95;
int population = 1000000;
long distance = 123456789L; // 长整型需加L后缀
float pi = 3.14f; // 浮点型需加f后缀
double salary = 50000.50;
char grade = 'A';
boolean isActive = true;
// 引用类型变量
String name = "Java Programming";
int[] numbers = {1, 2, 3, 4, 5};
List<String> languages = new ArrayList<>();
3.2 运算符与表达式
Java支持多种运算符:
java
// 算术运算符
int sum = a + b;
int difference = a - b;
int product = a * b;
int quotient = a / b;
int remainder = a % b;
// 赋值运算符
x = 10;
x += 5; // 等价于 x = x + 5
x *= 2; // 等价于 x = x * 2
// 比较运算符
boolean isEqual = (a == b);
boolean isGreater = (a > b);
boolean isLessOrEqual = (a <= b);
// 逻辑运算符
boolean andResult = (a > 0 && b < 10);
boolean orResult = (a > 0 || b < 10);
boolean notResult = !(a > b);
// 位运算符
int bitAnd = a & b;
int bitOr = a | b;
int bitXor = a ^ b;
int bitNot = ~a;
int leftShift = a << 2;
int rightShift = a >> 2;
3.3 控制流语句
条件语句
java
// if-else语句
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 60) {
System.out.println("及格");
} else {
System.out.println("不及格");
}
// switch语句 (Java 14+)
int dayOfWeek = 3;
String dayName = switch (dayOfWeek) {
case 1 -> "星期一";
case 2 -> "星期二";
case 3 -> "星期三";
case 4 -> "星期四";
case 5 -> "星期五";
case 6, 7 -> "周末";
default -> "无效日期";
};
循环语句
java
// for循环
for (int i = 0; i < 10; i++) {
System.out.println("Count: " + i);
}
// 增强for循环(foreach)
String[] fruits = {"苹果", "香蕉", "橙子"};
for (String fruit : fruits) {
System.out.println(fruit);
}
// while循环
int count = 0;
while (count < 5) {
System.out.println("While Count: " + count);
count++;
}
// do-while循环
int num = 1;
do {
System.out.println("Do-While Num: " + num);
num *= 2;
} while (num <= 16);
3.4 面向对象基础
类与对象
java
// 类定义
public class Person {
// 成员变量
private String name;
private int age;
private String email;
// 构造方法
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 成员方法
public void introduce() {
System.out.println("Hello, I'm " + name + ", " + age + " years old.");
}
// Getter和Setter方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age > 0 && age < 150) { // 数据验证
this.age = age;
} else {
throw new IllegalArgumentException("Invalid age");
}
}
}
// 对象创建与使用
public class Main {
public static void main(String[] args) {
// 创建对象
Person person = new Person("Alice", 30);
// 调用方法
person.introduce();
// 修改属性
person.setAge(31);
System.out.println(person.getName() + " is now " + person.getAge() + " years old");
}
}
继承与多态
java
// 父类
public class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void makeSound() {
System.out.println("Some sound");
}
public void eat() {
System.out.println(name + " is eating");
}
}
// 子类继承
public class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name); // 调用父类构造方法
this.breed = breed;
}
// 方法重写
@Override
public void makeSound() {
System.out.println("Woof! Woof!");
}
// 新增方法
public void fetch() {
System.out.println(name + " is fetching the ball");
}
}
// 多态演示
public class AnimalDemo {
public static void main(String[] args) {
Animal animal1 = new Animal("Generic Animal");
Animal animal2 = new Dog("Buddy", "Golden Retriever"); // 多态引用
animal1.makeSound(); // 输出 "Some sound"
animal2.makeSound(); // 输出 "Woof! Woof!" (多态)
// 类型转换
if (animal2 instanceof Dog) {
Dog dog = (Dog) animal2;
dog.fetch(); // 调用Dog类特有方法
}
}
}
四、Java高级特性
4.1 集合框架
Java集合框架提供了丰富的数据结构实现:
常用集合使用示例:
java
// ArrayList - 动态数组
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.remove(1); // 删除索引1的元素
System.out.println("Size: " + fruits.size());
for (String fruit : fruits) {
System.out.println(fruit);
}
// HashMap - 键值对集合
Map<String, Integer> scores = new HashMap<>();
scores.put("Math", 95);
scores.put("English", 88);
scores.put("Science", 92);
System.out.println("Math score: " + scores.get("Math"));
// 遍历Map
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// HashSet - 无序不重复集合
Set<String> uniqueNames = new HashSet<>();
uniqueNames.add("Alice");
uniqueNames.add("Bob");
uniqueNames.add("Alice"); // 重复元素不会被添加
System.out.println("Unique names count: " + uniqueNames.size());
4.2 泛型
泛型允许在编译时提供类型安全检查,避免类型转换错误:
java
// 泛型类定义
public class Box<T> {
private T content;
public void setContent(T content) {
this.content = content;
}
public T getContent() {
return content;
}
// 泛型方法
public static <E> void printArray(E[] array) {
for (E element : array) {
System.out.print(element + " ");
}
System.out.println();
}
}
// 泛型使用
public class GenericDemo {
public static void main(String[] args) {
// 创建不同类型的Box
Box<String> stringBox = new Box<>();
stringBox.setContent("Hello Generics");
Box<Integer> integerBox = new Box<>();
integerBox.setContent(12345);
// 类型安全,不需要强制转换
String content = stringBox.getContent();
Integer number = integerBox.getContent();
// 泛型方法调用
Integer[] intArray = {1, 2, 3, 4, 5};
String[] stringArray = {"Hello", "World"};
Box.printArray(intArray);
Box.printArray(stringArray);
}
}
4.3 异常处理
Java异常处理机制使用try-catch-finally结构:
异常处理示例:
java
public class ExceptionHandlingDemo {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
try {
// 可能发生异常的代码
int result = numbers[0] / 0; // 会抛出ArithmeticException
System.out.println("Result: " + result);
System.out.println("Element at 10: " + numbers[10]); // 会抛出ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
// 处理算术异常
System.err.println("Error: Division by zero - " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
// 处理数组越界异常
System.err.println("Error: Array index out of bounds - " + e.getMessage());
} catch (Exception e) {
// 处理其他异常
System.err.println("An error occurred: " + e.getMessage());
} finally {
// 无论是否发生异常都会执行
System.out.println("This will always be executed.");
}
// 自定义异常示例
try {
validateAge(151);
} catch (InvalidAgeException e) {
System.err.println("Custom exception: " + e.getMessage());
}
}
// 自定义异常
static class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
// 抛出自定义异常的方法
static void validateAge(int age) throws InvalidAgeException {
if (age < 0 || age > 150) {
throw new InvalidAgeException("Age must be between 0 and 150");
}
System.out.println("Valid age: " + age);
}
}
4.4 多线程编程
Java提供多种创建线程的方式:
java
// 方式1: 继承Thread类
class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + ": " + i);
try {
Thread.sleep(500); // 休眠500毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 方式2: 实现Runnable接口
class MyRunnable implements Runnable {
private String name;
public MyRunnable(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + ": " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 方式3: 使用Lambda表达式 (Java 8+)
Runnable lambdaRunnable = () -> {
for (int i = 0; i < 5; i++) {
System.out.println("Lambda Thread: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
public class ThreadDemo {
public static void main(String[] args) {
// 启动线程
MyThread thread1 = new MyThread("Thread-1");
Thread thread2 = new Thread(new MyRunnable("Thread-2"));
Thread thread3 = new Thread(lambdaRunnable);
thread1.start();
thread2.start();
thread3.start();
// 线程状态示例
System.out.println("Thread 1 status: " + thread1.getState());
// 使用线程池 (推荐方式)
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(() -> {
System.out.println("Task 1 executed by thread pool");
});
executor.submit(() -> {
System.out.println("Task 2 executed by thread pool");
});
executor.shutdown();
}
}
线程状态转换图:
五、Java IO与NIO
5.1 IO流体系
Java IO基于流模型,分为字节流和字符流:
文件IO操作示例:
java
// 使用字节流读取文件
try (InputStream is = new FileInputStream("file.txt");
BufferedInputStream bis = new BufferedInputStream(is)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
System.out.print(new String(buffer, 0, bytesRead));
}
} catch (IOException e) {
e.printStackTrace();
}
// 使用字符流写入文件
try (Writer writer = new FileWriter("output.txt");
BufferedWriter bw = new BufferedWriter(writer)) {
bw.write("Hello, Java IO!");
bw.newLine();
bw.write("This is a new line.");
bw.flush(); // 刷新缓冲区
} catch (IOException e) {
e.printStackTrace();
}
// Java 8+ Files类简化IO操作
try {
// 读取所有行
List<String> lines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);
for (String line : lines) {
System.out.println(line);
}
// 写入文件
String content = "Hello, Java NIO Files!";
Files.write(Paths.get("newfile.txt"), content.getBytes(StandardCharsets.UTF_8));
// 创建目录
Files.createDirectories(Paths.get("data/docs"));
// 复制文件
Files.copy(Paths.get("source.txt"), Paths.get("destination.txt"));
// 删除文件
Files.deleteIfExists(Paths.get("oldfile.txt"));
} catch (IOException e) {
e.printStackTrace();
}
5.2 NIO核心组件
Java NIO(New IO)引入了通道(Channel)、缓冲区(Buffer)和选择器(Selector)等新概念:
NIO使用示例:
java
// NIO缓冲区操作
try (RandomAccessFile file = new RandomAccessFile("data.txt", "rw");
FileChannel channel = file.getChannel()) {
// 创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 从通道读取数据到缓冲区
int bytesRead = channel.read(buffer);
while (bytesRead != -1) {
// 切换为读模式
buffer.flip();
// 从缓冲区读取数据
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
// 清空缓冲区,准备下一次读取
buffer.clear();
bytesRead = channel.read(buffer);
}
// 写入数据到通道
String newData = "New string to write to file..." + System.currentTimeMillis();
buffer.clear();
buffer.put(newData.getBytes());
buffer.flip();
while (buffer.hasRemaining()) {
channel.write(buffer);
}
} catch (IOException e) {
e.printStackTrace();
}
六、Java并发编程
6.1 线程安全与同步
多线程环境下保证线程安全的几种方式:
java
// 1. synchronized关键字
class Counter {
private int count = 0;
// 同步方法
public synchronized void increment() {
count++;
}
// 同步代码块
public void decrement() {
synchronized (this) {
count--;
}
}
public synchronized int getCount() {
return count;
}
}
// 2. 使用Lock接口
class LockCounter {
private final Lock lock = new ReentrantLock();
private int count = 0;
public void increment() {
lock.lock(); // 获取锁
try {
count++;
} finally {
lock.unlock(); // 确保释放锁
}
}
public int getCount() {
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
}
// 3. 使用原子类 (java.util.concurrent.atomic)
class AtomicCounter {
private final AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet();
}
public int getCount() {
return count.get();
}
}
6.2 并发集合
Java提供了线程安全的并发集合:
java
// ConcurrentHashMap - 线程安全的HashMap
ConcurrentMap<String, Integer> concurrentMap = new ConcurrentHashMap<>();
concurrentMap.put("key1", 1);
concurrentMap.putIfAbsent("key2", 2);
concurrentMap.compute("key1", (k, v) -> v * 2);
// CopyOnWriteArrayList - 读多写少场景的线程安全List
List<String> cowList = new CopyOnWriteArrayList<>();
cowList.add("element1");
cowList.add("element2");
for (String element : cowList) { // 迭代时可以安全修改
System.out.println(element);
cowList.remove(element);
}
// BlockingQueue - 支持阻塞操作的队列
BlockingQueue<String> queue = new ArrayBlockingQueue<>(10);
// 生产者线程
new Thread(() -> {
try {
queue.put("Task 1");
queue.put("Task 2");
Thread.sleep(1000);
queue.put("Task 3");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}).start();
// 消费者线程
new Thread(() -> {
try {
System.out.println(queue.take()); // 队列为空时阻塞
System.out.println(queue.take());
System.out.println(queue.take());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}).start();
6.3 线程池与Executor框架
Executor框架提供了线程池管理功能,避免频繁创建和销毁线程的开销:
java
public class ExecutorFrameworkDemo {
public static void main(String[] args) {
// 创建不同类型的线程池
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
// 提交任务
fixedThreadPool.submit(() -> {
System.out.println("Task executed by fixed thread pool");
return "Result";
});
// 提交带返回值的任务
Future<String> future = fixedThreadPool.submit(() -> {
Thread.sleep(1000);
return "Task completed";
});
try {
// 获取任务结果
String result = future.get(); // 阻塞直到任务完成
System.out.println("Future result: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
// 定时任务
scheduledThreadPool.schedule(() -> {
System.out.println("Task executed after 3 seconds");
}, 3, TimeUnit.SECONDS);
// 周期性任务
scheduledThreadPool.scheduleAtFixedRate(() -> {
System.out.println("Task executed every 2 seconds");
}, 0, 2, TimeUnit.SECONDS);
// 关闭线程池
fixedThreadPool.shutdown();
cachedThreadPool.shutdown();
scheduledThreadPool.shutdown();
singleThreadExecutor.shutdown();
// 自定义线程池 (推荐)
ThreadPoolExecutor customExecutor = new ThreadPoolExecutor(
2, // 核心线程数
5, // 最大线程数
60, // 空闲线程存活时间
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(10), // 工作队列
new ThreadFactory() {
private int count = 1;
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "custom-thread-" + count++);
}
},
new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
);
}
}
七、Java性能优化
7.1 JVM内存模型
Java虚拟机内存分为以下区域:
7.2 垃圾回收机制
Java垃圾回收(GC)自动管理内存,主要算法包括:
7.3 性能调优实践
Java性能优化常用技巧:
java
// 1. 字符串优化
// 反例
String result = "";
for (int i = 0; i < 10000; i++) {
result += i; // 每次都会创建新对象
}
// 正例
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++) {
sb.append(i); // 高效字符串拼接
}
String result = sb.toString();
// 2. 集合优化
// 初始化时指定容量
List<String> list = new ArrayList<>(100); // 避免频繁扩容
Map<String, Object> map = new HashMap<>(32);
// 3. 避免自动装箱拆箱
// 反例
Integer sum = 0;
for (int i = 0; i < 10000; i++) {
sum += i; // 频繁装箱拆箱
}
// 正例
int sum = 0;
for (int i = 0; i < 10000; i++) {
sum += i;
}
// 4. IO优化
// 使用缓冲流
try (BufferedReader br = new BufferedReader(new FileReader("largefile.txt"))) {
String line;
while ((line = br.readLine()) != null) {
// 处理数据
}
} catch (IOException e) {
e.printStackTrace();
}
// 5. 多线程优化
// 使用线程池而非直接创建线程
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
executor.submit(new Task(i));
}
executor.shutdown();
JVM调优参数示例:
bash
# 堆内存设置
java -Xms512m -Xmx1024m -jar application.jar
# 新生代设置
java -XX:NewSize=256m -XX:MaxNewSize=512m -jar application.jar
# 垃圾收集器设置
java -XX:+UseG1GC -jar application.jar
# 打印GC日志
java -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:gc.log -jar application.jar
# 元空间设置
java -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=256m -jar application.jar
# 线程栈大小
java -Xss256k -jar application.jar
八、Java常用框架与工具
8.1 Spring Framework
Spring是Java企业级应用开发的事实标准框架:
Spring Boot快速入门:
java
// 主应用类
@SpringBootApplication
public class MySpringBootApp {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApp.class, args);
}
}
// REST控制器
@RestController
@RequestMapping("/api")
public class UserController {
private final UserService userService;
// 构造方法注入
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/users")
public List<User> getAllUsers() {
return userService.findAll();
}
@GetMapping("/users/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
return userService.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping("/users")
public User createUser(@RequestBody @Valid User user) {
return userService.save(user);
}
@PutMapping("/users/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
return ResponseEntity.ok(userService.update(id, user));
}
@DeleteMapping("/users/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
userService.delete(id);
return ResponseEntity.noContent().build();
}
}
// 服务层
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public List<User> findAll() {
return userRepository.findAll();
}
public Optional<User> findById(Long id) {
return userRepository.findById(id);
}
@Transactional
public User save(User user) {
return userRepository.save(user);
}
@Transactional
public User update(Long id, User user) {
return userRepository.findById(id)
.map(existingUser -> {
existingUser.setName(user.getName());
existingUser.setEmail(user.getEmail());
return userRepository.save(existingUser);
})
.orElseThrow(() -> new UserNotFoundException(id));
}
@Transactional
public void delete(Long id) {
userRepository.deleteById(id);
}
}
8.2 构建工具
Java常用构建工具有Maven和Gradle:
Maven示例 (pom.xml):
xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>my-java-project</artifactId>
<version>1.0.0</version>
<name>My Java Project</name>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>5.3.10</spring.version>
</properties>
<dependencies>
<!-- Spring Core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>