开发环境搭建
# 验证安装
java -version
基础语法结构
int age = 25; // 原始类型
String name = "Alice"; // 引用类型
double PI = 3.1415926;
// Switch表达式(Java12+)
String result = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid";
};
public class BankAccount {
private double balance; // 封装
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
public void deposit(double amount) {
if (amount > 0) balance += amount;
}
}
abstract class Animal {
abstract void makeSound();
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Woof!");
}
}
interface Loggable {
default void log(String message) { // 默认方法
System.out.println("[LOG] " + message);
}
}
enum Status {
PENDING, PROCESSING, COMPLETED
}
Map<String, Integer> wordCount = new HashMap<>();
wordCount.put("apple", 3);
wordCount.computeIfPresent("apple", (k, v) -> v + 1); // Lambda表达式
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) { // try-with-resources
String line;
while ((line = br.readLine()) != null) {
process(line);
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
ExecutorService executor = Executors.newFixedThreadPool(4);
Future<Integer> future = executor.submit(() -> {
Thread.sleep(1000);
return 42;
});
// ...其他操作
System.out.println(future.get()); // 获取异步结果
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<String> filtered = names.stream()
.filter(name -> name.length() > 4)
.map(String::toUpperCase)
.collect(Collectors.toList());
推荐项目示例:电商订单系统
关键技术点:
// 使用Record简化DTO(Java16+)
public record Product(Long id, String name, BigDecimal price) {}
// 使用Spring Boot创建REST端点
@RestController
@RequestMapping("/api/products")
public class ProductController {
@GetMapping
public List<Product> getAllProducts() {
return productService.findAll();
}
}
进阶路线建议:
关键示例:使用Stream API进行数据处理
List<Order> orders = // 获取订单列表
Map<Customer, Double> customerExpenditure = orders.stream()
.filter(o -> o.getStatus() == Status.COMPLETED)
.collect(Collectors.groupingBy(
Order::getCustomer,
Collectors.summingDouble(Order::getTotal)
));
这个大纲可以帮助您在大约8-12周内建立完整的Java知识体系,具体进度可根据个人学习速度调整。建议每学完一个模块就进行对应的实战练习,保持"学练结合"的高效学习模式。