š Java Fundamentals
1. What Are the Key Features of Java?
Understanding the core characteristics of the Java language
- Object-Oriented: Supports encapsulation, inheritance, and polymorphism
- Platform Independence: Write Once, Run Anywhere (WORA)
- Automatic Memory Management: Garbage collection automatically releases memory
- Multi-threaded Support: Built-in threading mechanism facilitates concurrent programming
- Strong Security: Provides type checking, exception handling, and other security mechanisms
- Dynamic Features: Runtime type checking and dynamic class loading
2. What Is the Difference Between JDK, JRE, and JVM?
Understanding the three-layer structure of the Java runtime environment
- JVM (Java Virtual Machine): Virtual machine that executes bytecode, an abstract computing machine that implements cross-platform features
- JRE (Java Runtime Environment): Runtime environment containing JVM and necessary class libraries for execution
- JDK (Java Development Kit): Development toolkit containing JRE plus compiler, debugger, and other development tools
- Containment Relationship: JDK > JRE > JVM
3. What Is Bytecode? Why Can Java Run Across Platforms?
Deeply understanding the principles behind Java's cross-platform capability
- Bytecode Definition: Intermediate code generated from compiling Java source code, with file extension .class
- Cross-Platform Principle: Java source code ā Bytecode ā Execution by JVM on different platforms
- Advantage: Compile once, run anywhere; developers do not need to rewrite code for different platforms
- Execution Process: javac compiler compiles .java files into .class files, which are then interpreted and executed by each platform's JVM
4. What Are the Primitive Data Types in Java?
Mastering Java's type system
- Integer Type: byte (1 byte), short (2 bytes), int (4 bytes), long (8 bytes)
- Floating-Point Type: float (4 bytes), double (8 bytes)
- Character Type: char (2 bytes, supports Unicode)
- Boolean Type: boolean (1 byte, true/false)
- Default Values: Integer 0, floating-point 0.0, boolean false, char '\u0000'
- Wrapper Classes: Integer, Long, Float, Double, Boolean, and corresponding reference types
5. What Is the Difference Between final, finally, and finalize?
Distinguishing between three similar but completely different concepts
- final (Keyword): Modifying a class prevents inheritance, modifying a method prevents overriding, modifying a variable prevents reassignment
- finally (Keyword): Code block in try-catch-finally that executes regardless of exceptions, commonly used for resource release
- finalize (Method): Method of the Object class called before an object is garbage collected, used for resource cleanup (now deprecated)
- Application Scenarios: final for immutability control, finally for exception safety, finalize replaced by try-with-resources
šÆ Object-Oriented Programming
6. What Is Object-Oriented Programming? What Are the Four Key Characteristics?
Understanding the core concepts of OOP
- Object-Oriented Definition: Programming paradigm centered on objects, emphasizing object attributes and behaviors
- Four Key Characteristics:
- Abstraction: Extracting common characteristics of things while ignoring non-essential details
- Encapsulation: Hiding internal implementation details while exposing necessary interfaces, enhancing security
- Inheritance: Subclasses inherit attributes and methods from parent classes, achieving code reuse
- Polymorphism: Different implementations of the same interface with dynamic binding at runtime
7. What Is Polymorphism? What Are the Ways to Implement Polymorphism?
Deeply understanding Java's polymorphism mechanism
- Polymorphism Definition: An object possesses multiple forms; the same method call exhibits different behaviors on different objects
- Implementation Methods:
- Compile-Time Polymorphism (Overloading): Same method name with different parameters, determined at compile time
- Runtime Polymorphism (Overriding): Parent class reference pointing to child class object, method determined at runtime
- Runtime Polymorphism Conditions: Inheritance, overriding, upcasting
- Advantage: Improves code flexibility and maintainability, supports interface-based programming
8. What Is the Difference Between Interfaces and Abstract Classes?
Comparing the similarities and differences between two abstraction mechanisms
- Abstract Class: Modified by abstract keyword, can have both abstract and concrete methods
- Interface: Defined using interface keyword, methods default to public abstract (Java 8+ supports default implementations)
- Inheritance Relationship: A class can only inherit from one abstract class, but can implement multiple interfaces
- Access Modifiers: Abstract classes can use private/protected, interface members default to public
- Variables: Abstract classes have instance variables, interfaces only have static constants
- Use Cases: Abstract classes for code sharing, interfaces for defining specifications
9. What Is the Difference Between Overloading (Overload) and Overriding (Override)?
Distinguishing between two similar but different concepts
- Overloading:
- Same method name in the same class, different parameter types/counts/order
- Determined at compile time, belongs to static binding
- Return type can differ (but cannot be distinguished solely by return type)
- Overriding:
- Subclass reimplements parent class method with identical method signature
- Determined at runtime, belongs to dynamic binding
- Return type and exceptions must be compatible
10. What Are the Access Modifiers? What Is Their Scope?
Mastering Java's access control mechanism
- public: Public, accessible by all classes
- protected: Protected, accessible by same package and subclasses
- default (no modifier): Default, accessible within the same package
- private: Private, accessible only within the class
- Access Scope Comparison: public > protected > default > private
- Best Practice: Minimize access privileges, adhere to encapsulation principles
š¾ Memory Management and Garbage Collection
11. What Does Java Memory Structure Include?
Understanding JVM memory allocation
- Heap: Stores object instances, shared by all threads, primary area for garbage collection, configurable size
- Stack: Stores local variables and method calls, each thread has its own stack, automatically releases memory
- Method Area: Stores class structure information, runtime constant pool, static variables, etc., shared by all threads
- Program Counter: Records the current thread's bytecode instruction address
- Native Method Stack: Executes native methods (C/C++ code)
12. What Is Garbage Collection? What Are the Garbage Collection Algorithms?
Deeply understanding GC mechanism
- Garbage Collection Definition: Automatically reclaiming memory occupied by objects no longer in use
- Main Algorithms:
- Mark-Sweep: Mark alive objects, sweep garbage, produces fragmentation
- Copying Algorithm: Divide memory into two blocks, copy alive objects during cleanup, no fragmentation but wastes memory
- Mark-Compact: Mark then compress, no fragmentation but lower performance
- Generational Algorithm: Objects divided into young and old generations, different strategies for each generation
- Advantage: Automatic memory management, prevents memory leaks
13. What Is the Difference Between Heap and Stack?
Comparing two important memory regions
- Storage Content: Heap stores objects, stack stores primitive types and references
- Thread: Heap shared by all threads, each thread has independent stack
- Management: Heap managed by garbage collector, stack automatically released
- Size: Heap generally larger, stack relatively smaller
- Performance: Stack allocation fast, heap allocation relatively slow
- Exception: Heap overflow OutOfMemoryError, stack overflow StackOverflowError
14. What Is Memory Leak? How to Prevent It?
Recognizing common memory issues
- Memory Leak Definition: Program-allocated memory cannot be released, continuously occupying memory
- Common Causes:
- Long-lived objects holding references to short-lived objects
- Objects in collections not timely cleaned
- Listeners or callbacks not unregistered
- Static collections growing indefinitely
- Prevention Methods: Promptly release references, use try-with-resources, regularly monitor memory usage
15. What Are Strong References, Soft References, Weak References, and Phantom References?
Understanding Java's four reference types
- Strong Reference: Normal reference, object not recycled until no strong references remain
- Soft Reference (SoftReference): Recycled when memory is insufficient, used for caching
- Weak Reference (WeakReference): Recycled at next garbage collection, used in WeakHashMap
- Phantom Reference (PhantomReference): Recyclable at any time, must be used with reference queue, used for tracking object collection
- Collection Priority: Phantom Reference > Weak Reference > Soft Reference > Strong Reference
š¦ Collections Framework
16. What Is the Structure of Java Collections Framework?
Mastering the overall concept of the collections framework
- Collection Interface:
- List: Ordered and allows duplicates, such as ArrayList, LinkedList
- Set: Unordered and does not allow duplicates, such as HashSet, TreeSet
- Queue: Queue structure, such as LinkedList, PriorityQueue
- Map Interface:
- Key-Value Mapping: HashMap, TreeMap, ConcurrentHashMap
- Overall Hierarchy: Iterable ā Collection/Map ā Concrete Implementation Classes
17. What Is the Difference Between ArrayList and LinkedList?
Comparing two common list implementations
- Data Structure: ArrayList based on array, LinkedList based on doubly-linked list
- Random Access: ArrayList O(1), LinkedList O(n)
- Insertion/Deletion: ArrayList O(n), LinkedList O(1)
- Memory Usage: ArrayList contiguous, LinkedList scattered (pointer overhead)
- Thread Safety: Neither synchronized, can use Collections.synchronizedList() or CopyOnWriteArrayList
- Selection: Use ArrayList for frequent queries, LinkedList for frequent insertions/deletions
18. What Is the Principle and Performance of HashMap?
Deeply understanding HashMap's working mechanism
- Data Structure: Array + Linked List + Red-Black Tree (JDK 8+)
- Working Principle: hash(key) % table.length calculates array index, collisions linked or treeified
- Load Factor: Default 0.75, expansion occurs when used capacity ā„ capacity Ć load factor
- Expansion Mechanism: Capacity doubles, elements rehashed to new positions
- Time Complexity: Average O(1), worst O(n) (with many collisions)
- Thread Safety: Not synchronized, use ConcurrentHashMap for multithreading or Collections.synchronizedMap()
19. How Does HashSet Ensure No Duplicates?
Understanding Set's deduplication mechanism
- Underlying Implementation: Based on HashMap, key is element, value is fixed Object
- Deduplication Mechanism: First compare hashCode(), then use equals() to determine equality
- Addition Process: Calculate hash ā Check if exists ā Add if not ā Ignore if exists
- Custom Objects: Must override equals() and hashCode(), ensure consistency
- Performance: Addition, deletion, lookup average O(1), depends on hash quality
20. What Are fail-fast and fail-safe?
Understanding collection iterator safety mechanisms
- fail-fast:
- Modifying collection during iteration throws ConcurrentModificationException
- Detected through modCount and expectedModCount
- Examples: ArrayList, HashMap (non-thread-safe)
- fail-safe:
- Iteration based on collection snapshot or copy, modifying original collection does not affect iteration
- Examples: CopyOnWriteArrayList, ConcurrentHashMap
- Usage Recommendation: Use iterator's remove() during iteration, or use fail-safe collections
ā ļø Exception Handling
21. What Is Java's Exception Hierarchy?
Understanding Java exception classification
- Throwable (Root Class):
- Exception (Exception): Recoverable exceptions
- Error (Error): Virtual machine-level errors, not recoverable
- Exception Classification:
- Checked Exception: Must be caught or declared, such as IOException
- Unchecked Exception: Need not be caught, such as NullPointerException, IndexOutOfBoundsException
- Common Exceptions: NPE, ClassCastException, ArrayIndexOutOfBoundsException, etc.
22. What Is the Execution Order of try-catch-finally?
Mastering exception handling execution flow
- Normal Case: try ā finally ā Normal return
- Exception Case: try ā Exception occurs ā catch ā finally ā Exception propagates or returns
- finally Characteristic: Always executes, even if catch has return, throw, System.exit()
- Exception Case: finally return will override try/catch return
- Resource Release: Recommended using try-with-resources, automatically closes resources
- Best Practice: Do not change return value in finally, will cause exception loss
23. What Is the Difference Between throws and throw?
Distinguishing between two exception handling keywords
- throw:
- Manually throws an exception instance, must be used within method
- Format: throw new Exception("message")
- throws:
- Declares possible exceptions in method signature
- Format: public void method() throws IOException
- Handling Method: throw declared by throws, throws handled by caller
- Application: throw for specific exception handling, throws for exception propagation
24. How to Create Custom Exceptions?
Creating project-specific exception classes
- Inheritance Relationship: Extend Exception (checked exception) or RuntimeException (unchecked exception)
- Required Components:
- Provide no-argument constructor
- Provide constructor with message parameter
- Provide constructor with message and cause parameters
- Code Example: public class CustomException extends Exception { ... }
- Best Practice: Clear naming, clear documentation, inherit appropriate exception class
25. What Are the Benefits of try-with-resources Syntax?
Understanding automatic resource management
- Syntax: try (InputStream is = ...) { ... } automatically closes resources
- Requirement: Resources must implement AutoCloseable interface
- Advantage:
- Automatically calls close() method, no manual management needed
- Correctly handles suppressed exceptions when exceptions occur
- Code more concise, prevents resource leaks
- Applicable Scenarios: File, Stream, Connection, Statement, and other resource classes
š¤ String, StringBuilder, StringBuffer
26. What Is String Immutability and Why?
Understanding the deep design considerations of String
- Immutability Definition: String object cannot be modified after creation; any modification operation returns a new object
- Implementation Method: value array modified by final keyword, no setter method
- Immutability Reasons:
- String pool optimization, avoids duplicate creation
- Thread safe, no synchronization needed
- Supports hashCode caching, suitable as HashMap key
- Disadvantage: Frequent modifications create many intermediate objects
27. What Is the Difference Between String, StringBuilder, and StringBuffer?
Choosing appropriate string manipulation classes
- String: Immutable, thread safe, poor performance (frequent modifications)
- StringBuilder: Mutable, non-thread-safe, excellent performance (single-threaded)
- StringBuffer: Mutable, thread safe (synchronized methods), moderate performance (multi-threaded)
- Performance Comparison: StringBuilder > StringBuffer > String
- Usage Recommendation:
- Use StringBuilder for single-threaded string concatenation
- Use StringBuffer for multi-threaded string concatenation
- Use String when no modifications needed
28. What Is the String Constant Pool?
Understanding string caching mechanism
- Definition: JVM-maintained string cache storing string literals
- Location: JDK 7+ in heap, previously in method area
- Creation Mechanism:
- Literals like "abc" automatically enter the pool
- new String("abc") adds "abc" to pool if not already present
- intern() Method: Adds string to pool or returns existing reference
- Optimization Effect: Saves memory, accelerates string comparison
29. How to Compare String Equality?
Mastering string comparison methods
- == Comparison: Compares whether references are the same, does not compare content
- equals() Comparison: Compares whether string content is the same, recommended usage
- equalsIgnoreCase() Comparison: Compares content ignoring case
- compareTo() Comparison: Lexicographic comparison, returns integer
- Objects.equals(): Safe comparison handling null values
- Best Practice: Use equals() for string content comparison, avoid using ==
30. What Are the Performance Issues of String Concatenation?
Optimizing string concatenation performance
- Issue: String s = "a" + "b" + "c" creates multiple intermediate objects and copies
- Reason: String immutability, each concatenation creates new object
- Performance Impact: Loop concatenation O(n²) time complexity
- Optimization Solutions:
- Direct + outside loop: Compiler optimizes to StringBuilder
- Explicitly use StringBuilder or StringBuffer
- Use String.join(), StringJoiner and other utility tools
š Multi-threading and Concurrency
31. What Is a Thread? How to Create a Thread?
Mastering basic thread concepts and creation methods
- Thread Definition: Independent execution flow within process, shares memory but has independent stack
- Creation Methods:
- Extend Thread: public class MyThread extends Thread { public void run() {} }
- Implement Runnable: public class MyRunnable implements Runnable { public void run() {} }
- Implement Callable: Return value and exception support
- Difference: Runnable recommended, avoids single inheritance limitation
- Starting: Call thread.start(), cannot directly call run()
32. What Are Thread Life Cycle and States?
Understanding thread state transitions
- NEW: Thread created but not started
- RUNNABLE: Runnable state (waiting for execution or executing)
- BLOCKED: Blocked state, waiting to acquire lock
- WAITING: Waiting state, waiting for other thread notification
- TIMED_WAITING: Waiting for specified time period
- TERMINATED: Thread terminated
- State Transitions: NEW ā RUNNABLE ā BLOCKED/WAITING ā TERMINATED
33. How Does synchronized Work?
Understanding Java's built-in lock mechanism
- Synchronization Mechanism: Uses object's built-in lock to implement synchronization
- Usage Methods:
- Synchronized Method: public synchronized void method() {}
- Synchronized Block: synchronized(obj) { ... }
- Working Principle:
- Each object has built-in monitor
- Thread acquires lock to enter critical section, mutual exclusion execution
- Bytecode: monitorenter, monitorexit
- Characteristics: Reentrant, exclusive, automatic release
34. What Is the Function of volatile Keyword?
Understanding memory visibility and instruction reordering prevention
- Function:
- Visibility: Ensures modifications immediately visible to other threads
- Prevent Reordering: Prevents compiler and CPU reordering optimization
- Implementation: Memory barriers, force main memory read/write
- Limitation: Cannot guarantee atomicity, cannot replace synchronized
- Application Scenarios: Flag variables, double-checked singleton, status marks
- Comparison with synchronized: volatile lighter weight but limited functionality
35. What Are wait(), notify(), and notifyAll()? What Are the Differences?
Mastering inter-thread communication mechanism
- wait():
- Current thread releases lock and enters waiting, until notified
- Must be called within synchronized block
- notify():
- Wakes one waiting thread (randomly selected)
- Does not release lock, lock released after synchronized block ends
- notifyAll():
- Wakes all waiting threads
- Usage Pattern: Producer-Consumer pattern, monitor pattern
š” Interview Preparation Recommendations
Deepen Fundamentals: Not just knowing concepts, but understanding principles and implementation details
Practice More: Consolidate knowledge through coding practice, especially multi-threading and concurrency related
Read Source Code: Study Java library source code (collections, concurrency, etc.) to deepen understanding
Focus on Details: Master common pitfalls and best practices, such as string comparison, collection modification
Explain with Examples: Use specific examples to explain concepts during interviews, enhance expressiveness