Comprehensive Java Fundamentals and Interview Q&A
This article provides a thorough overview of core Java concepts—including object‑oriented features, polymorphism, interfaces, abstract classes, immutability, memory models, concurrency utilities, collections, JVM internals, and common interview questions—supplemented with code examples and clear explanations for developers preparing for technical interviews.
Related Concepts
Three Features of Object‑Oriented Programming
Encapsulation, inheritance, and polymorphism (sometimes abstraction) are the fundamental OOP characteristics.
Benefits of Polymorphism
Polymorphism allows different class objects to respond to the same message (method call) in various ways, offering replaceability, extensibility, interface provision, flexibility, and simplification.
How to Implement Polymorphism in Code
Three main ways: implement an interface, override methods in a subclass, or overload methods within the same class.
How the JVM Implements Polymorphism
Through dynamic binding, the actual object type is determined at runtime and the appropriate method is invoked.
Purpose of Interfaces
Interfaces provide specification, extensibility, and callbacks.
Purpose of Abstract Classes
Abstract classes offer a common type for subclasses, encapsulate shared code, and define abstract methods that enforce a consistent contract.
Comparison
Abstract Class
Interface
Default Methods
Can have default implementations
Before Java 8, no method bodies
Implementation
Subclass uses extends and must implement abstract methods
Class uses implements and must implement all declared methods
Constructors
Can define constructors
Cannot have constructors
Instantiation
Cannot be instantiated directly
Represents a completely different type
Access Modifiers
Methods can be public, protected, or package‑private
Methods are implicitly public; other modifiers are not allowed
Multiple Inheritance
Only one superclass allowed
Can implement multiple interfaces
Adding New Methods
Can provide default implementations to avoid breaking subclasses
New methods require all implementing classes to add implementations
Can a Static Method in a Superclass Be Overridden?
No. Static methods are hidden, not overridden, when a subclass defines a method with the same signature.
What Is an Immutable Object?
An object whose state cannot change after creation; any modification results in a new object (e.g., String, Integer).
Can an Immutable Object Contain Mutable Fields?
Yes, as long as mutable references are not exposed; typically a defensive copy is returned.
Ways to Create Objects in Java
Using new Via reflection
Using clone() Through serialization
Direct new creates tight coupling, which many frameworks try to reduce.
Can switch Use String ?
Supported since JDK 1.7; earlier versions only allowed primitive types, their wrappers, and enum s.
Common Methods of Object
equals() clone() getClass() notify(), notifyAll(),
wait()Four Types of References in Java
Strong, soft, weak, and phantom references, each affecting garbage‑collection behavior differently.
Difference Between WeakReference and SoftReference
Both aid GC, but a WeakReference is cleared as soon as the last strong reference disappears, whereas a SoftReference is cleared only when memory is low.
Why Different Reference Types Exist
They allow developers to influence object reclamation timing, useful for caching and avoiding OOM errors.
Difference Between == and equals() , and Between equals() and hashCode()
==compares primitive values or object identities; equals() can be overridden for logical equality. If two objects are equal, they must have the same hashCode(), though unequal objects may share a hash code.
Can Two Unequal Objects Have the Same hashCode ?
Yes, hash collisions are allowed.
Can hashCode Use Random Numbers?
No; the same object must consistently return the same hash code.
Difference Between a==b and a.equals(b)
a==bchecks reference identity; a.equals(b) checks logical equality, which often requires overriding.
Result of 3*0.1==0.3
Evaluates to false due to floating‑point precision.
Difference Between a=a+b and a+=b
a+=bincludes an implicit cast and may compile where a=a+b does not for narrow primitive types.
Purpose of Inner Classes
Provide encapsulation, allow multiple implementations of the same interface within an outer class, and can be instantiated independently of the outer instance.
Differences Among final , finalize , and finally
finalis a modifier for variables, methods, or classes; finalize() is a method called before garbage collection (no guarantee of timing); finally is a block that always executes after try / catch.
Where Does clone() Come From?
clone()is defined in Object; the Cloneable interface is a marker with no methods.
Shallow vs. Deep Copy
Shallow copy duplicates field values but shares referenced objects; deep copy recursively copies all referenced objects, producing an independent clone.
Uses of static
Static fields, static methods, static initialization blocks, static nested classes, and static imports (e.g., import static java.lang.Math.*;).
Uses of final
Prevents inheritance, method overriding, and reassignment of variables; may enable inlining and constant folding.
Data Type Sizes in Java
short 2 bytes, int 4 bytes, long 8 bytes, float 4 bytes, double 8 bytes, char 2 bytes. The size of int is always 32 bits, regardless of 32‑ or 64‑bit JVM.
Difference Between String , StringBuffer , and StringBuilder
Stringis immutable; StringBuffer is mutable and thread‑safe; StringBuilder is mutable but not thread‑safe, offering better performance when synchronization is unnecessary.
When to Use Compilation‑Time Constants
Public static final fields are inlined at compile time; changing them without recompiling dependent code can cause inconsistencies.
Choosing a Type for Monetary Values
Use BigDecimal for precise financial calculations; double may be acceptable when performance outweighs precision.
Converting byte[] to String
Use the String constructor with an explicit charset to avoid platform‑dependent defaults.
Effect of Casting int to byte
The high 24 bits are discarded, potentially causing overflow; byte range is –128 to 127.
Garbage‑Collection Algorithms
Mark‑Sweep, Mark‑Copy, Mark‑Compact, and generational collection.
How to Determine If an Object Is Eligible for GC
Via reference‑counting (now obsolete) or reachability analysis; the latter is used by modern JVMs.
What Happens When System.gc() Is Called?
It suggests that the JVM perform garbage collection, but the actual timing is not guaranteed.
Process, Thread, and Coroutine Differences
A process has its own memory space; threads share the process memory; coroutines are lightweight, cooperative units of execution.
Daemon vs. Non‑Daemon Threads
The JVM exits when only daemon threads remain; non‑daemon threads keep the JVM alive.
Thread Context Switching
The CPU switches execution from one running thread to another that is ready.
Creating Threads: Runnable vs. Extending Thread
Implementing Runnable allows extending another class and reduces overhead.
Difference Between Runnable and Callable
Runnablereturns void; Callable returns a result and can throw checked exceptions, often used with Future.
Thread Blocking Causes
Methods like sleep(), suspend() / resume(), wait(), and I/O can block a thread.
Difference Between wait() and sleep()
wait()releases the object monitor and must be called within a synchronized block; sleep() does not release locks and is a static method of Thread.
Difference Between synchronized and ReentrantLock
synchronizedis a language keyword; ReentrantLock is a class offering more features such as timed lock attempts and interruptible acquisition.
What Is FutureTask ?
A cancellable asynchronous computation that implements Runnable and wraps a Callable.
Handling Runtime Exceptions in Threads
Uncaught exceptions terminate the thread and release any held monitors.
Sharing Data Between Threads
Share mutable objects and coordinate via wait/notify, BlockingQueue, or other concurrency utilities.
Correct Use of wait()
Always call wait() inside a loop that re‑checks the condition.
Thread‑Local Variables
Each thread has its own isolated copy, preventing accidental sharing.
Producer‑Consumer Model
Balances production and consumption rates and decouples components; can be implemented with BlockingQueue or wait/notify.
ConcurrentHashMap Concurrency Level
Determined by the number of segments (default 16), allowing up to 16 threads to modify the map concurrently.
CyclicBarrier vs. CountDownLatch
CyclicBarrier blocks a set of threads until all arrive and can be reused; CountDownLatch decrements a counter and cannot be reset.
Is ++ Thread‑Safe?
No; it involves a read‑modify‑write sequence that can interleave with other threads.
Best Practices for Multithreaded Development
Name threads
Minimize synchronized scope
Prefer volatile where appropriate
Use high‑level concurrency utilities (e.g., BlockingQueue, Semaphore)
Prefer concurrent collections over synchronized ones
Consider thread pools
Volatile Array Creation
A volatile array reference is volatile, but the elements themselves are not protected by volatile.
Can volatile Make a Non‑Atomic Operation Atomic?
It guarantees atomic reads/writes of 64‑bit long and double, but does not make compound actions atomic.
Guarantees Provided by volatile
Prevents instruction reordering and ensures visibility (happens‑before) across threads; reads/writes of volatile long/double are atomic.
Java Collections Overview
Includes List, Map, Set, and their implementations; see the accompanying diagram for the inheritance hierarchy.
Difference Between poll() and remove()
poll()returns null if the queue is empty; remove() throws an exception.
LinkedHashMap vs. PriorityQueue
LinkedHashMap preserves insertion order; PriorityQueue orders elements by priority.
WeakHashMap vs. HashMap
WeakHashMap uses weak references for keys, allowing entries to be garbage‑collected when keys are no longer reachable.
ArrayList vs. LinkedList
ArrayList is backed by an array offering O(1) random access; LinkedList is a doubly‑linked list with O(n) access.
Default Sizes
ArrayList default capacity is 10; HashMap default capacity is 16 (power of two).
Comparator vs. Comparable
Comparabledefines natural ordering; Comparator defines external ordering and can have multiple implementations.
Sorting Collections
Use Collections.sort() on lists or sorted collections like TreeSet / TreeMap.
Printing Arrays
Use Arrays.toString() or Arrays.deepToString() for readable output.
LinkedList Implementation
It is a doubly‑linked circular list.
TreeMap Implementation
Based on a red‑black tree.
Correct Removal While Iterating an ArrayList
Use an Iterator and its remove() method to avoid ConcurrentModificationException.
ArrayMap (Android)
A memory‑efficient map implementation using parallel arrays; not relevant outside Android.
HashMap Implementation Overview
Combines an array with linked lists (or trees) for buckets; uses the key's hash code to locate entries.
Fail‑Fast Mechanism
Iterators throw ConcurrentModificationException if the underlying collection is modified during iteration.
Is SimpleDateFormat Thread‑Safe?
No; it must be confined to a thread or wrapped in ThreadLocal. Consider using Joda‑Time or java.time APIs.
Formatting Dates
Use SimpleDateFormat or the modern java.time.format.DateTimeFormatter for thread‑safe formatting.
Java Exception Hierarchy
Distinguishes checked exceptions (must be declared) from unchecked exceptions (runtime exceptions and errors).
Exception Chaining
Wrap a lower‑level exception inside a higher‑level one using the constructor that accepts a Throwable cause.
Difference Between throw and throws
throwactually raises an exception; throws declares that a method may propagate an exception.
Serializable vs. Externalizable
Serializableuses default JVM serialization; Externalizable requires explicit read/write methods for custom serialization.
JVM Characteristics
Provides platform independence by executing bytecode on a virtual machine.
Class Loaders
Four primary loaders (bootstrap, extension, system, application) follow the parent‑delegation model.
Heap vs. Stack
Stack stores method frames and primitive locals; heap stores objects and arrays.
JVM Memory Allocation Summary
Primitive locals and references reside on the stack.
Objects and arrays are allocated on the heap.
Static fields are allocated in the heap but referenced from the stack.
Instance fields live on the heap as part of the object.
Local variables are freed when their scope ends.
Endianness in Java
Java abstracts endianness; primitive values are stored in big‑endian order in the class file format, but the JVM handles native endianness transparently.
XML Parsing Methods
DOM (memory‑intensive), SAX (event‑driven, low memory), and Pull (pull‑based, similar to SAX).
JDK 1.7 Features
Try‑with‑resources, Fork/Join framework, switch on String, diamond operator ( <>).
JDK 1.8 Features
Lambda expressions, Stream API, new Date‑Time API, default/static methods in interfaces, repeatable annotations.
Maven vs. Ant
Maven follows convention‑over‑configuration, manages dependencies, and defines a standard project structure; Ant is a procedural build tool requiring explicit scripts.
JDBC Best Practices
Batch updates, use PreparedStatement, employ connection pools, access result sets by column name.
IO Best Practices
Use buffered streams, prefer NIO/NIO.2 or AIO over classic BIO, close streams in finally, consider memory‑mapped files for high‑performance I/O.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
