Java Interview Questions
Java 8+ Features
Q1. What are Lambda Expressions in Java 8?
A lambda expression is an anonymous function (without a name, return type, or access
modifier) that can be passed around as data. It simplifies implementing functional
interfaces and enables functional programming features in Java. Syntax: (parameters) -
> expression.
Q2. Explain the Java Stream API.
The Stream API is used to process collections of objects in a functional declarative
manner. Streams support aggregate operations (like filter, map, reduce) and allow
sequential and parallel execution. They don't store data but operate on the source data
structure.
Q3. What are Default Methods in Interfaces?
Java 8 introduced default methods in interfaces, allowing interfaces to contain concrete
method implementations using the 'default' keyword. This enables backward
compatibility so new methods can be added to interfaces without breaking implementing
classes.
Q4. What is the Optional class?
Optional is a container object which may or may not contain a non-null value. It was
introduced to handle null checks gracefully, preventing NullPointerExceptions and
expressing clearly that a return value might be absent.
Q5. What is a Functional Interface?
A Functional Interface is an interface that contains exactly one abstract method. They
can have multiple default or static methods. The @FunctionalInterface annotation
ensures the interface meets this criteria. They act as target types for lambda
expressions.
Q6. Difference between map() and flatMap() in Streams?
map() transforms each element of a stream into another object, creating a stream of
transformed objects (1-to-1). flatMap() transforms each element into a stream of objects
and then flattens all those streams into a single stream (1-to-many).
Q7. What are Method References?
Method references provide a shorthand syntax to refer to a method by name using the
'::' symbol. They are used to simplify lambda expressions that do nothing but call an
existing method. E.g., [Link]::println instead of x -> [Link](x).
Q8. Explain the new Date and Time API in Java 8.
The old [Link] API was flawed, mutable, and not thread-safe. Java 8 introduced
the [Link] package (LocalDate, LocalTime, LocalDateTime) which is immutable,
thread-safe, and provides clearer, fluent methods for date-time manipulation.
Q9. How do you parallelize a Stream?
You can convert a sequential stream into a parallel stream by simply calling the
.parallelStream() method on a collection or .parallel() on an existing stream. It utilizes
the ForkJoinPool to process elements concurrently.
Q10. What is a StringJoiner?
StringJoiner is a new class added in Java 8 to construct a sequence of characters
separated by a delimiter, optionally starting with a prefix and ending with a suffix. It
simplifies the joining of strings from lists or arrays.
Generated Document • Java 8+ Features