📚Java basics
1. What are the characteristics of Java?
Understand the core features of the Java language
- Object-oriented:Supports features such as encapsulation, inheritance, and polymorphism
- Platform independence:Write Once, Run Anywhere (WORA)
- Automatic memory management:Garbage collection mechanism automatically releases memory
- Multi-threading support:Built-in thread mechanism to facilitate concurrent programming
- Strong security:Provide security mechanisms such as type checking and exception handling
- Dynamic characteristics:Runtime type checking and dynamic loading
2. What are the differences between JDK, JRE and JVM?
Understand the three-tier structure of the Java runtime environment
- JVM (Java Virtual Machine):Virtual machine, an abstract computer that executes bytecode to achieve cross-platform features
- JRE (Java Runtime Environment):Runtime environment, including JVM and class libraries necessary for running
- JDK (Java Development Kit):Development tool kit, including JRE + compiler + debugging tools and other development tools
- Inclusion relationship:JDK > JRE > JVM
3. What is bytecode? Why is Java cross-platform?
Deeply understand the principles of Java's cross-platform mechanism
- Bytecode definition:The intermediate code generated by Java source code compilation, the file extension is .class
- Cross-platform principle:Java source code → bytecode → JVM execution on different platforms
- Advantages:Compile once, run anywhere; developers don’t need to rewrite code for different platforms
- Execution process:The javac compiler compiles the .java file into a .class file, which is then interpreted and executed by the JVM of each platform.
4. What are the basic data types in Java?
Master Java’s type system
- Integer type:byte (1 byte), short (2 byte), int (4 byte), long (8 byte)
- Floating point type:float (4 bytes), double (8 bytes)
- Character type:char (2 bytes, supports Unicode)
- Boolean type:boolean (1 byte, true/false)
- Default value:integer 0, float 0.0, boolean false, char '\u0000'
- Packaging category:Integer, Long, Float, Double, Boolean and other corresponding reference types
5. What is the difference between final, finally and finalize?
Distinguish between three similar but completely different concepts
- final (keyword):Modified classes cannot be inherited, modified methods cannot be overridden, and modified variables cannot be reassigned.
- finally (keyword):The code block in try-catch-finally will be executed regardless of whether there is an exception, and is often used for resource release.
- finalize (method):Method of the Object class, called before the object is garbage collected, used to clean up resources (obsolete)
- Application scenarios:final is used for immutability control, finally is used for exception safety, finalize has been replaced by try-with-resources
🎯 Object-oriented programming
6. What is object-oriented? What are the four major characteristics?
Understand the core concepts of OOP
- Object-oriented definition:The idea of programming based on objects, emphasizing the properties and behaviors of objects
- Four major features:
- Abstract:Extract common features of things and ignore non-essential details
- Package:Hide internal implementation details, expose necessary interfaces, and improve security
- Inheritance:Subclasses inherit the properties and methods of the parent class to achieve code reuse
- Polymorphism:Different implementations of the same interface, dynamic binding at runtime
7. What is polymorphism? What are the ways to implement polymorphism?
In-depth understanding of Java polymorphism mechanism
- Polymorphic definition:An object has multiple forms, and the same method call has different performances on different objects.
- Implementation method:
- Compile-time polymorphism (overloading):Methods with the same name but different parameters must be called during compilation.
- Runtime polymorphism (overridden):The parent class reference points to the child class object, and the runtime determines the actual method called.
- Runtime polymorphic conditions:Inherit, rewrite, upward transformation
- Advantages:Improve code flexibility and maintainability, and support interface programming
8. What is the difference between interface and abstract class?
Compare the similarities and differences between the two abstract mechanisms
- Abstract class:Using abstract modification, there can be abstract methods and concrete methods
- Interface:Use interface definition, the default method is public abstract (Java 8+ supports default implementation)
- Inheritance relationship:A class can only inherit a single abstract class, but can implement multiple interfaces
- Access modifiers:Abstract classes can be private/protected, and interface members can be public by default.
- Variables:Abstract classes have instance variables, interfaces only have static constants
- Usage scenarios:Abstract classes are used to share code and interface definition specifications
9. What are overload and override?
Distinguish between two similar but different concepts
- Overload:
- In the same class, the method names are the same, but the parameter types/number/order are different.
- It is determined at compile time and belongs to static binding.
- Return value types can be different (but not distinguished by return value alone)
- Override:
- The subclass reimplements the method of the parent class, and the method signature is exactly the same
- Determined at runtime and belongs to dynamic binding
- Return value types and exceptions must be compatible
10. What are the access modifiers? What is the scope of action?
Master Java’s access control mechanism
- public:Public, accessible to all classes
- protected:Protected, accessible in the same package and subclasses
- default (no modifier):By default, the same package is accessible
- private:Private, only accessible within the class
- Comparison of access scope:public > protected > default > private
- Best practices:Minimize access rights and follow the principle of encapsulation
đź’ľ Memory management and garbage collection
11. What does Java memory structure include?
Understanding JVM memory allocation
- Heap:Stores object instances, shared by all threads, main area for garbage collection, configurable size
- Stack:Store local variables and method calls, unique to each thread, and automatically release memory
- Method Area:Storage class structural information, runtime constant pool, static variables, etc., are shared by all threads
- Program counter:Record the bytecode instruction address executed by the current thread
- Local method stack:Execute native method (C/C++ code)
12. What is garbage collection? What are the garbage collection algorithms?
Deep understanding of GC mechanism
- Garbage collection definition:Automatically reclaim memory occupied by objects that are no longer used
- Main algorithm:
- Mark clear:Mark live objects, clear garbage, and generate fragments
- Copy algorithm:Divide memory into two pieces and copy surviving objects during clearing. No fragmentation but waste of memory.
- Tag sorting:Compression and defragmentation after marking, no fragmentation but poor performance
- Generational algorithm:Objects are divided into new generation and old generation, and different generations use different strategies.
- Advantages:Automatic memory management to avoid memory leaks
13. What is the difference between heap and stack?
Compare two important memory areas
- Storage content:Heap objects, stack basic types and references
- Thread:The heap is shared by all threads, and each thread has an independent stack
- Management:The heap is managed by the garbage collector and the stack is automatically released
- Size:The heap is generally larger and the stack is relatively smaller.
- Performance:Stack allocation is fast, heap allocation is relatively slow
- Exception:Heap overflow OutOfMemoryError, stack overflow StackOverflowError
14. What is a memory leak? How to avoid it?
Recognize common memory problems
- Memory leak definition:The memory requested by the program cannot be released and the memory is occupied for a long time.
- Common reasons:
- Long-lived objects refer to short-lived objects
- Objects in the collection are not cleaned up in time
- Listener or callback not unregistered
- Static collection grows infinitely
- How to avoid:Release references promptly, use try-with-resources, and check memory usage regularly
15. What are strong references, soft references, weak references, and virtual references?
Understand Java’s four reference types
- Strong quote:Ordinary reference, the object is not recycled until there is no strong reference
- SoftReference:It is recycled when there is insufficient memory and is used for caching.
- Weak Reference:It will be recycled in the next GC and used for WeakHashMap
- PhantomReference:Can be recycled at any time and must be used with a reference queue to track object recycling
- Recycling priority:Virtual reference > Weak reference > Soft reference > Strong reference
📦 Collection framework
16. What is the structure of Java Collections Framework?
Master the overall concept of collection framework
- Collection interface:
- List:Ordered and repeatable, such as ArrayList, LinkedList
- Set:Unordered and non-repeating, such as HashSet, TreeSet
- Queue:Queues, such as LinkedList, PriorityQueue
- Map interface:
- Key-value pair mapping:HashMap, TreeMap, ConcurrentHashMap
- Overall level:Iterable → Collection/Map → concrete implementation class
17. What is the difference between ArrayList and LinkedList?
Compare two commonly used list implementations
- Data structure:ArrayList is based on arrays, LinkedList is based on doubly linked lists
- Random access:ArrayList O(1), LinkedList O(n)
- Insertion and deletion:ArrayList O(n), LinkedList O(1)
- Memory usage:ArrayList is continuous, LinkedList is scattered (pointer overhead)
- Thread safety:Neither is synchronized, you can use Collections.synchronizedList() or CopyOnWriteArrayList
- Select:Use ArrayList for frequent queries and LinkedList for frequent insertions and deletions.
18. What is the principle and performance of HashMap?
Deep understanding of how HashMap works
- Data structure:Array + linked list + red-black tree (JDK 8+)
- How it works:hash(key) % table.length Calculate array subscript, link or tree in case of conflict
- Loading factor:Default is 0.75, expand when used capacity ≥ capacity × loading factor
- Expansion mechanism:Capacity doubled, elements rehashed
- Time complexity:Average O(1), worst O(n) (when there are a lot of conflicts)
- Thread safety:Not synchronized, use ConcurrentHashMap or Collections.synchronizedMap() for multi-threading
19. How to ensure that HashSet does not duplicate?
Understand the deduplication mechanism of Set
- Low-level implementation:Based on HashMap, key is element and value is fixed Object
- Deduplication mechanism:First compare hashCode(), then use equals() to determine equality.
- Add process:Calculate hash → check if it exists → add if it does not exist → ignore if it exists
- Custom objects:equals() and hashCode() must be rewritten to ensure consistency
- Performance:Adding, deleting, and searching average O(1), depending on hash quality
20. What are fail-fast and fail-safe?
Understand the iterator safety mechanism of collections
- fail-fast:
- Modifying the collection during the iteration process will throw ConcurrentModificationException
- Detected via modCount and expectedModCount
- Such as ArrayList, HashMap (not thread-safe)
- fail-safe:
- Iteration is based on a snapshot or copy of the collection. Modifying the original collection does not affect the iteration.
- Such as CopyOnWriteArrayList, ConcurrentHashMap
- Suggestions for use:When iterating, use the iterator's remove(), or use a fail-safe collection.
⚠️Exception handling
21. Java exception system?
Understand the classification of Java exceptions
- Throwable (root class):
- Exception:recoverable exception
- Error:Virtual machine level error, unrecoverable
- Exception Category:
- Checked exception (Checked):Must be caught or declared, such as IOException
- Unchecked exception (Unchecked):Can not be caught, such as NullPointerException, IndexOutOfBoundsException
- Common exceptions:NPE, ClassCastException, ArrayIndexOutOfBoundsException, etc.
22. Try-catch-finally execution order?
Master the execution flow of exception handling
- Normal situation:try → finally → return normally
- Exception:try → exception occurs → catch → finally → exception is passed or returned
- finally features:Must be executed, even if return, throw, System.exit() in catch
- Exceptions:The return in finally will override the return in try/catch
- Resource release:It is recommended to use try-with-resources to automatically close resources
- Best practices:Do not change the return value in finally, as this will cause exceptions to be lost
23. What is the difference between throws and throw?
Distinguish between two exception handling keywords
- throw:
- Manually throw exception instances, must be used within the method
- Format: throw new Exception("message")
- throws:
- Declare possible exceptions thrown in method signature
- Format: public void method() throws IOException
- Processing method:throw is declared by throws and throws is handled by the caller
- Application:throw is used for specific exception handling, throws is used for exception delivery
24. How to customize exceptions?
Create project-specific exception classes
- Inheritance relationship:Inherit Exception (checked exception) or RuntimeException (unchecked exception)
- Necessary parts:
- Provide a parameterless constructor
- Provide a constructor with message
- Provide a constructor with message and cause
- Code example:public class CustomException extends Exception { ... }
- Best practices:Clear naming, clear documentation, and inheritance of appropriate exception classes
25. What are the benefits of try-with-resources syntax?
Understand automatic resource management
- Syntax:try (InputStream is = ...) { ... } automatically close resources
- Requirements:Resources must implement the AutoCloseable interface
- Advantages:
- Automatically call the close() method without manual management
- Correct handling of exceptions when suppressed
- The code is more concise and avoids resource leakage
- Applicable scenarios:Resource classes such as File, Stream, Connection, Statement, etc.
🔤 String, StringBuilder, StringBuffer
26. String is immutable and why?
Understand the deep considerations behind String design
- Immutable definition:The String object cannot be modified after it is created, and any modification operation returns a new object.
- Implementation method:The value array is final modified and has no setter method.
- Immutable reasons:
- String buffer pool optimization to avoid repeated creation
- Thread safe, no synchronization required
- Supports hashCode caching, suitable for HashMap key
- Disadvantages:Frequent modifications create a large number of intermediate objects
27. What are the differences between String, StringBuilder and StringBuffer?
Choose the appropriate string manipulation class
- String:Immutable, thread-safe, poor performance (frequent modification)
- StringBuilder:Variable, non-thread-safe, excellent performance (single-threaded)
- StringBuffer:Mutable, thread-safe (synchronized methods), average performance (multi-threading)
- Performance comparison:StringBuilder > StringBuffer > String
- Suggestions for use:
- Single-threaded string concatenation using StringBuilder
- StringBuffer for multi-threaded string concatenation
- No need to modify, use String
28. What is the string constant pool?
Understand the string caching mechanism
- Definition:String cache maintained by JVM, storing string literals
- Location:JDK 7+ in the heap, previously in the method area
- Creation mechanism:
- Literals such as "abc" automatically enter the constant pool
- new String("abc") If "abc" is not in the pool, add it
- intern() method:Add a string to the constant pool or return an existing reference
- Optimization effect:Save memory and speed up string comparisons
29. How to compare strings for equality?
Learn how to compare strings
- == Compare:Compares whether references are the same, does not compare content
- equals() comparison:Compare string contents to see if they are the same. It is recommended to use
- equalsIgnoreCase() comparison:Ignore case comparison content
- compareTo() comparison:Lexicographic comparison, returning an integer
- Objects.equals():Handling safe comparisons of null values
- Best practices:Use equals() to compare string contents, avoid using ==
30. What are the performance issues with String concatenation?
Optimize the performance of string concatenation
- Question:String s = "a" + "b" + "c" produces multiple intermediate objects and copies
- Reason:String is immutable, and a new object is created every time it is spliced.
- Performance impact:O(n²) time complexity when splicing loops
- Optimization plan:
- Direct + outside the loop: the compiler will optimize to StringBuilder
- Explicitly use StringBuilder or StringBuffer
- Use tools like String.join(), StringJoiner, etc.
🔄 Multi-threading and concurrency
31. What is a thread? How to create a thread?
Master the basic concepts and creation methods of threads
- Thread definition:Independent execution flow within the process, shared memory but independent stack
- How to create:
- Inherit Thread:public class MyThread extends Thread { public void run() {} }
- Implement Runnable:public class MyRunnable implements Runnable { public void run() {} }
- Implement Callable:Return values and exception support
- Difference:Runnable is recommended to avoid single inheritance restrictions
- Start:Call thread.start(), you cannot call run() directly
32. Thread life cycle and status?
Understand the various state transitions of threads
- NEW:Thread created but not started
- RUNNABLE:Runnable status (waiting for execution or executing)
- BLOCKED:Blocked state, waiting to acquire the lock
- WAITING:Waiting state, waiting for notification from other threads
- TIMED_WAITING:Wait for specified time
- TERMINATED:Thread terminated
- State transition:NEW → RUNNABLE → BLOCKED/WAITING → TERMINATED
33. How does synchronized work?
Understand Java’s built-in locking mechanism
- Synchronization mechanism:Synchronization using the object's built-in lock
- How to use:
- Synchronization method:public synchronized void method() {}
- Sync block:synchronized(obj) { ... }
- How it works:
- Every object has a monitor
- The thread acquires the lock and enters the critical section, mutually exclusive execution
- Bytecode: monitorenter, monitorexit
- Features:Reentrant, exclusive, auto-release
34. What is the role of volatile keyword?
Understanding memory visibility and disabling instruction reordering
- Function:
- Visibility:Ensure changes are immediately visible to other threads
- Reflow prohibited:Prevent compiler and CPU reordering optimizations
- Implementation:Memory barrier, forcing reading and writing from main memory
- Limitations:Atomicity is not guaranteed and cannot replace synchronized
- Application scenarios:Flag bit, double check singleton, status mark
- Compare synchronized:volatile is more lightweight but has limited functionality
35. What are the functions and differences of wait(), notify() and notifyAll()?
Master the communication mechanism between threads
- wait():
- The current thread releases the lock and waits until it is awakened
- Must be called within a synchronized block
- notify():
- Wake up a waiting thread (randomly selected)
- Do not release the lock, wait until the end of the synchronization block before releasing it
- notifyAll():
- Wake up all waiting threads
- Usage mode:Producer-Consumer mode, monitor mode
đź’ˇ Interview preparation tips
Deepen the basics:Not only know the concepts, but also understand the principles and implementation details
Do more exercises:Consolidate knowledge through coding practice, especially related to multi-threading and concurrency
Read the source code:Study the Java library source code (collections, concurrency, etc.) to deepen your understanding
Pay attention to details:Master common pitfalls and best practices like string comparison, collection modification, and more
Example:Use specific examples to illustrate concepts during the interview and enhance your expressive power.