| Dimension | JIT (Just-in-Time Compilation) | AOT (Ahead-of-Time Compilation) |
|---|---|---|
| Compilation timing | Runtime compilation | Pre-runtime compilation |
| Startup speed | Slower (requires warm-up) | Faster (no warm-up needed) |
| Peak performance | Higher (runtime optimizations) | Lower (lacks runtime info) |
| Memory usage | Higher | Lower |
| Package size | Smaller | Larger (includes machine code) |
| Dynamic feature support | Fully supported | Limited (reflection, dynamic proxies, etc.) |
| Use cases | Long-running services | Cloud-native, Serverless, CLI tools |
The main advantages of AOT lie in startup time and memory usage, while JIT provides higher peak performance and can reduce maximum request latency.
Due to its ahead-of-time nature, AOT cannot support technologies like Spring and ASM. When dynamic features are required, JIT compilation should be used.
It is a common misconception that primitive data types are always stored on the stack. Their storage location depends on their scope and declaration. If they are local variables, they are stored on the stack; if they are member variables, they are stored in the heap/method area/metaspace.
Computers use binary representation, and numbers have limited precision. Infinite repeating decimals must be truncated when stored, leading to precision loss.
BigDecimal can perform precise floating-point calculations without precision loss. It is commonly used in scenarios requiring exact results (e.g., financial calculations).
Static variables are variables modified by the static keyword. They are shared across all instances of a class. No matter how many objects are created, they share the same static variable. Static variables are allocated only once, saving memory.
/**
* native method that returns the Class object of the current runtime object.
* It is final and cannot be overridden.
*/
public final native Class<?> getClass()
/**
* native method that returns the hash code of the object, mainly used in hash tables like HashMap.
*/
public native int hashCode()
/**
* Compares whether two objects have the same memory address.
* String overrides this method to compare values instead.
*/
public boolean equals(Object obj)
/**
* native method that creates and returns a copy of the object.
*/
protected native Object clone() throws CloneNotSupportedException
/**
* Returns a hexadecimal string of the object's hash code.
* It is recommended to override this method.
*/
public String toString()
/**
* native method that wakes up a single thread waiting on this object's monitor.
*/
public final native void notify()
/**
* native method that wakes up all threads waiting on this object's monitor.
*/
public final native void notifyAll()
/**
* native method that causes the current thread to wait.
* Note: sleep does not release locks, but wait does.
*/
public final native void wait(long timeout) throws InterruptedException
/**
* Additional nanoseconds parameter.
*/
public final void wait(long timeout, int nanos) throws InterruptedException
/**
* Waits indefinitely.
*/
public final void wait() throws InterruptedException
/**
* Called when the object is garbage collected.
*/
protected void finalize() throws Throwable { }
hashCode() is used to obtain the hash value, which determines the object’s position in a hash table.
When adding an object to a HashSet:
hashCode() is called to determine the bucket.equals():
If two objects are equal according to equals(), they must have the same hashCode(). Otherwise, collections like HashSet may behave incorrectly.
Modifying a String creates a new object. StringBuffer and StringBuilder modify the same object instead.
Both extend AbstractStringBuilder:
// 1. Check if "ab" exists in the string constant pool; if not, create it
// 2. Assign reference to aa
String aa = "ab";
// Directly return the reference from the pool
String bb = "ab";
System.out.println(aa==bb); // true
The parent class of all exceptions in Java is java.lang.Throwable, which has two important subclasses:
VirtualMachineError, OutOfMemoryError, NoClassDefFoundError, etc.Except for RuntimeException and its subclasses, all other Exception classes and their subclasses are checked exceptions. Common checked exceptions: IO‑related exceptions, ClassNotFoundException, SQLException.
Unchecked Exception – the code can compile successfully even if we do not handle them. RuntimeException and its subclasses are all unchecked exceptions. Common examples:
NullPointerExceptionIllegalArgumentException (e.g., wrong parameter type)NumberFormatException (subclass of IllegalArgumentException, thrown when string‑to‑number conversion fails)ArrayIndexOutOfBoundsExceptionClassCastExceptionArithmeticExceptionSecurityException (e.g., insufficient permissions)UnsupportedOperationException (e.g., duplicate user creation)// The resource must implement java.lang.AutoCloseable or java.io.Closeable.
// Multiple resources are separated by semicolons.
try (Scanner scanner = new Scanner(new File("test.txt"))) {
// use resource
} catch (Exception e) {
// handle exception
}
| Feature | Traditional try-catch-finally | try-with-resources |
|---|---|---|
| Code volume | Verbose | Concise |
| Resource closing | Manual, easy to miss | Automatic, compile‑time guarantee |
| Exception handling | Closing exception may mask primary exception | Closing exceptions are suppressed, primary exception preserved |
| Readability | Poor (closing logic scattered) | High (resource management centralized) |
new a new exception object.NumberFormatException instead of its parent IllegalArgumentException.
List
ArrayList: Object[] arrayVector: Object[] arrayLinkedList: doubly linked listSet
HashSet: backed by HashMap, unordered and unique.LinkedHashSet: subclass of HashSet, internally uses LinkedHashMap.TreeSet: red‑black tree, ordered and unique.Queue
PriorityQueue: priority queue.DelayQueue: delayed queue.ArrayDeque: resizable dynamic double‑ended array.Map
HashMap: array + linked list; when list length exceeds threshold (default 8), linked list converts to red‑black tree.LinkedHashMap: extends HashMap, adds a doubly linked list to maintain insertion order.Hashtable: array + linked list.TreeMap: red‑black tree.ArrayList and arraysArrayList dynamically grows and shrinks; arrays have fixed size after creation.ArrayList supports generics for type safety; arrays do not.ArrayList can only store objects (use wrapper classes for primitives); arrays can store primitive types directly.ArrayList supports insertion, deletion, traversal, etc.; arrays only support index‑based access.ArrayList does not require size specification at creation; arrays do.ArrayListInsertion:
Deletion:
LinkedList