Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

Java

Recruitment and knowledge question base. Filter, search and test your knowledge.

Topics

What is polymorphism?

easyooppolymorphismjava+1
Open question

Answer

Polymorphism lets you treat different objects through the same interface or superclass. Calling an overridden method on a base reference uses dynamic dispatch to run the concrete implementation at runtime; overloading provides compile‑time polymorphism.

Checked vs Unchecked Exceptions?

mediumexceptionerror-handlingjava
Open question

Answer

Checked exceptions must be caught or declared in a method’s throws clause (e.g., IOException) and represent recoverable conditions. Unchecked exceptions extend RuntimeException (e.g., NullPointerException) and usually signal programming errors; handling them is optional.

Interface vs Abstract Class?

mediumoopinterfaceabstract-class+2
Open question

Answer

An interface defines a contract; a class can implement many interfaces and interfaces can have default/static methods but no instance state. An abstract class can hold fields, constructors and partial implementation, but a class can extend only one. Use interfaces for capabilities and abstract classes for shared base behavior.

Why is String immutable in Java?

easystringimmutabilitymemory+1
Open question

Answer

String is immutable so it can be safely shared between threads, cached/interned in the String pool, and reliably used as a key in hash‑based collections (stable hashCode). It also improves security because values like class names or file paths can’t be modified after creation.

Java Memory Model: Stack vs Heap?

mediummemorystackheap+2
Open question

Answer

The stack is per‑thread memory holding call frames, local primitives and references; it’s allocated/deallocated on method entry/exit and is very fast. The heap is shared memory where all objects and arrays live; it’s managed by the garbage collector and objects usually outlive a single method call.

In Java, what’s the difference between `==` and `.equals()`?

easyequalsreferencestring
Open question

Answer

`==` compares references for objects (same instance), while `.equals()` compares logical equality as defined by the class (e.g., `String` compares content). For primitives, `==` compares values.

What does `final` mean for a variable, a method, and a class?

easyfinalinheritancejava-basics
Open question

Answer

A `final` variable can’t be reassigned, a `final` method can’t be overridden, and a `final` class can’t be extended. (It does not automatically make an object immutable.)

String vs StringBuilder vs StringBuffer — when to use which?

easystringstringbuilderperformance
Open question

Answer

`String` is immutable, so repeated concatenation creates many objects. `StringBuilder` is mutable and fast for building strings in a single thread; `StringBuffer` is similar but synchronized (rarely needed today).

Checked vs unchecked exceptions — what’s the difference?

mediumexceptionscheckedruntimeexception
Open question

Answer

Checked exceptions must be declared or handled at compile time (they extend `Exception` but not `RuntimeException`). Unchecked exceptions (`RuntimeException`) don’t require it and usually indicate programming errors or invalid state.

Autoboxing/unboxing — what is it and what are common pitfalls?

mediumautoboxingwrappernpe
Open question

Answer

Autoboxing converts primitives to wrappers (e.g., `int`→`Integer`) and unboxing does the reverse. Pitfalls: unboxing `null` causes NPE, `Integer` caching can confuse `==`, and extra allocations can hurt performance in hot code.

HashMap vs ConcurrentHashMap — what’s the practical difference?

mediumhashmapconcurrencyconcurrenthashmap
Open question

Answer

`HashMap` is not thread-safe; concurrent writes can corrupt it. `ConcurrentHashMap` supports safe concurrent access with good performance (and disallows null keys/values). Use it when multiple threads read/write without external locking.

Why must `equals()` and `hashCode()` follow a contract?

hardequalshashcodehashmap
Open question

Answer

If two objects are equal according to `equals()`, they must have the same `hashCode()`. Hash-based collections (HashMap/HashSet) rely on it; breaking the contract leads to “missing” entries and hard-to-debug behavior.

`volatile` vs `synchronized` — what problem does each solve?

hardconcurrencyvolatilesynchronized
Open question

Answer

`volatile` guarantees visibility (and ordering) of a variable between threads, but doesn’t make compound operations atomic. `synchronized` provides mutual exclusion and also establishes happens-before (visibility) for the protected code.

How does Java GC work at a high level (and why is it generational)?

hardgcjvmmemory
Open question

Answer

The heap is typically split into young/old generations: most objects die young, so collecting the young gen is cheap and frequent (minor GC). Surviving objects are promoted; old gen collections are rarer and usually more expensive.

CompletableFuture — what is it good for and a common pitfall?

hardcompletablefutureasyncconcurrency
Open question

Answer

It represents an async computation that you can compose (`thenApply/thenCompose`) without blocking. A common pitfall is calling `get()/join()` too early (turning it back into blocking code) or forgetting to handle exceptions (`exceptionally/handle`).

In Java, what does `static` mean for a field and a method?

easystaticclassoop
Open question

Answer

`static` means it belongs to the class, not to a specific instance. A static field is shared by all objects, and a static method can be called without creating an instance (but it can’t access instance fields directly).

HashSet vs TreeSet — what’s the difference?

mediumsethashsettreeset+2
Open question

Answer

HashSet is usually faster for add/contains (average O(1)) because it’s hash-based. TreeSet keeps elements sorted (balanced tree), so operations are O(log n) but you get ordering and range queries.

What is `Optional` used for, and what is a common misuse?

mediumoptionalnull-safetyapi
Open question

Answer

`Optional` represents a value that may be present or absent and forces the caller to handle the empty case. A common misuse is using it as a field in entities/DTOs everywhere; it’s mainly intended for return values, not for serialization or persistence fields.

How can you have a memory leak in Java even with garbage collection?

hardmemory-leakgcreferences+1
Open question

Answer

GC frees only objects that are unreachable. If you keep references by mistake (e.g., a static list/map that grows, caches without eviction, listeners not removed), objects stay reachable and memory usage grows.

Why is `ArrayList` not thread-safe, and how can you make list access safe?

hardconcurrencyarraylistthread-safety+1
Open question

Answer

`ArrayList` has no synchronization, so concurrent writes can corrupt its internal state or cause inconsistent reads. Options: external locking, `Collections.synchronizedList`, `CopyOnWriteArrayList` for mostly-reads, or using concurrent queues depending on the use case.

Interface vs abstract class — what’s the difference in Java?

easyinterfaceabstract-classoop
Open question

Answer

An interface defines a contract (what methods exist) and supports multiple inheritance of type. An abstract class can share state and implementation, but you can extend only one class. Use interface for capability, abstract class for shared base behavior.

HashMap vs LinkedHashMap — what’s the practical difference?

mediumhashmaplinkedhashmapcollections
Open question

Answer

HashMap doesn’t guarantee iteration order. LinkedHashMap maintains insertion order (or access order if configured), which is useful for predictable iteration and for building LRU-like caches.

What is try-with-resources and why should you use it?

mediumtry-with-resourcesautocloseableio
Open question

Answer

It automatically closes resources that implement `AutoCloseable` (files, streams, JDBC) even when exceptions happen. It prevents leaks and keeps cleanup logic reliable and simple.

Java Memory Model: what does “happens-before” mean (in simple terms)?

hardjmmhappens-beforeconcurrency+1
Open question

Answer

Happens-before is a rule that guarantees visibility and ordering between threads. If A happens-before B, then B must see the effects of A (e.g., via `synchronized`, `volatile`, or thread start/join).

WeakReference — what is it and when is it useful?

hardweakreferenceweakhashmapgc+1
Open question

Answer

A weak reference doesn’t prevent GC: if an object is only weakly referenced, it can be collected. It’s useful for memory-sensitive caches (e.g., WeakHashMap) where you’d rather drop entries than leak memory.

JDK vs JRE vs JVM - what is each?

easyjvmjrejdk+1
Open question

Answer

JVM runs Java bytecode. JRE is the runtime environment (JVM + standard libraries) needed to run apps. JDK is the development kit (JRE + compiler and tools) needed to build apps.

What is a Java record and when would you use it?

mediumrecordsdtoimmutability+1
Open question

Answer

A record is a concise syntax for an immutable data carrier. It generates final fields, a constructor, and `equals/hashCode/toString` automatically. Use it for DTOs, messages, and value-like objects—not for entities with complex mutable lifecycle.

Streams vs collections: what is the difference and a common pitfall?

mediumstreamscollectionsside-effects+1
Open question

Answer

A collection stores data; a stream describes a pipeline of operations (filter/map/reduce) to produce a result. Streams are typically single-use, and a common pitfall is side effects (mutating external state) inside `map/forEach`, which makes code harder to reason about.

What does `ThreadLocal` do and what is a common pitfall?

hardthreadlocalconcurrencythread-pool+1
Open question

Answer

`ThreadLocal` stores a separate value per thread (often used for request context). The common pitfall is thread pools: threads are reused, so values can “leak” between requests unless you clear them (`remove()` in a `finally`).

`synchronized` vs `ReentrantLock` - when would you choose one?

hardconcurrencylockssynchronized+1
Open question

Answer

`synchronized` is simpler and uses JVM monitors, giving mutual exclusion and a clear happens-before relationship. `ReentrantLock` is more flexible: `tryLock()`, timeouts, fairness options, and multiple `Condition`s—but you must always `unlock()` in `finally`.

What is the Java classpath and what is it used for?

easyclasspathjvmjar+1
Open question

Answer

The classpath is the list of places where the JVM looks for classes and resources (directories and JARs). If something is not on the classpath, you can get `ClassNotFoundException` / `NoClassDefFoundError`. You set it via build tools, IDE, or `-cp` when running Java.

Java `var`: what does it do and what does it NOT do?

mediumjavavartype-inference+1
Open question

Answer

`var` enables local variable type inference: the compiler infers the static type from the initializer. It does NOT make Java dynamically typed. You can use it only for local variables with an initializer (not for fields, method params, or without assignment).

`List.of(...)`: what kind of list does it create and a common gotcha?

mediumjavacollectionsimmutability+1
Open question

Answer

`List.of(...)` creates an unmodifiable (immutable) list. If you try to add/remove elements, you get `UnsupportedOperationException`. A common gotcha: it also does not allow null elements (it throws `NullPointerException` on creation).

Parallel streams: when can they help and what are common pitfalls?

hardjavastreamsparallel+2
Open question

Answer

Parallel streams can help for CPU-bound work on large collections when each element is independent and the work is heavy enough to amortize overhead. Pitfalls: they use `ForkJoinPool.commonPool` by default, they can be slower for small tasks, they are bad for blocking I/O, and side effects/shared mutable state can cause race conditions.

ClassLoaders: what are they and why can they cause surprising ClassCastException?

hardjavaclassloaderjvm+1
Open question

Answer

A ClassLoader loads classes/resources. In Java, a type is identified by (class name + defining ClassLoader). That means the “same” class name loaded by two different classloaders is treated as two different types, which can cause `ClassCastException` in plugin/app-server setups.

What is type erasure in Java generics and what limitation does it cause?

mediumjavagenericstype-erasure+1
Open question

Answer

Type erasure means generic type information is removed at runtime. As a result, you can’t do `new T()`, `T.class`, or `instanceof T`, and some generic checks are only compile‑time. The runtime sees raw types.

Java `record`: what does it generate and when is it a good fit?

easyjavarecorddto+1
Open question

Answer

A `record` is a concise data carrier. It generates private final fields, a canonical constructor, accessors, `equals`, `hashCode`, and `toString`. It’s a good fit for DTOs/value objects where equality is based on data, but it doesn’t make contained objects immutable.

What are sealed classes in Java and why use them?

mediumjavasealedinheritance+1
Open question

Answer

Sealed classes restrict which classes can extend/implement them (`permits`). This makes class hierarchies explicit and enables exhaustive `switch` in newer Java versions. It’s useful for modeling closed sets of variants.

`synchronized` vs `ReentrantLock`: what are the differences?

mediumjavaconcurrencylocks+1
Open question

Answer

`synchronized` uses intrinsic monitor locks with automatic release. `ReentrantLock` is an explicit lock with features like `tryLock`, fairness policies, and interruptible lock acquisition—but you must release it in `finally`. Both are reentrant.

Try-with-resources: what does it require and why is it useful?

easyjavaexceptionsresources+1
Open question

Answer

It requires resources that implement `AutoCloseable`. The resource is closed automatically (even on exceptions), which reduces boilerplate and prevents leaks. It’s safer than manual `finally` blocks.

StringBuilder vs StringBuffer: what’s the difference?

easyjavastringperformance+1
Open question

Answer

StringBuilder is not synchronized and is faster in single‑threaded code. StringBuffer is synchronized (thread‑safe), but usually slower. Both are mutable alternatives to `String`.

HashMap vs ConcurrentHashMap: when should you use each?

mediumjavacollectionsconcurrency+1
Open question

Answer

HashMap is not thread‑safe and is best for single‑threaded or externally synchronized use. ConcurrentHashMap supports safe concurrent reads/writes with better scalability; it disallows null keys/values. Use it when multiple threads access the map without external locking.

Generational garbage collection: why does the JVM split memory into young/old?

mediumjavagcjvm+2
Open question

Answer

Most objects die young. The JVM exploits this by collecting the young generation frequently (fast minor GCs) and promoting long‑lived objects to the old generation, which is collected less often. This improves throughput and pause times.

JIT compilation: what is it and why do Java apps “warm up”?

mediumjavajitperformance+1
Open question

Answer

The JVM starts by interpreting bytecode, then JIT‑compiles “hot” methods to native code based on profiling. Early requests can be slower; after warm‑up, optimized machine code runs faster.

Static nested class vs inner class: what’s the difference?

mediumjavanested-classinner-class+1
Open question

Answer

A static nested class does not hold an implicit reference to the outer instance; it can be created without an outer object. An inner class holds a reference to the outer instance, which can increase memory usage and lead to leaks if misused.