Java编程完全指南:从入门到精通

前言

Java作为全球最受欢迎的编程语言之一,以其跨平台、安全、稳定的特点,广泛应用于企业级应用开发、安卓开发、大数据处理等领域。本文将全面介绍Java编程的核心概念和实战技巧,帮助你从零开始掌握这门强大的编程语言。

Java编程

一、Java简介

1.1 Java的历史与发展

Java由Sun公司(现属Oracle)于1995年发布,其设计理念是”一次编写,到处运行”(Write Once, Run Anywhere)。

Java的发展历程:

版本 发布年份 主要特性
JDK 1.0 1996 首个正式版本
JDK 5 2004 泛型、枚举、注解
JDK 8 2014 Lambda表达式、Stream API
JDK 11 2018 LTS版本、HTTP Client
JDK 17 2021 LTS版本、记录类
JDK 21 2023 LTS版本、虚拟线程

Java发展历程

1.2 Java的特点

跨平台性

1
2
3
4
5
6
// 同一份代码可以在Windows、Linux、Mac上运行
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

面向对象

  • 封装、继承、多态三大特性
  • 一切皆对象的设计理念

安全性

  • 内存管理由JVM自动处理
  • 类型检查机制
  • 异常处理机制

高性能

  • JIT(Just-In-Time)编译器
  • 优化的垃圾回收机制

1.3 Java的应用领域

  • 企业级应用:银行系统、电商平台、ERP系统
  • 安卓开发:移动应用开发
  • 大数据:Hadoop、Spark等框架
  • 云计算:微服务架构
  • 物联网:嵌入式设备开发

二、Java基础语法

2.1 程序结构

一个完整的Java程序包含以下结构:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.example;           // 包声明

// 导入其他包中的类
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;

/**
* 这是一个文档注释
* 用于描述类的作用
*/
public class MyClass {
// 类变量(静态变量)
private static int count = 0;

// 实例变量
private String name;

/**
* 构造方法
*/
public MyClass(String name) {
this.name = name;
}

/**
* 实例方法
*/
public void sayHello() {
System.out.println("Hello, " + name + "!");
}

/**
* 主方法 - 程序入口
*/
public static void main(String[] args) {
// 创建对象
MyClass myObj = new MyClass("World");
// 调用方法
myObj.sayHello();
}
}

2.2 数据类型

Java有两类数据类型:基本类型和引用类型。

基本数据类型(8种):

类型 大小 默认值 包装类
byte 8位 0 Byte
short 16位 0 Short
int 32位 0 Integer
long 64位 0L Long
float 32位 0.0f Float
double 64位 0.0d Double
char 16位 ‘\u0000’ Character
boolean - false Boolean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 基本数据类型示例
byte b = 127;
short s = 32767;
int i = 2147483647;
long l = 9223372036854775807L;

float f = 3.14f;
double d = 3.1415926535;

char c = 'A';
boolean bool = true;

// 自动装箱和拆箱
Integer num = 100; // 自动装箱
int n = num; // 自动拆箱

引用类型:

  • 类(Class)
  • 接口(Interface)
  • 数组(Array)
  • 枚举(Enum)
1
2
3
4
// 引用类型示例
String str = "Hello";
int[] array = {1, 2, 3, 4, 5};
List<String> list = new ArrayList<>();

2.3 变量与常量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Variables {
// 实例变量
private int instanceVar;

// 类变量(静态变量)
private static int staticVar;

// 常量(final)
private static final double PI = 3.14159;

public void method() {
// 局部变量
int localVar = 10;

// 使用变量
System.out.println(localVar);
}
}

2.4 运算符

算术运算符:

1
2
3
4
5
6
7
8
9
10
11
int a = 10, b = 3;

int sum = a + b; // 13 加法
int diff = a - b; // 7 减法
int prod = a * b; // 30 乘法
int quot = a / b; // 3 除法(整数除法)
int rem = a % b; // 1 取模(求余)

// 自增自减
a++; // a = a + 1
a--; // a = a - 1

比较运算符:

1
2
3
4
5
6
7
8
int a = 10, b = 20;

boolean eq = (a == b); // false 等于
boolean neq = (a != b); // true 不等于
boolean gt = (a > b); // false 大于
boolean lt = (a < b); // true 小于
boolean gte = (a >= b); // false 大于等于
boolean lte = (a <= b); // true 小于等于

逻辑运算符:

1
2
3
4
5
boolean a = true, b = false;

boolean and = (a && b); // false 与(短路)
boolean or = (a || b); // true 或(短路)
boolean not = (!a); // false 非

位运算符:

1
2
3
4
5
6
7
8
9
int a = 5;  // 二进制:101
int b = 3; // 二进制:011

int and = a & b; // 1 按位与
int or = a | b; // 7 按位或
int xor = a ^ b; // 6 按位异或
int not = ~a; // -6 按位取反
int left = a << 1; // 10 左移
int right = a >> 1; // 2 右移

三、面向对象编程

3.1 类与对象

类的定义:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class Person {
// 成员变量(属性)
private String name;
private int age;
private String gender;

// 构造方法
public Person() {
this.name = "Unknown";
this.age = 0;
}

public Person(String name, int age) {
this.name = name;
this.age = age;
}

// Getter方法
public String getName() {
return name;
}

public int getAge() {
return age;
}

// Setter方法
public void setName(String name) {
this.name = name;
}

public void setAge(int age) {
if (age >= 0 && age <= 150) {
this.age = age;
}
}

// 成员方法
public void introduce() {
System.out.println("我叫" + name + ",今年" + age + "岁");
}
}

对象的创建与使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Main {
public static void main(String[] args) {
// 创建对象
Person person1 = new Person();
Person person2 = new Person("张三", 25);

// 访问属性
person1.setName("李四");
person1.setAge(30);

// 调用方法
person1.introduce(); // 我叫李四,今年30岁
person2.introduce(); // 我叫张三,今年25岁
}
}

3.2 封装

封装是面向对象的三大特性之一,它通过访问修饰符隐藏类的内部实现细节。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class BankAccount {
// 私有属性
private String accountNumber;
private double balance;

public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}

// 只提供必要的公共方法
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("存款成功,当前余额:" + balance);
}
}

public void withdraw(double amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
System.out.println("取款成功,当前余额:" + balance);
} else {
System.out.println("取款失败");
}
}

public double getBalance() {
return balance;
}
}

3.3 继承

继承允许子类继承父类的属性和方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// 父类
public class Animal {
protected String name;
protected int age;

public Animal(String name, int age) {
this.name = name;
this.age = age;
}

public void eat() {
System.out.println(name + "在吃东西");
}

public void sleep() {
System.out.println(name + "在睡觉");
}
}

// 子类
public class Dog extends Animal {
private String breed; // 品种

public Dog(String name, int age, String breed) {
super(name, age); // 调用父类构造方法
this.breed = breed;
}

// 重写父类方法
@Override
public void eat() {
System.out.println(name + "(" + breed + ")在吃狗粮");
}

// 子类特有方法
public void bark() {
System.out.println(name + "在汪汪叫");
}
}

public class Cat extends Animal {
public Cat(String name, int age) {
super(name, age);
}

@Override
public void eat() {
System.out.println(name + "在吃猫粮");
}

public void meow() {
System.out.println(name + "在喵喵叫");
}
}

3.4 多态

多态允许不同类的对象对同一消息作出不同的响应。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class PolymorphismDemo {
public static void main(String[] args) {
// 向上转型
Animal animal1 = new Dog("旺财", 3, "金毛");
Animal animal2 = new Cat("咪咪", 2);

// 多态调用
animal1.eat(); // 旺财(金毛)在吃狗粮
animal2.eat(); // 咪咪在吃猫粮

// 向下转型
if (animal1 instanceof Dog) {
Dog dog = (Dog) animal1;
dog.bark(); // 旺财在汪汪叫
}
}
}

四、异常处理

4.1 异常层次结构

Java的异常体系:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Throwable
├── Error(错误)
│ ├── OutOfMemoryError
│ ├── StackOverflowError
│ └── ...
└── Exception(异常)
├── RuntimeException(运行时异常)
│ ├── NullPointerException
│ ├── ArrayIndexOutOfBoundsException
│ └── ...
└── Checked Exception(检查异常)
├── IOException
├── SQLException
└── ...

4.2 异常处理语法

1
2
3
4
5
6
7
8
9
10
11
12
13
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("清理资源");
}

4.3 抛出异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Calculator {
public static int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
// 抛出异常
throw new ArithmeticException("除数不能为零");
}
return a / b;
}

public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("结果:" + result);
} catch (ArithmeticException e) {
System.out.println("错误:" + e.getMessage());
}
}
}

4.4 自定义异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 自定义异常类
public class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}

public class Bank {
private double balance;

public Bank(double initialBalance) {
this.balance = initialBalance;
}

public void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException("余额不足");
}
balance -= amount;
System.out.println("取款成功,余额:" + balance);
}
}

五、集合框架

5.1 集合体系

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Collection
├── List(有序,可重复)
│ ├── ArrayList
│ ├── LinkedList
│ └── Vector
├── Set(无序,不可重复)
│ ├── HashSet
│ ├── LinkedHashSet
│ └── TreeSet
└── Queue(队列)
├── LinkedList
├── PriorityQueue
└── ArrayDeque

Map(键值对)
├── HashMap
├── LinkedHashMap
├── TreeMap
└── Hashtable

5.2 List集合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.*;

public class ListExample {
public static void main(String[] args) {
// ArrayList - 动态数组
List<String> arrayList = new ArrayList<>();
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Orange");

// 遍历
for (String fruit : arrayList) {
System.out.println(fruit);
}

// LinkedList - 链表
List<Integer> linkedList = new LinkedList<>();
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);

// 常用操作
System.out.println("大小:" + arrayList.size());
System.out.println("包含Apple:" + arrayList.contains("Apple"));
arrayList.remove(0);
}
}

5.3 Set集合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class SetExample {
public static void main(String[] args) {
// HashSet - 无序,不重复
Set<String> hashSet = new HashSet<>();
hashSet.add("Java");
hashSet.add("Python");
hashSet.add("Java"); // 重复元素不会被添加

// TreeSet - 有序(自然排序)
Set<Integer> treeSet = new TreeSet<>();
treeSet.add(3);
treeSet.add(1);
treeSet.add(2);

// LinkedHashSet - 保持插入顺序
Set<String> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add("A");
linkedHashSet.add("C");
linkedHashSet.add("B");

System.out.println(hashSet); // [Java, Python]
System.out.println(treeSet); // [1, 2, 3]
System.out.println(linkedHashSet); // [A, C, B]
}
}

5.4 Map集合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class MapExample {
public static void main(String[] args) {
// HashMap
Map<String, Integer> map = new HashMap<>();
map.put("张三", 90);
map.put("李四", 85);
map.put("王五", 95);

// 遍历方式一:EntrySet
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

// 遍历方式二:KeySet
for (String key : map.keySet()) {
System.out.println(key + ": " + map.get(key));
}

// 常用操作
System.out.println("是否包含张三:" + map.containsKey("张三"));
System.out.println("Map大小:" + map.size());
map.remove("李四");
}
}

六、IO流

6.1 IO流的分类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
IO流
├── 字节流(8位)
│ ├── InputStream(输入)
│ │ ├── FileInputStream
│ │ ├── BufferedInputStream
│ │ └── ...
│ └── OutputStream(输出)
│ ├── FileOutputStream
│ ├── BufferedOutputStream
│ └── ...
└── 字符流(16位)
├── Reader(输入)
│ ├── FileReader
│ ├── BufferedReader
│ └── ...
└── Writer(输出)
├── FileWriter
├── BufferedWriter
└── ...

6.2 文件操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.io.*;
import java.nio.file.*;

public class FileExample {
public static void main(String[] args) throws IOException {
// 创建文件
File file = new File("test.txt");
if (!file.exists()) {
file.createNewFile();
}

// 写入文件(字符流)
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write("Hello, World!");
writer.newLine();
writer.write("Java编程示例");
}

// 读取文件(字符流)
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}

// 使用NIO复制文件
Path source = Paths.get("test.txt");
Path target = Paths.get("copy.txt");
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
}
}

七、多线程

7.1 创建线程的三种方式

方式一:继承Thread类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}

方式二:实现Runnable接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}

public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}

方式三:使用Lambda表达式(JDK 8+)

1
2
3
4
5
6
7
8
9
10
public class LambdaThread {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
});
thread.start();
}
}

7.2 线程同步

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class SynchronizedExample {
private static int counter = 0;

// 同步方法
public static synchronized void increment() {
counter++;
}

// 同步代码块
public static void incrementBlock() {
synchronized (SynchronizedExample.class) {
counter++;
}
}

public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[10];

for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 1000; j++) {
increment();
}
});
threads[i].start();
}

// 等待所有线程完成
for (Thread thread : threads) {
thread.join();
}

System.out.println("计数器:" + counter);
}
}

7.3 线程池

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.concurrent.*;

public class ThreadPoolExample {
public static void main(String[] args) {
// 创建固定大小线程池
ExecutorService executor = Executors.newFixedThreadPool(5);

// 提交任务
for (int i = 0; i < 10; i++) {
final int taskId = i;
executor.submit(() -> {
System.out.println("任务" + taskId + ":" +
Thread.currentThread().getName());
});
}

// 关闭线程池
executor.shutdown();
}
}

八、总结

Java是一门功能强大、应用广泛的编程语言。通过学习本文,你已经掌握了:

  1. ✅ Java的基础语法和数据类型
  2. ✅ 面向对象编程的核心概念
  3. ✅ 异常处理机制
  4. ✅ 集合框架的使用
  5. ✅ IO流操作
  6. ✅ 多线程编程

进阶学习建议

深入方向:

  • Spring框架(Spring Boot、Spring Cloud)
  • JVM原理与调优
  • 并发编程深入
  • 设计模式
  • 微服务架构

实践项目:

  • 开发一个简单的CRUD应用
  • 实现一个聊天程序
  • 构建一个电商平台

继续加油,Java的世界等待你的探索!