Showing posts with label #CoreJava. Show all posts
Showing posts with label #CoreJava. Show all posts

18 November 2025

#Exception-Handling

#Exception_Handling

Key Concepts


S.No Topic Sub-Topics
1IntroductionDefinition, Errors vs Exceptions, Exception flow, Why needed, Real-world examples
2Exception TypesChecked, Unchecked, Errors, Runtime, Throwable hierarchy
3try-catch BasicsSyntax, Single catch, Exception capture, Debugging, Execution flow
4Multiple catchMultiple catch block, Order, Specific vs Generic, Multi-catch Java 7, Best practices
5finally BlockExecution guarantee, Use cases, Resource cleanup, Try-finally, Finally behavior
6throw KeywordManual throwing, Use cases, Custom messages, Runtime behavior, Stack trace
7throws KeywordMethod signature, Propagation, Checked declaration, Compile errors, Best use
8Exception PropagationCall stack, Propagation rules, try vs throws, Runtime behavior, Examples
9Custom ExceptionsCreate class, Extend Exception, Extend RuntimeException, Fields, Constructors
10Exception Class HierarchyThrowable, Error, Exception, RuntimeException, Libraries
11Common Exception TypesNullPointer, ArrayIndex, Arithmetic, IO, ClassCast
12Stack TracePrint stack trace, Logging stack trace, Trace format, Frames, Debugging
13Best PracticesAvoid swallowing, Custom messages, Single responsibility, Fail fast, Graceful exit
14Checked vs UncheckedDifference, When to use, Design patterns, Pros/Cons, Standards
15Resource ManagementI/O exceptions, Close resources, try-catch-finally, Auto close, Patterns
16Try-with-resourcesJava 7 feature, AutoCloseable, Multiple resources, Suppressed exceptions, Syntax
17Suppressed ExceptionsMeaning, Access suppressed, PrintStackTrace, Use cases, Resource conflict
18Logging BasicsWhy log, Log levels, Log format, Logger libraries, Writing log
19Advanced LoggingSLF4J, Logback, Log4j, Pattern layout, Exception logging
20Exception TranslationMapping exceptions, Wrapping error, Abstraction, custom messages, Conversion
21Global Exception HandlingApplication-level handling, Default handlers, Hooks, Web apps, Spring global handler
22Spring Exception Handling@ExceptionHandler, @ControllerAdvice, Custom response, JSON errors, Logging
23Unit Testing ExceptionsJUnit test, assertThrows, Expected exceptions, Boundary cases, Testing messages
24Debugging TechniquesBreakpoints, Watches, IDE tools, Visual debug, Exception inspect
25Design PatternsCommand pattern exceptions, Builder validation, Strategy fallback, Template hook, Fail-safe
26Performance ConsiderationsCost of exceptions, Avoid overuse, Try/catch slow paths, Control flow bad practice, Benchmarks
27Enterprise HandlingAPI error model, Status codes, Error JSON, Unified error format, Standards
28Exception MetricsMonitoring, Counters, Failure rate, Alerting, Dashboard
29Security & ExceptionsLeaking info, Sanitizing output, Stack trace risk, Error pages, Secure messages
30Interview PrepTop 20 questions, Live coding, Common traps, Custom design, Real project demo

Interview question

Basic Level

  • What is an exception?
  • What is the difference between an error and an exception?
  • What is the difference between checked and unchecked exceptions?
  • What is a try-catch block?
  • What is the purpose of the finally block?
  • How do you throw an exception explicitly?
  • What is the throws keyword?
  • What is the difference between throw and throws?
  • What is a custom exception?
  • How do you create a custom exception?
  • What is the call stack when an exception occurs?
  • How do you print a stack trace?
  • What is exception propagation?
  • What happens if an exception is not caught?
  • What is the default exception handler?
  • What is an InterruptedException and when is it thrown?
  • What is NullPointerException and common causes?
  • What is ArrayIndexOutOfBoundsException?
  • What is ArithmeticException?
  • What is ClassCastException?
  • How do you catch multiple exceptions in a single catch block?
  • What is multi-catch in Java?
  • What is the purpose of Exception class?
  • Can you catch Throwable? Should you?
  • What is the effect of returning from a finally block?

Intermediate Level

  • What is exception chaining (cause)?
  • How do you set the cause of an exception?
  • What is suppression of exceptions?
  • How does try-with-resources work?
  • What are suppressed exceptions in try-with-resources?
  • What is the AutoCloseable interface?
  • How do you design exception messages?
  • What is exception translation/wrapping and why use it?
  • What are best practices for logging exceptions?
  • When should you rethrow an exception?
  • What is a fatal exception vs recoverable exception?
  • How do you implement retry logic safely?
  • What is circuit breaker pattern related to exceptions?
  • How do you handle exceptions in API boundaries?
  • What is error handling strategy in layered architecture?
  • How to avoid swallowing exceptions?
  • What is defensive programming with exceptions?
  • How do you test exception-throwing code?
  • How do you assert exceptions in unit tests?
  • What is the role of exception handling in transactions?
  • How do exceptions affect transactions (rollback)?
  • How to create meaningful exception hierarchies?
  • What are checked exceptions vs unchecked in API design?
  • When to use checked exceptions?
  • When to use unchecked exceptions?

Advanced Level

  • How do exceptions affect performance?
  • What is the cost of throwing exceptions vs checking conditions?
  • How does JVM handle stack traces for exceptions?
  • What is enabling/disabling stack trace generation (Throwable.fillInStackTrace)?
  • What is exception-safe code and strong exception safety guarantees?
  • How to implement circuit breakers with exception patterns?
  • How to design retry/backoff strategies for transient exceptions?
  • How to map exceptions to appropriate HTTP status codes?
  • What is the role of correlation IDs when handling exceptions in distributed systems?
  • How do you implement global exception handlers in web frameworks (e.g., Spring)?
  • How to propagate exceptions across threads and executors?
  • How to capture exceptions from CompletableFuture or async APIs?
  • How to implement exception translation across layers?
  • How do you differentiate transient vs permanent exceptions programmatically?
  • What is the role of idempotency when retrying after exceptions?
  • How to perform fault injection and chaos testing for exception scenarios?
  • How to detect and handle resource exhaustion exceptions?
  • How to design resilient fallbacks for failed operations?
  • What are common anti-patterns in exception handling?
  • How to handle exceptions in streaming or reactive pipelines?
  • How to debug memory leaks caused by exception-related resource leaks?

Expert Level

  • How to design a global error handling strategy for microservices?
  • How to ensure observability of exception events (traces, metrics, logs)?
  • How to design exception taxonomies for large codebases?
  • How to perform exception-driven feature flags and graceful degradation?
  • How to use typed error responses in public APIs while hiding internal details?
  • How to ensure security when exposing exception information?
  • How to correlate user requests with exception traces across services?
  • How to build a centralized exception collection and analysis pipeline?
  • How to use machine learning to detect anomalous exception patterns?
  • How to design for eventual consistency and exception recovery in distributed transactions?
  • How to handle partial failures in distributed systems?
  • What are best practices for exception handling in high-throughput low-latency systems?
  • How to minimize exception overhead in hot code paths?
  • How to use custom exception serializers for cross-language systems?
  • How to implement graceful shutdown with exception cleanup in concurrent services?
  • How to design contract-based error handling (e.g., gRPC status codes)?
  • How to handle exceptions originating from third-party libraries effectively?
  • How to manage breaking changes in exception types across API versions?
  • How to perform post-mortem and RCA for recurring exceptions?
  • How to build automated remediation for known exception patterns?

Bonus: Quick Practicals / Coding Prompts

  • Write code that demonstrates try-with-resources with multiple resources and suppressed exceptions.
  • Implement a custom checked exception and use it in a sample API.
  • Create a utility that converts stack traces to a structured JSON format for logging.
  • Implement retry logic with exponential backoff for a transient IO exception.
  • Demonstrate exception propagation across threads using ExecutorService and Future.
  • Show how to safely close resources even when exceptions are thrown.
  • Implement a global exception handler in a Spring Boot REST API.
  • Write unit tests that assert specific causes of exceptions.
  • Demonstrate wrapping and unwrapping exceptions while preserving the original cause.
  • Implement a simple circuit breaker that trips on repeated exceptions.

Related Topics


   Exception Basics   
   Exception Hierarchy   
   Throw & Throws   
   Custom Exceptions   
   Built-in Exceptions   

23 June 2021

#Collections

#Collections

Key Concepts


S.No Topic Sub-Topics
1CollectionsCollection, Collection vs Collections, Hierarchy, Root Interfaces, Use Cases
2Core InterfacesCollection, List, Set, Map, Queue, Marker Interfaces
3Iterable & IteratorsIterable, Iterator, ListIterator, forEach, Fail-fast
4List InterfaceIndexed Access, Order, Duplicate, add/remove, ListIterator
5ArrayListInternal Array, resize, load factor, random access, use cases
6LinkedListDoubly Linked, node structure, insertion cost, Deque support, use cases
7Vector & StackLegacy Classes, Synchronization, performance, Stack methods, use cases
8Set InterfaceUniqueness, hashing logic, duplicate detection, equals, hashCode
9HashSetHash table, buckets, collisions, load factor, iterator order
10LinkedHashSetInsertion order, doubly-linked buckets, access order, LRU
11TreeSetSorted, NavigableSet, Red-Black Tree, compareTo, Comparator
12Map InterfaceKey/Value, uniqueness of key, null handling, entrySet, hashing
13HashMapHashing, buckets, resizing, tree bins, load factor, collisions
14LinkedHashMapOrder, access-order mode, LRU cache, removeEldestEntry, use cases
15TreeMapRed-Black Tree, sorting keys, NavigableMap, comparator, range queries
16ConcurrentHashMapSegments, Lock-free, CAS, performance, concurrency model
17WeakHashMapGC aware keys, WeakReference, caching, memory leaks
18IdentityHashMapReference equality, == vs equals, special use cases, pitfalls
19EnumMap & EnumSetBitwise storage, speed, memory, enum key benefits
20Queue InterfaceFIFO behavior, offer/poll, peek, priority queue, Deque
21Deque InterfaceDouble-ended queue, addFirst/addLast, stack vs queue
22PriorityQueueHeap, priority logic, compareTo, ordering, use cases
23BlockingQueueProducer-consumer, put/take methods, thread safety, use cases
24CopyOnWrite CollectionsCopyOnWriteArrayList, snapshot, safety, performance trade-offs
25Collections Utility Classsort, reverse, shuffle, binarySearch, unmodifiable, synchronized
26Stream CollectorstoList, toSet, toMap, groupingBy, partitioningBy, mapping
27Custom ComparatorComparator interface, compare method, chaining, reversed, nullsFirst
28Big-O PerformanceComplexity, add/remove, get, contains, load factor, resizing
29Choosing Right CollectionDecision matrix, use cases, performance tuning, trade-offs
30Best Practices & PatternsImmutability, safe iteration, fail-fast, defensive copy, caching

Interview question

Basic

  1. What is the Java Collections Framework?
  2. Difference between Collection and Collections in Java?
  3. What are the main interfaces in the Java Collections Framework?
  4. Difference between List, Set, and Map?
  5. What is the difference between Array and ArrayList?
  6. What is the difference between ArrayList and LinkedList?
  7. Difference between HashSet and TreeSet?
  8. What is the difference between HashMap and Hashtable?
  9. What is the difference between HashMap and LinkedHashMap?
  10. What is the difference between HashMap and TreeMap?
  11. What is the default load factor of HashMap?
  12. How does HashMap handle collisions?
  13. What is the initial capacity of HashMap?
  14. What is the difference between fail-fast and fail-safe iterators?
  15. How do you iterate over a List in Java?
  16. How do you sort a List in Java?
  17. How do you reverse a List in Java?
  18. What is the use of Collections utility class?
  19. How do you make a List thread-safe?
  20. What is the difference between synchronized collections and concurrent collections?
  21. What is the difference between ArrayDeque and LinkedList as a Queue?
  22. What is the difference between Stack and Deque?
  23. What is the difference between PriorityQueue and TreeSet?
  24. How does PriorityQueue maintain ordering?
  25. What is the difference between Comparable and Comparator?

Intermediate

  1. Explain how HashMap works internally.
  2. What is the role of hashCode() and equals() in collections?
  3. Why are hashCode() and equals() important in HashMap/HashSet?
  4. What happens if you override equals() but not hashCode()?
  5. What happens if you override hashCode() but not equals()?
  6. What is the difference between shallow copy and deep copy in collections?
  7. How do you create an immutable collection in Java?
  8. What is the difference between unmodifiable and immutable collections?
  9. What are WeakHashMap and its use cases?
  10. How does IdentityHashMap differ from HashMap?
  11. What is EnumSet and EnumMap?
  12. What is the difference between LinkedHashSet and TreeSet?
  13. How does ConcurrentHashMap achieve thread safety?
  14. What is the difference between CopyOnWriteArrayList and ArrayList?
  15. What is the difference between ConcurrentSkipListMap and TreeMap?
  16. What is the difference between BlockingQueue and ConcurrentLinkedQueue?
  17. Explain how LinkedHashMap maintains insertion order.
  18. What is LRU cache and how can you implement it using LinkedHashMap?
  19. What are NavigableMap and NavigableSet?
  20. Explain differences between TreeSet and TreeMap.
  21. How do you synchronize a HashMap?
  22. What is the difference between Collections.synchronizedList and CopyOnWriteArrayList?
  23. What is Spliterator in Java collections?
  24. How do you iterate a map using Java 8 forEach?
  25. How do you convert between arrays and collections?

Advanced

  1. Explain HashMap resizing and rehashing process.
  2. What is the significance of 0.75 load factor in HashMap?
  3. What happens when two keys have the same hashCode in HashMap?
  4. What is the role of linked lists and balanced trees in HashMap buckets (Java 8+)?
  5. Explain the performance differences between ArrayList, LinkedList, and Vector.
  6. How does TreeMap ensure sorting of keys?
  7. Difference between natural ordering and custom ordering in TreeMap/TreeSet?
  8. How does ConcurrentHashMap split data into segments? (Java 7 vs Java 8)
  9. What is the difference between parallelStream() and stream() on collections?
  10. What is a fail-fast iterator? Which collections are fail-fast?
  11. What is a fail-safe iterator? Which collections are fail-safe?
  12. How does CopyOnWriteArrayList work internally?
  13. What are weak references and how does WeakHashMap use them?
  14. How does IdentityHashMap use reference equality?
  15. Explain the difference between Hashtable and ConcurrentHashMap.
  16. How does EnumMap achieve better performance than HashMap?
  17. What are concurrent collections introduced in Java 5?
  18. What is the difference between ArrayBlockingQueue and LinkedBlockingQueue?
  19. How does PriorityBlockingQueue work?
  20. What is DelayQueue and its use cases?
  21. How does LinkedTransferQueue work?
  22. What is the difference between ConcurrentLinkedDeque and ArrayDeque?
  23. How do you implement producer-consumer using BlockingQueue?
  24. How do you avoid ConcurrentModificationException in collections?
  25. Explain the difference between Collections.emptyList() and new ArrayList<>().

Expert

  1. Explain the red-black tree implementation in TreeMap.
  2. How does HashMap deal with hash collisions after Java 8?
  3. What is tail binning in ConcurrentHashMap?
  4. Explain bin migration in ConcurrentHashMap.
  5. What is structural modification in collections?
  6. How does Java?s ForkJoinPool interact with parallel streams on collections?
  7. How do you implement a custom collection in Java?
  8. What interfaces must a custom collection implement?
  9. How do you implement a custom comparator for complex sorting?
  10. How does Spliterator support parallelism in Java collections?
  11. What is the role of characteristics in Spliterator (e.g., ORDERED, DISTINCT, SIZED)?
  12. How do you use Collectors.toMap() without causing IllegalStateException on duplicate keys?
  13. How do you optimize collection performance for read-heavy workloads?
  14. How do you optimize collection performance for write-heavy workloads?
  15. How does ConcurrentSkipListMap ensure thread safety and ordering?
  16. Explain the difference between segment-locking (Java 7) and bucket-level locking (Java 8) in ConcurrentHashMap.
  17. How do you implement a thread-safe LRU cache?
  18. Explain memory overhead of different collections.
  19. How do you implement multi-level sorting using Comparator chaining?
  20. How do you detect and handle memory leaks in collections?
  21. How do you implement an observer pattern with collections?
  22. How does the Stream API integrate with collections?
  23. How do you design collections for large-scale distributed systems?
  24. How do you tune GC behavior for large collections in JVM?
  25. Future of Java collections: how Project Valhalla and new JVM features might affect them?

Related Topics


   Collections Basic   
   Array   
   ArrayList   
   LinkedList   
   HashSet   
   LinkedHashSet   
   TreeSet   
   HashMap   
   LinkedHashMap   
   TreeMap   
   ConcurrentHashMap   
   WeakHashMap   
   IdentityHashMap   

11 November 2020

#CoreJava_08

#CoreJava_08

Key Concepts


S.No Topic Sub-Topics
1Java 8 OverviewJava 8 introduction, Why Java 8, Major enhancements, Backward compatibility, Java 8 use cases
2Functional Programming Functional programming basics, Pure functions, Immutability, Stateless behavior, Lambda-driven design
3Lambda Expressions - BasicsLambda syntax, Lambda parameters, Lambda body, Lambda vs anonymous class, Lambda advantages
4Lambda Expressions - AdvancedLambda with collections, Lambda with threads, Lambda with methods, Effectively final variables, Lambda limitations
5Functional Interfaces @FunctionalInterface , Single abstract method, Lambda compatibility, Custom functional interfaces
6Built-in Functional InterfacesPredicate, Function, Consumer, Supplier, Bi-functional interfaces
7Predicate Interfacetest() method, Predicate chaining, and(), or(), negate(), Real-time examples
8Function Interfaceapply() method, Function chaining, compose(), andThen(), Real-time use cases
9Consumer Interfaceaccept() method, Consumer chaining, forEach usage, Logging examples, Printing data
10Supplier Interfaceget() method, Lazy value generation, Supplier vs Function, Factory usage, Random value generation
11Method ReferencesStatic method reference, Instance method reference, Constructor reference, Syntax (::), Lambda replacement
12Stream API - IntroductionWhat is stream, Stream vs collection, Stream pipeline, Intermediate operations, Terminal operations
13Stream CreationStream from collection, Stream.of(), Arrays.stream(), Infinite streams, Empty streams
14Stream Intermediate Operationsfilter(), map(), flatMap(), distinct(), sorted()
15Stream Terminal OperationsforEach(), collect(), reduce(), count(), findFirst()
16Stream CollectorsCollectors.toList(), toSet(), toMap(), groupingBy(), partitioningBy()
17Stream Reduction Operationsreduce() method, Identity value, Accumulator, Combiner, Aggregation examples
18Parallel StreamsparallelStream(), ForkJoinPool, Performance benefits, Thread safety issues, When to use parallel streams
19Optional ClassOptional creation, isPresent(), ifPresent(), orElse(), orElseThrow()
20Default Methods in InterfaceDefault method syntax, Multiple inheritance resolution, Diamond problem, Overriding defaults, Use cases
21Static Methods in InterfaceStatic method rules, Invocation syntax, Difference from default methods, Utility methods, Best practices
22ForEach MethodIterable forEach(), Lambda usage, Method reference usage, Internal iteration, Comparison with loops
23Nashorn JavaScript EngineNashorn overview, JavaScript execution, ScriptEngine API, Java-JS interaction, Use cases
24New Date & Time API - BasicsProblems with old Date API, LocalDate, LocalTime, LocalDateTime, Immutability
25New Date & Time API - AdvancedZonedDateTime, Period, Duration, DateTimeFormatter, Time zones
26CompletableFutureFuture limitations, CompletableFuture basics, Async execution, thenApply(), thenAccept()
27Collectors Grouping & PartitioninggroupingBy(), partitioningBy(), downstream collectors, Multi-level grouping, Real examples
28Stream PerformanceLazy evaluation, Short-circuiting, Stream reuse rules, Avoiding side effects, Performance tuning
29Java 8 Coding PatternsFilter-map-reduce pattern, Functional pipelines, Optional usage patterns, Lambda best practices, Stream refactoring
30Java 8 Revision & Interview PrepJava 8 feature recap, Common interview questions, Coding scenarios, Performance discussions, Best practices

Interview question

Basic Level

  1. What are the major features introduced in Java 8?
  2. Why was Java 8 introduced?
  3. What is functional programming in Java 8?
  4. What is a lambda expression?
  5. What problems do lambda expressions solve?
  6. What is the syntax of a lambda expression?
  7. Difference between lambda expression and anonymous class?
  8. What is a functional interface?
  9. What is @FunctionalInterface annotation?
  10. Can a functional interface have default methods?
  11. Can a functional interface have static methods?
  12. What are built-in functional interfaces?
  13. What is Predicate interface?
  14. What is Function interface?
  15. What is Consumer interface?
  16. What is Supplier interface?
  17. What is method reference?
  18. Types of method references?
  19. What is Stream API?
  20. Why streams are introduced?
  21. Difference between stream and collection?
  22. What is stream pipeline?
  23. What are intermediate operations?
  24. What are terminal operations?
  25. What is forEach() method?

Intermediate Level

  1. How to create a stream?
  2. What is filter() in streams?
  3. What is map() in streams?
  4. Difference between map() and flatMap()?
  5. What is distinct()?
  6. What is sorted()?
  7. What is limit() and skip()?
  8. What is collect()?
  9. What is Collectors class?
  10. What is Collectors.toList()?
  11. What is Collectors.toSet()?
  12. What is Collectors.toMap()?
  13. What is groupingBy()?
  14. What is partitioningBy()?
  15. Difference between groupingBy and partitioningBy?
  16. What is reduce() operation?
  17. What is Optional class?
  18. Why Optional was introduced?
  19. How to create Optional?
  20. Difference between orElse() and orElseGet()?
  21. What is ifPresent()?
  22. What are default methods?
  23. Why default methods are introduced?
  24. What is static method in interface?
  25. Can we override default methods?

Advanced Level

  1. How lambda expressions work internally?
  2. What is effectively final variable?
  3. Why local variables must be effectively final in lambda?
  4. How streams process data internally?
  5. What is lazy evaluation in streams?
  6. What is short-circuiting in streams?
  7. What is findFirst()?
  8. What is findAny()?
  9. Difference between findFirst and findAny?
  10. What is anyMatch(), allMatch(), noneMatch()?
  11. What are parallel streams?
  12. Difference between stream() and parallelStream()?
  13. When should we use parallel streams?
  14. Problems with parallel streams?
  15. What is ForkJoinPool?
  16. How parallel stream uses ForkJoinPool?
  17. What is Java 8 Date and Time API?
  18. Problems with old Date API?
  19. What is LocalDate?
  20. What is LocalTime?
  21. What is LocalDateTime?
  22. What is ZonedDateTime?
  23. What is Period?
  24. What is Duration?
  25. What is DateTimeFormatter?

Expert Level

  1. How groupingBy works internally?
  2. What are downstream collectors?
  3. How to perform multi-level grouping?
  4. How reduce() works internally?
  5. Difference between reduce() and collect()?
  6. How Optional avoids NullPointerException?
  7. Anti-patterns of Optional?
  8. Exception handling in lambda expressions?
  9. Exception handling in streams?
  10. How to debug stream pipelines?
  11. Performance comparison: stream vs loop?
  12. When streams should be avoided?
  13. CompletableFuture introduction?
  14. Difference between Future and CompletableFuture?
  15. What is thenApply()?
  16. What is thenAccept()?
  17. What is thenCombine()?
  18. What is async execution in Java 8?
  19. What is Nashorn JavaScript engine?
  20. Use cases of Nashorn?
  21. Best practices for lambda expressions?
  22. Best practices for Stream API?
  23. Java 8 real-time project use cases?
  24. Common Java 8 interview traps?
  25. Java 8 coding round expectations?

Related Topics


   Functional Interfaces   
   Lambda Expressions   
   Stream API   
   Built-in Functional Interfaces   
   Optional Class   
   Default Method