JavaSE Note

Last updated on February 19, 2026 pm

This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to original Chinese version. I am continuously working to improve the translation.

Quick Start

Java History

Java EE > Java SE > Java ME

JDK: Java Development kit

JRE: Java Runtime Environment

The JRE is the virtual machine that runs Java bytecode. To compile Java source code into Java bytecode, you need the JDK, because in addition to the JRE, the JDK also provides development tools such as a compiler and a debugger.

JRE = JVM + Runtime Library

JDK = JRE + compiler, debugger, etc.

Running

Suppose we have written a Hello.java program containing a main method

First we need

javac Hello.java

This produces a Hello.class file

Then run

java Hello

Note that the argument passed here is the class name, so just type Hello

and it will run

Java Program Basics

Basic Structure of a Java Program

Requirements for class names:

  • A class name must start with an English letter, followed by a combination of letters, digits, and underscores
  • By convention, it starts with an uppercase letter

Note that public is an access modifier, indicating that the class is public.

Without public, the code still compiles correctly, but the class cannot be executed from the command line.

Inside a class, you can define several methods:

public class Hello {
    public static void main(String[] args) { // 方法名是 main
        // 方法代码...
    } // 方法定义结束
}

Method names also follow naming rules: the same as class, but with a lowercase first letter.

A special kind of comment: starts with /** and ends with */; if it spans multiple lines, each line usually begins with an asterisk:

/**
 * 可以用来自动创建文档的注释
 * 
 * @auther liaoxuefeng
 */
public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
}

This special kind of multi-line comment must be written at the definition of a class or method, and can be used to automatically generate documentation.

Variables and Data Types

Primitive Data Types

Java defines the following primitive data types:

  • Integer types: byte, short, int, long
  • Floating-point types: float, double
  • Character type: char
  • Boolean type: boolean

byte is one byte, long is 8 bytes, char is two bytes, and the rest are the same as in C++.

For integer types, there is only signed, no unsigned

int i3 = 2_000_000_000; // 加下划线更容易识别
long n1 = 9000000000000000000L; // long 型的结尾需要加 L

For float, you need to add an f

The Java language does not specify how the boolean type is stored, because theoretically storing a boolean only requires 1 bit, but internally the JVM usually represents boolean as a 4-byte integer.

In addition to standard ASCII, Java's char type can also represent a Unicode character:

Java always uses Unicode to represent characters in memory

// 字符类型
public class Main {
    public static void main(String[] args) {
        char a = 'A';
        char zh = '中';
    }
}

You can also represent a character directly using the escape character \u plus a Unicode code:

// 注意是十六进制:
char c3 = '\u0041'; // 'A',因为十六进制 0041 = 十进制 65
char c4 = '\u4e2d'; // '中',因为十六进制 4e2d = 十进制 20013

Reference Types

Apart from the primitive types above, everything else is a reference type.

A variable of a reference type is similar to a pointer in C: it internally stores an "address" that points to the location of some object in memory.

Constants

Modified with final

The var Keyword

Equivalent to auto in C++

Operations

When shifting byte and short types, they are first converted to int before the shift is performed.

Integer promotion exists.

Casting: only C-style casting is supported.

String Operations

The Java compiler treats strings specially: you can use + to concatenate any string with other data types, which greatly simplifies string handling. For example:

// 字符串连接
public class Main {
    public static void main(String[] args) {
        String s1 = "Hello";
        String s2 = "world";
        String s = s1 + " " + s2 + "!";
        System.out.println(s); // Hello world!
    }
}

If you use + to concatenate a string with other data types, the other data types are automatically converted to strings first, then concatenated:

// 字符串连接
public class Main {
    public static void main(String[] args) {
        int age = 25;
        String s = "age is " + age;
        System.out.println(s); // age is 25
    }
}

There are also multi-line strings, with the format:

"""
...
"""

The specific details are not important.

Besides being a reference type, an important characteristic of Java strings is that strings are immutable.

Arrays

To define a variable of array type, use the array type "type[]", for example, int[]. Unlike a single primitive-type variable, initializing an array variable must use new int[5], which means creating an array that can hold 5 int elements.

Java arrays have several characteristics:

  • All elements of an array are initialized to default values: 0 for integer types, 0.0 for floating-point types, and false for the boolean type;
  • Once an array is created, its size cannot be changed.

You can use 数组变量.length to get the size of an array:

Arrays are reference types

You can also specify the initial elements directly when defining an array, in which case you don't need to write out the array size — the compiler infers it automatically.

int[] ns = new int[] { 68, 79, 91, 85, 62 };
// 或者
int[] ns = { 68, 79, 91, 85, 62 };

Flow Control

Formatted Output

Placeholder Description
%d Formats an integer for output
%x Formats a hexadecimal integer for output
%f Formats a floating-point number for output
%e Formats a floating-point number in scientific notation
%s Formats a string

Pretty much the same as C; for details you can ask an AI

Compared with output, input in Java is much more complicated.

Let's first look at an example of reading a string and an integer from the console:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); // 创建 Scanner 对象
        System.out.print("Input your name: "); // 打印提示
        String name = scanner.nextLine(); // 读取一行输入并获取字符串
        System.out.print("Input your age: "); // 打印提示
        int age = scanner.nextInt(); // 读取一行输入并获取整数
        System.out.printf("Hi, %s, you are %d\n", name, age); // 格式化输出
    }
}

Input

Let's first look at an example of reading a string and an integer from the console:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); // 创建 Scanner 对象
        System.out.print("Input your name: "); // 打印提示
        String name = scanner.nextLine(); // 读取一行输入并获取字符串
        System.out.print("Input your age: "); // 打印提示
        int age = scanner.nextInt(); // 读取一行输入并获取整数
        System.out.printf("Hi, %s, you are %d\n", name, age); // 格式化输出
    }
}

First, we import java.util.Scanner via the import statement. import is the statement for importing a class and must be placed at the beginning of the Java source code. We will explain in detail how to use import later in the section on Java packages.

Then, we create a Scanner object and pass in System.in. System.out represents the standard output stream, while System.in represents the standard input stream. Although it is possible to read user input directly using System.in, it requires more complicated code, whereas using a Scanner simplifies the subsequent code.

Once we have a Scanner object, to read a string of user input we use scanner.nextLine(), and to read an integer of user input we use scanner.nextInt(). The Scanner automatically converts data types, so there is no need to convert manually.

The switch Statement

Summary: a switch statement has its own return value, and each case uses -> to indicate the return.

When using switch, if you omit break, it can cause serious logic errors that are hard to spot in the source code. Starting from Java 12, the switch statement was upgraded to a more concise expression syntax, using an approach similar to pattern matching, which guarantees that only one path will be executed and does not require break statements:

// switch
public class Main {
    public static void main(String[] args) {
        String fruit = "apple";
        switch (fruit) {
        case "apple" -> System.out.println("Selected apple");
        case "pear" -> System.out.println("Selected pear");
        case "mango" -> {
            System.out.println("Selected mango");
            System.out.println("Good choice!");
        }
        default -> System.out.println("No fruit selected");
        }
    }
}

Note that the new syntax uses ->; if there are multiple statements, they need to be wrapped in {}. Do not write break statements, because the new syntax only executes the matched statements and has no fall-through effect.

Very often, we may also use a switch statement to assign a value to a variable. For example:

int opt;
switch (fruit) {
case "apple":
    opt = 1;
    break;
case "pear":
case "mango":
    opt = 2;
    break;
default:
    opt = 0;
    break;
}

Using the new switch syntax, not only do we not need break, but we can also return a value directly. Rewriting the code above:

// switch
public class Main {
    public static void main(String[] args) {
        String fruit = "apple";
        int opt = switch (fruit) {
            case "apple" -> 1;
            case "pear", "mango" -> 2;
            default -> 0;
        }; // 注意赋值语句要以;结束
        System.out.println("opt = " + opt);
    }
}

This yields more concise code.

Most of the time, inside a switch expression, we return simple values.

However, if complex statements are needed, we can also write multiple statements, put them inside {...}, and then use yield to return a value as the return value of the switch statement:

// yield
public class Main {
    public static void main(String[] args) {
        String fruit = "orange";
        int opt = switch (fruit) {
            case "apple" -> 1;
            case "pear", "mango" -> 2;
            default -> {
                int code = fruit.hashCode();
                yield code; // switch 语句返回值
            }
        };
        System.out.println("opt = " + opt);
    }
}

Array Operations

Use Arrays.toString() to quickly get the contents of an array; the argument is the array name

Sorting from the standard library: Arrays.sort(), with the array name as the argument

Definition of a multi-dimensional array: int [][] a

Use the Java standard library's Arrays.deepToString() to quickly get the contents of a multi-dimensional array

OOP

OOP Basics

Methods

A Java source file can contain definitions of multiple classes, but only one public class can be defined, and the public class name must match the file name. If you want to define multiple public classes, you must split them into multiple Java source files.

If a local variable and a field have the same name, the local variable takes higher priority, so you must add this:

class Person {
    private String name;

    public void setName(String name) {
        this.name = name; // 前面的 this 不可少,少了就变成局部变量 name 了
    }
}

Variable arguments are defined with 类型...; a variable argument is equivalent to an array type:

class Group {
    private String[] names;

    public void setNames(String... names) {
        this.names = names;
    }
}

However, it differs from an array: if you rewrite String... names as String[] names, then when passing arguments you need to construct a String[] like {"a", "b"} yourself, and you can pass in null, whereas variable arguments guarantee that this cannot happen, because when 0 arguments are passed, the actual value received is an empty array rather than null.

A constructor can call other constructors; the purpose of this is to facilitate code reuse. The syntax for calling another constructor is this(…):

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person(String name) {
        this(name, 18); // 调用另一个构造方法 Person(String, int)
    }

    public Person() {
        this("Unnamed"); // 调用另一个构造方法 Person(String)
    }
}

Inheritance

Java uses the extends keyword to implement inheritance

A subclass automatically obtains all public fields of the parent class; it is strictly forbidden to define fields with the same names as those in the parent class!

In OOP terminology, we call Person the super class, parent class, or base class, and call Student the subclass or extended class.

The super keyword represents the parent class (super class). When a subclass references a field of the parent class, it can use super.fieldName.

In Java, the first statement of any class's constructor must be a call to the parent class's constructor. If the parent class's constructor is not explicitly called, the compiler automatically adds a super(); for us.

If the parent class has no default constructor, the subclass must explicitly call super() with arguments so that the compiler can locate a suitable constructor of the parent class.

This also brings up another issue: a subclass does not inherit any of the parent class's constructors. The subclass's default constructor is automatically generated by the compiler, not inherited.

Preventing Inheritance

Starting from Java 15, classes can be modified with sealed, and the subclasses allowed to inherit from that class can be explicitly listed via permits.

For example, define a Shape class:

public sealed class Shape permits Rect, Circle, Triangle {
    ...
}

The Shape class above is a sealed class that only allows the specified 3 classes to inherit from it. If you write:

public final class Rect extends Shape {...}

there is no problem, because Rect appears in Shape's permits list. However, if you define an Ellipse, an error occurs:

public final class Ellipse extends Shape {...}
// Compile error: class is not allowed to extend sealed class: Shape

The reason is that Ellipse does not appear in Shape's permits list. Such sealed classes are mainly used in some frameworks to prevent inheritance from being abused.

Upcasting

A class higher up in the inheritance tree can be assigned an instance of one below it

Person p = new Student();

Downcasting is unsafe and may cause errors.

To avoid errors from downcasting, Java provides the instanceof operator, which can first determine whether an instance is actually of a certain type.

Using instanceof, you can check before downcasting:

Person p = new Student();
if (p instanceof Student) {
    // 只有判断成功才会向下转型:
    Student s = (Student) p; // 一定会成功
}

After Java 14, it can be written more concisely

if(p instanceof Student s) {
	// 可以使用 Student 型的对象 s
}

Polymorphism

Override

In an inheritance relationship, if a subclass defines a method with exactly the same signature as a method of the parent class, it is called an override (Override).

For example, in the Person class, we define a run() method:

class Person {
    public void run() {
        System.out.println("Person.run");
    }
}

In the subclass Student, we override this run() method:

class Student extends Person {
    @Override
    public void run() {
        System.out.println("Student.run");
    }
}

The difference between Override and Overload: if the method signatures differ, it is an Overload, and an Overload method is a new method; if the method signatures are the same and the return values are also the same, it is an Override.

Polymorphism means that for a method call on a certain type, the method actually executed depends on the actual type at runtime.

The most typical use case is inside a method where the method's parameter is Person p, but what gets passed in can be all kinds of subclasses derived from Person. The method called may have the same signature, but due to polymorphism, the actual effect of the call differs — yet the method itself does not need to care about this.

Overriding Object Methods

  • toString(): outputs the instance as a String;
  • equals(): determines whether two instances are logically equal;
  • hashCode(): computes the hash value of an instance.

Calling super

Calling the parent class's overridden method, e.g., super.hello()

final

If a parent class does not allow a subclass to override one of its methods, the method can be marked as final. A method modified with final cannot be Overriden.

If a class does not want any other class to inherit from it, the class itself can be marked as final. A class modified with final cannot be inherited.

If a class does not want any other class to inherit from it, the class itself can be marked as final. A class modified with final cannot be inherited.

Abstract Classes

If a class defines a method but provides no concrete implementation code, that method is an abstract method, and abstract methods are modified with abstract.

Because an abstract method cannot be executed, the class must also be declared as an abstract class.

It is somewhat like the virtual keyword in C++.

Interfaces

If an abstract class has no fields and all of its methods are abstract, the abstract class can be rewritten as an interface: interface.

In Java, you can declare an interface using interface:

interface Person {
    void run();
    String getName();
}

An interface is a purely abstract interface, even more abstract than an abstract class, because it cannot even have fields. Since all methods defined in an interface are public abstract by default, these two modifiers do not need to be written out (writing them or not has the same effect).

When a concrete class implements an interface, it needs to use the implements keyword.

A class can implement multiple interfaces.

Interface Inheritance

An interface can inherit from another interface. An interface inheriting from an interface uses extends, which effectively extends the methods of the interface. For example:

interface Hello {
    void hello();
}

interface Person extends Hello {
    void run();
    String getName();
}

When using them, the instantiated object can only ever be some concrete subclass, but it is always referenced through the interface, because an interface is more abstract than an abstract class:

List list = new ArrayList(); // 用 List 接口引用具体子类的实例
Collection coll = list; // 向上转型为 Collection 接口
Iterable it = coll; // 向上转型为 Iterable 接口

default Methods

Declare a method with the default keyword inside an interface and provide an implementation.

Static Fields and Methods

Static Fields of Interfaces

public interface Person {
    public static final int MALE = 1;
    public static final int FEMALE = 2;
}

In fact, the preceding modifiers can be omitted, becoming:

public interface Person {
    // 编译器会自动加上 public static final:
    int MALE = 1;
    int FEMALE = 2;
}

Packages

A class always belongs to some package; the class name (e.g., Person) is just an abbreviation, and the real fully qualified class name is 包名.类名.

When defining a class, we need to declare on the first line which package the class belongs to.

Xiao Ming's Person.java file:

package ming; // 申明包名 ming

public class Person {
}

Packages have no parent-child relationship. java.util and java.util.zip are different packages, and there is no inheritance relationship between them whatsoever.

Package Scope

For classes in the same package, fields and methods without any modifier belong to package scope.

Classes in the same package can access fields and methods within package scope, for example:

package hello;

public class Person {
    // 包作用域:
    void hello() {
        System.out.println("Hello!");
    }
}
package hello;

public class Main {
    public static void main(String[] args) {
        Person p = new Person();
        p.hello(); // 可以调用,因为 Main 和 Person 在同一个包
    }
}

To avoid name conflicts, we need to determine a unique package name. The recommended practice is to use an inverted domain name to ensure uniqueness. For example:

  • org.apache
  • org.apache.commons.log
  • com.liaoxuefeng.sample

Sub-packages can be named freely according to function.

Inner Classes

If a class is defined inside another class, it is an Inner Class:

class Outer {
    class Inner {
        // 定义了一个 Inner Class
    }
}

An instance of an Inner Class cannot exist independently; it must be attached to an instance of an Outer Class.

To instantiate an Inner, we must first create an instance of Outer, and then call the Outer instance's new to create the Inner instance:

Outer outer = new Outer();
Outer.Inner inner = outer.new Inner(); // 实例化一个 Inner

Anonymous Classes

Instantiating Runnable? I don't understand it; leaving a placeholder for now.

classpath

classpath is an environment variable used by the JVM; it tells the JVM how to search for classes.

It is recommended to set the classpath when starting the JVM, which in practice means passing arguments:

java -classpath .;C:\work\project1\bin;C:\shared abc.xyz.Hello

It searches for .class files in order, separated by ;.

Or use the shorthand:

java -cp .;C:\work\project1\bin;C:\shared abc.xyz.Hello

The default is .

Do not add any Java core libraries to the classpath! The JVM does not rely on the classpath at all to load core libraries!

Suppose we have a compiled Hello.class whose package name is com.example, and the current directory is C:\work. Then the directory structure must be as follows:

C:\work
└─ com
   └─ example
      └─ Hello.class

To run this Hello.class, you must use the following command in the current directory:

C:\work> java -cp . com.example.Hello

The JVM searches for com.example.Hello in the current directory according to the . set in the classpath, meaning the actual file being searched for must be located at com/example/Hello.class. If the specified .class file does not exist, or the directory structure does not match the package name, an error will be reported.

jar Packages

Essentially a .zip archive with the extension changed to .jar; it can contain many .class files, making them convenient to download and use.

class Versions

A higher-version JDK is compatible with lower-version JDKs, but a lower-version JDK is not compatible with higher-version JDKs; running a higher-version class file on a lower-version JVM reports a linkageError; a NoSuchMethodError means the current version of the JVM lacks the library method needed to run the file

Modules

Modules, introduced starting from Java 9, are mainly intended to solve the "dependency" problem. If a.jar must depend on another b.jar to run, then we should add some description to a.jar so that the program can automatically locate b.jar at compile time and runtime. Such a class container with built-in "dependency relationships" is a module.

How to write modules? How to run modules? How to package a JRE?

Modules can also isolate code access permissions.

This part feels quite confusing to read; to be filled in later

Java Core Classes

Strings and Encoding

String is a reference type.

Internally it is represented by a char[] array, so the following way of writing also works:

String s2 = new String(new char[] {'H', 'e', 'l', 'l', 'o', '!'});

Because String is so commonly used, Java provides the "..." string literal notation.

An important characteristic of Java strings is that strings are immutable. This immutability is achieved through the internal private final char[] field, together with the absence of any method that modifies the char[].

  • Equality check: equals()

  • Case-insensitive comparison: equalsIgnoreCase()

  • Whether a substring is contained: contains(); the parameter of this method is CharSequence rather than String, because CharSequence is an interface implemented by String.

  • Find the index of the first occurrence of a substring: indexOf()

  • Find the index of the last occurrence of a substring: lastIndexOf()

  • Check whether the prefix of a string is a certain substring: startsWith(), e.g., "hello".startsWith("he") == true

  • Check whether the suffix of a string is a certain substring: endsWith(), e.g., "hello".endsWith("lo") == true

  • Extract a substring: "Hello".substring(2); // "llo", "Hello".substring(2, 4); "ll".

  • Get a string with leading and trailing whitespace removed: trim() and strip(); the former only removes spaces, \t, \r, \n, while the latter also removes full-width spaces.

  • Empty check: isEmpty() (i.e., checks whether the length is 0)

  • Blank check: isBlank()

  • Replace substrings based on characters:

    s.replace('l', 'w'); // "hewwo",所有字符'l'被替换为'w'
  • Replace substrings based on substrings:

    s.replace("ll", "~~"); // "he~~o",所有子串"ll"被替换为"~~"
  • Regex replacement

    String s = "A,,B;C ,D";
    s.replaceAll("[\\,\\;\\s]+", ","); // "A,B,C,D"
  • Splitting strings: pass in a regular expression

    String s = "A,B,C,D";
    String[] ss = s.split("\\,"); // {"A", "B", "C", "D"}
  • Concatenating strings: the static method join(), which joins an array of strings with a specified string:

    String[] arr = {"A", "B", "C"};
    String s = String.join("***", arr); // "A***B***C"
  • Formatting, divided into the formatted() method and the static format() method:

    public class Main {
        public static void main(String[] args) {
            String s = "Hi %s, your score is %d!";
            System.out.println(s.formatted("Alice", 80));
            System.out.println(String.format("Hi %d, your score is %.2f!", "Bob", 90));
        }
    }

    There are many placeholders; if you don't know which one to use, just use %s.

  • Type conversion: the static method valueOf(), which is an overloaded method; the compiler automatically selects the appropriate method based on the arguments:

    String.valueOf(123); // "123"
    String.valueOf(45.67); // "45.67"
    String.valueOf(true); // "true"
    String.valueOf(new Object()); // 类似 java.lang.Object@636be97c

    To convert a string to other types, you need to use the static methods of each type

    int n1 = Integer.parseInt("123"); // 123
    int n2 = Integer.parseInt("ff", 16); // 按十六进制转换,255
    boolean b1 = Boolean.parseBoolean("true"); // true
    boolean b2 = Boolean.parseBoolean("FALSE"); // false
  • Conversion between String and char[]:

    char[] cs = "Hello".toCharArray(); // String -> char[]
    String s = new String(cs); // char[] -> String

    From the immutability design of String, we can see that if the object passed in might change, we need to copy it rather than reference it directly.

StringBuilder

A StringBuilder object can pre-allocate a buffer, so no new temporary objects are created when adding characters:

StringBuilder sb = new StringBuilder(1024);
for (int i = 0; i < 1000; i++) {
    sb.append(',');
    sb.append(i);
}
String s = sb.toString();

Chained operations are also possible:

var sb = new StringBuilder(1024);
sb.append("Mr").
    append("Bob");

This is because the append() method returns this.

Note: for ordinary string + operations, we do not need to rewrite them as StringBuilder, because the Java compiler automatically compiles multiple consecutive + operations into StringConcatFactory operations at compile time. At runtime, StringConcatFactory automatically optimizes string concatenation operations into array copies or StringBuilder operations.

StringJoiner

Solves the need to join an array of strings with a delimiter.

String[] names = {"Alice", "Bob", "Cathy"};
var sj = new StringJoiner(","); //指定分隔符
for (String name : names) {
	sj.add(name);	
}
// sj.toString()

You can also specify a prefix and a suffix; this is a constructor overload

var sj = new StringJoiner(",", "Hello", "!"); // "Hello"开头,"!"结尾

String.join()

String also provides a static method join(), which internally uses StringJoiner to concatenate strings. When you don't need to specify a "prefix" and "suffix", String.join() is more convenient:

String[] names = {"Bob", "Alice", "Grace"};
var s = String.join(", ", names);

Wrapper Types

The Java core library provides a corresponding wrapper type for each primitive type:

Primitive Type Corresponding Reference Type
boolean java.lang.Boolean
byte java.lang.Byte
short java.lang.Short
int java.lang.Integer
long java.lang.Long
float java.lang.Float
double java.lang.Double
char java.lang.Character

When creating wrapper types, it is not recommended to use new; it is recommended to use the static method valueOf()

Integer n1 = Integer.valueOf(100);
Integer n2 = Integer.valueOf("100");

Because Integer.valueOf() returns a cached Integer instance, this saves the overhead of allocating heap memory.

We call static methods that can create "new" objects static factory methods. Integer.valueOf() is a static factory method that returns cached instances whenever possible to save memory.

When creating new objects, prefer static factory methods over the new operator

In one sentence: Using new is like commanding a computer to "fetch a new brick"; using a static factory method is like telling the warehouse manager "I want a brick of this specification," and the manager will check whether there is a ready-made one in the warehouse, or give you a specially made brick that works even better.

Auto Boxing and Auto Unboxing

Since int and Integer can be converted to each other:

int i = 100;
Integer n = Integer.valueOf(i);
int x = n.intValue();

Therefore, the Java compiler can help us automatically convert between int and Integer:

Integer n = 100; // 编译器自动使用 Integer.valueOf(int)
int x = n; // 编译器自动使用 Integer.intValue()

This assignment style that directly turns an int into an Integer is called auto boxing; conversely, the assignment style that turns an Integer into an int is called auto unboxing.

Auto boxing and auto unboxing only happen at the compilation stage, with the purpose of writing less code.

Immutable Classes

All wrapper types are immutable

public final class Integer {
    private final int value;
}

Equality Comparison

Always use the equals() method, although there is an optimization for Integer when the value is less than 128.

Radix Conversion

The Integer class itself also provides many methods. For example, the most commonly used static method parseInt() can parse a string into an integer:

int x1 = Integer.parseInt("100"); // 100
int x2 = Integer.parseInt("100", 16); // 256,因为按 16 进制解析

Integer can also format an integer into a string in a specified radix:

// Integer:
public class Main {
    public static void main(String[] args) {
        System.out.println(Integer.toString(100)); // "100",表示为 10 进制
        System.out.println(Integer.toString(100, 36)); // "2s",表示为 36 进制
        System.out.println(Integer.toHexString(100)); // "64",表示为 16 进制
        System.out.println(Integer.toOctalString(100)); // "144",表示为 8 进制
        System.out.println(Integer.toBinaryString(100)); // "1100100",表示为 2 进制
    }
}

Java's wrapper types also define some useful static variables

// boolean 只有两个值 true/false,其包装类型只需要引用 Boolean 提供的静态字段:
Boolean t = Boolean.TRUE;
Boolean f = Boolean.FALSE;
// int 可表示的最大/最小值:
int max = Integer.MAX_VALUE; // 2147483647
int min = Integer.MIN_VALUE; // -2147483648
// long 类型占用的 bit 和 byte 数量:
int sizeOfLong = Long.SIZE; // 64 (bits)
int bytesOfLong = Long.BYTES; // 8 (bytes)

Handling unsigned

// Byte
public class Main {
    public static void main(String[] args) {
        byte x = -1;
        byte y = 127;
        System.out.println(Byte.toUnsignedInt(x)); // 255
        System.out.println(Byte.toUnsignedInt(y)); // 127
    }
}

JavaBean

A JavaBean is a class that conforms to naming conventions, defining properties through getter and setter methods.

The "read method (getter)" + "write method (setter)" together are called a property.

JavaBean is a specification.

Enum Classes

Under the hood, an enum class is just a bunch of statically instantiated object constants.

Defining an enum

enum Weekday {
    SUN, MON, TUE, WED, THU, FRI, SAT;
}

enum constants themselves carry type information and can only be compared with and assigned to enum constants of the same type.

Comparing enums

Although they are reference types, each constant of an enum type has only one unique instance in the JVM, so they can be compared with ==.

enum Classes

An enum is a class with the following characteristics:

  • It inherits from java.lang.Enum and cannot be inherited from
  • You can only define instances but cannot new an instance (internally avoided by making the constructor private)
  • Each defined instance is a unique instance of a reference type
  • The enum type can be used in switch statements

Write a Color enum class like this:

public enum Color {
    RED, GREEN, BLUE;
}

The internal principle of the compiled result is like this:

public final class Color extends Enum {
    public static final Color RED = new Color();
    public static final Color GREEN = new Color();
    public static final Color BLUE = new Color();
    private Color() {}
}

enum classes have these methods:

  • Return the constant name: name(), e.g., String s = Weekday.MON.name() // "MON"

  • Return the order in which the constants were defined: ordinal(), e.g., int n = Weekday.MON.ordinal() // 1. However, you should not use ordinal() to compare int values with enum classes, because the result would change if the order changes. The solution is to add a field like this:

    enum Color {
        RED(0), BLUE(1), GREEN(2);
        public final int value;
        private Color(int value) {
            this.value = value;
        }
    }

    Since each instance is static, there is a unique public final int value for that instance.

  • You can override the toString() method for an enum class:

    enum Color {
        RED(0, "红"), BLUE(1, "蓝"), GREEN(2, "绿");
        public final int value;
        private final String chinese;
        private Color(int value, String chinese) {
            this.value = value;
            this.chinese = chinese
        }
        @Override
        public String toString() {
            return this.chinese;
        }
    }

Record Classes

An immutable class has the following characteristics:

  1. Use final when defining the class, so it cannot be subclassed;
  2. Each field uses final, ensuring that no field can be modified after the instance is created.
  3. You also need to properly override the equals() and hashCode() methods so that it can be used correctly in collection classes.

Defining a record class

Introduced since Java 14, declared with the keyword record:

record Point(int x, int y) {}

Which is equivalent to:

代码JAVA · 19 行
final class Point extends Record {
    private final int x;
    private final int y;
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public int x() {return this.x;}
    public int y() {return this.y;}
    public String toString() {
        return String.format("Point[x=%s, y=%s]", x, y);
    }
    public boolean equals(Object o) {
        ...
    }
    public int hashCode() {
        ...
    }
}

Using the record keyword, you can write an immutable class in one line.

Constructors

Suppose the x and y of the Point class are not allowed to be negative; then we need to add checking logic to the constructor of Point:

public record Point(int x, int y) {
    public Point {
        if (x < 0 || y < 0) {
            throw new IllegalArgumentException();
        }
    }
}

The later this.x = x; this.y = y; does not need to be written; the compiler will generate it automatically, and you only need to write the checking logic.

You can add static methods. One commonly used static method is the of() method, used to create a Point:

public record Point(int x, int y) {
    public static Point of() {
        return new Point(0, 0);
    }
    public static Point of(int x, int y) {
        return new Point(x, y);
    }
}

BigInteger

High-precision large integers.

BigInteger bi = new BigInteger("123456789123456789");

Use instance methods for arithmetic (add(), etc.).

Like Integer and Long, BigInteger is also an immutable class and also inherits from the Number class. Because Number defines several methods for converting to primitive types:

  • Convert to byte: byteValue()
  • Convert to short: shortValue()
  • Convert to int: intValue()
  • Convert to long: longValue()
  • Convert to float: floatValue()
  • Convert to double: doubleValue()

Therefore, through the above methods, a BigInteger can be converted to primitive types.

If the range represented by a BigInteger exceeds the range of the primitive type, high-order information will be lost during conversion, i.e., the result may not be accurate. If you need to convert to a primitive type accurately, you can use methods such as intValueExact() and longValueExact(), which will directly throw an ArithmeticException if the value is out of range during conversion.

BigDecimal

High-precision decimals.

BigDecimal bd = new BigDecimal("123.4567");

The scale() method can find the number of decimal places. If the scale() of a BigDecimal returns a negative number, for example, -2, it means the number is an integer with 2 zeros at the end.

The stripTrailingZeros() method can format a BigDecimal into an equal BigDecimal but with trailing zeros removed.

You can set the scale of a BigDecimal. If the precision is lower than the original value, it will be rounded or directly truncated according to the specified method:

BigDecimal d1 = new BigDecimal("123.456789");
BigDecimal d2 = d1.setScale(4, RoundingMode.HALF_UP); // 四舍五入,123.4568

When doing division, you need to specify the precision and truncation mode to avoid non-terminating division:

BigDecimal d1 = new BigDecimal("123.456");
BigDecimal d2 = new BigDecimal("23.456789");
BigDecimal d3 = d1.divide(d2, 10, RoundingMode.HALF_UP); // 保留 10 位小数并四舍五入
BigDecimal d4 = d1.divide(d2); // 报错:ArithmeticException,因为除不尽

You can also do division on a BigDecimal while obtaining the remainder at the same time:

BigDecimal n = new BigDecimal("12.345");
BigDecimal m = new BigDecimal("0.12");
BigDecimal[] dr = n.divideAndRemainder(m);
System.out.println(dr[0]); // 102
System.out.println(dr[1]); // 0.105

When comparing, use the compareTo() method. Reason: the equals() method also requires the scale to be the same.

In fact, a BigDecimal is represented by a BigInteger and a scale, i.e., the BigInteger represents the complete integer, while the scale represents the number of decimal places:

public class BigDecimal extends Number implements Comparable<BigDecimal> {
    private final BigInteger intVal;
    private final int scale;
}

Common Utility Classes

Math

Math.abs(), Math.max(), Math.min(), Math,pow()...

SecureRandom

Used to create secure random numbers; for specific usage, just ask an LLM.

Exceptions

Introduction to Java Exceptions

graph BT
    %% 定义节点
    Object[Object]
    Throwable[Throwable]
    Error[Error]
    Exception[Exception]
    OOM[OutOfMemoryError]
    RE[RuntimeException]
    IOE[IOException]
    NPE[NullPointerException]
    IAE[IllegalArgumentException]
    OtherError[...]
    OtherExc[...]

    %% 定义继承关系
    Throwable --> Object
    Error --> Throwable
    Exception --> Throwable
    
    OOM --> Error
    OtherError --> Error
    
    RE --> Exception
    IOE --> Exception
    OtherExc --> Exception
    
    NPE --> RE
    IAE --> RE

    %% 样式美化(可选)
    style Object fill:#f9f,stroke:#333,stroke-width:2px
    style Throwable fill:#fff4dd,stroke:#d4a017,stroke-width:2px
    style Error fill:#fbb,stroke:#a00
    style Exception fill:#bbf,stroke:#00a

Error indicates a serious error that the program can do nothing about, such as running out of memory or a stack overflow;

Exception indicates a runtime error that can be caught and handled

Exception is further divided into two major categories:

  1. RuntimeException and its subclasses;
  2. Non-RuntimeException (including IOException, ReflectiveOperationException, etc.)

Java stipulates:

  • Exceptions that must be caught, including Exception and its subclasses, but not including RuntimeException and its subclasses; this type of exception is called a Checked Exception.
  • Exceptions that do not need to be caught, including Error and its subclasses, and RuntimeException and its subclasses.

The fact that the compiler does not force catching RuntimeException and its subclasses does not mean that the application itself should not catch and handle RuntimeException. Whether to catch it should be analyzed on a case-by-case basis.

Catching Exceptions

try {
    // 可能发生异常的代码
} catch(Exception e) {
    // 处理异常
}

When defining a method, using throws Xxx indicates the type of exception the method may throw. When calling, the caller must forcibly catch these exceptions; otherwise, the compiler will report an error.

If you call a method that throws an exception but do not want to handle it, you can write throws Xxx in the signature of the method that makes the call, thus passing the buck to a higher level.

From this we can see that as long as a Checked Exception is declared by a method, if it is not caught at the calling layer, it must be caught at a higher calling layer. All uncaught exceptions must ultimately be caught in the main() method; there will be no case of a missing try. This is guaranteed by the compiler. The main() method is also the last chance to catch an Exception.

If you do not want to write any try code, you can directly define the main() method as throws Exception; the cost is that once an exception occurs, the program will exit immediately.

All exceptions can call the printStackTrace() method to print the exception stack; this is a simple and useful method for quickly printing exceptions.

Catching Exceptions

Multiple catch Statements

try {
    process1();
    process2();
    process3();
} catch (IOException e) {
    System.out.println(e);
} catch (NumberFormatException e) {
    System.out.println(e);
}

After the JVM catches an exception, it matches the catch statements from top to bottom. Once a certain catch is matched, the catch code block is executed, and then it no longer continues matching.

The order of catch blocks is very important: subclasses must be written first.

The finally Statement

The finally block guarantees execution whether or not there is an error.

try {
    process1();
    process2();
    process3();
} catch (UnsupportedEncodingException e) {
    System.out.println("Bad encoding");
} catch (IOException e) {
    System.out.println("IO error");
} finally {
    System.out.println("END");
}

If no exception occurs, the try { ... } block executes normally, and then finally executes. If an exception occurs, the execution of the try { ... } block is interrupted, then the matching catch block is executed, and finally finally executes.

As you can see, finally is used to guarantee that some code must be executed.

Catching Multiple Exceptions

If the logic for handling different exceptions is the same, you can join them with |:

try {
    process();
} catch (IOException | NumberFormatException e) {
    // IOException 或 NumberFormatException
    System.out.println("Bad input");
}

Throwing Exceptions

Exception Propagation

Through printStackTrace(), you can print out the propagation path of an exception

Throwing Exceptions

It is divided into two steps:

  1. Create an instance of some Exception;
  2. Throw it with the throw statement.
void process(String s) {
    if (s == null) {
        throw new NullPointerException();
    }
}

When catching an exception and throwing it again, you must preserve the original exception; otherwise, it is very difficult to locate the original crime scene!

The so-called "preserving the original exception" means that the parameter can be passed in:

void process1() {
    try {
        process2();
    } catch (NullPointerException e) {
        throw new IllegalArgumentException(e); // HERE
    }
}

void process2() {
    throw new NullPointerException();
}

This way, when calling printStackTrace(), the root cause of the exception can be shown more clearly.

Throwing an exception inside a catch block does not affect the execution of finally. The JVM will first execute finally, and then throw the exception.

Exception Suppression

If an exception is thrown while executing the finally block, the exception that was about to be thrown in the catch block "disappears," because only one exception can be thrown. The exception that was not thrown is called a "suppressed" exception (Suppressed Exception).

Solution: first temporarily store the original exception, use Throwable.addSuppressed() to add the original exception, and finally throw it in finally:

Exception origin = null;
try {
	System.out.println(Integer.parseInt("abc"));
} catch (Exception e) {
    origin = e;
    throw e;
} finally {
    Exception e = new IllegalArgumentException();
    if (origin != null) {
        e.addSuppressed(origin);
    }
    throw e;
}

This way, both exceptions can be seen in the exception stack.

Custom Exceptions

Common exceptions defined by the Java standard library include:

Exception
├─ RuntimeException
│  ├─ NullPointerException
│  ├─ IndexOutOfBoundsException
│  ├─ SecurityException
│  └─ IllegalArgumentException
│     └─ NumberFormatException
├─ IOException
│  ├─ UnsupportedCharsetException
│  ├─ FileNotFoundException
│  └─ SocketException
├─ ParseException
├─ GeneralSecurityException
├─ SQLException
└─ TimeoutException

A custom BaseException should provide multiple constructors:

public class BaseException extends RuntimeException {
    public BaseException() {
        super();
    }

    public BaseException(String message, Throwable cause) {
        super(message, cause);
    }

    public BaseException(String message) {
        super(message);
    }

    public BaseException(Throwable cause) {
        super(cause);
    }
}

Using Assertions

Assertions are a debugging method; a failed assertion throws an AssertionError, and assertions can only be enabled during development and testing;

assert x > 0 : "x must > 0";

Assertions should not be used for recoverable errors; instead, exceptions should be thrown;

Assertions are rarely used; a better approach is to write unit tests.

Logging

To be filled in later; it feels like just a bunch of APIs

Using JDK Logging

A logging system that comes with Java; look up the specific API when you need it.

import java.util.logging.Level;
import java.util.logging.Logger;

Using Commons Logging

Commons Logging is a third-party logging library, a logging module created by Apache.

Using Log4j

Using SLF4J and Logback

Reflection

Java reflection means that a program can obtain all the information about an object at runtime. Reflection exists to solve the problem of how to call an instance's methods at runtime when you know nothing about that instance.

This is because Java allows passing parent classes or even interfaces as parameters.

The Class Class

Except for primitive types such as int, all other types in Java are class (including interface)

During execution, the JVM, each time it encounters (meaning it is loaded when encountered, not loaded at compile time; this is called dynamic loading) a type (such as a class you defined), creates a new static instance like this and stores it in memory:

public final class Class {
	private Class() {}
    // ...字段略
}

Note: the Class here is a class named Class.

In other words, there is a type named Class, which stores various information about that type.

For example, when the program encounters the String class, the JVM first reads String.class into memory, and then creates a Class instance: Class cls = new Class(String);. Only the JVM can perform this operation.

In a nutshell, the JVM holds many Class instances, and each Class instance points to a specific data type. A Class instance contains all the information about that type, such as the class name, package name, parent class, implemented interfaces, and so on.

The method of obtaining all the information about a type through a Class instance is called reflection.

Three methods to obtain the Class instance of a class:

  1. Class cls = String.class;
  2. String s = ""; Class cls = s.getClass();
  3. Class cls = Class.forName("java.lang.String");

Since a type corresponds to a unique Class instance in the JVM's memory, you can use == to compare them.

At this point, we need to distinguish between comparing Class instances with == and the instanceof relationship: the former requires a strict type match, while the latter also holds for subclasses.

How to get information from a Class instance? getName(), getSimpleName, getPackage(), isInterface(), isEnum(),isArray(), isPrimitive().

Note: arrays and primitive types also have corresponding Class instances. For example, for String[], the class name is Ljava.lang.String; int.class is also accessible.

With a Class instance, you can create an instance of the corresponding type through that Class instance:

Class cls = String.class;
String s = (String) cls.newInstance();

But there are limitations: you can only call the public no-argument constructor

Accessing Fields

Fields are represented by Field objects. You can obtain Field objects through a Class instance in the following ways:

  • Field getField(name): get a certain public field by field name (including parent classes)
  • Field getDeclaredField(name): get a certain field of the current class by field name (not including parent classes)
  • Field[] getFields(): get all public field values (including parent classes)
  • Field[] getDeclaredFields(): get all field values of the current class (not including parent classes)

For a Field object, there are several ways to get information about the field:

  • getName(): returns the field name, e.g., "name";

  • getType(): returns the field type, which is also a Class instance, e.g., String.class;

  • getModifiers(): returns the field's modifiers, which is an int where different bits represent different meanings.

    int m = f.getModifiers();
    Modifier.isFinal(m); // true
    Modifier.isPublic(m); // false
    Modifier.isProtected(m); // false
    Modifier.isPrivate(m); // true
    Modifier.isStatic(m); // false

You can get the value of a field corresponding to an instance through reflection:

Object p = new Person("Alice");
Class c = p.getClass();
Field f = p.getDeclaredField("name");
Object value = f.get(p); // value.equals("Alice")

If it is a private field and cannot be accessed, you can use

f.setAccessible(true);

to force access.

At the same time, you can set the value of a field via Field.set(Object, Object), where the first Object parameter is the specified instance, and the second Object parameter is the value to be set:

To modify a non-public field, you need to first call setAccessible(true).

Invoking Methods

Corresponding to accessing fields mentioned above is getting methods. We have a class Method, which occupies the same niche as Field. The methods for getting a Method are as follows:

  • Method getMethod(name, Class...): get a certain public Method (including parent classes); the class ... here refers to the method's parameters.
  • Method getDeclaredMethod(name, Class...): get a certain Method of the current class (not including parent classes)
  • Method[] getMethods(): get all public Methods (including parent classes)
  • Method[] getDeclaredMethods(): get all Methods of the current class (not including parent classes)

A Method object contains all the information about a method:

  • getName(): returns the method name, e.g., "getScore";
  • getReturnType(): returns the method's return value type, which is also a Class instance, e.g., String.class;
  • getParameterTypes(): returns the method's parameter types, which is a Class array, e.g., {String.class, int.class};
  • getModifiers(): returns the method's modifiers, which is an int where different bits represent different meanings.

To invoke a method, use invoke; the first parameter passed in is the object instance, i.e., on which instance to call the method. If it is a static method, pass null as the first parameter. See the sample code:

String s = "Hello, world";
Method m = String.class.getMethod("substring", int.class);
String r = (String) m.invoke(s, 6);

Note that substring() has two overloaded methods, and what we get is the String substring(int) method.

To call a non-public method, you can use Method.setAccessible(true) to allow the call.

Polymorphism

If a Person class defines a Hello() method, and its subclass Student also overrides the Hello() method, then when the Method obtained from Person.class is applied to a Student instance, the Hello() method overridden by the Student class is called.

Invoking Constructors

Since newInstance() has limitations and can only call the class's public no-argument constructor:

Person p = Person.class.newInstance();

Java's reflection API provides the Constructor object, which contains all the information about a constructor and can create an instance.

A Constructor object is very similar to a Method object.

The methods for getting a Constructor through a Class instance are as follows:

  • getConstructor(Class...): get a certain public Constructor;
  • getDeclaredConstructor(Class...): get a certain Constructor;
  • getConstructors(): get all public Constructors;
  • getDeclaredConstructors(): get all Constructors.

Note that a Constructor is always a constructor defined by the current class and has nothing to do with the parent class, so there is no polymorphism issue.

To invoke a Constructor, use newInstance(...), and the parameters are the corresponding constructor's parameters.

When invoking a non-public Constructor, you must first call setAccessible(true) to allow access. setAccessible(true) may fail.

Getting Inheritance Relationships

Getting the Class of the Parent Class

Just use the getSuperclass() method on the Class object.

Getting interfaces

Class[] is = cls.getInterfaces();

Pay special attention: getInterfaces() only returns the interface types directly implemented by the current class, and does not include the interfaces implemented by its parent classes.

Calling getSuperclass() on the Class of any interface returns null; to get an interface's parent interfaces, use getInterfaces().

If a class does not implement any interface, then getInterfaces() returns an empty array.

Inheritance Relationships

If it is two objects, and you want to determine whether it is of a certain type, or whether an upcast holds, you can use the instanceof operator;

If it is two Class instances and you want to make the same determination, you can use isAssignableFrom():

Object.class.isAssignableFrom(Integer.class); // true,因为 Integer 可以赋值给 Object

The parameter is the derived class or the class itself.

Dynamic Proxy

The approach of not implementing an interface but directly dynamically creating an interface object at runtime is called dynamic code. The JDK's way of dynamically creating interface objects is called dynamic proxy.

Dynamic proxy creates a proxy object through Proxy, and then "delegates" the interface methods to an InvocationHandler to complete.

The specific syntax is a bit complicated; I think just asking an LLM is fine. To be filled in later.

Annotations

Using Annotations

Annotations are a special kind of "comment" placed before classes, methods, fields, and parameters in Java source code, such as @Override, @PostConstruct, etc.

Comments are directly ignored by the compiler, while annotations can be packaged by the compiler into the class file.

Purpose of Annotations

The first category: annotations used by the compiler, such as

  • @Override: lets the compiler check whether the method correctly implements an override;
  • @SuppressWarnings: tells the compiler to ignore warnings generated by the code here.

Annotations of this kind are not compiled into the .class file; they are discarded by the compiler after compilation.

The second category: used by underlying libraries, and generally we do not need to handle them ourselves.

The third category: annotations that can be read at runtime and persist in the JVM; these are the most commonly used annotations. For example, a method configured with @PostConstruct will be automatically called after the constructor is invoked (this is a feature implemented by Java code reading the annotation; the JVM itself does not recognize the annotation).

When defining an annotation, you can also define configuration parameters, and these parameters must be constants.

The configuration parameters of an annotation can have default values; when a configuration parameter is missing, the default value will be used.

For example:

public class Hello {
    @Check(min=0, max=100, value=55)
    public int n;

    @Check(value=99)
    public int p;

    @Check(99) // @Check(value=99)
    public int x;
    // 大部分注解会有一个名为 value 的配置参数,对此参数赋值,可以只写常量,相当于省略了 value 参数。

    @Check
    public int y;
}

Defining Annotations

The Java language uses the @interface syntax to define annotations, in the following format:

public @interface Report {
    int type() default 0;
    String level() default "info";
    String value() default "";
}

The parameters of an annotation are similar to parameterless methods, and you can use default to set a default value (strongly recommended). The most commonly used parameter should be named value.

Meta-Annotations

Some annotations can modify other annotations; these annotations are called meta-annotations. The Java standard library has already defined some meta-annotations; we only need to use meta-annotations and usually do not need to write our own.

What does "modifying other annotations" mean? It means using meta-annotations to set some conventions for the annotations you write.

@Target

value is an ElementType[] array; when there is only one element, the array syntax can be omitted, and if there are multiple elements, it can be written in a form like @Target({Element.FIELD, Element.METHOD}).

ElementType is an enum class with the following kinds:

  • Class or interface: ElementType.TYPE;
  • Field: ElementType.FIELD;
  • Method: ElementType.METHOD;
  • Constructor: ElementType.CONSTRUCTOR;
  • Method parameter: ElementType.PARAMETER.

Usage example: to define the annotation @Report so that it can be used on methods, we must add @Target(ElementType.METHOD):

@Target(ElementType.METHOD)
public @interface Report {
    int type() default 0;
    String level() default "info";
    String value() default "";
}

@Retention

Defines the lifecycle of an annotation:

  • Compile time only: RetentionPolicy.SOURCE;
  • Class file only: RetentionPolicy.CLASS;
  • Runtime: RetentionPolicy.RUNTIME.

The default is CLASS, but in practice RUNTIME is generally used.

@Repeatable

After being modified by @Repeatable, multiple @Report annotations can be added at a type declaration:

@Report(type=1, level="debug")
@Report(type=2, level="warning")
public class Hello {
}

@Inherited

Use @Inherited to define whether a subclass can inherit the Annotation defined by the parent class.

@Inherited is only effective for annotation declarations of the @Target(ElementType.TYPE) type, and only for class inheritance; it has no effect on interface inheritance.

How to Define an Annotation

Step one, use @interface to define the annotation:

public @interface Report {
}

Step two, add parameters and default values:

public @interface Report {
    int type() default 0;
    String level() default "info";
    String value() default "";
}

Define the most commonly used parameter as value(), and it is recommended that all parameters have default values as much as possible.

Step three, configure the annotation with meta-annotations:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Report {
    int type() default 0;
    String level() default "info";
    String value() default "";
}

Among these, @Target and @Retention must be set; @Retention is generally set to RUNTIME, because our custom annotations usually need to be read at runtime. In general, there is no need to write @Inherited and @Repeatable.

Processing Annotations

Depending on the @Retention configuration:

  • Annotations of the SOURCE type are discarded at compile time;
  • Annotations of the CLASS type are only saved in the class file and are not loaded into the JVM;
  • Annotations of the RUNTIME type are loaded into the JVM and can be read by the program at runtime.

How annotations are used is entirely determined by the tools. Annotations of the SOURCE type are mainly used by the compiler, so we generally only use them and do not write them. Annotations of the CLASS type are mainly used by underlying tool libraries, involving class loading, and we rarely use them. Only annotations of the RUNTIME type are not only used but also frequently need to be written.

Since annotations are also a kind of class, and all annotations inherit from java.lang.annotation.Annotation, reading annotations requires the reflection API. These reflection APIs all apply to Class, Field, Method, or Constructor (but there are some differences in certain cases, which will be noted):

To check whether a certain annotation exists: use the isAnnotationPresent() method, for example, to check whether @Report exists on the Person class:

Person.class.isAnnotationPresent(Report.class);

To read an Annotation: use getAnnotation(Class):

Report report = Person.class.getAnnotation(Report.class);
int type = report.type();
String level = report.level();

If the Annotation does not exist, null will be returned.

Reading the Annotation of methods, fields, and constructors is similar to Class, but for method parameters it is more complicated, because a method parameter can be viewed as an array, and each parameter can have multiple annotations defined on it. For example:

For a method like this:

public void hello(@NotNull @Range(max=5) String name, @NotNull String prefix) {
}

First get the Method instance of this method, then get the Annotations of all parameters:

Method m = ...;
Annotation[][] annos = m.getParameterAnnotations();

Then get all Annotations of the first parameter (index 0):

Annotation[] annoOfName = annos[0];

Then iterate over annoOfName to read all the annotations.

Using Annotations

How annotations are used is entirely up to the program itself.

For example, I write an annotation Range, which is used to specify the length range of a String:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Range {
    int min() default 0;
    int max() default 255;
}

Then suppose I use this annotation in a class:

class Person {
    @Range(min=1, max=20)
    public String name;
}

Defining an annotation by itself has no effect on the program logic. We must write our own code to use the annotation. Here we write a checking method:

void check(Person p) throws IllegalArgumentException, ReflectiveOperationException {
	for (Field f : p.getClass().getFields()) {
		Range range = field.getAnnotation(Range.class);
        if (range != null) {
            Object value = field.get(p);
            if (value instanceof String) {
                if (s.length() < range.min() || s.length > range.max()) {
                    throw new IllegalArgumentException("Invalid field: " + field.getName());
                }
            }
        }
	}
}

Generics

What Are Generics

Actually pretty much the same as C++; there is not much to say about the concept itself.

Note the issue of upcasting here: ArrayList<T> can be upcast to List<T>, but you cannot upcast ArrayList<Integer> to ArrayList<Number> or List<Number>.

Using Generics

When using ArrayList, if you do not use generics, the so-called T will be Object:

List list = new ArrayList();
list.add("Hello");
String first = (String) list.get(0);

But after defining a generic type, the type is also strongly defined.

If the compiler can automatically infer the generic type, the generic type afterwards can be omitted, for example

List<String> list = new ArrayList<String>();

can be abbreviated as

List<String> list = new ArrayList<>();

Generic Interfaces

Arrays.sort(Object[]) can sort any array, but the elements to be sorted must implement the generic interface Comparable<T>:

public interface Comparable<T> {
    /**
     * 返回负数:当前实例比参数 o 小
     * 返回 0: 当前实例与参数 o 相等
     * 返回正数:当前实例比参数 o 大
     */
    int compareTo(T o);
}

Here, checking whether the interface is implemented is done via reflection, using isAssignableFrom().

Writing Generics

There is not much to say about simply writing them; the principles are similar to C++.

Static Methods

The generic type <T> cannot be used in static methods, but you can separately rewrite it as another generic type for the static method:

public class A<T> {
    private T a;
    public A(T a) {
        this.a = a;
    }
    public static <K> A<K> create(K a) {
        return new A<K>(a);
    }
}

Actually, writing the declaration as public static <T> A<T> create(T a) would also work, but this T has nothing to do with the T above; only by using different names can the static method's generic type be clearly distinguished from the instance type's generic type.

Multiple Generic Types

For example:

public class Map <K, V> {}

Type Erasure

So-called "type erasure" is the way the Java language implements generics.

Type erasure means that the virtual machine knows nothing about generics; all the work is done by the compiler.

In short, in the eyes of the virtual machine, all T in the code it sees are Object, and the compiler performs safe casts based on <T>.

From this, we can see that Java generics have the following limitations:

  1. <T> cannot be a primitive type, which is why we have wrapper classes like Integer.

  2. You cannot obtain a Class object with generics (in reflection). For all generic instances, no matter what the type of T is, getClass() returns the same Class instance, because after compilation they are all Pair<Object>.

  3. You cannot determine a type with generics: you can only check p instanceof Pair but not p instanceof Pair<String>.

  4. You cannot instantiate a generic type in code:

    public class Pair<T> {
        ...
        first = new T(); // compile error
    }

    Because after erasure it would become new Object(), which would be the case for any T, which is unreasonable, so the compiler will prevent it.

    However, you can use reflection to instantiate T:

    public class Pair<T> {
        private T first;
        private T last;
        public Pair(Class<T> clazz) {
            first = clazz.getDeclaredConstructor().newInstance();
            last = clazz.getDeclaredConstructor().newInstance();
        }
    }

    When using it, pass in Class<T>:

    Pair<String> pair = new Pair<>(String.class);

    Note: the reason Class<T> works here is that the Class class itself is also a class that supports generics; for example, String.class is actually Class<String>.

Generic Inheritance

A class can inherit from a generic class, for example written like this:

public class IntPair extends Pair<Integer> {}

As mentioned before, we cannot obtain the T type of Pair<T>; that is, given a variable Pair<Integer> p, we cannot get the Integer type from p.

To explain this: due to type erasure, at runtime only Pair exists, not Pair<Integer>. Of course, you can also understand it from the perspective of reflection on Class.

However, when the parent class is a generic type, the compiler must save the type T (for IntPair, that is, the Integer type) into the subclass's class file; otherwise the compiler would not know that IntPair can only store and retrieve the Integer type.

When inheriting from a generic type, the subclass can obtain the parent class's generic type:

Class<IntPair> clazz = IntPair.class;
Type t = clazz.getGenericSuperclass();
if (t instanceof ParameterizedType) {
    ParameterizedType pt = (ParameterizedType) t;
    Type[] types = pt.getActualTypeArguments();
    Type firstType = types[0];
    Class<?> typeClass = (Class<?>) firstType;
    System.out.println(typeClass); // Integer
}

If you can't understand this, to be filled in later.

extends Wildcards

Suppose we write a static method that takes a parameter Pair<Number>:

public static int add(Pair<Number> p) {
    return p.getFirst().intValue() + p.getSecond().intValue();
}

Then, using it like this:

add(new Pair<Number>(1, 2));

compiles fine, because although we wrote Number, the actual values 1 and 2 passed in are Integer.

Now, suppose we use it like this:

add(new Pair<Integer>(1, 2));

it no longer compiles, because of type erasure: Pair<Integer> is not a subclass of Pair<Number>.

But we do have the need to pass in its "subclasses", so we introduce the extends wildcard.

public static int add(Pair<? extends Number> p) {
	return p.getFirst().intValue() + p.getSecond().intValue();
}

This makes the method accept all Pair types whose generic type is Number or a subclass of Number.

This kind of generic definition using <? extends Number> is called an Upper Bounds Wildcard, i.e., the upper bound of the generic type T is limited to Number.

Regarding the requirements for assignment and the like with a type of <? extends Number> (abbreviated as X below): you can only read, not write.

Specifically, if there is a method signature Pair<? extends Number> getFirst(), it can be used safely; if the method signature is Pair<? extends Number> setFirst(), it cannot be used safely.

Here null is an exception; passing it in is allowed.

For example, suppose the original value was a Double, and I pass in an Integer; both satisfy <? extends Number>, but in fact they are not compatible.

Purpose of the extends Wildcard

For example, define a method like this:

int sumOfList(List<? extends Integer> list) {
    int sum = 0;
    for (int i=0; i<list.size(); i++) {
        Integer n = list.get(i);
        sum = sum + n;
    }
    return sum;
}

By using the extends wildcard, the use of the set method on list is prevented, indicating that this method is read-only and does not modify.

(Except for maliciously calling set(null).)

You can also use extends to restrict the T type.

super Wildcards

The opposite of the extends wildcard: it can accept this type as well as this type's parent classes.

Using the <? super Integer> wildcard means:

  • Calling the set(? super Integer) method with an Integer reference is allowed;
  • Calling the get() method to obtain an Integer reference is not allowed.

The only exception is that you can obtain an Object reference: Object o = p.getFirst().

In other words, using the <? super Integer> wildcard as a method parameter means that the code inside the method can only write to the parameter, not read from it.

Comparing with the extends wildcard, one is read-only and not writable, the other is write-only and not readable, except for passing in null and obtaining Object.

For example:

public class Collections {
    // 把 src 的每个元素复制到 dest 中:
    public static <T> void copy(List<? super T> dest, List<? extends T> src) {
        for (int i=0; i<src.size(); i++) {
            T t = src.get(i);
            dest.add(t);
        }
    }
}

Through different wildcards, reading and writing are restricted.

Another benefit is that you can safely add a List<Integer> to a List<Number>, but not the other way around.

The PECS Principle

Used to determine when to use the extends wildcard and when to use the super wildcard.

Producer Extends Consumer Super

If you need to return T, it is a producer (Producer), and you should use the extends wildcard; if you need to write T, it is a consumer (Consumer), and you should use the super wildcard.

Unbounded Wildcards

For example:

void sample(Pair<?> p) {
}

You can neither read nor write; you can only do some null checks.

The <?> wildcard has a unique characteristic: Pair<?> is the superclass of all Pair<T>.

Generics and Reflection

Part of Java's reflection API is also generic.

For example, Class<T> is generic, and Class<String> is equivalent to String.class.

Constructors are also generic.

We can declare arrays with generics, but we cannot create arrays with generics using the new operator:

Pair<String>[] ps = null; // ok
Pair<String>[] ps = new Pair<String>[2]; // compile error!

We must create arrays with generics through casting:

@SuppressWarnings("unchecked")
Pair<String>[] ps = (Pair<String>[]) new Pair[2];

We cannot directly create a generic array T[], because after erasure the code becomes Object[]:

// compile error:
public class Abc<T> {
    T[] createArray() {
        return new T[5];
    }
}

We must use Class<T> to create a generic array:

T[] createArray(Class<T> cls) {
    return (T[]) Array.newInstance(cls, 5);
}

Do not (use with caution) generic varargs, returning parameters to create generic variable arrays, and in general use generic varargs with caution.

The essence is still type erasure; in the eyes of the JVM, they are all Object[].

Collections

Introduction to Java Collections

The java.util package mainly provides three types of collections: List, Set, Map.

The Collection interface is the root interface of all other collection classes except Map.

A small number of collection classes are legacy classes and should no longer be used:

  • Hashtable: a thread-safe Map implementation;
  • Vector: a thread-safe List implementation;
  • Stack: a LIFO stack implemented based on Vector.

There are also a few legacy interfaces that should no longer be used:

  • Enumeration<E>: has been replaced by Iterator<E>.

Using List

Examining the List<E> interface, we can see several main interface methods:

  • Add an element at the end: boolean add(E e)
  • Add an element at a specified index: boolean add(int index, E e)
  • Remove the element at a specified index: E remove(int index)
  • Remove a certain element: boolean remove(Object e)
  • Get the element at a specified index: E get(int index)
  • Get the size of the list (the number of elements it contains): int size()

There are ArrayList and LinkedList.

List allows adding null.

You can also use the of method to quickly create a List:

List<Integer> list = List.of(1, 2, 5);

But what is created this way is neither an ArrayList nor a LinkedList, but an immutable short array, internally implemented sequentially.

Iterating Over a List

You can iterate using the form for(int i = 0; i < n; i++), but this is only efficient for ArrayList.

Stick to using the iterator Iterator to access a List; the for-each loop also uses Iterator internally.

Converting Between List and Array

There are three ways to convert a List to an Array:

  1.  List<String> list = List.of("apple", "pear", "banana");
     Object[] array = list.toArray();
     // 由于会损失类型信息所以应用很少
     
    
    2. ```java
        List<String> list = List.of("apple", "pear", "banana");
        String[] array = list.toArray(new String[3]);
  2. The functional style, introduced later; to be filled in later.

To convert an Array to a List: use the List.of(...) method.

Writing the equals Method

Must satisfy reflexivity, symmetry, transitivity, consistency, and always return false for null.

Using Map

put, contains, get

For a Map, to iterate over the key values, you can use a for each loop to iterate over the Set collection returned by the keySet() method of the Map instance:

Map<Integer, String> map = new HashMap<>();
...
for(Integer k : map.keySet()) {
    String v = map.get(k);
}

To iterate over both key and value entries at the same time, you can use a for each loop to iterate over the entrySet() collection of the Map object, which contains every key-value mapping:

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    String key = entry.getKey();
    Integer value = entry.getValue();
    System.out.println(key + " = " + value);
}

Writing the hashCode Method

There is not much to say about this; we learned quite a bit in CS61B.

Using EnumMap

If the object used as a key is of enum type, you can also use an EnumMap provided by the Java collection library. It stores values internally in a very compact array and directly locates the index of the internal array based on the enum-typed key, without needing to compute hashCode(). It is not only the most efficient but also has no extra space waste.

For example:

public class Main {
    public static void main(String[] args) {
        Map<DayOfWeek, String> map = new EnumMap<>(DayOfWeek.class);
        map.put(DayOfWeek.MONDAY, "星期一");
        map.put(DayOfWeek.TUESDAY, "星期二");
        map.put(DayOfWeek.WEDNESDAY, "星期三");
        map.put(DayOfWeek.THURSDAY, "星期四");
        map.put(DayOfWeek.FRIDAY, "星期五");
        map.put(DayOfWeek.SATURDAY, "星期六");
        map.put(DayOfWeek.SUNDAY, "星期日");
        System.out.println(map);
        System.out.println(map.get(DayOfWeek.MONDAY));
    }
}

Using TreeMap

A Map that sorts keys internally implements the SortedMap interface, and TreeMap is such a Map.

The keys put in must implement the Comparable interface, or a custom sorting algorithm must be specified when creating the SortedMap (by passing in your own implementation of the Comparator interface):

public class Main {
    public static void main(String[] args) {
        Map<Person, Integer> map = new TreeMap<>(new Comparator<Person>() {
            public int compare(Person p1, Person p2) {
                return p1.name.compareTo(p2.name); // compareTo 是 Comparable 接口的方法
            }
        })
    }
}

class Person {
	public String name;
    public int age;
}

Comparator is an interface:

public interface Comparator<T> {
    int compare(T o1, T o2);
}

What is passed in here is an anonymous inner class.

Note that the Key here does not override the equals() method, because the comparison in TreeMap does not depend on it, but on the compare method or compareTo.

Implementing compareTo or compare

If a<b, return a negative number; if a>b, return a positive number; if a.equals(b), return 0.

Using Properties

Java's default configuration files use the .properties extension, with each line expressed as key=value, which can be represented by Map<String, String>. Because configuration files are very common, the Java collection library provides a Properties to represent a set of "configurations".

# setting.properties

last_open_file=/data/hello.txt
auto_save_interval=60

Usage example:

String f = "setting.properties";
Properties props = new Properties();
props.load(new java.io.FileInputStream(f));

String filepath = props.getProperty("last_open_file");
String interval = props.getProperty("auto_save_interval", "120");
props.setProperty("language", "Java");

Using Set

  • Add an element to Set<E>: boolean add(E e)
  • Remove an element from Set<E>: boolean remove(Object e)
  • Check whether an element is contained: boolean contains(Object e)

Using Queue

The queue interface Queue defines the following methods:

  • int size(): get the length of the queue;
  • boolean add(E)/boolean offer(E): add an element to the tail of the queue;
  • E remove()/E poll(): get the head element and remove it from the queue;
  • E element()/E peek(): get the head element but do not remove it from the queue.

Note that adding, removing, and getting queue elements always come in two methods; this is because when adding or getting an element fails, the behavior of the two methods is different. We summarize in a table as follows:

throw Exception return false or null
Add element to tail add(E e) boolean offer(E e)
Get head element and remove E remove() E poll()
Get head element without removing E element() E peek()

Note: do not add null to a queue; otherwise, when the poll() method returns null, it is difficult to determine whether a null element was retrieved or the queue is empty.

Queue is an interface, and the class implementing this interface is LinkedList.

Using PriorityQueue

The methods are the same as Queue.

It is not an interface but a class; just use new PriorityQueue<>() directly.

However, the elements passed in must either implement the Comparable interface, or a Comparator interface must be passed in when creating the PriorityQueue.

Here it is always a min-heap by default; smaller elements will come out first when calling remove or poll.

Using Deque

Queue Deque
Add element to tail add(E e) / offer(E e) addLast(E e) / offerLast(E e)
Get head element and remove E remove() / E poll() E removeFirst() / E pollFirst()
Get head element without removing E element() / E peek() E getFirst() / E peekFirst()
Add element to head none addFirst(E e) / offerFirst(E e)
Get tail element and remove none E removeLast() / E pollLast()
Get tail element without removing none E getLast() / E peekLast()

The Deque interface extends Queue! This is the opposite of C++, where std::queue is built on std::deque.

Deque is an interface, and the classes implementing this interface include ArrayDeque and LinkedList.

Using Stack

In fact, Java has no Stack interface; you can only use Deque to simulate a Stack:

  • Push an element onto the stack: push(E)/addFirst(E);
  • "Pop" the element at the top of the stack: pop()/removeFirst();
  • Get the top element without popping: peek()/peekFirst().

Using Iterator

The basis for using for-each loops is that collection classes implement the Iterable interface, which returns an Iterator object by calling the iterator() method.

An Iterator object is an object that implements the Iterator interface, which requires implementing the next() and hasNext() methods.

Using Collections

Provides a series of methods.

Collections.sort() can sort a List; a mutable List must be passed in. Collections.shuffle() takes an ordered List and can randomly shuffle the order of the elements inside the List, with the effect of having the computer shuffle the cards.

Collections also provides a set of methods to wrap mutable collections into immutable collections:

  • Wrap into an immutable List: List<T> unmodifiableList(List<? extends T> list)
  • Wrap into an immutable Set: Set<T> unmodifiableSet(Set<? extends T> set)
  • Wrap into an immutable Map: Map<K, V> unmodifiableMap(Map<? extends K, ? extends V> m)

IO

Reading and writing file contents; to be filled in later.

Date and Time

It feels like just a bunch of APIs; to be filled in later.

Unit Testing

Writing JUnit Tests

Test-driven development: first write the interface, then immediately write the tests. Only after the tests are written do we start actually writing the implementation code.

package com.itranswarp.learnjava;

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class FactorialTest {

    @Test
    void testFact() {
        assertEquals(1, Factorial.fact(1));
        assertEquals(2, Factorial.fact(2));
        assertEquals(6, Factorial.fact(3));
        assertEquals(3628800, Factorial.fact(10));
        assertEquals(2432902008176640000L, Factorial.fact(20));
    }
}

Regular Expressions

To be filled in later.

Encryption and Security

To be filled in later.

Multithreading

Multithreading is the most basic concurrency model in Java.


JavaSE Note
https://blog.wendain.ing/en/posts/java-note/
Author
wendaining
Posted on
February 7, 2026
Updated on
February 19, 2026
Licensed under