Java 8 Interview Questions and Answers
1. What are the key features introduced in Java 8?
- Lambda Expressions, Functional Interfaces, Stream API, Optional class,
Method and Constructor References, Default and Static Methods in Interfaces,
New Date and Time API, Nashorn JavaScript Engine
2. What is a functional interface?
- An interface with exactly one abstract method. Example:
@FunctionalInterface
interface MyFunctionalInterface {
void execute();
3. Purpose of @FunctionalInterface annotation?
- Ensures the interface has only one abstract method.
4. What is a lambda expression?
- A concise way to represent an anonymous function.
Example: () -> System.out.println("Hello Lambda");
5. Difference between anonymous classes and lambda expressions?
- Lambda is concise and used only for functional interfaces. Anonymous
classes can have multiple methods.
6. What is Stream API?
- Provides a functional approach to process sequences of elements from a
source.
7. Difference between Collection and Stream?
- Collection stores data; Stream processes data.
8. Difference between map() and flatMap()?
- map() transforms elements; flatMap() flattens nested structures.
9. Intermediate vs Terminal operations?
- Intermediate: Returns a stream (map, filter).
Terminal: Produces result (collect, forEach).
10. How to filter a list using streams?
list.stream().filter(e -> e.startsWith("J")).collect(Collectors.toList());
11. Purpose of collect()?
- Used to accumulate elements into a collection or result.
12. What is Optional?
- A container to avoid null checks.
13. Difference between Optional.of(), ofNullable(), empty()?
- of(): throws if null, ofNullable(): accepts null, empty(): returns empty optional.
14. orElse(), orElseGet(), orElseThrow()?
- orElse: default value, orElseGet: supplier, orElseThrow: exception
15. What are method references?
- Shorthand for lambda expressions: ClassName::methodName
16. What are default methods?
- Interface methods with a body for backward compatibility.
17. Can an interface have static methods?
- Yes, they belong to the interface.
18. Conflict of default methods?
- Class must override to resolve.
19. New Date and Time API?
- LocalDate, LocalTime, LocalDateTime, Period, Duration, DateTimeFormatter
20. Period vs Duration?
- Period: Years, Months, Days; Duration: Hours, Minutes, Seconds