Backend Development 14 min read

Common Java Interview Questions and Answers

This article compiles a comprehensive list of frequently asked Java interview questions, covering topics such as the relationship between JDK/JRE/JVM, object creation methods, differences between == and equals, hashCode, String variants, synchronization mechanisms, lock implementations, collections, concurrency utilities, thread pools, and I/O models, providing concise explanations for each.

Wukong Talks Architecture
Wukong Talks Architecture
Wukong Talks Architecture
Common Java Interview Questions and Answers

Hello everyone, I'm Wukong. This article gathers high‑frequency Java interview questions and answers to help readers quickly get an overview of Java fundamentals.

JDK, JRE, JVM relationship?

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 + java core libraries

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

Ways to create a Java object?

new operator

Reflection

clone() method

Serialization mechanism

Difference between == and equals?

== compares primitive values or object references.

equals compares the logical equality of object values.

Purpose of hashCode()?

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

Difference among String, StringBuffer, StringBuilder?

String is immutable and thread‑safe, declared with final .

StringBuffer is mutable and thread‑safe, declared with synchronized .

StringBuilder is mutable but not thread‑safe, offering 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: an OS resource allocation unit; heavyweight, with its own memory space.

Thread: a lightweight execution unit within a process; shares memory, has its own stack and registers.

Internal principle of synchronized?

synchronized is a built‑in monitor lock. The compiler inserts monitorenter and monitorexit bytecode instructions, which rely on OS‑level mutexes.

Internal handling involves two queues: entryList and waitSet .

1. Threads entering a synchronized block first join entryList .

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

3. A thread calling wait() releases the lock, moves to waitSet , and waits to be notified.

4. Upon completing execution, the thread releases the lock, decrementing the count.

Difference between synchronized and ReentrantLock?

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

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

Both are re‑entrant.

Both are non‑fair by default; ReentrantLock also supports a fair mode.

ReentrantLock offers multiple lock acquisition methods: lock(), lockInterruptibly(), tryLock(), tryLock(timeout, TimeUnit), and can bind multiple Condition objects.

Principle of AbstractQueuedSynchronizer (AQS)?

AQS maintains a state field. Lock acquisition attempts CAS the state to 1 and record the owning thread ID; release resets state to 0 and clears the thread ID, waking queued threads.

Drawbacks of CAS?

CAS suffers from the ABA problem in high‑contention scenarios. Solutions include version counters or using AtomicStampedReference to pair a value with a stamp.

Common Java locks?

Optimistic and pessimistic locks

Distributed locks

Exclusive and shared locks

Mutex locks

Read‑write locks

Fair and non‑fair locks

Reentrant locks

Spin locks

Segmented locks

Lock upgrades (biased, lightweight, heavyweight)

Lock optimizations (lock coarsening, lock elimination)

HashMap principle?

HashMap consists of an array and linked lists (or red‑black trees in JDK 8+). Insertion computes a hash, places the entry in the bucket, and may convert a long list to a tree when the threshold is exceeded. Retrieval follows the same hash lookup.

How does ConcurrentHashMap ensure thread safety?

In JDK 7 it uses segment‑level locking (Segment + ReentrantLock). In JDK 8 it drops segments, using CAS and synchronized on bins, with array + linked list + red‑black tree structures.

Difference between ArrayList and LinkedList?

ArrayList: backed by a dynamic array, supports fast random access, insertion/deletion at the end is O(1), but middle operations are O(n); not thread‑safe.

LinkedList: backed by a doubly‑linked list, insertion/deletion anywhere is O(1), random access is O(n); not thread‑safe.

volatile 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 weakly‑referenced entries (key = ThreadLocal, value = thread‑specific data). Removing the entry via remove() prevents memory leaks.

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

ThreadPoolExecutor constructor parameters?

corePoolSize, maximumPoolSize, keepAliveTime, timeUnit, workQueue, threadFactory, rejectionHandler.

ThreadPoolExecutor rejection policies?

AbortPolicy (default)

CallerRunsPolicy

DiscardOldestPolicy

DiscardPolicy

Custom policies 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 readiness.

JavaJVMConcurrencyThreadJDKInterviewCollections
Wukong Talks Architecture
Written by

Wukong Talks Architecture

Explaining distributed systems and architecture through stories. Author of the "JVM Performance Tuning in Practice" column, open-source author of "Spring Cloud in Practice PassJava", and independently developed a PMP practice quiz mini-program.

0 followers
Reader feedback

How this landed with the community

login 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.