Java 学习指南
目录
基础语法
数据类型
java
// 基本数据类型
byte b = 127; // 8位
short s = 32767; // 16位
int i = 2147483647; // 32位
long l = 9223372036854775807L; // 64位
float f = 3.14f; // 32位
double d = 3.14; // 64位
char c = 'A'; // 16位
boolean bool = true; // 1位
// 包装类型
Integer integer = 100;
Double doubleValue = 3.14;
Boolean booleanValue = true;
// 字符串
String str = "Hello World";
StringBuilder sb = new StringBuilder();
StringBuffer sbf = new StringBuffer();说明:
- 基本数据类型
- 包装类型
- 字符串处理
- 类型转换
面向对象
java
// 类定义
public class Person {
// 属性
private String name;
private int age;
// 构造方法
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter/Setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// 方法
public void sayHello() {
System.out.println("Hello, I'm " + name);
}
}
// 继承
public class Student extends Person {
private String school;
public Student(String name, int age, String school) {
super(name, age);
this.school = school;
}
}
// 接口
public interface Animal {
void makeSound();
void move();
}
// 实现接口
public class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
@Override
public void move() {
System.out.println("Running...");
}
}说明:
- 类与对象
- 继承与多态
- 接口与实现
- 封装与抽象
集合框架
java
// List
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
// Set
Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);
// Map
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Orange", 3);
// 遍历
for (String item : list) {
System.out.println(item);
}
// Stream API
list.stream()
.filter(s -> s.startsWith("A"))
.map(String::toUpperCase)
.forEach(System.out::println);说明:
- List 集合
- Set 集合
- Map 集合
- Stream API
异常处理
java
// try-catch
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("除数不能为0");
} catch (Exception e) {
System.out.println("其他异常");
} finally {
System.out.println("总是执行");
}
// 自定义异常
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// 抛出异常
public void checkAge(int age) throws CustomException {
if (age < 0) {
throw new CustomException("年龄不能为负数");
}
}说明:
- 异常类型
- 异常处理
- 自定义异常
- 异常链
高级特性
泛型
java
// 泛型类
public class Box<T> {
private T content;
public void setContent(T content) {
this.content = content;
}
public T getContent() {
return content;
}
}
// 泛型方法
public <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}
// 泛型约束
public class NumberBox<T extends Number> {
private T number;
public void setNumber(T number) {
this.number = number;
}
}说明:
- 泛型类
- 泛型方法
- 类型约束
- 通配符
反射
java
// 获取类信息
Class<?> clazz = Person.class;
String className = clazz.getName();
Field[] fields = clazz.getDeclaredFields();
Method[] methods = clazz.getDeclaredMethods();
// 创建实例
Person person = (Person) clazz.newInstance();
// 调用方法
Method method = clazz.getMethod("sayHello");
method.invoke(person);
// 访问属性
Field field = clazz.getDeclaredField("name");
field.setAccessible(true);
field.set(person, "John");说明:
- 类信息获取
- 实例创建
- 方法调用
- 属性访问
注解
java
// 自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Log {
String value() default "";
}
// 使用注解
public class UserService {
@Log("查询用户")
public User getUserById(Long id) {
return new User(id, "John");
}
}
// 处理注解
Method method = UserService.class.getMethod("getUserById", Long.class);
Log log = method.getAnnotation(Log.class);
if (log != null) {
System.out.println("方法注解值: " + log.value());
}说明:
- 注解定义
- 注解使用
- 注解处理
- 元注解
Lambda
java
// Lambda 表达式
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));
// 方法引用
names.forEach(System.out::println);
// Stream API
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("A"))
.map(String::toUpperCase)
.collect(Collectors.toList());
// 函数式接口
@FunctionalInterface
public interface Calculator {
int calculate(int a, int b);
}
Calculator add = (a, b) -> a + b;
Calculator subtract = (a, b) -> a - b;说明:
- Lambda 表达式
- 方法引用
- Stream API
- 函数式接口
并发编程
线程基础
java
// 创建线程
Thread thread = new Thread(() -> {
System.out.println("线程运行中");
});
thread.start();
// 实现 Runnable
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("线程运行中");
}
}
// 线程状态
Thread.State state = thread.getState();
System.out.println("线程状态: " + state);说明:
- 线程创建
- 线程状态
- 线程控制
- 线程通信
线程池
java
// 创建线程池
ExecutorService executor = Executors.newFixedThreadPool(5);
// 提交任务
Future<String> future = executor.submit(() -> {
Thread.sleep(1000);
return "任务完成";
});
// 获取结果
String result = future.get();
// 关闭线程池
executor.shutdown();说明:
- 线程池类型
- 任务提交
- 结果获取
- 线程池管理
锁机制
java
// synchronized
public synchronized void increment() {
count++;
}
// ReentrantLock
private ReentrantLock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
// ReadWriteLock
private ReadWriteLock rwLock = new ReentrantReadWriteLock();
public void read() {
rwLock.readLock().lock();
try {
// 读操作
} finally {
rwLock.readLock().unlock();
}
}说明:
- synchronized
- ReentrantLock
- ReadWriteLock
- 锁优化
并发工具
java
// CountDownLatch
CountDownLatch latch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
new Thread(() -> {
// 任务
latch.countDown();
}).start();
}
latch.await();
// CyclicBarrier
CyclicBarrier barrier = new CyclicBarrier(3);
for (int i = 0; i < 3; i++) {
new Thread(() -> {
// 任务
barrier.await();
}).start();
}
// Semaphore
Semaphore semaphore = new Semaphore(3);
semaphore.acquire();
try {
// 临界区
} finally {
semaphore.release();
}说明:
- CountDownLatch
- CyclicBarrier
- Semaphore
- 其他工具类
JVM
内存模型
java
// 堆内存
byte[] array = new byte[1024 * 1024]; // 1MB
// 栈内存
int localVar = 100;
// 方法区
static String constant = "常量";
// 直接内存
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);说明:
- 堆内存
- 栈内存
- 方法区
- 直接内存
垃圾回收
java
// 手动触发 GC
System.gc();
// 对象引用
SoftReference<byte[]> softRef = new SoftReference<>(new byte[1024]);
WeakReference<byte[]> weakRef = new WeakReference<>(new byte[1024]);
PhantomReference<byte[]> phantomRef = new PhantomReference<>(new byte[1024], new ReferenceQueue<>());说明:
- GC 算法
- 垃圾收集器
- 内存分配
- 引用类型
类加载
java
// 类加载器
ClassLoader classLoader = Person.class.getClassLoader();
System.out.println("类加载器: " + classLoader);
// 自定义类加载器
public class CustomClassLoader extends ClassLoader {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
// 自定义类加载逻辑
return super.findClass(name);
}
}说明:
- 类加载过程
- 类加载器
- 双亲委派
- 自定义加载
性能调优
java
// JVM 参数
// -Xms2g -Xmx2g -XX:+UseG1GC
// 内存监控
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();
System.out.println("堆内存使用: " + heapUsage.getUsed());
// GC 监控
List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean gcBean : gcBeans) {
System.out.println("GC 名称: " + gcBean.getName());
System.out.println("GC 次数: " + gcBean.getCollectionCount());
}说明:
- JVM 参数
- 内存监控
- GC 监控
- 性能优化
最佳实践
1. 代码规范
- 遵循命名规范
- 使用设计模式
- 编写单元测试
- 代码审查
2. 性能优化
- 合理使用集合
- 避免内存泄漏
- 使用线程池
- 优化 GC
3. 安全实践
- 输入验证
- 异常处理
- 资源管理
- 安全配置
学习资源
官方文档
视频课程
- 慕课网
- 极客时间
- B站技术区
- YouTube 技术频道