Java 8 Interview Questions
Java 8 Interview Questions
5/28/20233 min read
1. What are the main features introduced in Java 8?
Answer:
Key features:
Lambda Expressions
Functional Interfaces
Stream API
Default & Static Methods in Interfaces
Optional Class
Date & Time API (java.time)
Method References
Nashorn JavaScript Engine
2. What is a Lambda Expression in Java 8?
Answer:
A lambda expression is an anonymous function (a block of code) that can be passed around as data.
Syntax:
(parameter) -> expression
Example:
List<String> list = Arrays.asList("A", "B", "C"); list.forEach(item -> System.out.println(item));
Benefits:
Reduces boilerplate code.
Makes code more readable.
Enables functional programming.
3. What is a Functional Interface?
Answer:
A Functional Interface is an interface that contains exactly one abstract method.
It can have default or static methods too.
Example:
@FunctionalInterface interface Calculator { int add(int a, int b); }
Built-in examples:
Runnable, Callable, Comparator, Consumer, Supplier, Function, Predicate.
4. What is the difference between Predicate, Function, Consumer, and Supplier?
InterfaceMethodInputOutputDescriptionPredicate<T>test(T t)YesbooleanUsed for condition checkingFunction<T,R>apply(T t)YesYesTransforms input to outputConsumer<T>accept(T t)YesNoConsumes data (no return)Supplier<T>get()NoYesSupplies data (no input)
Example:
Predicate<Integer> isEven = x -> x % 2 == 0; Function<Integer, Integer> square = x -> x * x; Consumer<String> printer = s -> System.out.println(s); Supplier<Double> randomValue = () -> Math.random();
5. What is the Stream API?
Answer:
Stream API allows processing of collections in a functional and declarative way.
Example:
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6); numbers.stream() .filter(n -> n % 2 == 0) .map(n -> n * n) .forEach(System.out::println);
Benefits:
No need for external iteration.
Parallel processing support.
Lazy evaluation.
6. Difference between Collection and Stream API?
FeatureCollectionStreamStorageStores dataDoesn’t store dataIterationExternalInternalReusabilityCan be reusedCan’t be reused once consumedExecutionEagerLazyParallelismManualEasy with .parallelStream()
7. What is Optional in Java 8 and why is it used?
Answer:
Optional is a container object used to avoid NullPointerException.
Example:
Optional<String> name = Optional.ofNullable(getName()); System.out.println(name.orElse("Unknown"));
Useful Methods:
isPresent()
orElse()
orElseGet()
ifPresent()
map()
flatMap()
8. What are Default Methods in Interfaces?
Answer:
Allows interfaces to have implemented methods using the default keyword.
Example:
interface Vehicle { default void start() { System.out.println("Vehicle started"); } }
Used to add new methods to interfaces without breaking old implementations.
9. What are Static Methods in Interfaces?
Answer:
Static methods can also be defined inside interfaces and are not inherited.
Example:
interface MathUtil { static int square(int n) { return n * n; } }
Usage:
MathUtil.square(5);
10. What are Method References?
Answer:
They are shorthand notations for lambda expressions that call existing methods.
Example:
list.forEach(System.out::println);
Types of Method References:
Static method → Class::staticMethod
Instance method → instance::instanceMethod
Constructor → Class::new
11. What is the difference between map() and flatMap() in Streams?
MethodInputOutputUse Casemap()Stream<T>Stream<R>Transform dataflatMap()Stream<Stream<T>>Stream<T>Flatten nested streams
Example:
List<List<Integer>> list = Arrays.asList(Arrays.asList(1,2), Arrays.asList(3,4)); list.stream().flatMap(List::stream).forEach(System.out::println);
12. What is the purpose of Collectors in Java 8?
Answer:
Collectors is a utility class for reducing stream elements into a collection or value.
Examples:
List<Integer> even = list.stream() .filter(i -> i % 2 == 0) .collect(Collectors.toList());
Other useful collectors:
toSet()
toMap()
joining()
counting()
groupingBy()
partitioningBy()
13. What is the use of forEach() method in Java 8?
Answer:
Simplifies iteration over collections and streams.
Example:
list.forEach(System.out::println);
For parallel streams:
list.parallelStream().forEachOrdered(System.out::println);
14. How does Java 8 handle Date and Time?
Answer:
Java 8 introduced a new Date and Time API (java.time) — immutable and thread-safe.
Example:
LocalDate today = LocalDate.now(); LocalDate dob = LocalDate.of(1990, 5, 15); Period age = Period.between(dob, today); System.out.println(age.getYears());
Key Classes:
LocalDate
LocalTime
LocalDateTime
ZonedDateTime
Period, Duration
15. How to achieve parallelism in Streams?
Answer:
Use parallelStream() instead of stream().
Example:
list.parallelStream() .filter(x -> x > 10) .forEach(System.out::println);
Note: Use only when operations are independent and stateless.
16. What is the difference between findFirst() and findAny()?
MethodBehaviorUsed WithfindFirst()Always returns first element in stream orderSequential streamfindAny()May return any elementParallel stream (faster)
17. What is the difference between peek() and map() in Streams?
MethodPurposeReturnspeek()For debugging/loggingOriginal Streammap()Transform each elementNew Stream
Example:
stream.peek(System.out::println).collect(Collectors.toList());
18. Can we use Streams multiple times?
Answer:
No. Streams are consumed after a terminal operation like collect() or forEach().
19. What are terminal and intermediate operations in Streams?
TypeExamplesReturnsIntermediatefilter(), map(), sorted(), distinct(), peek()StreamTerminalcollect(), forEach(), reduce(), count()Non-stream result
20. What is the reduce() method in Stream API?
Answer:
reduce() performs reduction on elements of the stream using an accumulator.
Example:
int sum = numbers.stream().reduce(0, (a, b) -> a + b);
Other uses: min, max, product, concatenation.