Common Java Interview Questions and Answers

This article compiles a comprehensive list of frequently asked Java interview questions, covering topics such as JDK/JRE/JVM relationships, object creation methods, equality comparison, concurrency mechanisms, collections, thread pools, and I/O models, providing concise answers for quick reference.

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture
Common Java Interview Questions and Answers

Hello, I'm Tom. Below is a collection of high-frequency Java interview questions and answers for quick reference.

What is the relationship between JDK, JRE, and JVM?

Answer:

JDK (Java Development Kit) can create, compile, and run programs.

JDK = JRE + java development tools (javac.exe/java.exe/jar.exe)

JRE (Java Runtime Environment) can run compiled programs but cannot create them.

JRE = JVM + core Java libraries

JVM (Java Virtual Machine) is the virtual machine that runs Java bytecode.

How can you create a Java object?

1. Using new 2. Using reflection

3. Using the clone method

4. Using serialization

What is the difference between == and equals ? == compares primitive values or object references. equals compares the logical equality of object values.

What is the purpose of hashCode() ?

It generates an int hash code used to locate the object in hash‑based collections.

Differences among String, StringBuffer, and StringBuilder

String: immutable, declared final, thread‑safe.

StringBuffer: mutable, uses synchronized, thread‑safe.

StringBuilder: mutable, not thread‑safe, higher performance in single‑threaded contexts.

Will finally execute if a return is present in catch ?

Yes, the finally block runs before the method returns.

Difference between process and thread

Process: OS resource allocation unit, heavier weight, independent memory space.

Thread: Smaller execution unit within a process, shares most resources, lighter weight.

Internal principle of synchronized

The keyword compiles to bytecode instructions monitorenter and monitorexit, which rely on OS‑level mutexes. Internally it uses two queues: entryList and waitSet.

Threads first enter entryList.

When a thread acquires the monitor, the lock count increments.

If a thread calls wait, it releases the lock, moves to waitSet, and waits to be notified.

When a thread finishes, it releases the lock and may wake waiting threads.

Difference between synchronized and ReentrantLock

ReentrantLock implements the Lock interface; synchronized is a language keyword.

ReentrantLock requires explicit lock/unlock calls; synchronized can lock blocks or methods.

Both are re‑entrant.

ReentrantLock supports fair and non‑fair modes, while synchronized defaults to non‑fair.

ReentrantLock offers multiple Condition objects and various lock acquisition methods (e.g., lock(), tryLock(), lockInterruptibly).

Principle of AbstractQueuedSynchronizer (AQS)

AQS maintains a state field and uses CAS to acquire the lock. When a thread obtains the lock, it records its thread ID; releasing the lock resets state to 0 and clears the thread ID, waking queued threads.

Drawbacks of CAS

ABA problem in high‑contention scenarios.

Solutions include versioned counters or using AtomicStampedReference in Java.

Common Java locks

Optimistic and pessimistic locks

Distributed locks

Exclusive and shared locks

Mutexes, read‑write locks, fair/non‑fair locks, re‑entrant locks, spin locks, segment locks, lock upgrading, lock coarsening/elimination

HashMap implementation

Internally uses an array of buckets with linked lists; from JDK 1.8 onward, buckets may become red‑black trees when they exceed a threshold, improving lookup performance.

How ConcurrentHashMap ensures thread safety

JDK 1.7: segment‑based locking using Segment (extends ReentrantLock) and HashEntry.

JDK 1.8: lock‑striped design with CAS and synchronized, using an array of nodes that may become red‑black trees.

Difference between ArrayList and LinkedList

ArrayList: backed by a resizable array, fast random access, slower insert/delete in the middle.

LinkedList: doubly‑linked list, constant‑time insert/delete at any position, no efficient random access.

volatile keyword principle

Writes to a volatile variable are immediately visible to other threads; the CPU enforces cache‑coherency so threads read the latest value from main memory.

ThreadLocal principle

ThreadLocal holds a static inner class ThreadLocalMap containing weak‑referenced entries that map each thread to its own value, preventing memory leaks when remove() is called.

What are working memory and main memory?

Working memory: registers and CPU caches (L1/L2/L3).

Main memory: the physical RAM.

Thread‑safe classes in java.util.concurrent

ConcurrentHashMap, CountDownLatch, CyclicBarrier, Semaphore, BlockingQueue, ThreadPoolExecutor, ReentrantLock, ReentrantReadWriteLock, CompletableFuture, etc.

ThreadPoolExecutor constructor parameters

Core pool size, maximum pool size, keep‑alive time, time unit, work queue, thread factory, rejection handler.

Rejection policies of ThreadPoolExecutor

AbortPolicy (default)

CallerRunsPolicy

DiscardOldestPolicy

DiscardPolicy

Custom policy via RejectedExecutionHandler Thread states and transitions

New → Runnable → Running → Blocked → Waiting → Timed Waiting → Terminated.

I/O models (five types)

Blocking I/O

Non‑blocking I/O

I/O multiplexing (select/epoll)

Signal‑driven I/O

Asynchronous I/O (AIO)

Difference between blocking and non‑blocking I/O

Blocking I/O waits until data is ready; non‑blocking I/O returns immediately with a status indicating whether data is available.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaJVMconcurrencyThreadPoolCollections
Full-Stack Internet Architecture
Written by

Full-Stack Internet Architecture

Introducing full-stack Internet architecture technologies centered on Java

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.