Top 50 Java 8 Interview Questions and Answers in 2021

Table of Contents

Scope of a Java Developer?

The scope of work for the Java developers is broad because they perform tasks from designing the (UI) user interfaces to testing the dynamic applications. Due to the wide range of Java, the developers who work with Java have to collaborate with other professionals like web designers and software engineers.

Are you preparing for a Java 8 Interview? Are you looking for Java 8 Interview Questions and Answers, then you are on the right page. Make sure you go through all the questions so that you will not miss any of them.

Java 8 Interview Questions and Answers

1) What is JAVA 8?

It is one of the standard edition platforms from the Java Development Kit, which comprises various features in java programming abilities. It implements the fundamentals of functional programming and OOPs. It is the latest release for java. The standard library of Java 8 has some enhanced features. It has many bug fixes and improvements when compared to the previous versions of Java

2) What are the features of Java 8?

Many new and exclusive features are added in Java 8:-

  1. Virtual Extension Methods and Lambda Expression 
  2. Date and Time API available
  3. Nashorn JavaScript engine – it is lightweight. (to run Javascript code)
  4. Enhance security (part of the nashorn in Java)
  5. Stream API
  6. Functional Interfaces
  7. Collection API 
Java 8 Interview Questions

3) Why should we go for Java 8 Stream API? What is the use of Java 8 Stream API in our projects?

Whenever we want to perform the following functions, Java 8 Stream API comes in handy:-

  1. Database operations
  2. Lazy loading of the application
  3. Implementation of functional programming
  4. Use of the internal iteration style
  5. Execute operations from the pipeline
  6. Improve the performance of the application
See also  Top 100 Power BI Interview Questions and Answers in 2021

Java Interview Questions and Answers

4) What is Type Inference? Is Type Inference available in older versions such as Java 7 and Before 7, or is it available only in Java SE 8?

In type inference for Java, it has the capability to look at every method and its declarations written in the code. It identifies the arguments passed in the function. There was type inference available in older versions of Java (before 7) as well. However, there are significant enhancements in the Java SE 8. 

5) Can you differentiate between Iterator and Spliterator in Java SE 8?

The answer below states the differences between the following terms – iterator and splieratro in Java 8. 

IteratorSpliterator
It works with just iterationsIt works with both splitters and iterations
It functions with interaction in a sequential manner (one by one) It can work in a sequential manner or all at once. 
Used for collection typesIt is used for collections, streams, and arrays. 
There is no way to determined the sizeThe estimated size is the actual size
Part of release version JDK 1.2It was first introduced in the version JDK 1.8

6) What is Optional in Java 8? What is the use of Optional? Advantages of Java 8 Optional?

In order to answer this question, we will examine the intricate details. The null pointer exception was always problematic in Java. It most certainly caused the crashing of the code very often. Nashorn in Java 8 has an enhancement or more like a solution to the problem. It has introduced a new optional class called java.util package. It basically works on avoiding the null checks. It suggests alternatives to the functions returning nulls. The following piece of code shows the implementation of the same. 

// Java program without Optional Class
public class Optional {  
    public static void main(String[] args) {  
        String[] sentence= new String[10];  
        String sentence= sentence[5].toLowerCase();  
        System.out. printIn(sentence);  
    }  
}
// Java program with Optional Class
import java.util.Optional;  
public class Optional {  
    public static void main(String[] args) {  
        String[] words = new String[10];  
        Optional<String> checkNull = 
                      Optional.ofNullable(words[5]);  
        if (checkNull.isPresent()) {  
            String sentence= sentence[5].toLowerCase();  
           System.out println(sentence);  
        } else  
            System.out println(" null");  
    }  
}  

7) What is Lambda Expression?

The lambda expression is recently added to the Java 8 version. Lambda expression works on taking the parameters along with their arguments. In your answer, also mention the alternative to this method.

parameter -> expression // simple lambda expression

(parameterA, parameterB) -> expression // can use more parameters in this lambda expression

Using the lambda expression

import java.util.ArrayList;
import java.util.function.Consumer;
public class Main {
  public static void main(String[] args) {
    LIST<Integer> numbers answer = new LISTt<Integer>();
    numbers.add(15);
    numbers.add(20);
    numbers.add(30);
    numbers.add(17);
    Consumer<Integer> method answer = (n) -> { System.out.println(n); };
    numbers.forEach( method );
  }
}

8) What is a Functional Interface? What is SAM Interface?

Function interface has just one abstraction within the interface. Another answer could be the alternate name for a functional interface is SAM – single abstract method interface. 

Here is the syntax for the same

// FunctionalInterface
public interface Changeable answer {
 public void change(T o);
}

Example 

@FunctionalInterface
interface NEWInterface answer {
   String reverse(String a);
}
public class ReverseString {
   public static void main( String[] args ) {
      MyInterface NEWInterface answer = (str) -> { // Lambda Expression
         String finalResult= "";
         for(int i = str.length()-1; i >= 0 ; i--)
            result += str.charAt(i);
         return finalResult;
      };
      System.out.println("The reversed string is: " + NewInterface.reverse answer (" java 8 interview questions"));
   }
}
OUTPUT: snoitseuq weivretni 8 avaj

9) List the three parts of a Lambda Expression? Define the type of Lambda Expression?

The following answer is divided into three parts of the lambda expression.

  1. Parameter list – the lambda expression can have 0 to many parameters. 
  2. Lambda arrow operator
  3. Lambda expression body

Data type in lambda expression can be anything from int, float to strings. 

Java 8 Interview Questions and Answers

10) What Is Stream Pipelining in Java 8?

A stream in java has the following elements 

  1. Sequence of elements
  2. Source
  3. Aggregate operations
  4. Pipelining
  5. Automatic iterations

Pipelining in Java 8 – The results are pipelined by the value returned by a stream. The operations are the intermediate part of the function. It captures the input, then processes it, and the value is collected in the target.collect() method takes the final input. This entire process is part of the Java stream pipelining. 

11) What is String::Value of Expression?

The string value of expression makes it easy for users to read the data. It converts data.  For example:-

  1. The string value of(num) – this will help with the visualization of a string of the numerical value.
  2. The string value of(data,0,11) – It will show an array starting from 0 to 11.

12) Can you differentiate between Intermediate and Terminal Operations?

The table below draws a comparison between intermediate and terminal operations. 

Intermediate OperationsTerminal Operations
This helps in converting methods into streams.This is basically the final operation that a method imposes on a stream.
What it returns is another streamWhat it returns is the final result
sorted(Comparator<T>)peek(Consumer<T>)distinct()forEachcounttoArray

13) What Is Nashorn in Java8?

In java 8, nashborn is an engine that has been improved with a series of versions in java. With each release, the engine has many enhancements. It basically boosts the performance and is lightweight compared to the previous versions. It has a lot more dynamic functionalities. Jjs is a command tool that is used to execute any javascript code. 

For example:-

print(“hello world”);
Command-line: C:\Program Files\Java>jjs. 
This will print: Hello world. 

14) Can you tell us about the New Date and Time API in Java 8?

With the previous date-time feature, Java had many issues like  – 

  1. It was not thread-safe.
  2. The design was not uniform.
  3. It was difficult to deal with different time zones.
See also  Top 80 Microservices Interview Questions and Answers in %currentyear%

These issues (thread-safe) were resolved through the new date and time API in Java 8. It has simplified packages dealing with time-related gaps. Following functions were created – local (for date-time) & Zoned (for time zones mapping). 

15) What is a Method Reference?

This new feature in java 8 (method reference) helps in making reference to the functional interfaces. It is similar to the lambda expression. Lambda expressions basically refer to objects and methods. Instead of those, method references can also be used. 

Method Reference

For Example

interface Test{  
    void test();  
}  
public class MethodReference {  
    public static void Trial_test(){  
        System.out.println("Static method is being evoked");  
    }  
    public static void main(String[] args) {  
        // Referring static method  
        Test test= MethodReference::saySomething;  
        // Calling interface method  
        Test.test();  
    }  
}  

16) Define the Default Method and When Do We Use It?

This default method was introduced in java 8 to increase the compatibility with some old versions that did a few backward functions. This is used for the implementations of interfaces in java. The forEach() can be used for a collection of objects of variables. Java 8 has allowed the usage of default methods that can implement functions like the forEach() method. 

Example:

public interface vehicle {
   default void print() {
      System.out.println("HelloWorld!");
   }
}

17) How to convert an array into a stream in Java 8?

Following code that shows the easiest way to convert an array 

import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
        //Object Array
        String[] array = {"h", "e", "l", "l", "o", "!"};
        //Arrays.stream
        Stream<String> stream1 = Arrays.stream(array);
        stream1.forEach(x -> System.out.println(x)); // method
        //Stream.of
        Stream<String> stream2 = Stream.of(array);
        stream2.forEach(x -> System.out.println(x));// method
        //Primitive Array
         int[] intArray = {1, 2, 3, 4, 5};
        //Arrays.stream
        IntStream intStream1 = Arrays.stream(intArray);
        intStream1.forEach(x -> System.out.println(x));
        //Stream.of
        Stream<int[]> tempStream = Stream.of(intArray);
        IntStream intStream2 = tempStream.flatMapToInt(x -> Arrays.stream(x));
        intStream2.forEach(x -> System.out.println(x));
}}
output: hello1234512345

18) Why do we use the peek() method in Java 8?

The brand new peek() method in Java 8 helps in giving the value of the new stream, which has a copy of all the elements of the old stream. This occurs once the consumer action is executed. It is part of the intermediate stream operations. It has to be used with the help of the terminal.
Syntax: Stream<T>peek ( Consumer <? Super T> action)

19) Can you give examples of intermediate operations in Java 8?

The following are the examples of the intermediate operations in Java 8

  1. skip()
  2. filter()
  3. limit()
  4. map()
  5. peek()
  6. flatmap()
  7. distinct()
  8. sorted()

20) What are some of the examples of terminal operations in Java 8?

Following are some of the examples of terminal operations in Java 8

  1. reduce()
  2. allMatch()
  3. max()
  4. anyMatch()
  5. min()
  6. noneMatch()
  7. forEach()
  8. noneMatch()
  9. count()
  10. collect()

21) Write a program that lists the number of employees and count the number of employees with ages less than 30?

List<Employee> employeeList = createEmployeeList();
long count = employeeList.stream()
.filter(e->e.getAge()>30)
.count();
System.out.println("Number of employees with less than 30 are: "+count)

22) Explain the Differences between Collection API and Stream API?

The answer below draws the differences between collection API and stream API used in java. 

Collection APIStream API
Storage of dataProcessing of data
java.util package is usedJava.util.stream is used in stream API
Computation occurs at the beginning Lazy loading operation is used in stream API
Addition and removal of objects can be doneStreams can not be altered
Iterations can happenIterations are internal to the functions in stream operations.

23) List the functional interface in Java 8?

Following is the list of the functional interface in Java 8:-

  1. Lambda Expression
  2. Built-in functions
  3. Function
  4. Predicate
  5. Unary Operator
  6. Binary Operator
  7. Supplier
  8. Consumer

24) What is the easiest way to find and remove duplicate elements from a list using Java 8?

This answer will be covered using a sample code. Following code will help with the removal of duplicate elements in the array.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ArrayListExample // start of the interface
{
    public static void main(String[] args) 
    {
        // ArrayList with duplicate elements
        ArrayList<Integer> numbersList = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));
        System.out.println(numbersList);
        List<Integer> listWithoutDuplicates = numbersList.stream().distinct().collect(Collectors.toList());
        System.out.println(listWithoutDuplicates);
    } // end of the interface
}

25)  How is a Base64 encoder that encodes URLs created in Java 8?

The base64 related functionalities and operations are now available in Java 8, and there is a class named – java.util.base64 that helps in enabling the capabilities. The encoder in java 8 encodes and decodes the value for further usage. One can create a function – getEncoder() to enable the process. URL encoding adds a layer of security that is very much necessary. ,

26) List the main advantages of using Java 8?

  1. More compact code
  2. Less boilerplate code
  3. More readable and reusable code
  4. More testable code
  5. Parallel operations

27) How can we get the current date and time using Java 8 Date and Time API?

We can use now method of LocalDate to get today’s date.

Example:

LocalDate currentDate = LocalDate.now();
System.out.println(currentDate);

28) Can you differentiate between Predicate and Function?

PredicateFunction
It is used for the transformation and to the return valuesIt is used to implement conditional checks.
It has an abstract method test().It has an abstract method apply().
It returns boolean values.It may return any type of value.
It will take one type parameter, which defines input type or argument type.It will take 2 types of parameters. The first one defines input type argument type, and the second one represents the return type.

29) Do we have PermGen in Java 8?

Until Java 7, JVM was using an area known as PermGen to store the classes. It got removed in Java 8, and it was replaced by MetaSpace.

See also  Top 70 Splunk Interview Questions and Answers in 2021

Metaspace in Java 8 is a new memory space starting from Java 8 version; it has replaced the older PermGen memory space. The difference is how it handles the memory allocation. Specifically, this native memory region will grow automatically by default.

30) Can you differentiate between Map and flatMap Stream Operation?

The following answer covers the differences between map() and flatMap operations. 

map()flatMap()
In simple words – stream of values Flatmap Stream of stream of values
1 to 1 mapping 1 to many mapping 
If one like to use a single value, this function is appropriateWhen one has to use multiple values, this function is appropriate 
It creates mapping It creates mapping and flattening

31) Write a program to find the maximum age of the employee?

List<Employee> employeeList = createEmployeeList();
        OptionalInt max = employeeList.stream().
                          mapToInt(Employee::getAge).max();
        if(max.isPresent())
            System.out.println("Maximum age of the Employee: "+max.getAsInt());

32) Will a functional interface extend/inherit another interface?

A functional interface cannot extend the other interface with an abstract method as it will violate the rule, i.e., one abstract method per functional interface.

33) Differentiate between Intermediate and terminal operations in Stream?

Intermediate OperationsTerminal Operations
They are lazy in nature and do not get executed immediately.They are not lazy, and they are executed as soon as encountered.

34) Differentiate between Stream’s findFirst() and findAny()?

findFirst()findAny()
It will always return the first element from the stream It is allowed to choose any element from the stream.
It has deterministic behavior.It is non-deterministic in behavior.

35)  Define consumer function interface?

The consumer function in Java is defined as a single argument functional interface that doesn’t return any value.

36) What is the Supplier Function Interface?

The Supplier Interface is defined as a part of the package java. util.function that was introduced in Java 8 in order to implement functional programming in Java. It defines a function that does not take in any argument but produces a value of type.

37) Define Predicate Function Interface?

The predicate function in Java 8 is defined as a functional interface that accepts the argument and will return a boolean. Typically, it is used to apply in a filter for the collection of objects.

38) Define Static Methods in Interfaces?

Static methods consist of method implementation that is owned by the interface and is called by using the interface name, it is used for defining the utility methods, and these methods cannot be overridden.

39) List the different categories of Pre-defined function interfaces?

Predicate: They perform a test and will return a Boolean value.

Operator: They perform a reduction-type operation that will accept the same input types.

Function: They are used to transform arguments in returnable value.

Consumer: They accept arguments but don’t return any values.

Supplier: They don’t accept any arguments but return a value. 

40) List some standard Java pre-defined functional interfaces?

Runnable: They are used to execute the instances of a class over the other thread with no arguments and no return values.

Comparable: They are used to sort objects in the natural sort order

Callable: They mainly execute the instances of a class over another thread with no arguments specified, and it will return either a value or throws an exception.

Comparator: It is used to sort different objects in a user-defined order.

41) Define Java 8 streams?

The streams are Introduced in Java 8, and the Stream API is mainly used to process the collection of objects. A stream is defined as a sequence of objects that will support different methods that are pipelined to produce the desired result. Streams do not change an original data structure; they provide the result as per the pipelined methods.

42) List the main components of a Stream? 

The components of the stream are listed below:

  1. A data source
  2. Set of Intermediate Operations to process data source.
  3. Single Terminal Operation that produces results.

43) Can you list the most commonly used Intermediate operations?

map(Funtion<T, R>) –  It will return a new Stream by transforming each element by applying the supplied mapper function.= sorted() –  It sorts the input elements and passes them to the next stage.

skip(long start) – It will skip the initial elements till the start.

flatMap(mapper) – It will transform each element to the stream of its constituent elements and then flatten all streams into a single stream.

limit(long max size) – It limits the stream size to maxsize.

Filter(Predicate<T>) –  It will allow selective processing of the Stream elements. It will return elements that are satisfying the supplied condition by a predicate.

44) Name the sources of data objects a Stream can process?

  1. A reactive source, for example, comments in social media or tweets/re-tweets
  2. A collection of an Array.
  3. A stream generator function 
  4. The I/O channel or an input device

45) What are Intermediate operations?

  1. Typically transforms a stream into another stream.
  2. They are lazy, i.e., they are not executed till a terminal operation is invoked.
  3. Process the stream elements.
  4. Does internal iteration of all the source elements
  5. Operations are applied as per defined order.
  6. Intermediate operations are mostly the lambda functions.
  7. We can chain any number of operations in a processing pipeline.

46) What are Terminal operations?

  1. Kick-starts the Stream pipeline
  2. used to collect the processed Stream data

47) Can you list the most common type of Terminal operations?

reduce() – It will produce a single result from all the elements of stream sequence

  • count() – It is used to return the number of elements on the stream.
  • min() – It will return the min element from the stream.
  • max() – It will return the max element from the stream.

collect() – It will collect a single result from all elements of the stream sequence.

Iterative operations

  • forEach() – It accepts a consumer.
  • forEachOrdered() – It is helpful to maintain order in the parallel streams.

Search/Query operations

  • Tt takes Predicate as input for the match condition.
  • Stream processing will be stopped as and the result can be determined.

48) List the important packages for the new Data and Time API?

  1. java.time
    1. dates 
    2. times 
    3. Instants 
    4. durations 
    5. time-zones 
    6. periods
  2. Java.time.format
  3. Java.time.temporal
  4. java.time.zone

49) List the feature of the new Date and Time API in Java 8?

  1. Fluent methods for object creation and arithmetic
  2. Immutable classes and Thread-safe 
  3. Timezone support
  4. Addresses I18N issue for earlier APIs
  5. All packages are based on the ISO-8601 calendar system
  6. Influenced by popular joda-time package

50) Differentiate between Collections and Stream?

CollectionsStream
It is mainly used to store and manipulate a group of data.Stream API is used for processing a group of data.
All the elements in collections are computed at the beginning.In streams, the intermediate operations are lazy.
All classes and interfaces of this API are in Java.util packageAll the classes and interfaces of this API are in the java.util.stream  package
Collections perform an iteration over the collection.Stream performs iteration internally.
In collections, one can remove or add elements.Here, we cannot modify streams.

 Good luck with your Java 8 interview, hope our Java 8 Interview Questions and answers were of some help to you. You can also check our .NET Interview questions and answers, which might be of some help to you.

Recommended Articles