前言
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版本、虚拟线程 |

1.2 Java的特点
跨平台性
1 2 3 4 5 6
| 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; 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; int diff = a - b; int prod = a * b; int quot = a / b; int rem = a % b;
a++; a--;
|
比较运算符:
1 2 3 4 5 6 7 8
| int a = 10, b = 20;
boolean eq = (a == b); boolean neq = (a != b); boolean gt = (a > b); boolean lt = (a < b); boolean gte = (a >= b); boolean lte = (a <= b);
|
逻辑运算符:
1 2 3 4 5
| boolean a = true, b = false;
boolean and = (a && b); boolean or = (a || b); boolean not = (!a);
|
位运算符:
1 2 3 4 5 6 7 8 9
| int a = 5; int b = 3;
int and = a & b; int or = a | b; int xor = a ^ b; int not = ~a; int left = a << 1; int right = a >> 1;
|
三、面向对象编程
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; } public String getName() { return name; } public int getAge() { return age; } 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(); person2.introduce(); } }
|
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) { List<String> arrayList = new ArrayList<>(); arrayList.add("Apple"); arrayList.add("Banana"); arrayList.add("Orange"); for (String fruit : arrayList) { System.out.println(fruit); } 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) { Set<String> hashSet = new HashSet<>(); hashSet.add("Java"); hashSet.add("Python"); hashSet.add("Java"); Set<Integer> treeSet = new TreeSet<>(); treeSet.add(3); treeSet.add(1); treeSet.add(2); Set<String> linkedHashSet = new LinkedHashSet<>(); linkedHashSet.add("A"); linkedHashSet.add("C"); linkedHashSet.add("B"); System.out.println(hashSet); System.out.println(treeSet); System.out.println(linkedHashSet); } }
|
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) { Map<String, Integer> map = new HashMap<>(); map.put("张三", 90); map.put("李四", 85); map.put("王五", 95); for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } 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); } } 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是一门功能强大、应用广泛的编程语言。通过学习本文,你已经掌握了:
- ✅ Java的基础语法和数据类型
- ✅ 面向对象编程的核心概念
- ✅ 异常处理机制
- ✅ 集合框架的使用
- ✅ IO流操作
- ✅ 多线程编程
进阶学习建议
深入方向:
- Spring框架(Spring Boot、Spring Cloud)
- JVM原理与调优
- 并发编程深入
- 设计模式
- 微服务架构
实践项目:
- 开发一个简单的CRUD应用
- 实现一个聊天程序
- 构建一个电商平台
继续加油,Java的世界等待你的探索!