Here are the top 20 Java 8 interview questions along with their answers:
### 1. **What are the main features introduced in Java 8?**
**Answer:**
Java 8 introduced several new features:
- Lambda Expressions
- Functional Interfaces
- Streams API
- Default and Static Methods in Interfaces
- Optional Class
- New Date and Time API (java.time package)
- Nashorn JavaScript Engine
- Method References
- Collectors in Streams API
### 2. **What is a lambda expression in Java 8?**
**Answer:**
A lambda expression is a short block of code that takes in parameters and returns a value. Lambda expressions are used primarily to define the inline implementation of a functional interface, making the code concise and readable.
Example:
```java
(parameters) -> expression
(int a, int b) -> a + b
```
### 3. **What is a functional interface?**
**Answer:**
A functional interface is an interface that contains only one abstract method. It can contain multiple default or static methods. Functional interfaces are annotated with `@FunctionalInterface`.
Example:
```java
@FunctionalInterface
public interface MyFunctionalInterface {
void singleAbstractMethod();
}
```
### 4. **Explain the purpose of the `default` and `static` methods in interfaces.**
**Answer:**
Default methods allow developers to add new methods to interfaces without breaking the existing implementations. Static methods can be called on the interface itself, without needing an instance.
Example:
```java
public interface MyInterface {
default void defaultMethod() {
System.out.println("Default Method");
}
static void staticMethod() {
System.out.println("Static Method");
}
}
```
### 5. **What is the Streams API in Java 8?**
Classification of hardware and software computer with merit and demerit
**Answer:**
The Streams API is used to process sequences of elements (such as collections) in a functional style. It supports operations like map, filter, reduce, and collect.
Example:
```java
List<String> list = Arrays.asList("a", "b", "c");
list.stream().filter(s -> s.startsWith("a")).forEach(System.out::println);
```
### 6. **What is the difference between `map()` and `flatMap()` in Streams?**
**Answer:**
- `map()` transforms each element in the stream using a function and returns a stream of transformed elements.
- `flatMap()` transforms each element into a stream of elements and then flattens the resulting streams into a single stream.
### 7. **What is the Optional class in Java 8?**
**Answer:**
`Optional` is a container object which may or may not contain a non-null value. It provides methods to deal with null values more gracefully and avoid `NullPointerException`.
Example:
```java
Optional<String> optional = Optional.ofNullable("Hello");
optional.ifPresent(System.out::println);
```
### 8. **How does the `filter()` method work in Streams?**
**Answer:**
The `filter()` method is used to select elements based on a given predicate. It returns a stream consisting of the elements that match the predicate.
Example:
```java
List<String> list = Arrays.asList("a", "b", "c");
list.stream().filter(s -> s.equals("a")).forEach(System.out::println);
```
### 9. **Explain the use of method references in Java 8.**
**Answer:**
Method references provide a way to refer to methods without invoking them. They are used to replace lambda expressions with a method call.
Example:
```java
List<String> list = Arrays.asList("a", "b", "c");
list.forEach(System.out::println);
```
### 10. **What is the new Date and Time API in Java 8?**
**Answer:**
Java 8 introduced a new date and time API in the `java.time` package. It includes classes like `LocalDate`, `LocalTime`, `LocalDateTime`, `ZonedDateTime`, `Period`, and `Duration` to work with dates and times in a more comprehensive and straightforward manner.
### 11. **How do you create an immutable list in Java 8?**
**Answer:**
You can create an immutable list using `Collections.unmodifiableList()` or the `List.of()` method introduced in Java 9.
Example:
```java
List<String> list = Arrays.asList("a", "b", "c");
List<String> immutableList = Collections.unmodifiableList(list);
```
### 12. **Explain the `reduce()` operation in Streams.**
**Answer:**
The `reduce()` method performs a reduction on the elements of the stream using an associative accumulation function and returns an `Optional` describing the reduced value.
Example:
```java
List<Integer> list = Arrays.asList(1, 2, 3, 4);
Optional<Integer> sum = list.stream().reduce((a, b) -> a + b);
```
### 13. **What are the main differences between Collections and Streams?**
**Answer:**
- Collections are in-memory data structures that hold elements and are mutable.
- Streams are not data structures; they are sequences of elements that support aggregate operations and are immutable.
### 14. **What is the use of the `Collectors` class in Java 8?**
**Answer:**
The `Collectors` class provides static methods to collect stream elements into collections like `List`, `Set`, or `Map`. It also supports operations like joining strings and computing statistics.
Example:
```java
List<String> list = Arrays.asList("a", "b", "c");
List<String> result = list.stream().collect(Collectors.toList());
```
### 15. **Explain the difference between `findFirst()` and `findAny()` in Streams.**
**Answer:**
- `findFirst()` returns the first element of the stream, ensuring a deterministic result.
- `findAny()` may return any element from the stream and is useful in parallel streams for better performance.
### 16. **What is the purpose of the `Stream.generate()` method?**
**Answer:**
`Stream.generate()` is used to create an infinite sequential unordered stream where each element is generated by the provided `Supplier`.
Example:
```java
Stream<String> stream = Stream.generate(() -> "Hello").limit(5);
stream.forEach(System.out::println);
```
### 17. **How can you sort a stream in Java 8?**
**Answer:**
You can sort a stream using the `sorted()` method. It can take a comparator to define the sorting order.
Example:
```java
List<Integer> list = Arrays.asList(3, 1, 4, 1, 5, 9);
list.stream().sorted().forEach(System.out::println);
```
### 18. **What are the characteristics of `Collectors.groupingBy()`?**
**Answer:**
`Collectors.groupingBy()` is used to group the elements of a stream by a classifier function. It returns a `Map` where keys are the result of applying the classifier function, and values are Lists of items.
Example:
```java
Map<Integer, List<String>> groupedByLength = list.stream()
.collect(Collectors.groupingBy(String::length));
```
### 19. **What is the difference between `Optional.of()` and `Optional.ofNullable()`?**
**Answer:**
- `Optional.of()` throws a `NullPointerException` if the provided value is null.
- `Optional.ofNullable()` returns an empty `Optional` if the provided value is null.
### 20. **How does the `parallelStream()` method work?**
**Answer:**
`parallelStream()` is used to process the stream elements in parallel, leveraging multiple threads to improve performance on large datasets.
Example:
```java
List<String> list = Arrays.asList("a", "b", "c", "d");
list.parallelStream().forEach(System.out::println);
```
These questions and answers cover a broad range of Java 8 features and concepts that are frequently discussed in technical interviews.
Post a Comment