Top 20+ Java 8 Interview Questions with Answers
Java 8 brought a host of new features and improvements to the Java programming language, making it a crucial version for developers to master. Whether you're preparing for a job interview or simply brushing up on your skills, understanding the nuances of Java 8 is essential. Here, we’ve compiled a list of the top 20+ Java 8 interview questions along with their answers to help you get ready for your next technical interview.
1. What are the new features introduced in Java 8?
Answer: Java 8 introduced several significant features:
2. Explain Lambda Expressions in Java 8.
Answer: Lambda expressions are a way to create anonymous functions (functions without a name) in Java. They enable you to treat functionality as a method argument, or pass a block of code around as if it were data. The syntax is (parameters) -> expression or (parameters) -> { statements; }.
Example:
// Traditional way new Thread(new Runnable() { @Override public void run() { System.out.println("Hello from a thread"); } }).start(); // Using lambda expression new Thread(() -> System.out.println("Hello from a thread")).start();
3. What is a Functional Interface?
Answer: A functional interface in Java is an interface with exactly one abstract method. They can have any number of default or static methods. Functional interfaces are used as the types for lambda expressions.
Example:
@FunctionalInterface public interface MyFunctionalInterface { void myMethod(); default void anotherMethod() { System.out.println("Default method"); } }
4. What is the Stream API?
Answer: The Stream API is used to process collections of objects in a functional style. It provides a way to perform operations on data such as filtering, mapping, and reducing.
Example:
List<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1"); myList.stream() .filter(s -> s.startsWith("c")) .map(String::toUpperCase) .sorted() .forEach(System.out::println);
5. What is Optional and how can it be used?
Answer: Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values.
Example:
Optional<String> optional = Optional.of("Hello"); optional.ifPresent(System.out::println); Optional<String> emptyOptional = Optional.empty(); System.out.println(emptyOptional.orElse("Default Value"));
6. What are Default Methods in Interfaces?
Answer: Default methods are methods defined in interfaces with the default keyword, allowing interfaces to have concrete methods without breaking the classes that implement the interface.
Example:
public interface MyInterface { default void defaultMethod() { System.out.println("Default Method"); } }
7. How does the new Date and Time API work?
Answer: The new Date and Time API under the java.time package provides a comprehensive set of classes to represent date, time, and date-time, as well as utilities to manipulate them.
Example:
LocalDate date = LocalDate.now(); LocalTime time = LocalTime.now(); LocalDateTime dateTime = LocalDateTime.now(); System.out.println(date); System.out.println(time); System.out.println(dateTime);
8. What is the Nashorn JavaScript Engine?
Answer: Nashorn is a lightweight JavaScript runtime that allows embedding JavaScript code within Java applications. It improves upon the previous JavaScript engine with better performance and compliance with the ECMAScript specification.
Example:
ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("nashorn"); engine.eval("print('Hello from JavaScript')");
9. How can you use Method References in Java 8?
Answer: Method references are a shorthand notation of a lambda expression to call a method. They are used to directly refer to methods by their names using :: operator.
Example:
List<String> names = Arrays.asList("John", "Jane", "Jack"); names.forEach(System.out::println);
10. What is the purpose of the Collectors class in Java 8?
Answer: The Collectors class provides static methods to collect the results of a stream into collections or other forms. It is often used with the collect method of the Stream API.
Example:
List<String> list = Arrays.asList("a", "b", "c"); List<String> result = list.stream().collect(Collectors.toList()); System.out.println(result);
领英推荐
11. Explain the forEach method in Java 8.
Answer: The forEach method is part of the Iterable interface and is used to iterate over each element of a collection. It is often used with lambda expressions.
Example:
List<String> list = Arrays.asList("a", "b", "c"); list.forEach(item -> System.out.println(item));
12. What is the difference between findFirst and findAny?
Answer: Both findFirst and findAny are terminal operations used to retrieve elements from a Stream. findFirst returns the first element in the Stream, while findAny can return any element, particularly useful in parallel streams for better performance.
Example:
List<String> list = Arrays.asList("a", "b", "c"); Optional<String> first = list.stream().findFirst(); Optional<String> any = list.parallelStream().findAny();
13. What are the four core interfaces in the Java Stream API?
Answer: The four core interfaces are:
14. How do you create an infinite stream in Java 8?
Answer: Infinite streams can be created using Stream.iterate or Stream.generate.
Example:
Stream<Integer> infiniteStream = Stream.iterate(0, n -> n + 2); infiniteStream.limit(10).forEach(System.out::println);
15. How does Stream.filter work?
Answer: The filter method is used to select elements from a stream that match a given predicate.
Example:
List<String> list = Arrays.asList("a1", "a2", "b1", "c2", "c1"); list.stream().filter(s -> s.startsWith("c")).forEach(System.out::println);
16. What is the purpose of Stream.map?
Answer: The map method is used to apply a function to each element of the stream, transforming it into a new stream of transformed elements.
Example:
List<String> list = Arrays.asList("a1", "a2", "b1", "c2", "c1"); list.stream().map(String::toUpperCase).forEach(System.out::println);
17. Explain Stream.reduce with an example.
Answer: The reduce method is used to perform a reduction on the elements of the stream using an associative accumulation function and returns an Optional.
Example:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); Optional<Integer> sum = numbers.stream().reduce(Integer::sum); sum.ifPresent(System.out::println);
18. How does Stream.collect work?
Answer: The collect method is used to accumulate elements of the stream into a collection, String, or another container.
Example:
List<String> list = Arrays.asList("a", "b", "c"); List<String> result = list.stream().collect(Collectors.toList()); System.out.println(result);
19. What are the benefits of the new Date and Time API?
Answer: The new Date and Time API provides:
20. How can you convert a List to a Stream?
Answer: You can convert a List to a Stream using the stream method.
Example:
List<String> list = Arrays.asList("a", "b", "c"); Stream<String> stream =