Java 8 Interview Questions
1. Have you used Java 8? What features are you familiar with?
Yes, Java 8 was a major release. Key features include:
* Lambda Expressions: Concise way to represent anonymous functions.
* Functional Interfaces: Interfaces with a single abstract method.
* Stream API: Functional-style operations on streams of elements.
* Optional Class: Container to avoid NullPointerExceptions.
* Default and Static Methods in Interfaces: Backward compatibility.
* Method References: Shorthand for Lambdas calling a specific method.
* New Date and Time API: LocalDate, LocalTime (Immutable, Thread-safe).
2. What is the lambda expression?
- A Lambda expression is essentially an anonymous function (a function without a name) that can be passed around.
- It provides a concise way to implement a Functional Interface (an interface with a single abstract method).
- Syntax:
(parameters) -> { body } - Example:
(a, b) -> a + b
3. What is the functional Interface? Is @FunctionalInterface annotation required?
- A Functional Interface is an interface that contains exactly one abstract method.
- It can contain any number of
defaultorstaticmethods. - Examples:
Runnable,Callable,Comparator,Predicate,Function,Consumer,Supplier.
a. Follow Up: Is @FunctionalInterface annotation required? * No, it is optional. * However, it is recommended because it instructs the compiler to verify that the interface has exactly one abstract method. If you add a second abstract method, compilation will fail.
4. How do lambda expressions and functional interfaces work together? Provide an example.
- A Lambda expression is treated as an instance of a Functional Interface. The Lambda provides the implementation for that single abstract method.
Example:
@FunctionalInterface
interface MathOperation {
int operate(int a, int b);
}
public class Test {
public static void main(String[] args) {
// Using Lambda to implement the interface
MathOperation addition = (a, b) -> a + b;
MathOperation subtraction = (a, b) -> a - b;
System.out.println("10 + 5 = " + addition.operate(10, 5));
System.out.println("10 - 5 = " + subtraction.operate(10, 5));
}
}
5. Comparator vs Comparable
| Feature | Comparable | Comparator |
|---|---|---|
| Package | java.lang |
java.util |
| Method | compareTo(T o) |
compare(T o1, T o2) |
| Usage | Defines the natural ordering of objects. | Defines custom/multiple ordering strategies. |
| Implementation | The class itself implements it (modifies the class). | A separate class or lambda implements it (no change to original class). |
| Example | Collections.sort(list) |
Collections.sort(list, comparator) |
6. What is stream API in Java 8?
- The Stream API (
java.util.stream) is used to process collections of objects. - It allows functional-style operations on elements (like SQL queries).
- A Stream does not store data; it conveys elements from a source (like a Collection) through a pipeline of computational operations.
7. What is terminal operation and what is intermediate operation?
- Intermediate Operation:
- Returns a new Stream.
- Lazy: They are not executed until a terminal operation is invoked.
- Examples:
filter(),map(),sorted(),distinct(),limit().
- Terminal Operation:
- Produces a result (non-stream) or side-effect.
- Triggers the processing of the pipeline.
- Stream closes after a terminal operation.
- Examples:
collect(),forEach(),reduce(),count(),min(),max().
8. Differences between stream and collection.
| Feature | Collection | Stream |
|---|---|---|
| Storage | Stores data in memory. | Does not store data (computes on demand). |
| Modification | Can add/remove elements. | Cannot modify the source. |
| Iteration | External iteration (loops). | Internal iteration. |
| Consumption | Can be traversed multiple times. | Can be traversed only once. |
| Processing | Eager (computes all elements). | Lazy (computes only what's needed). |
9. Is stream API sequential or parallel? How do we do parallel streams?
- By default, streams are sequential.
- Parallel Streams: Divide the data into chunks and process them in multiple threads (using the Fork/Join framework).
- How to create:
collection.parallelStream()stream.parallel()
10. What is flatMap?
map()transforms one object into another (One-to-One).flatMap()transforms one object into a Stream of objects, and then flattens (merges) all the streams into a single Stream (One-to-Many).- Usage: Flattening nested structures (e.g.,
Stream<List<String>>toStream<String>).
11. What is the default method and what is the static method?
- Default Method:
- Allows interfaces to have methods with implementation using the
defaultkeyword. - Reason: Enables adding new functionality to interfaces without breaking existing classes that implement them (Backward Compatibility).
- Allows interfaces to have methods with implementation using the
- Static Method:
- Utility methods defined in the interface using the
statickeyword. - Called using the interface name.
- Utility methods defined in the interface using the
12. What is Optional in Java 8?
Optional<T>is a container object which may or may not contain a non-null value.- Purpose: To represent the presence or absence of a value without using
null, thereby avoidingNullPointerException. - Methods:
isPresent(),ifPresent(),orElse(),orElseGet(),orElseThrow().