









































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The Java Technical Interview Ultimate Exam is an advanced preparation resource created for software developers and programmers preparing for Java coding interviews and technical assessments. This exam includes core Java concepts, object-oriented programming principles, data structures, algorithms, multithreading, collections framework, exception handling, JDBC, Spring fundamentals, and coding problem-solving scenarios frequently asked in interviews. The preparation materials help candidates improve technical proficiency, analytical thinking, and confidence during Java developer interviews and assessments.
Typology: Exams
1 / 49
This page cannot be seen from the preview
Don't miss anything!










































Question 1. Which component of the JVM is responsible for loading core Java classes such as java.lang.Object? A) Application ClassLoader B) Extension ClassLoader C) Bootstrap ClassLoader D) System ClassLoader Answer: C Explanation: The Bootstrap ClassLoader loads the core Java runtime classes from the /jre/lib directory, including java.lang.Object. Question 2. In which JVM memory area are local variables and method call frames stored? A) Heap B) Metaspace C) Stack D) Code Cache Answer: C Explanation: The Java stack holds frames for each method invocation, containing local variables, operand stacks, and return addresses. Question 3. Which of the following statements about autoboxing is true? A) Autoboxing always creates a new wrapper object. B) Autoboxing can cause hidden performance overhead due to object creation. C) Autoboxing is only applicable to primitive type int. D) Autoboxing bypasses the JVM’s garbage collector. Answer: B Explanation: Autoboxing converts a primitive to its wrapper class, potentially creating new objects and incurring allocation and GC overhead.
Question 4. Which of the following comparisons correctly checks if two strings have the same contents? A) str1 == str2 B) str1.equals(str2) C) str1.compareTo(str2) == 0 D) Both B and C are correct. Answer: D Explanation: String.equals checks content equality, and compareTo returns 0 for equal strings; == checks reference equality. Question 5. What is the primary advantage of using StringBuilder over String when concatenating many strings in a loop? A) Thread-safety B) Immutable nature C) Reduced memory allocation D) Automatic pooling of characters Answer: C Explanation: StringBuilder is mutable, allowing in-place modifications, which avoids creating many intermediate String objects. Question 6. Which garbage collector is designed for low pause times and works well with large heaps? A) Serial GC B) Parallel GC C) G1 GC D. ZGC Answer: D Explanation: ZGC (Z Garbage Collector) is a low-latency collector targeting pause times of a few milliseconds, even with multi-terabyte heaps. Question 7. When overriding equals(), which contract must also be satisfied?
C) When you want to enforce a strict “is-a” relationship. D) When you need multiple inheritance of state. Answer: A Explanation: Composition (“has-a”) enables code reuse without the tight coupling inherent in inheritance. Question 11. Which SOLID principle states that a class should have only one reason to change? A) Open/Closed Principle B) Single Responsibility Principle C) Liskov Substitution Principle D) Interface Segregation Principle Answer: B Explanation: The Single Responsibility Principle (SRP) dictates that a class should have one responsibility. Question 12. In the Observer design pattern, which component notifies observers of state changes? A) ConcreteObserver B) Subject C) ConcreteSubject D) Observer Interface Answer: C Explanation: The ConcreteSubject (or Subject implementation) maintains a list of observers and notifies them when its state changes. Question 13. Which creational pattern ensures that only one instance of a class exists throughout the JVM? A) Factory Method B) Builder C) Prototype
D) Singleton Answer: D Explanation: The Singleton pattern restricts instantiation to a single object, often using a private constructor and a static accessor. Question 14. What is the time complexity of ArrayList.get(int index)? A) O(1) B) O(log n) C) O(n) D) O(n log n) Answer: A Explanation: ArrayList stores elements in a contiguous array, allowing constant-time random access. **Question 15. Which internal structure does LinkedList use to store its elements? ** A) Dynamic array B) Doubly-linked nodes C) Hash table D) Binary tree Answer: B Explanation: LinkedList is implemented as a doubly-linked list, enabling constant-time insertions/removals at both ends. Question 16. How does HashSet ensure uniqueness of its elements? A) By storing elements in a sorted tree. B) By using the element’s hashCode() and equals() methods. C) By maintaining a linked list of all elements. D) By using reference equality only. Answer: B
Explanation: CopyOnWriteArrayList creates a fresh copy on each mutative operation, allowing safe iteration without locks. Question 20. Which interface should a class implement to define a natural ordering? A) Comparator B) Comparable C) Iterable D) Serializable Answer: B Explanation: Implementing Comparable allows an object to define its own natural ordering via compareTo. Question 21. Which thread state indicates that a thread is waiting indefinitely for another thread to release a monitor? A) RUNNABLE B) BLOCKED C) TIMED_WAITING D) WAITING Answer: B Explanation: A thread in the BLOCKED state is waiting to acquire a monitor lock held by another thread. Question 22. What does the volatile keyword guarantee? A) Atomicity of compound actions. B) Visibility of changes to other threads and ordering of reads/writes. C) Mutual exclusion. D) That the variable is stored on the heap. Answer: B Explanation: volatile ensures that reads/writes go directly to main memory, providing visibility and preventing certain reordering.
Question 23. Which executor service method schedules a task to run after a fixed delay? A) execute(Runnable) B) submit(Callable) C) schedule(Runnable, long delay, TimeUnit unit) D) invokeAll(Collection>) Answer: C Explanation: ScheduledExecutorService.schedule schedules a one-time execution after the specified delay. Question 24. Which lock allows multiple readers but only one writer at a time? A) ReentrantLock B) StampedLock C) ReadWriteLock D) Semaphore Answer: C Explanation: ReadWriteLock provides a read lock (shared) and a write lock (exclusive), enabling high concurrency for read-heavy workloads. Question 25. Which method must be called to release a lock obtained via ReentrantLock.lock()? A) unlock() B) release() C) close() D) signal() Answer: A Explanation: ReentrantLock.unlock() releases the lock; failing to call it can cause deadlocks.
A) Function B) Consumer C) Supplier D) Predicate Answer: D Explanation: Predicate has a single abstract method test(T t) returning a boolean. Question 30. In a stream pipeline, which operation is intermediate? A) collect() B) reduce() C) filter() D) forEach() Answer: C Explanation: filter returns a new stream and is evaluated lazily; terminal operations like collect trigger execution. Question 31. Which method of Optional returns the contained value or throws NoSuchElementException if empty? A) orElse(T other) B) orElseGet(Supplier supplier) C) get() D) orElseThrow() Answer: C Explanation: Optional.get() retrieves the value but throws if the Optional is empty; other methods provide safe alternatives. Question 32. Which Java keyword allows local variable type inference introduced in Java 10? A) let B) var
C) auto D) def Answer: B Explanation: var lets the compiler infer the variable’s type from the initializer. Question 33. Which of the following is a valid text block syntax introduced in Java 13? A) """Hello World""" B) """ followed by newline, content, then """ on a new line. C) """ on the same line as content, ending with """. D) """ must be preceded by a semicolon. Answer: B Explanation: Text blocks start with """ followed by a newline, contain the text, and end with """ on its own line. Question 34. What is a Java record primarily used for? A) Defining mutable objects with custom getters/setters. B) Creating lightweight immutable data carriers with automatically generated methods. C) Implementing the Singleton pattern. D) Providing a way to store binary data. Answer: B Explanation: Records automatically generate equals, hashCode, toString, and accessor methods for declared components, and are immutable. Question 35. Which statement about sealed classes (Java 17) is correct? A) A sealed class can be subclassed by any class in the same package. B) Sealed classes must declare permitted subclasses using the permits clause. C) Sealed classes cannot be abstract. D) Sealed classes are final by definition.
Explanation: System.exit() terminates the JVM immediately; finally blocks are not executed. Question 39. Which statement correctly creates a custom unchecked exception? A) class MyException extends Exception {} B) class MyException extends RuntimeException {} C) class MyException extends Throwable {} D) class MyException implements Serializable {} Answer: B Explanation: Extending RuntimeException creates an unchecked exception that does not need to be declared or caught. Question 40. Which logging facade allows you to plug in different logging implementations at runtime? A) java.util.logging B) Log4j C) SLF4J D) java.util.logging.Logger Answer: C Explanation: SLF4J (Simple Logging Facade for Java) provides a uniform API while delegating to concrete implementations like Logback or Log4j2. Question 41. In Spring, which annotation marks a class as a candidate for component scanning and automatic bean creation? A) @Service B) @Repository C) @Component D) @Bean Answer: C Explanation: @Component is the generic stereotype; @Service and @Repository are specializations but also trigger scanning.
Question 42. Which Spring annotation indicates that a method should be executed within a transactional context? A) @Transactional B) @EnableTransactionManagement C) @Commit D) @Atomic Answer: A Explanation: @Transactional demarcates transaction boundaries for the annotated method or class. Question 43. What problem does the “N+1 selects” issue describe in JPA/Hibernate? A) Executing N+1 concurrent transactions. B) Performing one query to fetch parent entities and N additional queries to fetch each child collection. C) Using N+1 threads for a single query. D) Overloading the connection pool with N+1 connections. Answer: B Explanation: The N+1 problem occurs when lazy loading triggers separate queries for each association, leading to performance degradation. Question 44. Which Spring Boot starter provides embedded Tomcat, Jetty, or Undertow servers automatically? A) spring-boot-starter-web B) spring-boot-starter-data-jpa C) spring-boot-starter-security D) spring-boot-starter-actuator Answer: A Explanation: spring-boot-starter-web pulls in spring-boot-starter-tomcat (or Jetty/Undertow) for serving HTTP requests.
A) Monolith B) Microservices C) Layered Architecture D) Client-Server Answer: B Explanation: Microservices decompose a system into small, independently deployable services. Question 49. Which component in a microservice ecosystem is responsible for routing requests to appropriate services and handling cross-cutting concerns? A) Service Registry B) API Gateway C) Circuit Breaker D) Message Broker Answer: B Explanation: An API Gateway acts as a single entry point, handling routing, authentication, rate limiting, etc. Question 50. Which pattern helps prevent cascading failures by providing fallback behavior when a remote call fails? A) Proxy B) Circuit Breaker C) Strategy D) Decorator Answer: B Explanation: The Circuit Breaker pattern monitors failures and opens the circuit to return a fallback, protecting the system. Question 51. Which Kafka consumer configuration controls the maximum number of records returned in a single poll? A) max.poll.interval.ms
B) fetch.min.bytes C) max.poll.records D) consumer.timeout.ms Answer: C Explanation: max.poll.records limits the number of records the consumer receives per poll() call. Question 52. Which JWT claim typically contains the user’s unique identifier? A) iss (issuer) B) sub (subject) C) aud (audience) D) exp (expiration) Answer: B Explanation: The sub claim represents the principal (often a user ID) that the token refers to. Question 53. Which isolation level prevents dirty reads but allows non-repeatable reads? A) READ_UNCOMMITTED B) READ_COMMITTED C) REPEATABLE_READ D) SERIALIZABLE Answer: B Explanation: READ_COMMITTED ensures that a transaction only sees committed data, avoiding dirty reads; however, rows can change between reads. Question 54. Which caching strategy stores frequently accessed data in memory to reduce database load? A) Write-through cache B) Lazy loading cache
D) record Person(int id, String name); Answer: B Explanation: The canonical record declaration includes the component list in parentheses followed by an optional body. Question 58. Which lock implementation provides optimistic read operations that may fail and need to be retried? A) ReentrantLock B) ReadWriteLock C) StampedLock D) Semaphore Answer: C Explanation: StampedLock offers tryOptimisticRead which can be validated; if the lock was written in the meantime, the read must be retried. Question 59. Which method of Thread causes the current thread to pause execution for a specified time? A) sleep(long millis) B) wait(long timeout) C) yield() D) join(long millis) Answer: A Explanation: Thread.sleep suspends the current thread for the given duration. Question 60. In Java streams, which terminal operation returns the first element of a stream wrapped in an Optional? A) findAny() B) findFirst() C) anyMatch() D) allMatch() Answer: B
Explanation: findFirst returns an Optional containing the first element, respecting encounter order. Question 61. Which of the following is NOT a valid way to create an immutable collection in Java 9+? A) List.of(1,2,3) B) Set.of("a","b") C) Map.of(1,"one",2,"two") D) Collections.unmodifiableList(new ArrayList<>()) Answer: D Explanation: While Collections.unmodifiableList returns an unmodifiable view, the underlying list can still be modified; the others produce truly immutable collections. Question 62. Which annotation is used to map a method argument to a URI path variable in Spring MVC? A) @RequestParam B) @PathVariable C) @RequestHeader D) @ModelAttribute Answer: B Explanation: @PathVariable binds a method parameter to a template variable in the request URI. Question 63. Which JPA annotation defines a bidirectional one-to-many relationship? A) @OneToOne B) @ManyToOne C) @OneToMany(mappedBy="parent") D) @ManyToMany Answer: C