Technical Interview Questions from JD and Baidu for Java Developer Roles
Self-Introduction Example
Interviewer, hello! My name is Angela, 23 years old, from Guizhou. I graduated from Blue Sky Technical School with a major in Electronic Information Engineering and have two years of work experience. I previously interned at Huawei, where I was part of the Nova team responsible for core component development and tackling technical challenges with teammates.
Currently, I work at Tmall International, leading a small R&D team focused on activity development. Over the past year, I've participated in over 30 activities that generated millions in GMV. The projects I've worked on primarily utilize microservices design principles and distributed deployment methods.
Frequently used middleware includes Redis, RocketMQ, ElasticSearch, Logstash, Canal, and Dubbo. I have conducted in-depth research into Dubbo's source code and have developed an RPC framework using Netty, which is now open-sourced on GitHub with 20,000 stars.
In my spare time, I write technical blogs and have built a following across various platforms. I'm familiar with all e-commerce business processes and have my own understanding of handling online issues and performance optimization. I'm also well-versed in business R&D design workflows.
Due to personal reasons, I'm seeking new opportunities and would be excited to contribute immediately if given the chance to join your company. That concludes my introduction. Thank you!
Note: The above self-introduction is fictional and serves only as a demonstration of how to structure an interview introduction.
Technical Questions and Answers
HashMap Implementation Details
Describe the put() method process in JDK1.7 HashMap.
In JDK1.7, HashMap uses an array + linked list structure. The put() method follows these steps:
- Calculate the hash value of the key
- Determine the bucket index using (n-1) & hash
- Traverse the linked list at that bucket
- If a matching key is found, update the value
- Otherwise, add a new entry at the head of the list
What change were introduced in JDK1.8?
JDK1.8 introduced several optimizations:
- When linked lists exceed 8 nodes, they convert to red-black trees
- Hash calculation was optimized to reduce collisions
- The resize mechanism was improved for better performance
What thread safety issues exist in JDK1.7 HashMap and why?
JDK1.7 HashMap has thread safety issues during resize operations, which can lead to infinite loops. This occurs because the resize process reverses the linked list order, and concurrent modifications can create circular references.
How does chaining work in JDK1.8, and when does conversion to red-black tree occur?
In JDK1.8, HashMap still uses chaining for collision resolution. When a bucket's linked list reaches 8 nodes (with default load factor of 0.75), it converts to a red-black tree to maintain O(log n) performance for operations.
When does a red-black tree revert to a linked list?
When the number of nodes in a tree drops to 6 or below, the structure reverts to a linked list to save memory.
Why was 8 chosen as the threshold for tree conversion?
Statistical analysis shows that with a load factor of 0.75, the probability of a bucket having exactly 8 elements is less than one in a million. This makes 8 a reasonable threshold where the benefits of tree structure outweigh the overhead.
HashMap vs HashTable
What are the differences between HashMap and HashTable?
- Thread Safety: HashTable is synchronized, HashMap is not
- Null Values: HashTable doesn't allow null keys or values, HashMap allows one null key and multiple null values
- Performance: HashMap is generally faster due to lack of synchronization
- Iteration: HashTable uses Enumeration, HashMap uses Iterator
ConcurrentHashMap
How does ConcurrentHashMap insure thread safety in JDK1.8?
JDK1.8 ConcurrentHashMap uses a combination of CAS (Compare-And-Swap) operations and synchronized blocks:
- CAS is used for initial insertions
- synchronized is used on individual bucket heads for updates
- This provides better granularity than previous versions
What optimizations were made compared to JDK1.7?
JDK1.8 removed segment locking and uses finer-grained locking at the bucket level, reducing contention and improving concurrent performance.
Synchronized Keyword
What's the difference between synchronized on static methods vs enstance methods?
- Instance method synchronization locks on the object instance
- Static method synchronization locks on the class object
- These are different locks that don't interfere with each other
Singleton Pattern
Describe the Singleton pattern and differences between lazy and eager initialization.
The Singleton pattern ensures a class has only one instance and provides a global access point.
Lazy Initialization:
public class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {}
public static LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
Eager Initialization:
public class EagerSingleton {
private static final EagerSingleton instance = new EagerSingleton();
private EagerSingleton() {}
public static EagerSingleton getInstance() {
return instance;
}
}
How to make lazy initialization thread-safe?
public class ThreadSafeSingleton {
private static ThreadSafeSingleton instance;
private ThreadSafeSingleton() {}
public static synchronized ThreadSafeSingleton getInstance() {
if (instance == null) {
instance = new ThreadSafeSingleton();
}
return instance;
}
}
What are thread-safe Singleton implementations?
- Double-Checked Locking:
public class DCLSingleton {
private static volatile DCLSingleton instance;
private DCLSingleton() {}
public static DCLSingleton getInstance() {
if (instance == null) {
synchronized (DCLSingleton.class) {
if (instance == null) {
instance = new DCLSingleton();
}
}
}
return instance;
}
}
- Static Inner Class:
public class InnerClassSingleton {
private InnerClassSingleton() {}
private static class SingletonHolder {
private static final InnerClassSingleton INSTANCE = new InnerClassSingleton();
}
public static InnerClassSingleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
- Enum Implementation:
public enum EnumSingleton {
INSTANCE;
public void businessMethod() {
// Implementation
}
}
JVM Memory Model
Describe the JVM memory model components:
- Method Area: Stores class metadata, constants, static variables
- Heap: Stores object instances and arrays, main GC area
- Java Stack: Stores method frames with local variables and references
- Native Method Stack: Similar to Java stack but for native methods
- Program Counter Register: Tracks current execution line
Garbage Collection Algorithms
What garbage collection algorithms exist?
- Mark-Sweep: Marks reachable objects, sweeps unmarked ones
- Copying: Copies live objects to new space, clears old space
- Mark-Compact: Marks live objects, compacts them to eliminate fragmentation
- Generational Collection: Divides heap into young and old generations, uses different algorithms for each
How does JVM determine if an object should be collected?
The JVM uses reachability analysis starting from GC Roots. Objects unreachable from any root after two marking cycles become eligible for collection, unless rescued in finalize().
CMS vs G1 Collectors
CMS (Concurrent Mark Sweep) Collector:
- Designed for low pause times
- Uses concurrent marking and sweeping
- Prone to fragmentation
- May experience "Concurrent Mode Failure"
G1 (Garbage First) Collector:
- Predictable pause times
- Divides heap into regions
- Uses concurrent and parallel phases
- Better for large heaps
String Creation
What's the difference between String a = "abc"; and String b = new String("abc");?
The first creates a string in the string constant pool, while the second creates a new string object on the heap. They may not be equal when compared with ==.
Object Creation Process
Describe JVM object creation process:
- Class loading check
- Memory allocation
- Memory initialization to zero values
- Object header setup
- Constructor execution
Byte Operations
What happens with byte a = 127; byte b = 127; a += b; vs a = a + b;?
a += b causes overflow to negative values. a = a + b causes compilation error due to type promotion to int.
MySQL Isolation Levels
Describe MySQL isolation levels and associated problems:
- Read Uncommitted: Dirty reads possible
- Read Committed: Prevents dirty reads, allows non-repeatable reads
- Repeatable Read: Prevents non-repeatable reads, allows phantom reads
- Serializable: Prevents all concurrency issues but reduces performance
MVCC (Multi-Version Concurrency Control)
What is MVCC and what does it achieve?
MVCC allows multiple versions of data to coexist, enabling read operations without blocking write operations. It improves concurrency by maintaining version chains for records.
Database Optimization
How to optimize database queries?
- Add indexes on frequently queried columns
- Avoid NULL comparisons in WHERE clauses
- Use appropriate data types
- Limit result sets
- Avoid SELECT *
- Use EXISTS instead of IN for subqueries
MyBatis vs Hibernate
Compare MyBatis and Hibernate:
- Hibernate: Full ORM, generates SQL automatically, heavier
- MyBatis: SQL mapping framework, manual SQL control, lighter
- Performance: MyBatis often faster for complex queries
- Learning Curve: Hibernate has steeper learning curve
Hibernate Object States
Describe Hibernate object states:
- Transient: New object not associated with session
- Persistent: Object associated with session, has database representation
- Detached: Object was persistent but session closed
- Removed: Object scheduled for deletion
Spring Framework
Explain Spring's IOC and AOP:
- IOC (Inversion of Control): Container manages object creation and dependencies
- AOP (Aspect-Oriented Programming): Separates cross-cutting concerns from business logic
AOP Implementation Methods
What are AOP implementation methods and their performance?
- JDK Dynamic Proxy: Interface-based, uses reflection
- CGLib: Class-based, uses bytecode generation
Performance Comparison:
- CGLib is faster at runtime but slower to create proxies
- JDK proxies are faster to create but slower at runtime
- For singleton beans, CGLib is often preferred
Spring Transaction Propagation
Describe Spring transaction propagation behaviors:
- REQUIRED: Use existing transaction or create new
- REQUIRES_NEW: Always create new transaction
- NESTED: Create nested transaction within existing
- SUPPORTS: Use transaction if exists, otherwise non-transactional
- NOT_SUPPORTED: Execute non-transactionally
- NEVER: Throw exception if transaction exists
- MANDATORY: Require existing transaction