Java 8 Interview Questions and Answers [Must Read for 2020]

In this article, we will list all the frequently and most asked Java 8 Interview Questions with Answers.

Introduction

Java 8 was released by Oracle in the year 2014 and this version is used by a lot of organizations as it is a stable and has many features.

Version 8 of Java was released with many new features and functionalities as well as very effective updates on old features.

Java Interview Questions for experienced candidates are flooded with java 8 questions in the year 2020.

So Let’s get started :

Java 8 Interview Questions

  1. What are the New Features added in Java 8?
  2. What are the advantages of Java 8 New Features?
  3. What is Lambda Expression and Why is it used?
  4. Explain three parts of a Lambda Expression ?
  5. What is the type of Lambda Expression ?
  6. What are the characteristics of a Lambda Expression ?
  7. What is a Functional Interface?
  8. What is a SAM Interface?
  9. Name few Functional Interfaces present in Java 8 Standard Library ?
  10. What Is a Method Reference ?
  11. What is String::Valueof Expression ?
  12. What Is Optional? Why it is used?
  13. What Is a Default Method in Java and When We Use It?
  14. What Is Nashorn in Java 8?
  15. What is JJS?
  16. What is Stream API? Why is it used ?
  17. Explain Difference between Collection API and Stream API?
  18. What is Stream Pipelining in Java 8 ?
  19. State the difference between Intermediate and Terminal Operations?
  20. State the difference between Map and flatMap Stream Operations?
  21. Explain new Date and Time API released in Java 8 ?

Java 8 Interview Questions and Answers

In this section of the post, we are providing detailed answers for Java 8 interview questions. If you want any additional help, please post in below comment box.

Q1. What are the New Features added in Java 8?

Java 8 was released with a ton of features. Some of the important features that you must learn for Java 8 interview questions are below :

1) Lambda Expressions :

It is one of the most significant Java feature. Lambda expression is a new language.

It provides a very clear way for representing one method interface (Functional interface) using an expression. Lambda Expression helps in extracting data from collection as well as iterating and filtering data.

These expression requires very less line of codes.

2) Functional Interface :

Functional interface is a new functionality released in Java version 8. It is a new type of interface which have only one abstract method.

The implementation of the functional interface is provided by Lambda expression.

3) Java 8 Optional :

Optional is a special wrapper class which is used for expressing the optionality. It helps in overcoming the NullPointerException in Java.

4) Date API :

A new improved Date API was released in Java 8. It is immutable in nature and it is a JodaTime-inspired API.

5) Stream API :

It is new API that is released in Java 8. It is one of the most important Java 8 interview questions. Stream is a API used for pipeline processing of data.

It is considered as a special iterator class . It is used to process the collections of objects in functional manner.

6) Default methods:

From the version 8 of Java , We can now add default methods as well which are not abstract. So interfaces in Java 8 can have complete methods too.

7) Method References :

This functionality allows us to reference the methods by their names instead of calling / invoking them directly. We can use function as a parameter for this.

8) Nashorn, JavaScript Engine :

It is new Java-based engine. It used for execution and evaluation of JavaScript code

The above list has all the new features of Java version 8 . Java 8 has additionally released lot of other enhancements as well at the level of compiler and JVM.

Q2. What are the advantages of Java 8 New Features ?

Java 8 features adds many advantages into Java language. These are mentioned below :

  • Increases the Reusability of code.
  • Ability to write parallel code.
  • Improves the performance of application.
  • Enhances Readability of code.
  • Code is more concise.
  • Ability for writing Database like operations.
  • Improves the Maintainability of code.
  • Improves the Testability of code.
  • Enhances Productivity of code.
  • It adds highly Concurrent and highly Scalable Code

Q3. What is Lambda Expression and Why is it used ?

Lambda Expressions were released in Java version 8. These are used for implementing the Functional Interfaces in Java.

Interfaces which have only one abstract method are known as Functional Interfaces. Functional interfaces were also released in java 8.

Lambda Expression is like a anonymous block of code or anonymous function.

It can have zero or more parameters and it can return void or output.

This piece of code is executed on instruction by others.

Syntax of Lambda Expression :

lambda parameter -> body

Lambda expression is a must to learn for Java 8 interview question in 2020.

Complete tutorial for Lambda Expression with Examples.

Q4. Explain three parts of a Lambda Expression ?

Below are the three parts of Lambda Expression :

1) Lambda Parameter : It is the parameter of Lambda Expression. It can have zero or more parameters.

2) Arrow-token : It is a arrow symbol ( -> ). This links the Lambda parameter and the body.

3) Body : This is Lambda Body. It contains the expressions, statements of Lambda Expression.

Q5. What is the type of Lambda Expression ?

The type of Lambda expression in Java 8 is the Functional Interface.

Q6. What are the characteristics of a Lambda Expression ?

Lambda expression has below mentioned characteristics :

1) Optional type declaration :

Optional type declaration states that when we are declaring the Lambda argument on the left side of the lambda then the type (of argument) is not required to declare. Compiler itself infer them from their values. For example :

  1. int param -> { body.. }
  2. param -> { body.. }

Both are valid.

2) Optional parentheses :

Optional parentheses states that parentheses are not required in case only one single parameter is declared in Lambda. For Example :

  1. param -> { body.. }
  2. (param) -> { body.. }

Both are valid statements.

3) Optional curly braces :

It states that curly braces around lambda body is not required if the expressions part only has a single statement. For example :

  • param – > statement
  • param – > {statement;}

Both are valid expressions.

4) Optional return statement :

It states that if a lambda expression returns a value and the value is wrapped inside curly braces then the return statement is not required.

  1. (x, y) – > {return x+y;}
  2. (x, y) – > {x+y;}

Both are valid and equal.

Q7. What is a Functional Interface?

Functional interface was released in Java 8. It is a special type of interface which has only one abstract method.

@FunctionalInterface annotation can be used to declare an interface as a Functional interface.

Q8. What is a SAM Interface?

SAM interface stands for Single Abstract Method interface. It is the other name for Functional interface. SAM has only one abstract method.

Java 8 had released many functional interfaces.

Q9. Name few Functional Interfaces present in Java 8 Standard Library ?

There are many Functional interfaces are present in Java 8. These are available under the package java.util.function.

Some popular and most commonly used functional interfaces are :

InterfaceNo. of ParameterReturns Result ?
SupplierNoneYes
ConsumerOneNo (represents side effect)
FunctionOneYes
PredicateOneYes (Boolean)
BiFunctionTwoYes
UnaryOperatorOneYes (type of parameter and result will be same)
BinaryOperatorTwoYes (type of both parameter and result will be same)

Q10. What Is a Method Reference ?

Method reference in Java 8 is a construct which is used to reference a method without invoking it directly.

These helps in reducing verbosity of lambdas. Method references are used for treating normal methods as Lambda Expressions.

Java 8 method reference has syntax like below :

class or object name :: method name

It has different kind of variations, as defined below :

This lambda expression –

(o) -> o.toString();

can be written as –

Object::toString();

Some more examples of method reference :

String::valueOf; //static method reference

String::toString; //Unbound instance method reference

Q11. What is String::Valueof Expression ?

This is a representation of static method reference to the valueOf method. valueOf method is from String class.

Q12. What Is Optional? Why it is used?

Java 8 Optional is a final class. It is available under java.util package. It basically works as container type for the values which may be null or not available.

Java 8 Optional prevents NullPointerException.

The main idea behind Optional is to be the return type of methods which previously would return null.

Below is the simple example for Optional :

Optional<Employee> optional = findEmployee("5423");

optional.ifPresent(emp -> {
    System.out.println("Employee is " + emp.getName());    
})

It has below advantages :

  • Null value checking is not required in the application.
  • NullPointerException are prevented at run-time.
  • Easy to develop clean and neat APIs.
  • Boilerplate code not required.

Optional Complete tutorial with Examples.

Q13. What Is a Default Method in Java and When We Use It?

A Default method in Java 8 is the interface method which have its implementation that means it is not abstract.

Default methods was introduced in Java version 8.

These are used for adding a new functionality to the old interface (existing interfaces) but still maintaining the compatibility with the classes which have already implemented that interface.

Like below example :

public interface Vehicle {
    public void break();
    default void autodrive() {
        System.out.println("driving!");
    }
}

Suppose, If we add a new abstract method in the existing interface then all the implementing classes of that interface will need to be re written.

As they are not required to implement all the abstract methods of an interface.

This problem is solved in java version 8 by releasing Default methods.

Q14. What Is Nashorn in Java 8?

Nashorn was released in Java version 8. It is a new Java Engine which is designed for pricessing of Javascript in the Java platform.

Earlier, Java was using the Mozilla Rhino for JavaScript processing.

However, Nashorn has additional advantes.

It provides better runtime performance and better compliance with the ECMA normalized JavaScript specification.

Q15. What is JJS?

JJS is a new executable or command line tool. It was released in Java version 8.

It is used for executing the Javascript code at the console.

Q16. What is Stream API? Why is it used ?

Stream API was released in Java version 8. It is simply an iterator. It accepts set of actions and then it applies those actions into each member it contains.

Java Stream represents a sequence of Objects and the source of objects must support the aggregate operations such as Collection.

Stream helps in making the processing of collection much simpler and concise. It also helps in pipelining the output.

The iteration logic is implemented inside the Java Stream. Java 8 Streams are lazily loaded.

Below is the simple example of Java 8 Stream :

int add = Arrays.stream(new int[]{2, 4, 6})
.filter(i -> i >= 2)
.map(i -> i * 4)
.sum();

We can use Java 8 Stream in all of the below mentioned scenarios :

  • For writing Functional Style programs.
  • If we need the internal iteration of elements.
  • If we want any operation to be lazily loaded.
  • For better performance.
  • For performing Parallel Operations.
  • If we want to perform Pipelining operations.
  • For performing Database like Operations such as orderby, groupby operation etc.

This is one of the most asked Java 8 Interview question.

Q17. Explain Difference between Collection API and Stream API?

Below are the key differences between these Collection and Stream APIs :

Stream APICollection API
It was introduced in Java version 8It was introduced in Java version 1.2
It can store either Limited or Infinite Number of Elements.It can store Limited Number of Elements.
Stream API is used for computing data.Collection API is used for storing data.
Stream API Object is Lazily constructed.Collection API Object is Eagerly constructed.
Stream allows to iterate and consume elements only once.


There is no restriction in Collection API regarding number of iteration and consumption.
It is allowed to add elements to Stream Object even without the prior computation.
It defines that these objects are computed on-demand.
We can add elements to Collection object only after the computation is completed.

Java Collection framework complete tutorial.

Q18. What is Stream Pipelining in Java 8 ?

Java 8 Stream API supports Pipelining. The Stream Pipelining means that we are performing chaining operations together.

We can perform Pipelining by splitting the operations into below mentioned categories :

  1. Intermediate Operations
  2. Terminal Operations.

The Intermediate Operation in Stream returns the Stream instance itself when it runs. Thus, we can set arbitrary number of these operations for processing data as pipeline.

The Terminal operation returns a final value and is used for terminating the pipeline.

Q19. State the difference between Intermediate and Terminal Operations?

We need to combine the Stream Operations into pipeline in order to process Java 8 Streams. All the Stream operations are categorized into one of the operation – Intermediate or Terminal.

Intermediate Operations returns the stream instance itself and allows further operations on stream.

The Intermediate Operations of Java Stream are Lazy. It means, these operations do not process the stream as they are called but it only processes the data when there is a terminal operation.

Below are some of the example of Intermediate Operations :

  • filter
  • map
  • flatMap etc.

The Terminal operations are used to terminate the pipeline and the it initiates stream processing.

When there is a call to Terminal Operation then the Stream will go through all the intermediate operations.

Below are some of the example of Terminal Operations :

  • forEach
  • reduce
  • Collect
  • sum etc.

Below Example will clear the understanding :

public static void main(String[] args) {

System.out.println(" Java 8 Stream without the terminal operation ");

Arrays.stream(new int[] { 2, 4, 6 }).map(i -> {
    System.out.println("Multiplying with 2 - " + i);
    return i * 2;
});

System.out.println(" Java 8 Stream with the terminal operation - sum() ");
    Arrays.stream(new int[] { 2, 4, 6 }).map(i -> {
        System.out.println("Multiplying with 2 - " + i);
        return i * 2;
}).sum();
}

Output :

  Java 8 Stream without the terminal operation Stream with terminal operation
  Java 8 Stream with the terminal operation - sum() 
  Multiplying with 2 - 2
  Multiplying with 2 - 4
  Multiplying with 2 - 6

Q20. State the difference between Map and flatMap Stream Operations?

The map and flatMap both operations are Intermediate Stream Operations. These operations receives the function and applies that function to each member of Stream.

Operations map and flatMap has difference in their signatures.

A map operation used to wrap the return value inside its ordinal type. However , a flatMap option does not.

Suppose, We are applying a map operation in Java 8 Optional then :

  • a map operation will return type – Optional.
  • a flatMap will return type – String.

Now, after completion of mapping operation, we are required to unwrap the object in order to retrieve the value. But, after completion of flat mapping, there is no such requirement as Object is itself flattened.

The same scenario happens in map and flatMap of Streams.

The map operation in Stream will return the value. However, flatMap operation will return the Stream. The operation flatMap seems to flatten the streams into one.

Look at below example :

Map<String, List<String>> hashmap = new HashMap<>();

hashmap.put("Chandler", Arrays.asList("222-2234", "222-4499"));

hashmap.put("Rachel", Arrays.asList("222-3354", "222-6375"));

hashmap.put("Joey", Arrays.asList("222-7765", "222-4353"));

hashmap.put("Phoebe", Arrays.asList("222-7765", "222-4353"));

 
List<String> numbers  = hashmap.values().stream()
  .flatMap(Collection::stream)
    .collect(Collectors.toList());

Q21. Explain new Date and Time API released in Java 8 ?

Java 8 is released with a new Date and Time API. These APIs solved many problems for Java developers , as defined below.

Java Programmers always had the problem for inadequate support of date and time manipulation, which is required in almost every project.

There are some existing classes like SimpleDateFormat and java.util.Date but these are not thread safe. So these classes have potential concurrency issues for developers.

The Old Java Date API has a poor design as well.

For Example – In java.util.Date API, year start at 1900 and months start at 1 and days start at 0. This is not very innate.

These type of issues forces Java to use other popular third-party date and time libraries. One of them is Joda-Time.

So Java 8 released new Date and Time API inspired by Joda-Time to solve these problem and to provide better support.

The new API is available under java.time package.

Further Reading :

Spring Boot Interview Questions [Updated 2020]

Conclusion

We have explored some of the best java 8 interview questions. Java 8 needs to be prepared very efficiently in order to excel the Java interview for Experienced. Especially in this year 2020.

As Java 8 is now used by almost every company and interviewers expect interviewees to have great knowledge of Java 8.

Best of luck !!!

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

Leave a Reply