What is the difference between JDK, JRE and JVM?
Interview flashcards
264 questions collected from every lesson, from core Java to microservices. Try answering out loud before you reveal the model answer.
You know 0 of 264 questions.
Why is Java called platform independent?
What is autoboxing and what can go wrong?
Is var dynamic typing?
What is the difference between i++ and ++i?
What does short-circuit evaluation mean?
What is the difference between a switch statement and a switch expression?
What does yield do?
From Loops and arrays
Can you change an array's size?
From Loops and arrays
Array or ArrayList?
Is Java pass-by-reference for objects?
Overloading vs overriding?
Why does nextLine() return an empty string after nextInt()?
printf vs String.format?
Why not use double for money?
Random vs SecureRandom?
From Recursion
What causes StackOverflowError?
From Recursion
Recursion or iteration?
Can a constructor be private?
What is constructor chaining?
Can a static method access instance variables?
final, finally and finalize?
Why use packages?
What is package-private access?
What is the difference between protected and package-private?
Can an overriding method reduce visibility?
What are the four pillars of OOP?
Why doesn't Java allow multiple inheritance of classes?
Can you overload a method by changing only the return type?
Can a static method be overridden?
Animal a = new Dog(); which decides the method that runs, the reference or the object?
Upcasting vs downcasting?
When would you pick an abstract class over an interface today?
Can an interface have a constructor?
Can an interface have a constructor or instance fields?
When would you still choose an abstract class over an interface with default methods?
Why prefer composition over inheritance?
When is inheritance the right choice?
Aggregation vs composition?
How do IS-A and HAS-A map to Java code?
Static nested vs inner class?
When is an anonymous class still useful instead of a lambda?
From Enums in depth
Can enums have constructors?
From Enums in depth
Why are enums good singletons?
What does a record generate automatically?
Why use sealed classes?
What happens if you override equals without hashCode?
Can two unequal objects have the same hashCode?
From Immutable objects
How do you make a class immutable?
From Immutable objects
unmodifiableList vs List.copyOf?
Why is String immutable?
String vs StringBuilder vs StringBuffer?
From Regular expressions
matches() vs find()?
From Regular expressions
Why compile a Pattern once?
From Exception handling
Checked vs unchecked exceptions?
From Exception handling
Does finally always run?
Process vs thread?
Runnable vs Callable?
synchronized vs volatile?
How do you prevent deadlock?
shutdown() vs shutdownNow()?
What does a ThreadPoolExecutor do when all core threads are busy?
CountDownLatch vs CyclicBarrier?
How does AtomicInteger stay thread-safe without locks?
What is work stealing in ForkJoinPool?
When should you not use a parallel stream?
From CompletableFuture
thenApply vs thenCompose?
From CompletableFuture
Future vs CompletableFuture?
From Virtual threads
Virtual vs platform threads?
From Virtual threads
Do virtual threads make code faster?
ArrayList vs LinkedList?
HashSet vs LinkedHashSet vs TreeSet?
What is type erasure?
Explain PECS.
How does PriorityQueue order its elements?
Queue vs Deque?
ArrayList vs LinkedList: which is faster for random access and why?
When would you choose LinkedList?
HashMap vs LinkedHashMap vs TreeMap?
How would you build an LRU cache in Java?
What happens when two keys have the same hashCode?
Why is the default load factor 0.75?
Is hashCode() unique for every object?
Why is HashMap lookup O(1) on average?
Why is HashMap's capacity always a power of two?
What does h ^ (h >>> 16) do?
What does HashMap.put() return?
How does put() decide whether a key already exists?
What is the time complexity of HashMap.get()?
How do you tell a missing key from a key mapped to null?
What is a hash collision in HashMap?
What happens to HashMap performance if hashCode() always returns the same value?
How does HashMap handle collisions?
What is open addressing?
What is the equals/hashCode contract?
What happens if you override equals() but not hashCode() for a HashMap key?
What is the load factor of a HashMap?
Why is the default load factor 0.75?
What capacity does new HashMap<>(100) get?
How do you create a HashMap that holds n entries without resizing?
What happens during a HashMap resize in Java 8+?
Does a HashMap shrink when entries are removed?
When does a HashMap bucket become a red-black tree?
Why does HashMap use a tree and not always a list?
Name three differences between HashMap in Java 7 and Java 8.
Why could a Java 7 HashMap hang a thread?
Why should HashMap keys be immutable?
A key object must change. How do you do it safely?
HashSet vs TreeSet?
How do you remove duplicates from a list but keep the original order?
How does LinkedHashMap maintain order?
How do you build an LRU cache with LinkedHashMap?
From HashMap vs Hashtable
HashMap vs Hashtable?
From HashMap vs Hashtable
Why doesn't Hashtable allow null?
How does ConcurrentHashMap achieve thread safety in Java 8+?
Why doesn't ConcurrentHashMap allow null keys or values?
Comparable vs Comparator?
What happens if compareTo is inconsistent with equals?
Comparable vs Comparator?
How do you sort by salary descending, then by name?
Iterator vs ListIterator?
How do you remove elements from a list while iterating?
Fail-fast vs fail-safe iterators?
Can ConcurrentModificationException happen with a single thread?
Why was java.time introduced?
Instant vs LocalDateTime?
java.io.File vs java.nio.file.Path?
How do you read a huge file without running out of memory?
What does transient do?
Why declare serialVersionUID?
How does Spring use reflection?
Why must an annotation have @Retention(RUNTIME) to be read by reflection?
TCP vs UDP?
What does ServerSocket.accept() do?
What is a Locale used for?
How do resource bundles pick a file?
Stack vs heap?
What are GC roots?
ClassNotFoundException vs NoClassDefFoundError?
What is the parent delegation model?
What is a functional interface?
Why must captured variables be effectively final?
From Stream API
Intermediate vs terminal operations?
From Stream API
map vs flatMap?
groupingBy vs partitioningBy?
How do you count items per group?
orElse vs orElseGet?
Should Optional be used for fields or parameters?
What do sealed classes add to pattern matching?
Which recent Java versions are LTS releases?
What is a guarded pattern?
How do sealed types and pattern matching work together?
From Modules (JPMS)
What does exports do in module-info.java?
From Modules (JPMS)
exports vs opens?
send vs sendAsync?
Why reuse a single HttpClient?
What is the time complexity of HashMap.get?
What does amortised O(1) mean?
Merge sort vs quick sort?
Which algorithm does Java use to sort objects?
How do you detect a cycle in a linked list?
When would you choose a linked list over an array list?
From Trees and graphs
BFS vs DFS?
From Trees and graphs
What does an in-order walk of a BST produce?
From Dynamic programming
Memoisation vs tabulation?
From Dynamic programming
When does a problem suit dynamic programming?
What makes a method clean?
When should you write a comment?
From SOLID principles
Explain the Liskov substitution principle with an example.
From SOLID principles
How does Spring help with dependency inversion?
How do you implement a thread-safe singleton in Java?
Builder vs telescoping constructors?
Decorator vs Proxy?
Give a JDK example of the Adapter pattern.
Strategy vs Template method?
Where is the observer pattern used in Spring?
What are Maven dependency scopes?
What does mvn install do?
Why use SLF4J instead of System.out.println?
What is MDC?
What is the Arrange-Act-Assert pattern?
What makes a good unit test?
From Mocking with Mockito
Mock vs stub vs spy?
From Mocking with Mockito
What shouldn't you mock?
How do you read a Java stack trace?
What is a conditional breakpoint?
What are the annotation retention policies?
Why is reflection considered risky or expensive?
From JSON with Jackson
Serialisation vs deserialisation?
From JSON with Jackson
How do you handle unknown fields from an external API?
Statement vs PreparedStatement?
Why use a connection pool?
Is Hibernate the same as JPA?
What does Spring Data JPA add?
What is the owning side of a relationship?
What are JPA's default fetch types?
What is dirty checking?
persist vs merge?
What is the N+1 select problem?
Why not just use FetchType.EAGER?
Why doesn't @Transactional work on self-invocation?
Optimistic vs pessimistic locking?
Why is constructor injection preferred?
@Component vs @Bean?
Why is constructor injection preferred?
How do you fix NoUniqueBeanDefinitionException?
Is a singleton bean thread-safe?
What happens when you inject a prototype bean into a singleton?
@Component vs @Bean?
How does Spring Boot let you override an auto-configured bean?
How does Spring implement AOP?
Which advice type can change the return value or skip the method?
Why doesn't @Transactional work when a method is called from the same class?
JDK dynamic proxy vs CGLIB proxy?
Are Spring application events asynchronous?
@EventListener vs @TransactionalEventListener?
Explain the Spring MVC request flow.
@Controller vs @RestController?
What does @SpringBootApplication do?
How does auto-configuration work?
@Value vs @ConfigurationProperties?
How do profiles work?
How does Spring Data create repository implementations?
Page vs Slice?
PUT vs PATCH?
How do you handle exceptions globally in Spring Boot?
@SpringBootTest vs @WebMvcTest?
Why use Testcontainers instead of H2?
@Cacheable vs @CachePut?
Local cache vs Redis?
fixedRate vs fixedDelay?
Why might @Async not work?
What is the difference between Mono and Flux?
What is backpressure?
Authentication vs authorization?
How is a JWT validated?
Which component turns security exceptions into 401 and 403 responses?
How does Spring choose between several SecurityFilterChain beans?
What does UserDetailsService do?
How does Spring Security check a password?
Why use BCrypt instead of SHA-256 for passwords?
What is a salt and where is it stored?
hasRole vs hasAuthority?
How do you make sure users can only access their own data?
Why are JWTs hard to revoke, and how do you deal with it?
HS256 vs RS256?
OAuth 2.0 vs OpenID Connect?
Which OAuth flow should a single-page app use?
When is it safe to disable CSRF protection?
Is CORS a security feature for your API?
When would you not use microservices?
Why a database per service?
What does an API gateway do?
Client-side vs server-side discovery?
When would you choose Kafka over REST between services?
How does Kafka guarantee ordering?
Explain the circuit breaker states.
Why add jitter to retries?
What is the saga pattern?
Choreography vs orchestration?
Liveness vs readiness probe?
What is distributed tracing?
CI vs CD?
How do you handle secrets in a pipeline?