Java Fundamentals
What is the difference between int and Integer?
What is the difference between int and Integer?
- Data Type:
intis a primitive data type, whileIntegeris a wrapper class - Default Value:
intdefaults to 0, whileIntegerdefaults to null - Memory Storage:
intstores the value directly,Integerstores an object reference - Instantiation:
Integermust be instantiated,intdoes not need to be - Comparison:
intuses==,Integershould use.equals()method - Generics:
Integercan be used in generics,intcannot
- Use Integer: In Spring Boot controllers to receive parameters (null handling)
- Use int: For class properties where null values are not allowed (better performance)
Explain the difference between abstract class and interface
Explain the difference between abstract class and interface
| Aspect | Abstract Class | Interface |
|---|---|---|
| Keyword | abstract | interface |
| Member Variables | No restrictions | Only public static final constants |
| Constructor | Has constructor, cannot instantiate | No constructor |
| Methods | Can have concrete methods | Default public abstract (JDK 8+ supports default/static) |
| Inheritance | Single inheritance | Multiple inheritance |
- Abstract Class (is-a relationship): Template-based design with common features
- Example: Car abstract class with chassis, horn - different configurations can have different implementations
- Interface (can-do relationship): Contract-based design defining behavior
- Example: Flyable interface - both Plane and Bird can implement fly() method differently
Difference between String, StringBuilder, and StringBuffer?
Difference between String, StringBuilder, and StringBuffer?
- Mutability:
Stringis immutable (cannot be changed)StringBuilderandStringBufferare mutable
- Thread Safety:
Stringis thread-safe (immutable)StringBufferis thread-safe (synchronized methods)StringBuilderis not thread-safe (faster)
- Performance:
Stringcreates new objects for each modificationStringBuildermodifies the object itself (fastest)StringBufferadds synchronization overhead
- String: For constant strings or few modifications
- StringBuilder: Single-threaded string concatenation (preferred)
- StringBuffer: Multi-threaded string concatenation
Why is String immutable?
Why is String immutable?
- Design: The character array is
finalandprivate, with no modification methods exposed - Inheritance: String class is
final, preventing subclasses from breaking immutability
- Thread Safety: No synchronization needed
- Security: Used for passwords, file paths, network connections
- String Pool: Enables efficient memory reuse
- HashCode Caching: Hash value can be cached safely
What are the three OOP characteristics?
What are the three OOP characteristics?
- Control access to properties through public interfaces
- Simplifies object relationships and reduces coupling
- Example: Getters and setters
- Subclass inherits properties and behaviors from parent class
- Enables code reuse
- Follows Liskov Substitution Principle
- Same behavior with different implementations based on runtime object type
- Achieved through method overriding and interfaces
Java Collections
Explain HashMap's put operation
Explain HashMap's put operation
- Create Entry/Node object and place it at that position
- Check if expansion is needed
- Create Entry and insert at head of linked list (head insertion)
- Determine if current node is linked list or red-black tree
- If red-black tree: add as tree node (checking for duplicates)
- If linked list: append to tail (tail insertion), checking duplicates
- If list length ≥ 8, convert to red-black tree
- Finally check if expansion needed
- JDK 7 uses head insertion, JDK 8 uses tail insertion
- JDK 8 introduces red-black tree for better performance with many collisions
- Load factor default is 0.75 (balance between space and time)
Why does HashMap use red-black tree?
Why does HashMap use red-black tree?
- Used only linked lists for collision handling
- Worst case: O(n) search time
- Tree insertion has overhead (self-balancing)
- For small amounts of data, linked list is simpler and faster
- When data is large, linked list search becomes O(n)
- Red-black tree provides O(log n) search time
- Probability of having 8+ collisions is very low (Poisson distribution)
- Balance between linked list simplicity and tree efficiency
- Converts back to linked list when nodes reduce to 6
- Avoids frequent conversion at boundary
What are thread-safe List implementations?
What are thread-safe List implementations?
- Vector
- Uses
synchronizedon methods - Both read and write operations are locked
- Oldest and least efficient
- Uses
- CopyOnWriteArrayList
- Copies array on every write operation
- Read operations don’t need locks (extremely fast reads)
- Write operations are expensive
- Best for read-heavy scenarios
- Collections.synchronizedList()
- Wraps existing List with synchronized blocks
- Both read and write are locked
- More flexible than Vector
JVM & Concurrency
Explain the class loading process
Explain the class loading process
- Loading (加载): Read .class file into memory
- Linking (链接):
- Verification: Verify bytecode format and semantics
- Preparation: Allocate memory for static variables (default values)
- Resolution: Convert symbolic references to direct references
- Initialization (初始化): Execute static initializers and assign actual values
Explain the parent delegation model
Explain the parent delegation model
- Delegates to parent class loader first
- Parent tries to load, and delegates to its parent
- Reaches Bootstrap ClassLoader at top
- If parent cannot load, child tries to load
- Bootstrap ClassLoader: Loads
<JAVA_HOME>/lib(rt.jar) - Extension ClassLoader: Loads
<JAVA_HOME>/lib/ext - Application ClassLoader: Loads application classpath
- Custom ClassLoader: User-defined loaders
- Security: Prevents modification of core Java classes
- Avoid Duplicate Loading: Same class only loaded once
- Guarantee Uniqueness: Core classes always from same loader
Explain thread pool core parameters
Explain thread pool core parameters
- corePoolSize: Number of core threads (always kept alive)
- maximumPoolSize: Maximum number of threads allowed
- keepAliveTime: How long excess idle threads wait before termination
- unit: Time unit for keepAliveTime
- workQueue: Queue to hold tasks waiting for execution
- threadFactory: Factory to create new threads
- handler: Rejection policy when queue is full
- If threads < corePoolSize, create new thread
- If threads = corePoolSize, add to queue
- If queue is full and threads < maximumPoolSize, create new thread
- If threads = maximumPoolSize and queue is full, execute rejection policy
- AbortPolicy: Throw exception (default)
- CallerRunsPolicy: Run in caller’s thread
- DiscardPolicy: Silently discard
- DiscardOldestPolicy: Discard oldest task
What is the role of volatile?
What is the role of volatile?
volatile is a lightweight synchronization mechanism that provides:- Visibility: Changes to volatile variables are immediately visible to all threads
- No Atomicity: Does not guarantee atomic operations
- Prevents Reordering: Compiler won’t reorder instructions around volatile access
- Flags to signal state changes between threads
- Double-checked locking pattern
- Reading/writing single variables
Explain synchronized implementation
Explain synchronized implementation
- Each object has an associated Monitor
- Monitor contains a mutex lock and wait queue
- Thread acquires Monitor to execute synchronized code
- Biased Lock (偏向锁): Single thread access, minimal overhead
- Lightweight Lock (轻量级锁): Multiple threads, no heavy contention, uses CAS
- Heavyweight Lock (重量级锁): Heavy contention, uses OS-level mutex
- Automatic lock release (managed by JVM)
- Can lock methods or code blocks
- Unfair lock (threads can cut in line)
- Provides both visibility and atomicity
Database & MySQL
InnoDB vs MyISAM storage engines
InnoDB vs MyISAM storage engines
| Feature | InnoDB | MyISAM |
|---|---|---|
| Transaction Support | Yes (ACID) | No |
| Locking | Row-level (default) | Table-level only |
| Foreign Keys | Yes | No |
| Crash Recovery | Strong (via redo log) | Weak |
| Storage | Clustered index (data with index) | Separate data and index files |
| Performance | Better for writes, high concurrency | Better for read-only |
- InnoDB: Modern applications, transactions required, high concurrency (default since MySQL 5.5)
- MyISAM: Read-heavy, no transaction needs, logging systems
ACID transaction properties
ACID transaction properties
- Atomicity (原子性): All or nothing - implemented via undo log
- Consistency (一致性): Data integrity maintained - implemented via undo log
- Isolation (隔离性): Transactions don’t interfere - implemented via locks and MVCC
- Durability (持久性): Changes are permanent - implemented via redo log
- Read Uncommitted: Dirty read possible
- Read Committed: Prevents dirty read
- Repeatable Read: Prevents dirty read and non-repeatable read (MySQL default)
- Serializable: Prevents all issues, lowest concurrency
Why does B+ tree make queries fast?
Why does B+ tree make queries fast?
- Shallower Tree (Less I/O):
- Non-leaf nodes only store keys (not data)
- More keys fit per node → fewer levels
- Fewer disk I/O operations needed
- Redundant Nodes:
- All non-leaf nodes are redundant indexes
- Makes insertion/deletion more efficient
- Less tree restructuring needed
- Linked Leaf Nodes:
- Leaf nodes connected as linked list
- Efficient range queries
- B tree requires tree traversal for ranges
- Binary Tree: Too deep, too many I/O operations
- B Tree: Stores data in all nodes, not optimal for range queries
- B+ Tree: Best balance for database use cases
When does index fail?
When does index fail?
- Left/Both-side LIKE:
LIKE '%abc'orLIKE '%abc%' - Function on Column:
WHERE UPPER(name) = 'JOHN' - Expression Calculation:
WHERE age + 1 = 30 - Implicit Type Conversion: String column with numeric input
- Not Following Leftmost Prefix: In composite index (a,b,c), query only uses b
- OR without Index:
WHERE indexed_col = 1 OR non_indexed_col = 2
Explain MVCC (Multi-Version Concurrency Control)
Explain MVCC (Multi-Version Concurrency Control)
- Each row modification creates a new version
- Versions linked by rollback pointer
- Old versions kept in undo log
- Snapshot of active transactions
- Determines which version is visible
- Different behavior for isolation levels:
- Read Committed: New ReadView per query
- Repeatable Read: Reuse same ReadView in transaction
- If version’s transaction ID < ReadView’s low watermark → visible
- If version’s transaction ID in active list → not visible
- Otherwise check specific rules
- Readers don’t block writers
- Writers don’t block readers
- Higher concurrency than lock-based approach