1. What are the key features introduced in Java 8?
Answer: Java 8 introduced several significant features, including:
- Lambda Expressions: To express instances of single-method interfaces (functional interfaces) more concisely.
- Stream API: For functional-style operations on sequences of elements.
- Functional Interfaces: Interfaces with just one abstract method, enabling lambda expressions.
- Default Methods: Methods with a default implementation in interfaces.
- New java.time API: For better date and time handling.
- Optional Class: To prevent
NullPointerExceptions
and handle null values more effectively.
2. What is a lambda expression in Java?
Answer: A lambda expression is a concise way to represent an anonymous function (a function without a name). It allows you to treat functionality as a method argument, or to create a more compact way of writing code that would otherwise require creating a separate method or class.
Example:
java
(int a, int b) -> a + b
3. Explain the Stream API in Java 8.
Answer: The Stream API is a new abstraction introduced in Java 8 for working with sequences of data. It allows you to process data in a declarative manner (using functional-style operations). Streams can support operations such as:
- map: Transforms data.
- filter: Filters data based on a condition.
- reduce: Reduces elements into a single result.
- forEach: Iterates through the stream and performs actions on each element.
Example:
java
List<String> names = Arrays.asList("John", "Jane", "Jack");
names.stream().filter(name -> name.startsWith("J")).forEach(System.out::println);
4. What is a functional interface?
Answer: A functional interface is an interface that contains only one abstract method. It may contain multiple default or static methods, but only one abstract method is allowed. It can be used as the target type for lambda expressions or method references.
Example:
java
@FunctionalInterface
interface MyFunctionalInterface {
void apply();
}
5. What are default methods in interfaces?
Answer: Default methods in interfaces allow you to add new methods to interfaces with a default implementation, without breaking existing implementations. This enables backward compatibility when new methods are added to an interface.
Example:
java
interface MyInterface {
default void greet() {
System.out.println("Hello!");
}
}
6. What is the purpose of the java.util.function package in Java 8?
Answer: The java.util.function
package in Java 8 contains functional interfaces that can be used for lambda expressions and method references. Examples include:
- Predicate: Represents a boolean-valued function.
- Function: Represents a function that accepts one argument and produces a result.
- Consumer: Represents an operation that accepts a single input argument and returns no result.
- Supplier: Represents a function that supplies a result.
These interfaces help you to write more modular, reusable, and clean code using lambda expressions.
7. Explain the forEach method in the Stream API.
Answer: The forEach
method is a terminal operation in the Stream API that iterates over each element of the stream and applies a specified action to each element. It consumes the stream and does not produce a result.
Example:
java
List<String> names = Arrays.asList("John", "Jane", "Jack");
names.stream().forEach(name -> System.out.println(name));
8. What is the difference between map and flatMap in the Stream API?
Answer:
- map: The
map
operation transforms each element of the stream into another element. It returns a stream of the transformed elements.
java
List<Integer> lengths = names.stream().map(String::length).collect(Collectors.toList());
- flatMap: The
flatMap
operation transforms each element into a stream of values and then flattens all the streams into a single stream. It's useful when you want to work with nested structures.
java
List<List<String>> nestedList = Arrays.asList(Arrays.asList("a", "b"), Arrays.asList("c", "d"));
List<String> flatList = nestedList.stream().flatMap(List::stream).collect(Collectors.toList());
9. What is the Optional class in Java 8?
Answer: The Optional
class is used to represent a value that may or may not be present. It helps prevent NullPointerExceptions
and makes code more expressive and safer by explicitly handling cases where a value might be absent.
Example:
java
Optional<String> name = Optional.ofNullable(getName());
name.ifPresent(n -> System.out.println("Name is: " + n));
10. What is the java.time package and how is it different from previous date/time APIs?
Answer: The java.time
package, introduced in Java 8, provides a comprehensive and immutable API for working with dates, times, durations, and time zones. It fixes many issues found in the older java.util.Date
and java.util.Calendar
classes, such as mutability and poor design.
Key classes include:
- LocalDate: For date without time.
- LocalTime: For time without date.
- LocalDateTime: For both date and time.
- ZonedDateTime: For date and time with timezone support.