1. Hello World
1 2 3 4 5 public class Main { public static void main (String[] args) { System.out.println("Hello, World!" ); } }
2. 变量与数据类型
1 2 3 4 5 6 7 8 9 10 public class Main { public static void main (String[] args) { int a = 10 ; double b = 3.14 ; char c = 'A' ; boolean d = true ; String s = "Java" ; System.out.println(a + " " + b + " " + c + " " + d + " " + s); } }
3. 条件语句(if / else / switch)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class Main { public static void main (String[] args) { int x = 5 ; if (x > 0 ) System.out.println("Positive" ); else if (x < 0 ) System.out.println("Negative" ); else System.out.println("Zero" ); switch (x) { case 1 : System.out.println("One" ); break ; case 5 : System.out.println("Five" ); break ; default : System.out.println("Other" ); } } }
4. 循环(for / while / do-while)
1 2 3 4 5 6 7 8 9 public class Main { public static void main (String[] args) { for (int i = 0 ; i < 3 ; i++) System.out.println("For: " + i); int j = 0 ; while (j < 3 ) System.out.println("While: " + j++); int k = 0 ; do { System.out.println("DoWhile: " + k++); } while (k < 3 ); } }
5. 方法定义与调用
1 2 3 4 5 6 7 8 public class Main { static int add (int a, int b) { return a + b; } public static void main (String[] args) { System.out.println(add(3 , 4 )); } }
6. 数组与字符串
1 2 3 4 5 6 7 8 9 public class Main { public static void main (String[] args) { int [] nums = {1 , 2 , 3 }; for (int n : nums) System.out.print(n + " " ); String s = "Hello" ; System.out.println("\n" + s.toUpperCase()); } }
7. 类与对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Person { String name; int age; void greet () { System.out.println("Hi, I'm " + name); } } public class Main { public static void main (String[] args) { Person p = new Person (); p.name = "Alice" ; p.age = 25 ; p.greet(); } }
8. 构造函数与 this 关键字
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Person { String name; int age; Person(String name, int age) { this .name = name; this .age = age; } void show () { System.out.println(name + ", " + age); } } public class Main { public static void main (String[] args) { Person p = new Person ("Bob" , 30 ); p.show(); } }
9. 继承与方法重写(@Override )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Animal { void speak () { System.out.println("Animal speaks" ); } } class Dog extends Animal { @Override void speak () { System.out.println("Dog barks" ); } } public class Main { public static void main (String[] args) { Animal a = new Dog (); a.speak(); } }
10. 接口与多态
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 interface Drawable { void draw () ; } class Circle implements Drawable { public void draw () { System.out.println("Drawing Circle" ); } } public class Main { public static void main (String[] args) { Drawable d = new Circle (); d.draw(); } }
11.
异常处理(try-catch-finally)
1 2 3 4 5 6 7 8 9 10 11 public class Main { public static void main (String[] args) { try { int x = 10 / 0 ; } catch (ArithmeticException e) { System.out.println("Error: " + e.getMessage()); } finally { System.out.println("Done" ); } } }
12. 静态方法和变量
1 2 3 4 5 6 7 8 9 10 11 12 13 class Utils { static int count = 0 ; static void greet () { System.out.println("Hello from static method" ); } } public class Main { public static void main (String[] args) { Utils.greet(); System.out.println(Utils.count); } }
13. 枚举(enum)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 enum Color { RED, GREEN, BLUE } public class Main { public static void main (String[] args) { Color c = Color.GREEN; switch (c) { case RED -> System.out.println("Red" ); case GREEN -> System.out.println("Green" ); case BLUE -> System.out.println("Blue" ); } } }
14. 集合框架(List / Set / Map)
1 2 3 4 5 6 7 8 9 10 11 12 13 import java.util.*;public class Main { public static void main (String[] args) { List<String> list = Arrays.asList("A" , "B" , "C" ); Set<Integer> set = new HashSet <>(Arrays.asList(1 , 2 , 2 )); Map<String, Integer> map = Map.of("a" , 1 , "b" , 2 ); list.forEach(System.out::println); set.forEach(System.out::println); map.forEach((k, v) -> System.out.println(k + ": " + v)); } }
15. Lambda 表达式与 Stream
API(Java 8+)
1 2 3 4 5 6 7 8 9 import java.util.*;import java.util.stream.*;public class Main { public static void main (String[] args) { List<Integer> nums = Arrays.asList(1 , 2 , 3 , 4 , 5 ); nums.stream().filter(n -> n % 2 == 0 ).forEach(System.out::println); } }
16. 多线程基础:Thread 与
Runnable
1 2 3 4 5 6 public class Main { public static void main (String[] args) { Thread t = new Thread (() -> System.out.println("Hello from thread!" )); t.start(); } }
17. 泛型(类、方法、限定通配符)
1 2 3 4 5 6 7 8 9 10 11 12 class Box <T> { T value; Box(T value) { this .value = value; } T get () { return value; } } public class Main { public static void main (String[] args) { Box<String> b = new Box <>("Hello" ); System.out.println(b.get()); } }
泛型方法示例:
1 2 3 4 5 6 7 8 9 10 public class Main { public static <T> void printArray (T[] array) { for (T t : array) System.out.println(t); } public static void main (String[] args) { printArray(new Integer []{1 , 2 , 3 }); printArray(new String []{"a" , "b" , "c" }); } }
18. 内部类与匿名类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Outer { int outerVal = 10 ; class Inner { void show () { System.out.println("Inner: " + outerVal); } } } public class Main { public static void main (String[] args) { Outer.Inner inner = new Outer ().new Inner (); inner.show(); } }
匿名类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class Main { interface Hello { void say () ; } public static void main (String[] args) { Hello h = new Hello () { public void say () { System.out.println("Hello from anonymous class" ); } }; h.say(); } }
19. 注解(Annotation)
1 2 3 4 5 6 7 8 9 10 11 12 13 @Retention(RetentionPolicy.RUNTIME) @interface Info { String author () ; int version () ; } @Info(author = "Yao", version = 1) public class Main { public static void main (String[] args) { Info info = Main.class.getAnnotation(Info.class); System.out.println(info.author() + " v" + info.version()); } }
20. 反射基础
1 2 3 4 5 6 7 8 9 10 11 import java.lang.reflect.Method;public class Main { public static void main (String[] args) throws Exception { Class<?> cls = Class.forName("java.lang.String" ); for (Method m : cls.getDeclaredMethods()) { if (m.getName().equals("length" )) System.out.println("Found: " + m); } } }
21. 文件读写(IO)
1 2 3 4 5 6 7 8 9 10 11 12 import java.io.*;public class Main { public static void main (String[] args) throws IOException { try (BufferedWriter writer = new BufferedWriter (new FileWriter ("test.txt" ))) { writer.write("Hello File!" ); } try (BufferedReader reader = new BufferedReader (new FileReader ("test.txt" ))) { System.out.println(reader.readLine()); } } }
22. NIO 文件读取(Java 7+)
1 2 3 4 5 6 7 8 import java.nio.file.*;public class Main { public static void main (String[] args) throws Exception { String content = Files.readString(Path.of("test.txt" )); System.out.println("Read: " + content); } }
23. 枚举增强用法:带方法和属性
1 2 3 4 5 6 7 8 9 10 11 12 enum Level { LOW(1 ), MEDIUM(2 ), HIGH(3 ); int val; Level(int v) { this .val = v; } public int getVal () { return val; } } public class Main { public static void main (String[] args) { System.out.println(Level.HIGH.getVal()); } }
24. Optional(避免
NullPointerException)
1 2 3 4 5 6 7 8 import java.util.Optional;public class Main { public static void main (String[] args) { Optional<String> maybe = Optional.of("Hello" ); System.out.println(maybe.map(String::toUpperCase).orElse("Empty" )); } }
25. synchronized
关键字:线程安全同步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class Main { private static int count = 0 ; public static synchronized void increment () { count++; } public static void main (String[] args) throws InterruptedException { Thread t1 = new Thread (() -> { for (int i = 0 ; i < 1000 ; i++) increment(); }); Thread t2 = new Thread (() -> { for (int i = 0 ; i < 1000 ; i++) increment(); }); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(count); } }
26. 线程池 ExecutorService
1 2 3 4 5 6 7 8 9 10 import java.util.concurrent.*;public class Main { public static void main (String[] args) throws Exception { ExecutorService executor = Executors.newFixedThreadPool(2 ); Future<Integer> future = executor.submit(() -> 1 + 2 ); System.out.println("Result: " + future.get()); executor.shutdown(); } }
27. volatile
保证变量可见性
1 2 3 4 5 6 7 8 9 10 11 12 13 public class Main { private static volatile boolean running = true ; public static void main (String[] args) throws Exception { Thread t = new Thread (() -> { while (running); System.out.println("Stopped" ); }); t.start(); Thread.sleep(1000 ); running = false ; } }
28. ReentrantLock 可重入锁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import java.util.concurrent.locks.ReentrantLock;public class Main { private static final ReentrantLock lock = new ReentrantLock (); public static void main (String[] args) { lock.lock(); try { System.out.println("Locked section" ); } finally { lock.unlock(); } } }
29. Stream
API:map/filter/collect
1 2 3 4 5 6 7 8 9 10 11 12 13 import java.util.*;import java.util.stream.*;public class Main { public static void main (String[] args) { List<String> list = List.of("apple" , "banana" , "orange" ); List<String> upper = list.stream() .filter(s -> s.startsWith("a" )) .map(String::toUpperCase) .collect(Collectors.toList()); System.out.println(upper); } }
30. record(Java 14+):简化数据类
1 2 3 4 5 6 7 8 record Person (String name, int age) {}public class Main { public static void main (String[] args) { Person p = new Person ("Alice" , 30 ); System.out.println(p.name() + ", " + p.age()); } }
31. sealed class(Java 15+)
1 2 3 4 5 6 7 8 9 10 11 sealed interface Shape permits Circle, Square {}final class Circle implements Shape {}final class Square implements Shape {}public class Main { public static void main (String[] args) { Shape s = new Circle (); if (s instanceof Circle) System.out.println("It's a Circle" ); } }
32. 简单 Java GUI 示例(Swing)
1 2 3 4 5 6 7 8 9 10 11 12 13 import javax.swing.*;public class Main { public static void main (String[] args) { JFrame frame = new JFrame ("Hello GUI" ); JButton button = new JButton ("Click Me" ); button.addActionListener(e -> JOptionPane.showMessageDialog(frame, "Hello" )); frame.add(button); frame.setSize(200 , 100 ); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true ); } }
33. Socket 网络通信(客户端)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import java.io.*;import java.net.*;public class Main { public static void main (String[] args) throws IOException { Socket socket = new Socket ("example.com" , 80 ); PrintWriter out = new PrintWriter (socket.getOutputStream()); out.print("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n" ); out.flush(); BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream())); System.out.println(in.readLine()); socket.close(); } }
34. JDBC 简单访问(以 SQLite
为例)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import java.sql.*;public class Main { public static void main (String[] args) throws Exception { Class.forName("org.sqlite.JDBC" ); Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db" ); Statement stmt = conn.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS users (name TEXT)" ); stmt.executeUpdate("INSERT INTO users VALUES ('Alice')" ); ResultSet rs = stmt.executeQuery("SELECT * FROM users" ); while (rs.next()) { System.out.println(rs.getString("name" )); } conn.close(); } }
35. Java 模块系统(Java 9+)
1 2 3 4 module com.example.hello { exports com.example.hello; }
1 2 3 4 5 6 7 8 package com.example.hello;public class Hello { public static void say () { System.out.println("Hello from module!" ); } }
1 2 3 4 5 6 7 8 import com.example.hello.Hello;public class Main { public static void main (String[] args) { Hello.say(); } }
36. Lambda 表达式 与
函数式接口
1 2 3 4 5 6 7 8 import java.util.function.Function;public class Main { public static void main (String[] args) { Function<String, Integer> strLength = s -> s.length(); System.out.println(strLength.apply("Hello" )); } }
37. CompletableFuture 异步编程
1 2 3 4 5 6 7 8 9 import java.util.concurrent.*;public class Main { public static void main (String[] args) throws Exception { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello" ) .thenApply(s -> s + " World" ); System.out.println(future.get()); } }
38. JUnit5 单元测试基础
确保使用 JDK + Maven 或 IDE 支持,添加依赖后可运行:
1 2 3 4 5 6 public class Calculator { public int add (int a, int b) { return a + b; } }
1 2 3 4 5 6 7 8 9 10 11 import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.assertEquals;public class CalculatorTest { @Test void testAdd () { Calculator calc = new Calculator (); assertEquals(5 , calc.add(2 , 3 )); } }
(需要 JUnit 5 依赖,Maven 示例可提供)
39. 使用 Gson 解析和生成 JSON
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import com.google.gson.*;class Person { String name; int age; } public class Main { public static void main (String[] args) { String json = "{\"name\":\"Alice\",\"age\":30}" ; Gson gson = new Gson (); Person p = gson.fromJson(json, Person.class); System.out.println(p.name + " is " + p.age); } }
(需添加 Gson
依赖:com.google.code.gson:gson:2.10.1
)
40. 使用 Maven 构建项目(示例
pom.xml
)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 <project xmlns ="http://maven.apache.org/POM/4.0.0" ... > <modelVersion > 4.0.0</modelVersion > <groupId > com.example</groupId > <artifactId > demo</artifactId > <version > 1.0</version > <dependencies > <dependency > <groupId > com.google.code.gson</groupId > <artifactId > gson</artifactId > <version > 2.10.1</version > </dependency > </dependencies > </project >
41. 使用 Gradle
构建项目(示例 build.gradle
)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 plugins { id 'java' } repositories { mavenCentral() } dependencies { implementation 'com.google.code.gson:gson:2.10.1' testImplementation 'org.junit.jupiter:junit-jupiter:5.10.0' } test { useJUnitPlatform() }
42. Java Servlet 示例(Java
Web)
1 2 3 4 5 6 7 8 9 10 11 import jakarta.servlet.*;import jakarta.servlet.http.*;import java.io.*;public class HelloServlet extends HttpServlet { protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter out = resp.getWriter(); out.println("Hello from Servlet!" ); } }
(需部署到如 Tomcat、Jetty 的 Servlet 容器)
43. 注解(Annotation)与反射使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import java.lang.annotation.*;import java.lang.reflect.Method;@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface MyAnnotation { String value () ; } public class Main { @MyAnnotation("HelloAnnotation") public void sayHello () { System.out.println("Hello" ); } public static void main (String[] args) throws Exception { Method method = Main.class.getMethod("sayHello" ); if (method.isAnnotationPresent(MyAnnotation.class)) { MyAnnotation ann = method.getAnnotation(MyAnnotation.class); System.out.println("Annotation value: " + ann.value()); } new Main ().sayHello(); } }
44. 反射动态创建类与调用方法
1 2 3 4 5 6 7 8 9 10 11 public class Main { public static void greet (String name) { System.out.println("Hello, " + name); } public static void main (String[] args) throws Exception { Class<?> clazz = Class.forName("Main" ); Method method = clazz.getMethod("greet" , String.class); method.invoke(null , "World" ); } }
45. 多线程基础:实现 Runnable
接口
1 2 3 4 5 6 7 8 9 10 public class Main implements Runnable { public void run () { System.out.println("Thread running: " + Thread.currentThread().getName()); } public static void main (String[] args) { Thread t = new Thread (new Main ()); t.start(); } }
46. 多线程:使用 synchronized
同步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public class Counter { private int count = 0 ; public synchronized void increment () { count++; } public static void main (String[] args) throws InterruptedException { Counter counter = new Counter (); Thread t1 = new Thread (() -> { for (int i = 0 ; i < 1000 ; i++) counter.increment(); }); Thread t2 = new Thread (() -> { for (int i = 0 ; i < 1000 ; i++) counter.increment(); }); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Count: " + counter.count); } }
47. 使用 ReentrantLock
进行加锁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import java.util.concurrent.locks.ReentrantLock;public class Main { private final ReentrantLock lock = new ReentrantLock (); private int count = 0 ; public void increment () { lock.lock(); try { count++; } finally { lock.unlock(); } } public static void main (String[] args) throws InterruptedException { Main main = new Main (); Thread t1 = new Thread (() -> { for (int i = 0 ; i < 1000 ; i++) main.increment(); }); Thread t2 = new Thread (() -> { for (int i = 0 ; i < 1000 ; i++) main.increment(); }); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Count: " + main.count); } }
48. volatile 保证变量可见性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public class Main { private volatile boolean running = true ; public void run () { while (running) { } System.out.println("Stopped." ); } public void stop () { running = false ; } public static void main (String[] args) throws InterruptedException { Main m = new Main (); Thread t = new Thread (m::run); t.start(); Thread.sleep(1000 ); m.stop(); } }
49. Socket
编程:简单服务器与客户端
Server.java
1 2 3 4 5 6 7 8 9 10 11 12 import java.io.*;import java.net.*;public class Server { public static void main (String[] args) throws IOException { ServerSocket server = new ServerSocket (6666 ); Socket socket = server.accept(); BufferedReader reader = new BufferedReader (new InputStreamReader (socket.getInputStream())); System.out.println("Client says: " + reader.readLine()); server.close(); } }
Client.java
1 2 3 4 5 6 7 8 9 10 11 import java.io.*;import java.net.*;public class Client { public static void main (String[] args) throws IOException { Socket socket = new Socket ("localhost" , 6666 ); PrintWriter writer = new PrintWriter (socket.getOutputStream(), true ); writer.println("Hello from client!" ); socket.close(); } }
50. 枚举类型的高级用法
1 2 3 4 5 6 7 8 9 10 11 12 13 enum Operation { PLUS { double apply (double x, double y) { return x + y; } }, MINUS { double apply (double x, double y) { return x - y; } }; abstract double apply (double x, double y) ; } public class Main { public static void main (String[] args) { System.out.println(Operation.PLUS.apply(2 , 3 )); System.out.println(Operation.MINUS.apply(5 , 2 )); } }
继续为你整理 Java 更高级和实用的语法特性(第 51 ~ 60
部分),每个示例都可直接运行 。
51. Java Stream
高级操作:groupingBy + averaging
1 2 3 4 5 6 7 8 9 10 11 12 13 import java.util.*;import java.util.stream.*;public class Main { public static void main (String[] args) { List<String> names = Arrays.asList("Tom" , "Jerry" , "Tom" , "Spike" , "Jerry" ); Map<String, Long> counts = names.stream() .collect(Collectors.groupingBy(name -> name, Collectors.counting())); System.out.println(counts); } }
52. try-with-resources
自动释放资源
1 2 3 4 5 6 7 8 9 10 11 import java.io.*;public class Main { public static void main (String[] args) { try (BufferedReader br = new BufferedReader (new FileReader ("test.txt" ))) { System.out.println(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } }
test.txt
文件需在项目根目录。适用于任何
AutoCloseable
类型。
53. record:简化 Java Bean(Java
14+)
1 2 3 4 5 6 7 8 public record User (String name, int age) {}public class Main { public static void main (String[] args) { User u = new User ("Tom" , 30 ); System.out.println(u.name() + ", " + u.age()); } }
54. Java Lambda
表达式与函数式接口
1 2 3 4 5 6 7 8 import java.util.function.Function;public class Main { public static void main (String[] args) { Function<String, Integer> parseLength = str -> str.length(); System.out.println(parseLength.apply("Hello" )); } }
55. Optional 使用:避免
NullPointerException
1 2 3 4 5 6 7 8 9 import java.util.Optional;public class Main { public static void main (String[] args) { Optional<String> name = Optional.ofNullable(null ); String result = name.orElse("Default" ); System.out.println(result); } }
56. 接口的默认方法(Java 8+)
1 2 3 4 5 6 7 8 9 10 11 interface Greeter { default void greet () { System.out.println("Hello from default method!" ); } } public class Main implements Greeter { public static void main (String[] args) { new Main ().greet(); } }
57. 文件读写(Java NIO)
1 2 3 4 5 6 7 8 9 10 11 12 import java.nio.file.*;import java.io.IOException;public class Main { public static void main (String[] args) throws IOException { Path path = Paths.get("output.txt" ); Files.write(path, "Hello NIO" .getBytes()); String content = Files.readString(path); System.out.println(content); } }
58. 使用 ThreadPoolExecutor
线程池
1 2 3 4 5 6 7 8 9 10 import java.util.concurrent.*;public class Main { public static void main (String[] args) { ExecutorService executor = Executors.newFixedThreadPool(2 ); executor.submit(() -> System.out.println("Task 1" )); executor.submit(() -> System.out.println("Task 2" )); executor.shutdown(); } }
59. 动态代理(Proxy)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import java.lang.reflect.*;interface Hello { void say () ; } public class Main { public static void main (String[] args) { Hello hello = (Hello) Proxy.newProxyInstance( Hello.class.getClassLoader(), new Class []{Hello.class}, (proxy, method, args1) -> { System.out.println("Before method" ); return null ; } ); hello.say(); } }
60. 简单 GUI(Swing 示例)
1 2 3 4 5 6 7 8 9 10 11 12 13 import javax.swing.*;public class Main { public static void main (String[] args) { JFrame frame = new JFrame ("Hello GUI" ); JButton button = new JButton ("Click Me" ); button.addActionListener(e -> JOptionPane.showMessageDialog(null , "Button clicked!" )); frame.add(button); frame.setSize(300 , 200 ); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true ); } }