Information Technology
Java Interview Questions & Answers
Robust, object-oriented language for enterprise backend systems.
Annotations
All 15 questionsAnnotations are a form of metadata that attach information to Java code elements (classes, methods, fields, parameters) without directly affecting program logic -- they're read by…
- How do you create a custom annotation in Java, and what role do @Retention and @Target play? Intermediate
A custom annotation is defined using @interface; @Retention specifies how long the annotation is retained (SOURCE, CLASS, or RUNTIME -- with RUNTIME needed if you want to read it v…
Use java.lang.reflect classes (Class.getDeclaredMethods(), Method.getAnnotation(YourAnnotation.class), Field.isAnnotationPresent()) to inspect a class's structure at runtime, check…
Compile-time annotation processing runs during compilation itself (implementing AbstractProcessor, registered via META-INF/services), generating new source files or validating code…
@Override tells the compiler a method is intended to override a superclass/interface method, causing a compile error if no matching method actually exists (catching typos like a mi…
Arrays & Multidimensional Arrays
All 15 questionsAn array is declared with a type followed by square brackets (int[] arr), instantiated with new specifying its fixed size (new int[5]) or using an initializer literal ({1, 2, 3}),…
Java doesn't have true multidimensional arrays in the C sense; a 2D array (int[][]) is actually an array of arrays, where each row is an independently allocated one-dimensional arr…
Java arrays are covariant, meaning Object[] arr = new String[3] is legal (a String[] reference can be assigned to an Object[] variable) since arrays retain their actual runtime com…
Arrays provides static utility methods including sort() (in-place sorting, dual-pivot quicksort for primitives, TimSort for objects), binarySearch() (requires a pre-sorted array),…
System.arraycopy() is a native method performing highly optimized bulk memory copying (often using intrinsic CPU instructions), generally the fastest option for copying array range…
Build Tools: Maven & Gradle
All 15 questionsBuild tools automate compiling source code, managing external library dependencies (downloading and resolving version conflicts automatically), running tests, packaging the applica…
Maven's default lifecycle is a fixed, ordered sequence of phases, where running any given phase automatically executes all preceding phases in order: validate (checks project struc…
When multiple dependencies (directly or transitively) require different versions of the same library, Maven resolves the conflict using "nearest definition wins": the version decla…
Maven's pom.xml is a purely declarative XML document describing what the project needs (dependencies, plugins, configuration), with the actual build logic entirely hidden inside Ma…
Gradle tracks fine-grained inputs and outputs for every task (source files, dependency versions, configuration), using content hashing to detect whether a task's actual inputs have…
Class Loading & Bytecode Verification
All 15 questionsA ClassLoader is responsible for locating and loading .class files (bytecode) into the JVM at runtime, converting them into Class objects usable by running code -- the JVM has a hi…
- What is the parent delegation model in Java class loading, and why is it important for security and consistency? Intermediate
The parent delegation model means a class loader, before attempting to load a class itself, first delegates the request up to its parent loader (bootstrap being the ultimate root),…
A custom ClassLoader extends ClassLoader (or URLClassLoader for JAR/URL-based loading) and overrides findClass() to define how to locate and read the raw bytecode from your custom…
- What are the phases of class loading (loading, linking, initialization), and what specifically happens during each? Intermediate
Loading finds the class's bytecode and creates its Class object in memory; Linking has three sub-phases -- verification (bytecode verifier checks the class file is structurally val…
Bytecode verification is a mandatory JVM safety check performed during the linking phase, ensuring loaded bytecode (whether from a trusted compiler or a potentially malicious/corru…
Collections Framework
All 15 questionsThe Collections Framework is a unified architecture of interfaces and implementations for storing and manipulating groups of objects -- List represents an ordered, index-accessible…
ArrayList backs its elements with a resizable array, giving O(1) random access (get(index)) but O(n) insertion/removal at arbitrary positions (requires shifting subsequent elements…
HashMap stores entries in an internal array of buckets, using a key's hashCode() (further scrambled via an internal hash-spreading function to reduce clustering) to determine the t…
Any two objects considered equal via equals() MUST return the identical hashCode() value (though the converse isn't required -- unequal objects may share a hash code, called a coll…
HashMap provides no ordering guarantee whatsoever (iteration order can even change between runs or after resizing), offering the best average-case O(1) performance for get/put/remo…
Concurrency & Threads
All 15 questionsYou can either extend the Thread class directly (overriding run()) or implement the Runnable functional interface (defining run() and passing an instance to a new Thread) -- implem…
synchronized (applied to a method, or as a block with an explicit object reference) ensures only one thread at a time can execute the protected code while holding that object's int…
ReentrantLock provides everything synchronized offers (mutual exclusion, reentrancy -- a thread already holding the lock can re-acquire it without deadlocking itself) plus addition…
ExecutorService decouples task submission from the mechanics of thread creation, pooling, and lifecycle management -- a fixed or cached thread pool (created via Executors factory m…
CompletableFuture represents a value that will be available asynchronously in the future, with fluent composition methods letting you chain dependent asynchronous operations withou…
Design Patterns in Java
All 15 questions- What is the Singleton pattern, and how would you implement a thread-safe Singleton in Java? Beginner
Singleton ensures a class has exactly one instance and provides a global access point to it -- the enum-based approach is generally considered the simplest, safest way to implement…
The telescoping constructor problem arises when a class has many optional fields, leading to an unwieldy proliferation of overloaded constructors covering various combinations of p…
The Observer pattern defines a one-to-many dependency where a subject notifies registered observers of state changes -- implementable manually with a List and a notify loop, via th…
Strategy defines a family of interchangeable algorithms behind a common interface, letting the algorithm used by a context object be selected/swapped at runtime -- prior to Java 8,…
Decorator lets you dynamically add responsibilities to an object by wrapping it in one or more decorator objects that implement the same interface as the original, each adding its…
Enums
All 15 questionsAn enum defines a fixed, type-safe set of named constants, where each constant is actually a full singleton instance of the enum type itself -- unlike int or String constants (whic…
Since each enum constant is a singleton instance, an enum can have instance fields (typically final, set via a private constructor invoked implicitly for each constant), and both r…
An enum can have each individual constant override an abstract method with its own unique implementation (a "constant-specific class body"), letting the enum itself directly encaps…
EnumSet and EnumMap are specialized collection implementations designed exclusively for use with enum types, internally represented as a compact bitvector (EnumSet) or array indexe…
Every enum implicitly extends java.lang.Enum (making explicit inheritance of another class impossible, since Java lacks multiple inheritance), with each constant compiled as a publ…
equals(), hashCode() & toString() Contracts
All 15 questionsObject's default equals() implementation performs reference equality (== comparison, true only if both references point to the exact same instance), and its default hashCode() is t…
Reflexive: x.equals(x) must always be true; Symmetric: x.equals(y) must equal y.equals(x); Transitive: if x.equals(y) and y.equals(z), then x.equals(z) must also be true; Consisten…
Using getClass() == getClass() comparison in equals() strictly requires both objects to be the exact same runtime class (a subclass instance is never equal to a superclass instance…
Objects.equals(a, b) performs a null-safe equality check (returning true if both are null, false if only one is null, and delegating to a.equals(b) otherwise), avoiding the need to…
The equals()/hashCode() contract requires that equal objects (per equals()) MUST produce the same hashCode() value -- if you override equals() to compare field values but leave has…
Exceptions
All 15 questionsChecked exceptions (subclasses of Exception but not RuntimeException, like IOException) must either be caught or explicitly declared in a method's throws clause, enforced by the co…
try-with-resources (any resource implementing AutoCloseable, declared within the try's parentheses) automatically calls the resource's close() method when the try block exits, whet…
When catching a lower-level exception and throwing a different, higher-level exception more meaningful to the caller (a common pattern for translating a checked exception into an u…
Catching an overly broad exception type (Exception, or especially Throwable, which also catches Errors like OutOfMemoryError that generally indicate unrecoverable JVM-level problem…
A well-designed custom exception hierarchy typically has a common base exception for the application/domain (like OrderException extends RuntimeException), with specific subtypes f…
Functional Interfaces & Method References
All 15 questionsA functional interface has exactly one abstract method, making it eligible for lambda expression or method reference assignment -- Function transforms an input of type T into an ou…
Static method reference (ClassName::staticMethod) refers to a static method; bound instance method reference (instance::method) refers to a specific, already-existing object's inst…
A lambda capturing a local variable from its enclosing method doesn't actually capture the variable itself, but rather captures a copy of its value at the time the lambda is create…
andThen(after) creates a composed function that first applies the original function, then applies the 'after' function to that result (f.andThen(g) means g(f(x))); compose(before)…
A custom functional interface is warranted specifically when a built-in interface's method name and semantic meaning wouldn't clearly communicate the interface's actual purpose in…
Garbage Collection
All 15 questionsGarbage collection automatically identifies and reclaims heap memory occupied by objects no longer reachable from any active reference (a local variable, static field, or another s…
The generational hypothesis observes that in typical applications, the vast majority of objects become garbage very shortly after creation (like short-lived local variables or temp…
G1 (Garbage-First, the default collector since Java 9) divides the heap into many small, equally-sized regions and prioritizes collecting the regions with the most garbage first, a…
A strong reference (the default, ordinary Java reference) prevents an object from ever being garbage collected as long as it exists; a SoftReference allows the object to be collect…
Despite automatic garbage collection, a Java application CAN still leak memory if objects remain unintentionally strongly reachable (via a reference chain the developer didn't inte…
Generics
All 15 questionsBefore generics (Java 5+), collections like List stored elements as plain Object references, meaning retrieving an element required an explicit cast (risking a runtime ClassCastExc…
Type erasure means the compiler uses generic type parameters ONLY for compile-time type checking, then removes (erases) them from the compiled bytecode, replacing an unbounded type…
? extends T (an upper-bounded wildcard) means the parameterized type is T or some unknown subtype of T, letting you safely READ elements as T (since whatever the actual type is, it…
A generic method declares its own type parameter(s) in angle brackets immediately before the return type (independent of whether the enclosing class itself is generic), and the com…
A class can declare multiple type parameters (class Pair ), and a bounded type parameter ( ) restricts what types can be substituted for T to only SomeType or its subtypes, letting…
I/O & NIO
All 15 questionsByte streams (InputStream/OutputStream) work with raw 8-bit bytes, appropriate for binary data (images, serialized objects, arbitrary binary files) where no text encoding interpret…
Unbuffered I/O typically issues a separate, relatively expensive system call to the underlying OS for every single read/write operation (even reading just one byte), while a buffer…
The classic java.io model is stream-oriented and blocking (a read() call blocks the calling thread until data is available or the stream ends, processing data sequentially byte-by-…
Path represents a file system location (replacing the older File class's more limited abstraction), and the Files utility class provides a comprehensive set of static methods (read…
Memory-mapped I/O (via FileChannel.map()) maps a region of a file directly into the process's virtual memory address space, letting you read/write file contents through simple memo…
Inner Classes & Anonymous Classes
All 15 questionsA non-static inner class is defined within another class and holds an implicit reference to a specific instance of its enclosing class, meaning an inner class instance cannot exist…
A static nested class is declared with the static modifier, meaning it does NOT hold an implicit reference to any specific enclosing instance and can be instantiated independently…
A local class is defined and named within a method body, scoped entirely to that method, usable multiple times within the method and even instantiated multiple times, capturing eff…
An anonymous class implementing a functional interface (like a click listener or comparator) provides an inline, one-off implementation directly at the point of use -- for interfac…
The compiler translates a non-static inner class into a genuinely separate top-level class file (named OuterClass$InnerClass.class) at compile time, adding a synthetic (compiler-ge…
Interfaces & Abstract Classes
All 15 questionsAn abstract class can have both abstract (unimplemented) and concrete (implemented) methods, constructors, instance fields with actual state, and any access modifier on its members…
A default method (marked with the default keyword) provides a concrete implementation directly within an interface, which implementing classes inherit automatically unless they cho…
If a class implements two interfaces that both declare a default method with the same signature, and NEITHER interface is a subtype of the other, the compiler forces the implementi…
A static method on an interface (also introduced in Java 8) belongs to the interface itself, not to any implementing class, meaning it's called via InterfaceName.staticMethod() and…
Private interface methods (both regular private instance methods and private static methods) let an interface share common implementation logic BETWEEN its own default methods with…
Java Date & Time API (java.time)
All 15 questionsThe legacy java.util.Date and Calendar classes suffered from serious, well-documented design flaws: Date was mutable (making it unsafe to share/cache without defensive copying), ha…
- What is the difference between LocalDate, LocalTime, LocalDateTime, and ZonedDateTime, and when would you use each? Intermediate
LocalDate represents a date without any time-of-day or timezone component (like a birthday, January 15); LocalTime represents a time-of-day without any date or timezone (like 'ever…
Instant represents a single, unambiguous point on the timeline measured as elapsed time since the epoch (1970-01-01T00:00:00Z), stored internally with nanosecond precision, entirel…
Period represents a date-based amount of time in human calendar terms (years, months, days), appropriate for calculating differences between LocalDate values where calendar irregul…
ZonedDateTime is DST-aware, automatically adjusting its underlying offset when arithmetic operations (like plusHours() or plusDays()) cross a DST transition boundary -- the 'spring…
Java Fundamentals: Syntax, Data Types & Operators
All 15 questionsThe eight primitives are byte, short, int, long (integer types of increasing size), float, double (floating-point types), char (a single 16-bit Unicode character), and boolean (tru…
Operator precedence determines which operators bind more tightly (evaluated first) in an expression with multiple different operators (multiplication/division bind tighter than add…
Autoboxing automatically converts a primitive value to its corresponding wrapper object (int to Integer via Integer.valueOf(), which the JVM's small-integer cache -128 to 127 may s…
== on String references compares object identity (whether both references point to the literal same object instance), while .equals() compares actual character content -- Java's st…
Widening conversions (byte to short to int to long to float to double, roughly in that order of increasing range) happen automatically/implicitly since they cannot lose information…
Java Networking & HTTP Client
All 15 questionsHttpClient provides a modern, fluent, builder-based API for constructing and sending HTTP requests (supporting HTTP/1.1 and HTTP/2, synchronous and asynchronous execution, and buil…
client.sendAsync(request, bodyHandler) immediately returns a CompletableFuture > without blocking the calling thread, letting you compose the eventual response using CompletableFut…
HttpResponse.BodyHandlers provides several built-in options beyond the common ofString()/ofByteArray() (which fully buffer the response body in memory before returning), including…
HttpClient.newBuilder() lets you configure a connectTimeout (maximum time to establish the initial TCP/TLS connection) at the client level, while an individual HttpRequest.Builder'…
Since HttpClient doesn't include built-in retry logic, implementing resilient retry behavior requires wrapping request execution in your own retry loop (or using a dedicated resili…
Java Platform Module System (JPMS)
All 15 questionsJPMS introduces explicit, JVM-enforced modules (declared via a module-info.java file) as a higher-level organizational unit above individual packages/JARs, letting you explicitly d…
requires ModuleName declares that your module depends on another named module, making that dependency's exported packages available to your module's own code (and causing a compile…
A plain requires ModuleName gives your module access to that dependency's exported packages, but does NOT automatically propagate that access to modules that in turn require YOUR m…
exports makes a package's public types accessible to other modules at COMPILE time and normal runtime method calls, but does NOT permit deep reflective access (like calling setAcce…
Any code placed on the traditional classpath (rather than the module path) is automatically treated as part of a special 'unnamed module', which is granted implicit access to read…