Top 30 java 8 interview questions
In this post, we will discuss some important interview questions specifically about Java 8.
1) Mention the new features introduced in Java 8?
Below is a list of important features:
- Lambda expression
- Default interface
- Functional interface
- Optional
- Legal reference
- Date API
- Stream API
- Nashorn, JavaScript engine
2) Explain some advantages of using Java
8?
Some advantages of Java 8 are :
- Low Boiler Code
- More readable and reusable code
- More testable code
- Parallel operation
- More compact code
3) What is Lambda expression in Java 8?
It is an anonymous function having parameters, lambda (->) and a function body.
Lambda expressions structure
(Argument
List) ->{expression;} or
(Argument List) ->{statements;}
Here is an example of thread execution:
public class ThreadSample {
public static void main(String[] args) {
// old way
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Thread is
started");
}
}).start();
// using Lambda Expression
new Thread(()->System.out.println("Thread is
started")).start();
}
}
4) Explain parts of lambda
expression?
The structure of the Lambda expression is divided into three parts:
1. Argument List
The argument list is not compulsory.
()->{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
You can choose not to declare one type of arguments as it can be removed from the context.
(a,b)->{a+b};//two argument, will return sum of these two numbers
You cannot declare a type of an argument and a type
for other arguments.
(int a,b)->{a+b}; // compilation error
It is not mandatory to use brackets when there is a
single parameter
a->{System.out.println(a)};
2.
Array Token (->)
3.
Body
- The body may contain expressions or statements.
- If there is only one statement in the body, then the curly brace is not needed and the anonymous function of the return type is the same as the body expression.
- If there is more than one statement, it must be in curly braces and the anonymous function of the return type is the same as the value return from the code block, zero if nothing is returned.
5) What are the functional interfaces in
Java 8?
Functional interfaces are interfaces that can have
only one abstract method. It can have Static, default methods or can also override the class methods of the object.
Some examples are comparable, runnable functional interfaces.
6) What is the relation between lambda expression and
functional interfaces?
Lambda expressions can only be applied to an
abstract method of a functional interface.
For example
Runnable has only one abstract method to run, so it
can be used below:
// using lambda expression
Thread
t1=new Thread(
()->System.out.println("In Run
method")
);
Here the thread constructor is taking Runnable as a
parameter. As you can see we have not specified any function name here, since
runnable has only one abstract method, Java will clutterlessly create anonymous
runnable and execute run method.
It would be as good as the code below.
Thread
t1=new Thread(new Runnable() {
@Override
public void run() {
System.out.println("In Run
method");
}
});
7) How to generate user-defined functional
interface?
Yes, you can create your own functional interface.
@FunctionalInterface can be used to create a custom functional interface.
Examples:
Create an interface named "printable" as
below
Create a main class named
"FunctionalIntefaceMain"
Running the program will give the output as:
Form of printing
8) What is the method reference in Java
8?
It is nothing but a compact way of expressing a
lambda. In this Lambda expression can be replaced with method reference
Syntax:
Class :: methodName
9) What is optional in Java 8? Why and
how can you use it?
It is a new class in Java8. It is used to avoid NullPointerException.
Let's take a simple example
You have written below the function to get the first
non-repeated character in the string.
You call the above method as below.
Character c=getNonRepeatedCharacter("SASAS");
System.out.println("Non repeated character is :"+c.toString());
Do you see this problem, there is no repetitive
character for getNonRepeatedCharacter ("SASAS"), so it will be null
and we are calling c.toString, so it will explicitly throw NullPointerception.
We can use the optional to avoid this NullPointerException.
Optional<Character> opCh=getNonRepeatedCharacterOpt("SASAS");
if(opCh.isPresent()){
System.out.println("Non repeated
character is :"+opCh.toString());
else{
System.out.println("No non-repeated
character found in String");
}
10) What are the default methods in Java
8?
Default Methods An interface consists of methods that contain a body and use the default keyword. It is introduced to provide backward compatibility.
11) State the differences between Predicate and Function?
Both are functional interfaces.
Predicate <T> is a single argument function
and is either true or false. Predicate function can be used in Lambda expression or method reference as an assignment target.
The function <T, R> is also a single logic
function but returns an object. Here T represents one type of input for the
function and R represents one type of result.
It can also be used as a lambda expression or assignment target for a method reference.
12) Are you aware of the date and time
API presented in Java 8? What are the issues with the old date and time API?
Issues
with the old date and time API:
Thread
Safety: You may already know that java.util. The date is
mutable and not thread-safe. Even java.text.SimpleDateFormat is not
thread-safe. The new Java 8 date and time APIs are thread-safe.
Performance:
The new APIs of Java 8 is better in performance than the older Java APIs.
More readable: Older APIs such as calendar and date are poorly designed and difficult to understand. The Java 8 Date and Time API is easy to understand and comply with ISO standards.
13) Can you provide some APIs for Java 8
date and time?
LocalDate, LocalTime and LocalDateTime are core API classes for Java 8. As the name suggests, these classes are local about the observer. It refers to the current date and time regarding the observer.
14) How we can print current date and
time using Java 8 Date and Time API?
You can just use the method of localdate to get
today's date.
LocalDate currentDate = LocalDate.now();
System.out.println(currentDate);
The output will be:
2017-09-09
You can use
the method of local time to get the current time.
LocalTime currentTime = LocalTime.now();
System.out.println(currentTime);
The output will be:
23:17:51.817
15) Do we have PermGen in Java 8? Do
you know about Metaspace?
By Java 7, JVM used a field called PermGen to store
classes. It was removed in Java 8 and replaced by Metaspace.
Key benefits of Metaspace over Permit:
PermGen was fixed to the maximum size and cannot
grow dynamically, but the metaspace can grow dynamically and is not a constraint of any size.
The next 7 questions will be based on the
class below.
16) Looking at a list of employees, you
need to filter all employees whose age is more than 20 and print employee
names. (Java 8 API only)
Answer:
You can do this simply by using the statement below.
List<String> employeeFilteredList
= employeeList.stream()
.filter(e->e.getAge()>20)
.map(Employee::getName)
.collect(Collectors.toList());
The complete main program for the above argument.
17) Looking at the list of employees,
calculate the number of employees aged 25 using Java 8?
Answer:
You can use a combination of filter and count to
find it.
18) Looking at the list of employees,
find an employee named "Mary" using java 8.
Answer:
This is again a very simple argument, change the main
function to the lower class.
19) Looking at the list of the employee,
find the maximum age of the employee using Java 8?
Answer:
This is again a very simple argument, change the main function to the lower class.
20) Looking at a list of employees, sort
all employees by age? Use java 8 API only.
When we are using foreach in the above example, we are actually passing the consumer functional interface.
21) Using Java 8, mix all employee names
with ","?
Output:
Employees are: John, Martin, Mary, Stephan, Gary
22) Looking at the list of employee,
group them by employee name?
Answer:
You can use Collections.groupBy () to group employees by name of employee.
Output:
Name: John ==>[Employee Name: John age: 21, Employee Name: John
age: 26]
Name: Martin ==>[Employee Name: Martin age: 19]
Name: Mary ==>[Employee Name: Mary age: 31, Employee Name: Mary age: 18]
23) Difference between intermediate and
terminal operations in the stream?
Answer:
The Java 8 stream supports both intermediate and
terminal operations.
Intermediate operations are lazy in nature and do
not execute immediately. Terminal operations are not lazy, they are executed as
soon as possible. The intermediate operation is recalled and is called terminal
operation.
All intermediate operations return the stream
because it does not convert the stream to another and terminal operation.
Examples
of intermediate operations are:
- Filter (predicate)
- Map (function)
- flatmap (function)
- Sort (Comparative)
- Specific ()
- Range (long n)
- skip (long n)
Examples
of terminal operations are:
- foreach
- toArray
- low down
- Collect
- Minute
- Maximum
- Count
- anyMatch
- allMatch
- noneMatch
- findFirst
- find any
24) Looking at the list of numbers,
remove duplicate elements from the list using Java 8 stream.
answer:
You can just use the stream and then collect it to
collect.
To avoid duplicates as following you can use different Change the main method of the above program as below.
25) Difference between FindFirst () and
FindAny () of Java's stream?
findFirst will always return the first element from
the stream while findAny is allowed to select any element from the stream.
findFirst has deterministic behaviour while findAny is nondeterministic
behaviour.
26) Looking at the list of numbers,
square them and filter the numbers which are more than 10000 and then find an
average of them. (Java 8 API only)
Answer:
You can use the map function to square the number and then filter to avoid numbers that are less than 10000. We will use the average as a closing function in this case.
output:
21846.666666666668
27) What is the use of optional in Java
8?
Answer:
Java 8 optional is used to avoid NullPointerException. Optional is a container object that is used to do non-null objects. An optional object is used to represent the null with absent value. There are various useful methods in this class, so that the code can be made easier to handle values like 'available' or 'not available' instead of checking the code values.
28) What is the predicate function interface?
Answer:
A predicate is a single argument function that
returns true or false. It has a test method that returns a boolean.
When we are using a filter in the above example, we
are actually passing the Predicate functional interface to it.
29) What is the consumer function
interface in Java 8?
Answer:
The consumer is a single logic functional interface
that does not return any value.
When we are using foreach in the above example, we
are actually passing the consumer functional interface.
30) What is the supplier function
interface in Java)?
Answer:
The supplier is a function interface that takes no
parameters, but returns values using the get method.
1 Comments
Awesome description. Thanks concepts clear
ReplyDelete