Top 30 Java 8 interview questions and answers

Java 8 interview questions

In this post, we will some important interview questions specifically on Java 8. Java has changed a lot over years and Java 8 has introduced many new features which you need to know when you are preparing for Java interview. 
Here is a list of most asked Java 8 interview questions.

Table of Contents

1)  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:

2) What are main advantages of using Java 8?

  • More compact code
  • Less boiler plate code
  • More readable and reusable code
  • More testable code
  • Parallel operations

3) What is lambda expression?

Lambda expression is an anonymous function that has a set of parameters, a lambda (->) symbol, and a function body. Essentially, it is a function without a name.

Structure of Lambda Expressions

 Let see a simple example of thread execution:

You can refer to lambda expression in java for more details.

4) Can you explain the syntax of Lambda expression?

The structure of a lambda expression can be divided into three parts:
1. Argument list or parameters
Lambda expression can have zero or more arguments.
You can omit the declaration of argument types, as they can be inferred from the context.
You cannot declare the type for one argument and omit it for another; types must be consistently declared or inferred for all arguments.
When there is a single parameter and its type is inferred, parentheses are not mandatory.
2. Array token (->)

3. Body

  • The body can contain either an expression or statements.
  • If the body contains only one statement, curly braces are not needed, and the return type of the anonymous function matches that of the body expression.
  • If there are multiple statements, they must be enclosed in curly braces, and the return type of the anonymous function corresponds to the value returned from the code block, or void if nothing is returned.

5) What are functional interfaces?

Functional interfaces are those interfaces that can have only one abstract method. They can include static methods, default methods, or even override methods from the Object class.

There are many functional interfaces already present in java such as Comparable, Runnable.

Since Runnable has only one method, it is considered a functional interface.

You can read more about the functional interface.

6) How lambda expression and functional interfaces are related?

Lambda expressions can be applied only to the abstract method of a functional interface.
For example

Runnable has only one abstract method named run(), so it can be used as follows:

Here, we are using the Thread constructor that takes a Runnable as a parameter. As you can see, we did not specify any function name here. Since Runnable has only one abstract method, Java will implicitly create an anonymous Runnable and execute the run method.
It will be as good as below code:

7) Can you create your own functional interface?

Yes, you can create your own functional interface. Although Java can implicitly identify a functional interface, you can also annotate it with @FunctionalInterface to explicitly indicate its purpose.
Example:
Create interface named Printable as below:

Create main class named "FunctionalIntefaceMain"

When you run above program, you will get below output:

Printing form

As you can see, because Printable has only one abstract method called print(), we were able to invoke it using a lambda expression.

8) What is method reference in java 8?

Method reference is used refer method of functional interface. It is simply a more compact form of a lambda expression. You can replace a lambda expression with a method reference.
Syntax:
class::methodname

9) What is Optional? Why and how can you use it?

Java 8 introduced a new class called Optional, primarily to avoid NullPointerException in Java. The Optional class encapsulates an optional value that may or may not be present. It acts as a wrapper around an object and can be used to prevent NullPointerExceptions.
Let’s take a simple example:

You have written below function to get first non repeated character in String.

You call above method as below:

Do you see the problem? There is no non-repeating character in getNonRepeatedCharacter("SASAS") ; hence, it will return null. When calling c.toString(), so it will obviously throw a NullPointerException.
You can use Optional to avoid this NullPointerException. Let’s modify the method to return an Optional object rather than a String:

When above method returned Optional, you are already aware that it can return null value too.
You can call Optional’s isPresent method to check if there is any value wrapped in Optional.

If no value is present in Optional, it will simply print "No non-repeating character found in the string."

10) What are defaults methods?

Default methods are those methods in an interface that have a body and use the default keyword. They were introduced in Java 8, mainly for backward compatibility.
You can refer to default method in java for more details.

11) What is the difference between Predicate and Function?

Both are functional interfaces.Predicate<T> is a single-argument function that returns either true or false. It can be used as the assignment target for a lambda expression or method reference.

Function<T, R> is a single-argument function that returns an object. Here, T denotes the type of input to the function, and R denotes the type of result. This can also be used as the assignment target for a lambda expression or method reference.

12) Are you aware of Date and Time API introduced in Java 8? What the issues with Old Date and time API?

Issues with old Date and TIme API:

Thread Safety:You might already be aware that java.util.Date is mutable and not thread-safe. Similarly, java.text.SimpleDateFormat is also not thread-safe. The new Java 8 date and time APIs are thread-safe.

Performance: Java 8 ‘s 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.

13) Can you 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.

14) 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.

It will give you output in below format:

2017-09-09

You can use now() method of LocalTime to get current time.

It will give you output in below format:

23:17:51.817

15) Do we have PermGen in Java 8? Are you aware of MetaSpace?

Until Java 7, the JVM used an area called PermGen to store classes. This was removed in Java 8 and replaced by MetaSpace.
Major advantage of MetaSpace over permgen:
PermGen had a fixed maximum size and could not grow dynamically, but MetaSpace can grow dynamically and does not have any size constraints.


Next 7 questions will be based on below class:


16) Given a list of employees, you need to filter all the employee whose age is greater than 20 and print the employee names.(Java 8 APIs only)

Answer:
You can simply do it using below statement:

Complete main program for above logic:



17) Given the list of employees, count number of employees with age 25?

Answer:
You can use a combination of filter() and count() to find this.



18) Given the list of employees, find the employee with name “Mary”.

Answer:
The logic is quite simple; modify the main function in the above class as follows:



19)Given a list of employee, find maximum age of employee?

Answer:
The logic is quite simple; modify the main function in the above class as follows:



20) Given a list of employees, sort all the employee on the basis of age? Use java 8 APIs only

You can simply use the sort() method of the list to sort the list of employees.


21) Join the all employee names with “,” using java 8?

Answer:

Output:

Employees are: John,Martin,Mary,Stephan,Gary


22) Given the list of employee, group them by employee name?

Answer:
You can use Collections.groupBy() to group list of employees by employee name.

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 Stream?

Answer:
Java 8 Streams support both intermediate and terminal operation.

Intermediate operations are lazy in nature and are not executed immediately. Terminal operations, on the other hand, are not lazy and are executed as soon as they are encountered. An intermediate operation is memorized and is called when a terminal operation is invoked.

All intermediate operations return a stream, as they transform one stream into another, while terminal operations do not.

Example of Intermediate operations are:

filter(Predicate)
map(Function)
flatmap(Function)
sorted(Comparator)
distinct()
limit(long n)
skip(long n)

Example of terminal operations are :

forEach
toArray
reduce
collect
min
max
count
anyMatch
allMatch
noneMatch
findFirst
findAny


24) Given the list of numbers, remove the duplicate elements from the list.

Answer:
You can simply use a stream and then collect it into a set using the Collections.toSet() method.

You can also use distinct to avoid duplicates, as follows:


25) Difference between Stream’s 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 exhibits deterministic behavior, whereas findAny has nondeterministic behavior.



26) Given a list of numbers, square them and filter the numbers which are greater 10000 and then find average of them.( Java 8 APIs only)

Answer:
You can use the map function to square the numbers and then apply a filter to exclude numbers that are less than 10,000. We will use average as the terminating function in this case.

output:

21846.666666666668


27) What is use of Optional in Java 8?

Answer:
Java 8’s Optional can be used to avoid NullPointerException. You can read the detailed tutorial for more information.



28)
What is 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 use filter in the above example, we are actually passing a Predicate functional interface to it.



29) What is consumer function interface?

Answer:
A Consumer is a single-argument functional interface that does not return any value. When we use forEach in the above example, we are actually passing a Consumer functional interface to it.



30) What is supplier function interface?

Answer:
A Supplier is a functional interface that does not take any parameters but returns a value using the get() method.

You may also like other interview questions:

  1. Top 100+ Java coding interview questions
  2. Core java interview questions
  3. Java Collections interview questions
  4. Java Multithreading interview questions
  5. Java String interview questions
  6. OOPs interview questions in java
  7. Exceptional handling interview questions in java
  8. Java Serialization interview questions in java
  9. Method overloading and overriding interview questions
  10. Spring interview questions
  11. Hibernate interview questions
  12. Spring boot interview questions
  13. web services interview questions
  14. restful web services interview questions

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *