Java 常见代码示例大全:基础语法到并发编程
66 个 Java 关键代码示例,涵盖基础语法、数据类型、控制结构、面向对象、集合框架、异常处理、文件 I/O 及多线程并发等核心知识点。通过可运行的代码片段,帮助开发者快速掌握 Java 编程规范与高级并发技巧,适用于从入门到进阶的学习需求。

66 个 Java 关键代码示例,涵盖基础语法、数据类型、控制结构、面向对象、集合框架、异常处理、文件 I/O 及多线程并发等核心知识点。通过可运行的代码片段,帮助开发者快速掌握 Java 编程规范与高级并发技巧,适用于从入门到进阶的学习需求。

摘要:本文详细列举了 66 个 Java 编程中的关键代码示例,包括基础语法、数据类型、条件判断、循环、数组、方法、面向对象、继承、接口、抽象类、多态、封装、静态变量、内部类、匿名类、泛型、集合框架、异常处理、文件 I/O、多线程、同步以及高级并发概念,帮助你从入门到成长为架构师。
引言
在当今的编程世界中,Java 作为一种广泛使用的编程语言,涵盖了从基础语法到复杂架构的方方面面。无论是刚接触编程的新手,还是经验丰富的开发者,掌握 Java 的核心技术和常用模式,都是成为一名高效开发者的必经之路。本篇文章将带您通过 66 个关键代码示例,从零开始深入学习 Java,从最基础的语法到高阶的并发编程,帮助您成为一名合格的 全栈开发者 或 架构师。
这篇文章不仅包含了 Java 编程语言 中的核心概念、常见技术栈,还为您详细解析了 面向对象编程(OOP)与 多线程并发 的实际应用技巧。无论是构建简单的应用程序,还是设计复杂的分布式系统,本文的示例代码将为您提供明确的指导,帮助您快速上手并实现功能。

src/main/java 目录下单独运行。如何运行:
# 以单文件方式运行 javac Demo01.java && java Demo01
public class Demo01 {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
public class Demo02 {
public static void main(String[] args) {
int age = 18;
double score = 98.5;
boolean ok = true;
char c = 'A';
long big = 9_223_372_036_854_775_807L; // 下划线增强可读性
var msg = "Java"; // JDK 10 局部类型推断
System.out.printf("age=%d, score=%.1f, ok=%b, c=%c, msg=%s\n", age, score, ok, c, msg);
}
}
public class Demo03 {
public static void main(String[] args) {
int i = 10;
long l = i; // 自动提升
double d = l;
int j = (int) d; // 强转可能丢失精度
System.out.println(j);
}
}
public class Demo04 {
public static final double PI = 3.141592653589793;
public static void main(String[] args) {
System.out.println(PI);
}
}
public class Demo05 {
public static void main(String[] args) {
int a = 5, b = 2;
System.out.println(a / b); // 2 整除
System.out.println(a / (double) b); // 2.5 浮点
System.out.println(a++); // 5(先用后加)
System.out.println(++a); // 7(先加后用)
System.out.println(a & 1); // 位运算判断奇偶
}
}
public class Demo06 {
public static void main(String[] args) {
String s = " Java ";
System.out.println(s.trim().toUpperCase().replace(" ", ""));
System.out.println(String.join(",", "A", "B", "C"));
}
}
import java.util.*;
public class Demo07 {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
System.out.print("请输入名字:");
String name = sc.nextLine();
System.out.println("Hi, " + name);
}
}
}
public class Demo08 {
public static void main(String[] args) {
System.out.printf("%-10s | %8.2f\n", "Revenue", 12345.678);
}
}
public class Demo09 {
public static void main(String[] args) {
int score = 86;
String level = score >= 90 ? "A" : score >= 80 ? "B" : "C";
System.out.println(level);
}
}
public class Demo10 {
public static void main(String[] args) {
String day = "MON";
int num = switch (day) {
case "MON", "TUE", "WED", "THU", "FRI" -> 1;
case "SAT", "SUN" -> 2;
default -> 0;
};
System.out.println(num);
}
}
public class Demo11 {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
System.out.println(sum);
}
}
public class Demo12 {
public static void main(String[] args) {
int n = 3;
do {
System.out.println(n--);
} while (n > 0);
}
}
public class Demo13 {
public static void main(String[] args) {
outer: for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) break outer;
System.out.printf("(%d,%d) ", i, j);
}
}
}
}
import java.util.*;
public class Demo14 {
public static void main(String[] args) {
for (var x : List.of(1, 2, 3)) System.out.println(x);
}
}
import java.util.Arrays;
public class Demo15 {
public static void main(String[] args) {
int[] arr = {3, 1, 2};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
import java.util.Arrays;
public class Demo16 {
public static void main(String[] args) {
int[][] m = {{1, 2}, {3, 4}};
System.out.println(Arrays.deepToString(m));
}
}
import java.util.Arrays;
public class Demo17 {
public static void main(String[] args) {
int[] a = {1, 3, 5, 7};
System.out.println(Arrays.binarySearch(a, 5));
int[] b = Arrays.copyOf(a, 6);
System.out.println(Arrays.toString(b));
}
}
public class Demo18 {
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(1, 2));
System.out.println(add(1.2, 3.4));
}
}
public class Demo19 {
static int sum(int... xs) {
int s = 0;
for (int x : xs) s += x;
return s;
}
public static void main(String[] a) {
System.out.println(sum(1, 2, 3, 4));
}
}
class User {
String name;
int age;
}
public class Demo20 {
public static void main(String[] args) {
User u = new User();
u.name = "Tom";
u.age = 20;
System.out.println(u.name + ":" + u.age);
}
}
class Account {
private double balance;
public double getBalance() {
return balance;
}
public void deposit(double amt) {
if (amt <= 0) throw new IllegalArgumentException();
balance += amt;
}
}
class Point {
int x, y;
Point() {
this(0, 0);
}
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
class IdGen {
static long next = 1;
static {
System.out.println("class loaded");
}
static synchronized long nextId() {
return next++;
}
}
class Animal {
void say() {
System.out.println("...");
}
}
class Dog extends Animal {
@Override
void say() {
super.say();
System.out.println("wang");
}
}
class Shape {
double area() {
return 0;
}
}
class Circle extends Shape {
double r;
Circle(double r) {
this.r = r;
}
@Override
double area() {
return Math.PI * r * r;
}
}
class Square extends Shape {
double a;
Square(double a) {
this.a = a;
}
@Override
double area() {
return a * a;
}
}
abstract class Transport {
abstract void move();
}
class Car extends Transport {
void move() {
System.out.println("Car go");
}
}
interface Logger {
void info(String msg);
default void warn(String msg) {
System.out.println("WARN " + msg);
}
static Logger nop() {
return m -> {};
}
}
class Outer {
private int v = 42;
class Inner {
int get() {
return v;
}
}
}
class UseAnon {
static Runnable r = new Runnable() {
public void run() {
System.out.println("anon run");
}
};
}
class Box<T> {
private T v;
public void set(T v) {
this.v = v;
}
public T get() {
return v;
}
}
import java.util.*;
class G {
static <T> void copy(List<? super T> dst, List<? extends T> src) {
dst.addAll(src);
}
}
enum Role {
ADMIN, USER, GUEST
}
import java.util.*;
public class Demo32 {
public static void main(String[] a) {
List<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(2);
Deque<Integer> link = new LinkedList<>();
link.addFirst(3);
link.addLast(4);
System.out.println(arr + " | " + link);
}
}
import java.util.*;
public class Demo33 {
public static void main(String[] a) {
Map<String, Integer> m1 = new HashMap<>();
m1.put("b", 2);
m1.put("a", 1);
Map<String, Integer> m2 = new LinkedHashMap<>();
m2.put("b", 2);
m2.put("a", 1);
Map<String, Integer> m3 = new TreeMap<>();
m3.put("b", 2);
m3.put("a", 1);
System.out.println(m1.keySet());
System.out.println(m2.keySet());
System.out.println(m3.keySet());
}
}
import java.util.*;
public class Demo34 {
public static void main(String[] a) {
System.out.println(new HashSet<>(List.of(3, 1, 2))); // 无序
System.out.println(new LinkedHashSet<>(List.of(3, 1, 2))); // 插入序
System.out.println(new TreeSet<>(List.of(3, 1, 2))); // 自然序
}
}
import java.util.*;
public class Demo35 {
public static void main(String[] a) {
Queue<Integer> q = new ArrayDeque<>();
q.offer(1);
q.offer(2);
System.out.println(q.poll());
Deque<Integer> d = new ArrayDeque<>();
d.addFirst(1);
d.addLast(2);
System.out.println(d.removeLast());
}
}
import java.util.*;
class Person implements Comparable<Person> {
String n;
int a;
Person(String n, int a) {
this.n = n;
this.a = a;
}
public int compareTo(Person o) {
return Integer.compare(a, o.a);
}
public String toString() {
return n + ":" + a;
}
}
public class Demo36 {
public static void main(String[] a) {
List<Person> list = new ArrayList<>(List.of(new Person("A", 30), new Person("B", 20)));
list.sort(Comparator.comparing(p -> p.n)); // 使用 Comparator
System.out.println(list);
}
}
import java.util.*;
import java.util.stream.*;
public class Demo37 {
public static void main(String[] a) {
var r = IntStream.rangeClosed(1, 10).filter(x -> x % 2 == 0).map(x -> x * x).boxed().toList();
System.out.println(r);
}
}
import java.util.*;
public class Demo38 {
static Optional<String> find(boolean ok) {
return ok ? Optional.of("ok") : Optional.empty();
}
public static void main(String[] a) {
System.out.println(find(true).orElse("N/A"));
}
}
import java.util.*;
import java.util.stream.*;
public class Demo39 {
public static void main(String[] a) {
record P(String n, int a) {}
var ps = List.of(new P("A", 18), new P("B", 20), new P("C", 20));
var byAge = ps.stream().collect(Collectors.groupingBy(P::a));
var part = ps.stream().collect(Collectors.partitioningBy(p -> p.a >= 20));
System.out.println(byAge);
System.out.println(part);
}
}
public class Demo40 {
public static void main(String[] args) {
try {
Integer.parseInt("x");
} catch (NumberFormatException | NullPointerException e) {
System.out.println("bad number");
} finally {
System.out.println("done");
}
}
}
class BizException extends RuntimeException {
BizException(String m) {
super(m);
}
}
import java.io.*;
public class Demo42 {
public static void main(String[] args) throws Exception {
try (var in = new ByteArrayInputStream("hi".getBytes());
var out = new ByteArrayOutputStream()) {
out.write(in.readAllBytes());
System.out.println(out);
}
}
}
import java.nio.file.*;
import java.nio.charset.StandardCharsets;
import java.io.IOException;
public class Demo43 {
public static void main(String[] args) throws IOException {
Path p = Path.of("/tmp/demo.txt");
Files.writeString(p, "hello", StandardCharsets.UTF_8);
System.out.println(Files.readString(p));
}
}
import java.io.*;
class Book implements Serializable {
String name;
Book(String n) {
name = n;
}
}
public class Demo44 {
public static void main(String[] args) throws Exception {
var f = new File("/tmp/book.bin");
try (var o = new ObjectOutputStream(new FileOutputStream(f))) {
o.writeObject(new Book("Java"));
}
try (var i = new ObjectInputStream(new FileInputStream(f))) {
System.out.println(((Book) i.readObject()).name);
}
}
}
import java.io.*;
public class Demo45 {
public static void main(String[] args) throws Exception {
try (var in = new BufferedInputStream(new FileInputStream("/etc/hosts"))) {
byte[] buf = in.readAllBytes();
System.out.println(buf.length);
}
}
}
import java.nio.file.*;
import java.io.IOException;
public class Demo46 {
public static void main(String[] a) throws IOException {
try (var s = Files.walk(Path.of("."), 1)) {
s.forEach(System.out::println);
}
}
}
import java.util.regex.*;
public class Demo47 {
public static void main(String[] a) {
var m = Pattern.compile("(\\w+)@(\\w+\.\\w+)").matcher("hi [email protected]");
if (m.find()) System.out.println(m.group(1) + "@" + m.group(2));
}
}
public class Demo48 {
public static void main(String[] args) {
for (String s : args) System.out.println(s);
}
}
public class Demo49 {
public static void main(String[] a) {
new Thread(() -> System.out.println("hi from " + Thread.currentThread().getName())).start();
}
}
public class Demo50 {
public static void main(String[] a) throws InterruptedException {
Thread t = new Thread(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
});
t.start();
t.join();
System.out.println("joined");
}
}
class Counter {
private int c;
public synchronized void inc() {
c++;
}
public synchronized int get() {
return c;
}
}
public class Demo52 {
static volatile boolean running = true; // 保证线程间可见
public static void main(String[] a) throws Exception {
var t = new Thread(() -> {
while (running) {
}
});
t.start();
Thread.sleep(10);
running = false;
t.join();
System.out.println("stop");
}
}
import java.util.concurrent.atomic.*;
class Cnt {
AtomicInteger n = new AtomicInteger();
void inc() {
n.incrementAndGet();
}
}
import java.util.concurrent.locks.*;
class SafeBox {
private int v;
private final Lock lock = new ReentrantLock();
void set(int x) {
lock.lock();
try {
v = x;
} finally {
lock.unlock();
}
}
int get() {
lock.lock();
try {
return v;
} finally {
lock.unlock();
}
}
}
import java.util.concurrent.locks.*;
class CacheRW {
private int v;
private final ReadWriteLock rw = new ReentrantReadWriteLock();
int get() {
rw.readLock().lock();
try {
return v;
} finally {
rw.readLock().unlock();
}
}
void set(int x) {
rw.writeLock().lock();
try {
v = x;
} finally {
rw.writeLock().unlock();
}
}
}
import java.util.concurrent.locks.*;
class Waiter {
final Lock lock = new ReentrantLock();
final Condition ready = lock.newCondition();
boolean ok = false;
void waitIt() throws InterruptedException {
lock.lock();
try {
while (!ok) ready.await();
} finally {
lock.unlock();
}
}
void fire() {
lock.lock();
try {
ok = true;
ready.signalAll();
} finally {
lock.unlock();
}
}
}
public class Demo57 {
static ThreadLocal<String> ctx = ThreadLocal.withInitial(() -> "guest");
}
import java.util.concurrent.*;
public class Demo58 {
public static void main(String[] a) throws Exception {
BlockingQueue<Integer> q = new LinkedBlockingQueue<>(2);
new Thread(() -> {
try {
for (int i = 1; i <= 3; i++) {
q.put(i);
}
q.put(-1);
} catch (InterruptedException ignored) {
}
}).start();
new Thread(() -> {
try {
for (;;) {
int x = q.take();
if (x == -1) break;
System.out.println("consume " + x);
}
} catch (InterruptedException ignored) {
}
}).start();
}
}
import java.util.concurrent.*;
public class Demo59 {
public static void main(String[] a) throws Exception {
var latch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) new Thread(() -> {
latch.countDown();
}).start();
latch.await();
System.out.println("all done");
}
}
import java.util.concurrent.*;
public class Demo60 {
public static void main(String[] a) {
var barrier = new CyclicBarrier(3, () -> System.out.println("go!"));
for (int i = 0; i < 3; i++) new Thread(() -> {
try {
barrier.await();
} catch (Exception ignored) {
}
}).start();
}
}
import java.util.concurrent.*;
public class Demo61 {
public static void main(String[] a) {
var sem = new Semaphore(2);
for (int i = 0; i < 5; i++) new Thread(() -> {
try {
sem.acquire();
System.out.println("in");
Thread.sleep(50);
} catch (Exception ignored) {
} finally {
sem.release();
}
}).start();
}
}
import java.util.concurrent.*;
public class Demo62 {
public static void main(String[] a) {
Phaser p = new Phaser(3);
for (int i = 0; i < 3; i++) new Thread(() -> {
p.arriveAndAwaitAdvance();
System.out.println("phase1");
p.arriveAndDeregister();
}).start();
}
}
import java.util.concurrent.*;
public class Demo63 {
public static void main(String[] a) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(4);
Future<Integer> f = pool.submit(() -> 42);
System.out.println(f.get());
pool.shutdown();
}
}
import java.util.concurrent.*;
public class Demo64 {
public static void main(String[] a) {
var sch = Executors.newScheduledThreadPool(1);
sch.scheduleAtFixedRate(() -> System.out.println("tick"), 0, 1, TimeUnit.SECONDS);
}
}
提示:示例 64 会持续打印,可在演示时添加退出条件或手动停止进程。
import java.util.concurrent.*;
public class Demo65 {
public static void main(String[] a) throws Exception {
var f = CompletableFuture.supplyAsync(() -> 21).thenApply(x -> x * 2);
System.out.println(f.get());
}
}
import java.util.concurrent.*;
import java.util.*;
public class Demo66 {
static class Sum extends RecursiveTask<Long> {
final int[] arr;
final int lo, hi;
static final int TH = 1_000;
Sum(int[] arr, int lo, int hi) {
this.arr = arr;
this.lo = lo;
this.hi = hi;
}
protected Long compute() {
if (hi - lo <= TH) {
long s = 0;
for (int i = lo; i < hi; i++) s += arr[i];
return s;
}
int mid = (lo + hi) / 2;
var left = new Sum(arr, lo, mid);
var right = new Sum(arr, mid, hi);
left.fork();
right.compute();
left.join() + r;
}
}
{
[] data = ().ints(, , ).toArray();
ForkJoinPool.commonPool().invoke( (data, , data.length));
System.out.println(s);
}
}
record / Collections.unmodifiable*)。HttpClient)、JSON 编解码(选择 Jackson/Gson 等库)、向量数据库/消息队列客户端的异步调用,落地到 CompletableFuture 组合编排。
微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online
JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online
使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online
Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online