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.
Answer: Java 8 introduced several significant features:
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();
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"); } }
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);
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"));
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"); } }
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);
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')");
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);
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);
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));
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();
Answer: The four core interfaces are:
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);
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);
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);
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);
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);
Answer: The new Date and Time API provides:
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 =