Java 实例

字符串、数组、时间、文件等常见任务的实用代码片段。

Beginner
Key Points把高频操作固化成片段:字符串反转、数组排序、日期格式化、文件读写,用的时候直接改。

Java 字符串

Strings are the most-used type. Reverse with StringBuilder.reverse, test emptiness with isEmpty / isBlank, and always compare content with equals.

Java
public class StringExample {
    public static void main(String[] args) {
        String s = "Hello";

        System.out.println(new StringBuilder(s).reverse());
        System.out.println(s.charAt(0));
        System.out.println(s.substring(1, 3));
        System.out.println(s.toUpperCase());
        System.out.println("".isEmpty());
        System.out.println("  ".isBlank());
    }
}
Output
olleH
H
el
HELLO
true
true

Java 数组

Array staples: max/min, sum, sort, search and converting to a list. Arrays and Collections cover almost everything without hand-written loops.

Java
import java.util.Arrays;

public class ArrayExample {
    public static void main(String[] args) {
        int[] a = {5, 2, 9, 1};

        Arrays.sort(a);
        System.out.println(Arrays.toString(a));
        System.out.println(a[a.length - 1]);
        System.out.println(Arrays.stream(a).sum());
        System.out.println(Arrays.binarySearch(a, 5));
    }
}
Output
[1, 2, 5, 9]
9
17
2

Java 时间处理

Handle time with java.time: now, format, shift, measure gaps. Avoid Date and Calendar — mutable and not thread-safe.

Java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class TimeExample {
    public static void main(String[] args) {
        LocalDate a = LocalDate.of(2024, 1, 1);
        LocalDate b = LocalDate.of(2024, 12, 31);

        System.out.println(a.format(DateTimeFormatter.ofPattern("yyyy/MM/dd")));
        System.out.println(a.plusMonths(1));
        System.out.println(ChronoUnit.DAYS.between(a, b));
        System.out.println(b.getDayOfWeek());
    }
}
Output
2024/01/01
2024-02-01
365
TUESDAY

Java 文件操作

Small files: Files.readString / writeString in one line. Line-based: Files.readAllLines. Large files: stream with Files.lines.

Java
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class FileExample {
    public static void main(String[] args) throws Exception {
        Path p = Path.of("example.txt");

        Files.writeString(p, "a\nb\nc\n");
        System.out.println(Files.readString(p).lines().count());

        Files.write(p, List.of("x", "y"));
        System.out.println(Files.readAllLines(p));

        System.out.println(Files.exists(p));
    }
}
Output
3
[x, y]
true

打印图形

Nested loops printing shapes is the classic control-flow drill. The outer loop is rows, the inner one spaces and symbols; find the row-to-count rule and the code follows.

Java
public class Pyramid {
    public static void main(String[] args) {
        int n = 4;
        for (int i = 1; i <= n; i++) {
            for (int s = 0; s < n - i; s++) {
                System.out.print(" ");
            }
            for (int k = 0; k < 2 * i - 1; k++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
Output
   *
  ***
 *****
*******

Friends & Partners