Java 是一种功能强大的编程语言,广泛应用于企业级应用、移动应用和大型系统中。这篇教程将带你从零基础开始,通过循序渐进的方式,掌握 Java 编程的方方面面。本文将尽可能详细地涵盖每一个关键点,确保即便是初学者也能理解和掌握每一部分内容。
🧑 博主简介:现任阿里巴巴嵌入式技术专家,15年工作经验,深耕嵌入式+人工智能领域,精通嵌入式领域开发、技术管理、简历招聘面试。CSDN优质创作者,提供产品测评、学习辅导、简历面试辅导、毕设辅导、项目开发、C/C++/Java/Python/Linux/AI等方面的服务,如有需要请站内私信或者联系任意文章底部的的VX名片(ID:
gylzbk
)
💬 博主粉丝群介绍:① 群内初中生、高中生、本科生、研究生、博士生遍布,可互相学习,交流困惑。② 热榜top10的常客也在群里,也有数不清的万粉大佬,可以交流写作技巧,上榜经验,涨粉秘籍。③ 群内也有职场精英,大厂大佬,可交流技术、面试、找工作的经验。④ 进群免费赠送写作秘籍一份,助你由写作小白晋升为创作大佬。⑤ 进群赠送CSDN评论防封脚本,送真活跃粉丝,助你提升文章热度。有兴趣的加文末联系方式,备注自己的CSDN昵称,拉你进群,互相学习共同进步。
【Java】Java零基础从入门到精通
概述
Java 是一种功能强大的编程语言,广泛应用于企业级应用、移动应用和大型系统中。这篇教程将带你从零基础开始,通过循序渐进的方式,掌握 Java 编程的方方面面。本文将尽可能详细地涵盖每一个关键点,确保即便是初学者也能理解和掌握每一部分内容。
1. Java 简介和环境配置
Java 简介
Java 是由 Sun Microsystems(现为 Oracle 旗下)开发的面向对象编程语言。它有以下几个显著特点:
- 跨平台性:Java 程序可以在任何安装了 Java 虚拟机 (JVM) 的平台上运行。
- 面向对象:Java 支持 OOP 特性,如封装、继承和多态。
- 丰富的标准库:Java 提供了丰富的标准库,简化了几乎所有类型的开发工作。
安装和配置
安装 JDK
- 下载:从 Oracle 官方网站 下载最新的 Java Development Kit (JDK)。
- 安装:根据操作系统的提示完成安装。
配置环境变量
为了在命令行中方便使用 Java 编译器和运行时,需要配置环境变量。
Windows
- 打开控制面板,进入系统和安全 -> 系统 -> 高级系统设置。
- 点击“环境变量”按钮。
- 在“系统变量”中点击“新建”,输入变量名
JAVA_HOME
,变量值为 JDK 的安装路径,例如C:\Program Files\Java\jdk-11.0.1
。 - 在“系统变量”中找到
Path
,点击“编辑”,在变量值末尾添加;%JAVA_HOME%\bin
。
macOS / Linux
编辑 ~/.bash_profile
(或 ~/.zshrc
/ ~/.bashrc
) 文件,添加以下内容:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH
然后,运行以下命令使配置生效:
source ~/.bash_profile
验证安装
在终端中运行命令:
java -version
如果显示 Java 版本信息,则说明安装及配置成功。
安装开发环境
推荐使用 IntelliJ IDEA 或 Eclipse 作为开发工具。
- IntelliJ IDEA:从 JetBrains 官网 下载并安装。
- Eclipse:从 Eclipse 官网 下载并安装。
2. Java 基本语法
Hello World 程序
创建并运行你的第一个 Java 程序。
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
保存文件为 HelloWorld.java
,然后在终端中运行以下命令:
javac HelloWorld.java // 编译程序
java HelloWorld // 运行程序
基本数据类型和变量
Java 中的基本数据类型分为四类共八种:
- 整数类型:
byte
,short
,int
,long
- 浮点类型:
float
,double
- 字符类型:
char
- 布尔类型:
boolean
示例
public class DataTypeExample {
public static void main(String[] args) {
int anInt = 10;
double aDouble = 20.5;
char aChar = 'A';
boolean aBoolean = true;
System.out.println("Integer: " + anInt);
System.out.println("Double: " + aDouble);
System.out.println("Char: " + aChar);
System.out.println("Boolean: " + aBoolean);
}
}
操作符
算术操作符
- 加法:
+
- 减法:
-
- 乘法:
*
- 除法:
/
- 取余:
%
关系操作符
- 等于:
==
- 不等于:
!=
- 大于:
>
- 小于:
<
- 大于等于:
>=
- 小于等于:
<=
逻辑操作符
- 逻辑与:
&&
- 逻辑或:
||
- 逻辑非:
!
流程控制
条件语句
if-else
switch
循环语句
for
while
do-while
示例
public class ControlFlowExample {
public static void main(String[] args) {
int number = 5;
// if-else
if (number > 0) {
System.out.println("Positive number");
} else {
System.out.println("Negative number");
}
// switch
switch (number) {
case 1:
System.out.println("One");
break;
case 5:
System.out.println("Five");
break;
default:
System.out.println("Number not matched");
}
// for loop
for (int i = 0; i < 3; i++) {
System.out.println("for loop iteration: " + i);
}
// while loop
int j = 0;
while (j < 3) {
System.out.println("while loop iteration: " + j);
j++;
}
// do-while loop
int k = 0;
do {
System.out.println("do-while loop iteration: " + k);
k++;
} while (k < 3);
}
}
3. 面向对象编程(OOP)
类和对象
定义类
public class Animal {
// 属性(成员变量)
private String name;
private int age;
// 构造函数
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
// 方法(成员函数)
public void speak() {
System.out.println("Animal speaks");
}
// 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) {
this.age = age;
}
}
创建对象
public class Main {
public static void main(String[] args) {
// 创建 Animal 对象
Animal myAnimal = new Animal("Buddy", 5);
// 调用对象方法
myAnimal.speak();
// 获取属性值
System.out.println("Name: " + myAnimal.getName());
System.out.println("Age: " + myAnimal.getAge());
}
}
封装、继承和多态
封装
封装是指在一个类中将数据和方法包装在一起,并通过访问修饰符来控制对数据的访问。
继承
继承使我们可以创建一个新类,该类从现有类继承属性和方法:
public class Dog extends Animal {
// 调用父类构造函数
public Dog(String name, int age) {
super(name, age);
}
// 重写父类的方法
@Override
public void speak() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
// 创建 Dog 对象
Dog myDog = new Dog("Buddy", 5);
// 调用重写的方法
myDog.speak();
}
}
多态
多态性使得一个对象可以有多种形态:
public class Main {
public static void main(String[] args) {
// 父类引用指向子类对象
Animal myDog = new Dog("Buddy", 5);
// 调用的是子类的重写方法
myDog.speak();
}
}
接口和抽象类
接口
接口定义了类必须实现的方法,但不包含方法的实现:
public interface Animal {
void speak();
}
public class Dog implements Animal {
@Override
public void speak() {
System.out.println("Dog barks");
}
}
抽象类
抽象类是不能实例化的类,它可以包含抽象方法和非抽象方法:
public abstract class Animal {
public abstract void speak();
public void sleep() {
System.out.println("Animal sleeps");
}
}
public class Dog extends Animal {
@Override
public void speak() {
System.out.println("Dog barks");
}
}
内部类
内部类是定义在另一个类中的类:
public class OuterClass {
private String message = "Hello, World!";
public class InnerClass {
public void printMessage() {
System.out.println(message);
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.printMessage();
}
}
4. Java 核心类库
字符串处理
String 类
String
是一个不可变类:
public class StringExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String str3 = str1 + ", " + str2 + "!";
System.out.println(str3); // 输出:Hello, World!
}
}
StringBuilder 和 StringBuffer
StringBuilder
和 StringBuffer
提供了可变的字符串操作:
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(", World!");
System.out.println(sb.toString()); // 输出:Hello, World!
}
}
日期和时间
Java 8 引入了全新的日期时间 API:
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeExample {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println("Current Date: " + date);
System.out.println("Current Time: " + time);
System.out.println("Current DateTime: " + dateTime.format(formatter));
}
}
数学函数和随机数
Math 类
Math
类提供了常用的数学函数:
public class MathExample {
public static void main(String[] args) {
double squareRoot = Math.sqrt(16); // 平方根
double power = Math.pow(2, 3); // 次方
double random = Math.random(); // 随机数 [0.0, 1.0)
System.out.println("Square Root of 16: " + squareRoot);
System.out.println("2 to the power of 3: " + power);
System.out.println("Random number: " + random);
}
}
Random 类
Random
类用于生成随机数:
import java.util.Random;
public class RandomExample {
public static void main(String[] args) {
Random random = new Random();
int randomInt = random.nextInt(100); // 生成 [0, 100) 之间的随机整数
System.out.println("Random integer between 0 and 100: " + randomInt);
}
}
5. 异常处理
基本概念
异常是程序在运行过程中出现的错误。Java 提供了异常处理机制,以捕获和处理异常,使程序能够继续运行或以合理的方式终止。
捕获异常
使用 try-catch
块捕获和处理异常:
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = divide(10, 0);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
}
public static int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
return a / b;
}
}
声明和抛出异常
使用 throws
关键字声明方法可能抛出的异常,使用 throw
关键字抛出异常:
public static int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
return a / b;
}
自定义异常
你可以定义自己的异常类:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class ExceptionExample {
public static void main(String[] args) {
try {
validateAge(15);
} catch (CustomException e) {
System.out.println(e.getMessage());
}
}
public static void validateAge(int age) throws CustomException {
if (age < 18) {
throw new CustomException("Age must be 18 or older.");
}
}
}
6. 集合框架
Java 集合框架提供了一组用于存储和处理数据的类和接口。
List 接口
ArrayList
ArrayList
是一种动态数组:
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
for (String fruit : list) {
System.out.println(fruit);
}
}
}
LinkedList
LinkedList
是一种链表实现:
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
for (String fruit : list) {
System.out.println(fruit);
}
}
}
Set 接口
HashSet
HashSet
是一种没有重复元素的集合:
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // 重复元素不会被添加
for (String fruit : set) {
System.out.println(fruit);
}
}
}
TreeSet
TreeSet
是一种有序的集合:
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<String> set = new TreeSet<>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");
for (String fruit : set) {
System.out.println(fruit);
}
}
}
Map 接口
HashMap
HashMap
是一种键值对映射:
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
for (String key : map.keySet()) {
System.out.println("Key: " + key + ", Value: " + map.get(key));
}
}
}
TreeMap
TreeMap
是一种有序的键值对映射:
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<String, Integer> map = new TreeMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
for (String key : map.keySet()) {
System.out.println("Key: " + key + ", Value: " + map.get(key));
}
}
}
迭代和遍历
Iterator
Iterator
接口用于遍历集合,可以避免使用原生循环,特别是在删除集合中的元素时表现出色:
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String fruit = iterator.next();
System.out.println(fruit);
if ("Banana".equals(fruit)) {
iterator.remove(); // 正确删除元素的方法
}
}
System.out.println("After removal: " + list);
}
}
增强型 for
循环
增强型 for
循环是一种方便遍历集合元素的方式:
import java.util.ArrayList;
public class EnhancedForLoopExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
for (String fruit : list) {
System.out.println(fruit);
}
}
}
7. 多线程编程
基本概念
多线程编程允许并发执行多个线程以提高程序的效率。Java 提供了强大的多线程支持。
线程的创建和启动
有两种主要的创建线程方法:
继承 Thread
类
public class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}
实现 Runnable
接口
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable thread is running");
}
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start(); // 启动线程
}
}
同步和锁
同步主要通过 synchronized
关键字来实现,以防止线程间的数据不一致:
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
public static void main(String[] args) {
Counter counter = new Counter();
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
};
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final count: " + counter.getCount());
}
}
线程通信
使用 wait
、notify
和 notifyAll
方法处理线程间的通信问题:
class SharedResource {
private int value;
private boolean available = false;
public synchronized void produce(int value) {
while (available) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.value = value;
available = true;
System.out.println("Produced: " + value);
notify();
}
public synchronized void consume() {
while (!available) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Consumed: " + value);
available = false;
notify();
}
}
class Producer implements Runnable {
private SharedResource resource;
public Producer(SharedResource resource) {
this.resource = resource;
}
public void run() {
for (int i = 0; i < 10; i++) {
resource.produce(i);
}
}
}
class Consumer implements Runnable {
private SharedResource resource;
public Consumer(SharedResource resource) {
this.resource = resource;
}
public void run() {
for (int i = 0; i < 10; i++) {
resource.consume();
}
}
}
public class ThreadCommunicationExample {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Thread producerThread = new Thread(new Producer(resource));
Thread consumerThread = new Thread(new Consumer(resource));
producerThread.start();
consumerThread.start();
}
}
8. 输入输出(I/O)
文件操作
File 类
File
类用于处理文件和目录的创建、删除等操作:
import java.io.File;
public class FileExample {
public static void main(String[] args) {
File file = new File("example.txt");
try {
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
字节流和字符流
输入和输出流
InputStream
和 OutputStream
处理字节数据:
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class ByteStreamExample {
public static void main(String[] args) {
try (FileOutputStream fos = new FileOutputStream("example.txt")) {
fos.write("Hello, World!".getBytes());
} catch (Exception e) {
e.printStackTrace();
}
try (FileInputStream fis = new FileInputStream("example.txt")) {
int content;
while ((content = fis.read()) != -1) {
System.out.print((char) content);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
字符流
Reader
和 Writer
处理字符数据:
import java.io.FileReader;
import java.io.FileWriter;
public class CharStreamExample {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("example.txt")) {
writer.write("Hello, World!");
} catch (Exception e) {
e.printStackTrace();
}
try (FileReader reader = new FileReader("example.txt")) {
int content;
while ((content = reader.read()) != -1) {
System.out.print((char) content);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
序列化与反序列化
序列化用于将对象转换为字节序列,反序列化则是将字节序列恢复为对象,使用 Serializable
接口实现:
import java.io.*;
class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
public class SerializationExample {
public static void main(String[] args) {
Person person = new Person("John", 30);
// 序列化
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
oos.writeObject(person);
} catch (Exception e) {
e.printStackTrace();
}
// 反序列化
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
Person deserializedPerson = (Person) ois.readObject();
System.out.println("Deserialized Person: " + deserializedPerson);
} catch (Exception e) {
e.printStackTrace();
}
}
}
9. 网络编程
基本概念
Java 提供了一些类用于网络编程,包括 InetAddress
、Socket
、ServerSocket
等。
InetAddress
用于标识网络中的计算机:
import java.net.InetAddress;
public class InetAddressExample {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("www.google.com");
System.out.println("IP Address: " + address.getHostAddress());
System.out.println("Hostname: " + address.getHostName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Socket 编程
客户端
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 8080)) {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("Hello, Server");
String response = in.readLine();
System.out.println("Server response: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
服务器
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Server is listening on port 8080");
while (true) {
Socket socket = serverSocket.accept();
new ServerThread(socket).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ServerThread extends Thread {
private Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
String message = in.readLine();
System.out.println("Client message: " + message);
out.println("Hello, Client");
} catch (Exception e) {
e.printStackTrace();
}
}
}
10. Java 数据库开发 (JDBC)
JDBC 概述
Java 数据库连接 (JDBC) 是一种用于执行 SQL 语句的 Java API。它使得 Java 程序可以连接数据库并执行查询、更新和其他与数据库交互的操作。
数据库连接
连接数据库需要使用 JDBC 驱动程序。
示例:连接 MySQL 数据库
import java.sql.Connection;
import java.sql.DriverManager;
public class DatabaseConnection {
public static void main(String[] args) {
String jdbcURL = "jdbc:mysql://localhost:3306/testdb";
String username = "root";
String password = "password";
try {
Connection connection = DriverManager.getConnection(jdbcURL, username, password);
System.out.println("Connected to the database");
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
查询和更新
使用 Statement
和 PreparedStatement
执行 SQL 语句。
示例:查询数据
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DatabaseQuery {
public static void main(String[] args) {
String jdbcURL = "jdbc:mysql://localhost:3306/testdb";
String username = "root";
String password = "password";
try {
Connection connection = DriverManager.getConnection(jdbcURL, username, password);
Statement statement = connection.createStatement();
String sql = "SELECT * FROM users";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
示例:插入数据
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class DatabaseInsert {
public static void main(String[] args) {
String jdbcURL = "jdbc:mysql://localhost:3306/testdb";
String username = "root";
String password = "password";
try {
Connection connection = DriverManager.getConnection(jdbcURL, username, password);
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, "John Doe");
statement.setString(2, "john.doe@example.com");
int rows = statement.executeUpdate();
if (rows > 0) {
System.out.println("A new user has been inserted.");
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
事务控制
JDBC 支持事务管理,允许多个 SQL 操作要么全部执行,要么全部回退。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class TransactionExample {
public static void main(String[] args) {
String jdbcURL = "jdbc:mysql://localhost:3306/testdb";
String username = "root";
String password = "password";
Connection connection = null;
try {
connection = DriverManager.getConnection(jdbcURL, username, password);
connection.setAutoCommit(false); // 开启事务
String sql1 = "INSERT INTO accounts (name, balance) VALUES (?, ?)";
String sql2 = "UPDATE accounts SET balance = balance - ? WHERE name = ?";
String sql3 = "UPDATE accounts SET balance = balance + ? WHERE name = ?";
PreparedStatement statement1 = connection.prepareStatement(sql1);
statement1.setString(1, "Alice");
statement1.setDouble(2, 1000.0);
statement1.executeUpdate();
PreparedStatement statement2 = connection.prepareStatement(sql2);
statement2.setDouble(1, 100.0);
statement2.setString(2, "Alice");
statement2.executeUpdate();
PreparedStatement statement3 = connection.prepareStatement(sql3);
statement3.setDouble(1, 100.0);
statement3.setString(2, "Bob");
statement3.executeUpdate();
connection.commit(); // 提交事务
System.out.println("Transaction completed successfully.");
} catch (Exception e) {
try {
if (connection != null) {
connection.rollback(); // 回滚事务
}
} catch (Exception ex) {
ex.printStackTrace();
}
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.setAutoCommit(true);
connection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
11. 高级主题
泛型
泛型提供了一种机制,使得类型可以在类、接口和方法定义中作为参数应用。
import java.util.ArrayList;
import java.util.List;
public class GenericExample {
public static <T> void printElements(List<T> list) {
for (T element : list) {
System.out.println(element);
}
}
public static void main(String[] args) {
List<String> stringList = new ArrayList<>();
stringList.add("Hello");
stringList.add("World");
List<Integer> integerList = new ArrayList<>();
integerList.add(1);
integerList.add(2);
printElements(stringList);
printElements(integerList);
}
}
注解
注解提供了一种注释代码的方式,这些注释随后可用于编译阶段处理。
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation {
String value();
}
class AnnotationExample {
@MyAnnotation(value = "Hello Annotations")
public void myMethod() {
System.out.println("My Method");
}
}
public class Main {
public static void main(String[] args) {
try {
AnnotationExample example = new AnnotationExample();
Method method = example.getClass().getMethod("myMethod");
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
System.out.println("Annotation value: " + annotation.value());
example.myMethod();
} catch (Exception e) {
e.printStackTrace();
}
}
}
反射
反射允许程序在运行时获取类的信息并操作对象。
import java.lang.reflect.*;
public class ReflectionExample {
public static void main(String[] args) {
try {
Class<?> clazz = Class.forName("java.util.ArrayList");
System.out.println("Class Name: " + clazz.getName());
Method[] methods = clazz.getMethods();
for (Method method : methods) {
System.out.println("Method: " + method.getName());
}
Constructor<?> constructor = clazz.getConstructor();
Object instance = constructor.newInstance();
Method addMethod = clazz.getMethod("add", Object.class);
addMethod.invoke(instance, "Hello");
addMethod.invoke(instance, "World");
System.out.println("Instance: " + instance.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Lambda 表达式
Lambda 表达式提供了一种简洁的方式来表示匿名函数,流则用于处理集合数据。
import java.util.function.*;
public class LambdaExample {
public static void main(String[] args) {
Predicate<String> isNonEmptyString = (String s) -> s != null && !s.isEmpty();
System.out.println(isNonEmptyString.test("Hello")); // true
System.out.println(isNonEmptyString.test("")); // false
}
}
Stream API
Stream API 用于处理集合的简洁操作:
import java.util.Arrays;
import java.util.List;
public class StreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Paul", "George", "Ringo");
long count = names.stream()
.filter(name -> name.startsWith("J"))
.count();
System.out.println("Number of names starting with 'J': " + count);
}
}
12. Java 开发工具和框架
构建工具
Maven
Maven 是一个项目管理和构建自动化工具,广泛用于 Java 项目。它使用 pom.xml
配置文件来管理项目依赖、模块和构建生命周期。
配置 pom.xml
<!-- pom.xml -->
<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-app</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- 添加依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
常用命令
# 创建 Maven 项目
mvn archetype:generate -DgroupId=com.example -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
# 编译项目
mvn compile
# 运行单元测试
mvn test
# 打包项目
mvn package
Gradle
Gradle 是另一种流行的构建工具,使用 Groovy 或 Kotlin 作为配置脚本语言。
配置 build.gradle
// build.gradle
plugins {
id 'java'
}
group 'com.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
testImplementation 'junit:junit:4.12'
}
常用命令
# 初始化 Gradle 项目
gradle init --type java-application
# 编译项目
gradle build
# 运行单元测试
gradle test
# 运行应用程序
gradle run
测试框架
JUnit
JUnit 是一个常用的单元测试框架,支持编写和运行可重复的测试。
示例测试类
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calculator = new Calculator();
int result = calculator.add(2, 3);
assertEquals(5, result);
}
}
配置 Maven 和 Gradle
在 Maven 中,添加 JUnit 依赖到 pom.xml
:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
在 Gradle 中,添加 JUnit 依赖到 build.gradle
:
dependencies {
testImplementation 'junit:junit:4.12'
}
Web 开发框架
Spring 和 Spring Boot
Spring 是一个功能强大的企业级框架,用于构建复杂的应用程序。Spring Boot 是基于 Spring 的更简化和便捷的框架。
创建 Spring Boot 项目
使用 Spring Initializr 创建 Spring Boot 项目,选择所需的依赖项,并生成项目。
示例 Controller
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
配置 Spring Boot 应用
在 src/main/resources/application.properties
中配置应用属性:
server.port=8080
启动 Spring Boot 应用
在主类中添加 SpringBootApplication
注解并运行:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
ORM 框架
Hibernate
Hibernate 是 Java 的一个对象关系映射(ORM)框架,简化了数据库操作。
配置 Hibernate
在 Maven 或 Gradle 项目中添加 Hibernate 依赖:
<!-- Maven -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.30.Final</version>
</dependency>
// Gradle
dependencies {
implementation 'org.hibernate:hibernate-core:5.4.30.Final'
}
示例实体类
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class User {
@Id
private Long id;
private String name;
private String email;
// Getters and Setters
}
配置 Hibernate Session 工厂
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
使用 Session 进行数据库操作
import org.hibernate.Session;
import org.hibernate.Transaction;
public class App {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
User user = new User();
user.setId(1L);
user.setName("John Doe");
user.setEmail("john.doe@example.com");
session.save(user);
transaction.commit();
session.close();
}
}
13. 项目实战
小型项目实践
控制台应用程序
实现一个简单的控制台应用程序,如计算器。
import java.util.Scanner;
public class CalculatorApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
System.out.print("Choose an operation (+, -, *, /): ");
char operation = scanner.next().charAt(0);
double result = 0;
switch (operation) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Error: Division by zero");
return;
}
break;
default:
System.out.println("Invalid operation");
return;
}
System.out.println("Result: " + result);
}
}
Web 应用程序
使用 Spring Boot 开发简单的 Web 应用
实现一个简单的 RESTful Web 服务,提供用户信息的 CRUD 操作。
创建项目结构
使用 Spring Initializr 创建项目并添加必要的依赖项,如 Spring Web 和 Spring Data JPA。
配置数据库连接
编辑 src/main/resources/application.properties
:
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
创建实体类和仓库接口
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Getters and Setters
}
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
创建控制器
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public List<User> getAllUsers() {
return userRepository.findAll();
}
@PostMapping
public User createUser(@RequestBody User user) {
return userRepository.save(user);
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("User not found"));
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User userDetails) {
User user = userRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("User not found"));
user.setName(userDetails.getName());
user.setEmail(userDetails.getEmail());
return userRepository.save(user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
User user = userRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("User not found"));
userRepository.delete(user);
}
}
启动应用程序
在主类中添加 SpringBootApplication
注解并运行:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
14. 资源和学习建议
在线资源
书籍推荐
- 《Java 编程思想》 – Bruce Eckel
- 《Effective Java》 – Joshua Bloch
- 《Java 核心技术卷 I》 – Cay S. Horstmann
学习建议
- 动手实践:通过编写代码来巩固所学知识。
- 做笔记:记录重要的概念和常犯的错误,以便复习。
- 参与开源项目:参与开源项目不仅能学到新技能,还能与其他开发者交流。
- 定期复习:定期回顾和复习所学内容,以确保理解和掌握。
通过认真学习和实践,本教程所涵盖的内容应该能帮助你从零基础逐步掌握 Java 编程,并在实际项目中应用所学知识。希望这篇超级详细的 Java 教程对你有帮助,祝你编程之旅顺利。如果有任何疑问或需要进一步的指导,欢迎在评论区交流和讨论!