以下是整理后的Markdown格式Java学习指南:
Java学习全攻略:从入门到精通的详细指南
一、引言
1. Java的背景和发展
- 由Sun Microsystems(现Oracle)于1995年推出,最初用于嵌入式系统。
- 因”Write Once, Run Anywhere”的跨平台特性,成为互联网时代的主流语言。
- 广泛应用于企业级开发、大数据、移动应用(Android)等领域。
2. 学习Java的意义
- 多领域适用性:Web开发、移动应用、大数据处理等。
- 庞大的生态系统:丰富的开源框架(Spring、Hibernate)和工具链。
- 培养面向对象编程思维,提升软件设计能力。
二、Java的核心特性
1. 面向对象编程(OOP)
- 封装:通过访问控制符(public/private/protected)保护数据。
- 继承:使用
extends
实现代码重用。
- 多态:通过方法重载和重写实现动态行为。
2. 跨平台性
- 依赖Java虚拟机(JVM)运行字节码,实现平台无关性。
3. 自动内存管理
4. 强大的标准库
- 涵盖数据结构(集合框架)、网络编程、IO操作等功能。
三、Java基础语法
1. 变量与数据类型
原始类型
- 数值型:
byte
/short
/int
/long
/float
/double
- 字符型:
char
- 布尔型:
boolean
引用类型
2. 运算符
1 2 3 4
| int a = 10, b = 20; int sum = a + b; boolean isEqual = (a == b); boolean logical = (a > 5) && (b < 30);
|
3. 控制结构
条件语句
1 2 3 4 5
| if (score >= 60) { System.out.println("及格"); } else { System.out.println("不及格"); }
|
循环语句
1 2 3
| for (int i = 1; i <= 5; i++) { System.out.println(i); }
|
4. 数组
1 2 3 4
| int[] scores = {90, 85, 70}; for (int score : scores) { System.out.println(score); }
|
四、面向对象编程
1. 类与对象
1 2 3 4 5 6 7
| public class Person { private String name; public Person(String name) { this.name = name; } public void sayHello() { System.out.println("Hello, " + name); } }
|
2. 封装
- 使用
private
修饰属性,通过getter/setter
访问。
3. 继承
1 2 3 4 5 6 7
| public class Student extends Person { private int studentId; public Student(String name, int id) { super(name); this.studentId = id; } }
|
4. 多态
1 2 3 4 5 6 7
| public class Animal { public void makeSound() { System.out.println("动物叫"); } }
public class Dog extends Animal { @Override public void makeSound() { System.out.println("汪汪"); } }
|
五、Java内置类与库
1. 常用类
String类
1 2 3
| String str = "Hello"; int length = str.length(); boolean isEmpty = str.isEmpty();
|
Math类
1 2
| double sqrt = Math.sqrt(16); double random = Math.random();
|
2. 集合框架
1 2 3
| List<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana");
|
3. 日期与时间
1 2 3
| LocalDate today = LocalDate.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); System.out.println(today.format(formatter));
|
六、异常处理
1. 处理机制
1 2 3 4 5 6 7
| try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("错误:" + e.getMessage()); } finally { System.out.println("执行完毕"); }
|
2. 自定义异常
1 2 3
| public class AgeException extends Exception { public AgeException(String message) { super(message); } }
|
七、多线程编程
1. 创建线程
1 2 3
| new Thread(() -> { System.out.println("线程运行中"); }).start();
|
2. 同步机制
1 2 3
| synchronized (lockObject) { }
|
八、Java新特性
1. Lambda表达式
1 2
| List<Integer> numbers = Arrays.asList(1, 2, 3); numbers.forEach(n -> System.out.println(n));
|
2. Stream API
1 2 3 4
| int sum = numbers.stream() .filter(n -> n % 2 == 0) .mapToInt(Integer::intValue) .sum();
|