Java 8 Interview Questions and Answers
The Best LIVE Mock Interview - You should go through before Interview
Test your skills through the online practice test: Java 8 Quiz Online Practice Test
Ques 1. What are main advantages of using Java 8?
There are the main advantages of using Java 8:
- More compact code
- Less boiler plate code
- More readable and reusable code
- More testable code
- Parallel operations
Is it helpful?
Add Comment
View Comments
Ques 2. What is the difference between Predicate and Function?
Both are functional interfaces.
- Predicate<T> is single argument function and either it returns true or false. This can be used as the assignment target for a lambda expression or method reference.
- Function<T,R> is also single argument function but it returns an Object. Here T denotes type of input to the function and R denotes type of Result. This can also be used as the assignment target for a lambda expression or method reference.
Is it helpful?
Add Comment
View Comments
Freshers / Beginner level questions & answers
Ques 3. What are new features which got introduced in Java 8?
There are lots of new features which were added in Java 8. Here is the list of important features:
- Lambda Expression
- Stream API
- Default methods in the interface
- Functional Interface
- Optional
- Method references
- Date API
- Nashorn, JavaScript Engine
Is it helpful?
Add Comment
View Comments
Ques 4. Can you explain the syntax of Lambda expression?
So we can divide structure of Lambda expression to three parts:
- Arguments
- Array Token
- Statements
1. Argument list or parameters
Lambda expression can have zero or more arguments. First part before '->' is called as argument list or parameters.
()->{System.out.println("Hello")}; //Without argument, will print hello
(int a)->{System.out.println(a)} //; One argument, will print value of a
(int a,int b)-> {a+b};//two argument, will return sum of these two integers
2. Array token (->)
3. Body
- Body can have expression or statements.
- If there is only one statement in body, curly brace is not needed and return type of the anonymous function is same as of body expression.
- If there are more than one statements, then it should be in curly braces and return type of anonymous function is same as value return from code block, void if nothing is returned.
Is it helpful?
Add Comment
View Comments
Ques 5. What are functional interfaces?
- Functional interfaces are those interfaces which can have only one abstract method. It can have static method, default methods or can override Object’s class methods.
- There are many functional interfaces already present in java such as Comparable, Runnable.
- As we have only one method in Runnable, hence it is considered as functional interface.
Is it helpful?
Add Comment
View Comments
Ques 6. What Is a Default Method and When Do We Use It?
A default method is a method with an implementation – which can be found in an interface.
We can use a default method to add a new functionality to an interface while maintaining backward compatibility with classes that are already implementing the interface:
public interface CarBehaviour {
public void move();
default void peep() {
System.out.println("peep!");
}
}
Usually, when a new abstract method is added to an interface, all implementing classes will break until they implement the new abstract method. In Java 8, this problem has been solved by the use of default method.
For example, Collection interface does not have forEach method declaration. Thus, adding such method would simply break the whole collections API.
Java 8 introduces default method so that Collection interface can have a default implementation of forEach method without requiring the classes implementing this interface to implement the same.
Is it helpful?
Add Comment
View Comments
Ques 7. What is Optional and how can we use it?
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.
Following is the declaration for java.util.Optional<T> class:
public final class Optional<T> extends Object
Coding Example:
import java.util.Optional;
public class OptionalTester {
public static void main(String args[]) {
OptionalTester optionalTester = new OptionalTester();
Integer value1 = null;
Integer value2 = new Integer(10);
//Optional.ofNullable - allows passed parameter to be null.
Optional<Integer> a = Optional.ofNullable(value1);
//Optional.of - throws NullPointerException if passed parameter is null
Optional<Integer> b = Optional.of(value2);
System.out.println(optionalTester.sum(a,b));
}
public Integer sum(Optional<Integer> a, Optional<Integer> b) {
//Optional.isPresent - checks the value is present or not
System.out.println("First parameter is present: " + a.isPresent());
System.out.println("Second parameter is present: " + b.isPresent());
//Optional.orElse - returns the value if present otherwise returns
//the default value passed.
Integer value1 = a.orElse(new Integer(0));
//Optional.get - gets the value, value should be present
Integer value2 = b.get();
return value1 + value2;
}
}
It should produce the following output:
First parameter is present: false
Second parameter is present: true
10
Is it helpful?
Add Comment
View Comments
Ques 8. Provide some APIs of Java 8 Date and Time.
LocalDate, LocalTime, and LocalDateTime are the Core API classes for Java 8. As the name suggests, these classes are local to context of observer. It denotes current date and time in context of Observer.
Is it helpful?
Add Comment
View Comments
Ques 9. How will you get current date and time using Java 8 Date and TIme API?
You can simply use now() method of LocalDate to get today’s date.
LocalDate currentDate = LocalDate.now();
System.out.println(currentDate);
Output:
2017-09-09
You can use now() method of LocalTime to get current time.
LocalTime currentTime = LocalTime.now();
System.out.println(currentTime);
Output:
23:17:51.817
Is it helpful?
Add Comment
View Comments
Intermediate / 1 to 5 years experienced level questions & answers
Ques 10. What is lambda expression?
Lambda expression is anonymous function which have set of parameters and a lambda (->) and a function body. You can call it function without name.
Structure of Lambda Expressions:
(Argument List) ->{expression;} or
(Argument List) ->{statements;}
For instance, the Runnable interface is a functional interface, so instead of:
Thread thread = new Thread(new Runnable() {
public void run() {
System.out.println("Hello World!");
}
});
Using Lambda you can simply do the following:
Thread thread = new Thread(() -> System.out.println("Hello World!"));
Functional interfaces are usually annotated with the @FunctionalInterface annotation - which is informative and does not affect the semantics.
Is it helpful?
Add Comment
View Comments
Ques 11. Given a list of employees, sort all the employee on the basis of age by using java 8 APIs only.
You can simply use sort method of list to sort the list of employees.
List<Employee> employeeList = createEmployeeList();
employeeList.sort((e1,e2)->e1.getAge()-e2.getAge());
employeeList.forEach(System.out::println);
Is it helpful?
Add Comment
View Comments
Ques 12. Given the list of employees, find the employee with name 'John' using Java 8 API.
Check the following code:
List<Employee> employeeList = createEmployeeList();
Optional<Employee> e1 = employeeList.stream()
.filter(e->e.getName().equalsIgnoreCase("Mary")).findAny();
if(e1.isPresent())
System.out.println(e1.get());
Is it helpful?
Add Comment
View Comments
Ques 13. Given a list of employee, find maximum age of employee using Java 8 API.
Check the following code:
List<Employee> employeeList = createEmployeeList();
OptionalInt max = employeeList.stream().
mapToInt(Employee::getAge).max();
if(max.isPresent())
System.out.println("Maximum age of Employee: "+max.getAsInt());
Is it helpful?
Add Comment
View Comments
Ques 14. Provide some examples of Intermediate operations.
Example of Intermediate operations are:
- filter(Predicate)
- map(Function)
- flatmap(Function)
- sorted(Comparator)
- distinct()
- limit(long n)
- skip(long n)
Is it helpful?
Add Comment
View Comments
Ques 15. Provide some examples of Terminal operations.
Example of Terminal operations are:
- forEach
- toArray
- reduce
- collect
- min
- max
- count
- anyMatch
- allMatch
- noneMatch
- findFirst
- findAny
Is it helpful?
Add Comment
View Comments
Experienced / Expert level questions & answers
Ques 16. How lambda expression and functional interfaces are related?
Lambda expressions can only be applied to abstract method of functional interface.
For example:
Runnable has only one abstract method called run, so it can be used as below:
// Using lambda expression
Thread t1=new Thread(
()->System.out.println("In Run method")
);
Here we are using Thread constructor which takes Runnable as parameter. As you can see we did not specify any function name here, as Runnable has only one abstract method, java will implicitly create anonymous Runnable and execute run method.
It will be as good as below code.
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
System.out.println("In Run method");
}
});
Is it helpful?
Add Comment
View Comments
Ques 17. Can you create your own functional interface?
Yes, you can create your own functional interface. Java can implicitly identify functional interface but you can also annotate it with @FunctionalInterface.
Example:
Create interface named "Readable" as below:
public interface Readable {
void read();
default void readBook()
{
System.out.println("Reading the book.");
}
}
Create main class named "MyFunctionalInteface":
public class MyFunctionalInteface {
public static void main(String[] args)
{
MyFunctionalInteface myFuncInterface = new MyFunctionalInteface();
myFuncInterface.readMyBook(() -> System.out.println("Reading my book"));
}
public void readMyBook(Readable p)
{
p.read();
}
}
When you run above program, you will get below output:
Reading my book
As you can see, since Readable has only one abstract method called read(), we were able to call it using lambda expression.
Is it helpful?
Add Comment
View Comments
Ques 18. What is method reference in java 8?
Method reference is used refer method of functional interface. It is nothing but compact way of lambda expression.You can simply replace lambda expression with method reference.
Syntax:
class::methodname
Is it helpful?
Add Comment
View Comments
Ques 19. What the issues with Old Date and time API before Java 8? Date and Time API differences between Java 8 and earlier Java version.
Issues with old Date and Time API:
- Thread Safety: You might be already aware that java.util.Date is mutable and not thread safe. Even java.text.SimpleDateFormat is also not Thread-Safe. New Java 8 date and time APIs are thread safe.
- Performance: Java 8 new APIs are better in performance than old Java APIs.
- More Readable: Old APIs such Calendar and Date are poorly designed and hard to understand. Java 8 Date and Time APIs are easy to understand and comply with ISO standards.
Is it helpful?
Add Comment
View Comments
Ques 20. Do we have PermGen in Java 8? What is MetaSpace in Java 8?
Until Java 7, JVM used an area called PermGen to store classes. It got removed in Java 8 and replaced by MetaSpace.
Major advantage of MetaSpace over permgen:
PermGen was fixed in term of maximum size and can not grow dynamically but Metaspace can grow dynamically and do not have any size constraint.
Is it helpful?
Add Comment
View Comments
Ques 21. Difference between Intermediate and terminal operations in Stream.
Java 8 Stream supports both intermediate and terminal operation.
- Intermediate operations are lazy in nature and do not get executed immediately. Terminal operations are not lazy, they are executed as soon as encountered.
- Intermediate operation is memorized and is called when terminal operation is called.
- All Intermediate operations return stream as it just transforms stream into another and terminal operation don't.
Is it helpful?
Add Comment
View Comments
Ques 22. Given the list of numbers, remove the duplicate elements from the list.
See the following code:
Integer[] arr=new Integer[]{1,2,3,4,3,2,4,2};
List<Integer> listWithDuplicates = Arrays.asList(arr);
Set<Integer> setWithoutDups = listWithDuplicates.stream().collect(Collectors.toSet());
setWithoutDups.forEach((i)->System.out.print(" "+i));
Is it helpful?
Add Comment
View Comments
Ques 23. Difference between Stream findFirst() and findAny().
- findFirst will always return the first element from the stream whereas findAny is allowed to choose any element from the stream.
- findFirst has deterministic behavior whereas findAny is nondeterministic behavior.
Is it helpful?
Add Comment
View Comments
Ques 24. What is consumer function interface?
It is a functional interface defined in java.util.function package. It contains an abstract accept() and a default andThen() method. It can be used as the assignment target for a lambda expression or method reference.
Consumer is single argument functional interface which does not return any value.public static void main(String[] args) {
Consumer<String> consumerString = s->System.out.println(s);
consumerString.accept("John");
}
We have created consumer object which takes String object as input and print it. It is simple use of Consumer interface to print String.
Output:
John
Is it helpful?
Add Comment
View Comments
Ques 25. What is predicate function interface?
Predicate is single argument function which returns true or false. It has test method which returns boolean. Usually, it used to apply in a filter for a collection of objects.
public static void main(String[] args) {
Predicate<Integer> predicate = i -> i > 100;
boolean greaterCheck = predicate.test(200);
System.out.println("is 200 greater than 100: "+greaterCheck);
}
Output:
is 200 greater than 100: true
Is it helpful?
Add Comment
View Comments
Ques 26. What Is a Stream? How Does It Differ from a Collection?
- In simple terms, a stream is an iterator whose role is to accept a set of actions to apply on each of the elements it contains.
- The stream represents a sequence of objects from a source such as a collection, which supports aggregate operations. They were designed to make collection processing simple and concise. Contrary to the collections, the logic of iteration is implemented inside the stream, so we can use methods like map and flatMap for performing a declarative processing.
- And yet another important distinction from collections is that streams are inherently lazily loaded and processed.
- Another difference is that the Stream API is fluent and allows pipelining:
- int sum = Arrays.stream(new int[]{1, 2, 3}).filter(i -> i >= 2).map(i -> i * 3).sum();
Is it helpful?
Add Comment
View Comments
Ques 27. What Is the Difference Between Map and flatMap Stream Operation?
- There is a difference in signature between map and flatMap. Generally speaking, a map operation wraps its return value inside its ordinal type while flatMap does not.
- For example, in Optional, a map operation would return Optional<String> type while flatMap would return String type.
- So after mapping, one needs to unwrap (read “flatten”) the object to retrieve the value whereas, after flat mapping, there is no such need as the object is already flattened. The same concept is applied to mapping and flat mapping in Stream.
- Both map and flatMap are intermediate stream operations that receive a function and apply this function to all elements of a stream.
- The difference is that for the map, this function returns a value, but for flatMap, this function returns a stream. The flatMap operation “flattens” the streams into one.
Is it helpful?
Add Comment
View Comments
Ques 28. What is Stream Pipelining in Java 8?
- Stream pipelining is the concept of chaining operations together. This is done by splitting the operations that can happen on a stream into two categories: intermediate operations and terminal operations.
- Each intermediate operation returns an instance of Stream itself when it runs, an arbitrary number of intermediate operations can, therefore, be set up to process data forming a processing pipeline.
- There must then be a terminal operation which returns a final value and terminates the pipeline.
Is it helpful?
Add Comment
View Comments
Ques 29. What does the flatmap() function do? why you need it?
The flatmap function is an extension of the map function. Apart from transforming one object into another, it can also flatten it.
For example, if you have a list of the list but you want to combine all elements of lists into just one list. In this case, you can use flatMap() for flattening. At the same time, you can also transform an object like you do use map() function.
public static void main(String[] args) {
String[][] data = new String[][]{{"a", "b"}, {"c", "d"}, {"e", "f"}};
//Stream<String[]>
Stream<String[]> temp = Arrays.stream(data);
//Stream<String>, GOOD!
Stream<String> stringStream = temp.flatMap(x -> Arrays.stream(x));
Stream<String> stream = stringStream.filter(x -> "a".equals(x.toString()));
stream.forEach(System.out::println);
}
Is it helpful?
Add Comment
View Comments
Ques 30. What is the parallel Stream? How can you get a parallel stream from a List?
A parallel stream can parallel execute stream processing tasks. For example, if you have a parallel stream of 1 million orders and you are looking for orders worth more than 1 million, then you can use a filter to do that.
Unlike sequential Stream, the parallel Stream can launch multiple threads to search for those orders on the different part of Stream and then combine the result.
In short, the parallel Stream can paralyze execution.
Is it helpful?
Add Comment
View Comments
Most helpful rated by users:
- What are new features which got introduced in Java 8?
- What are main advantages of using Java 8?
- Can you explain the syntax of Lambda expression?
- What are functional interfaces?
- What Is a Default Method and When Do We Use It?