Top 30 Java 8 Interview Questions and Answers

Most Frequently asked Java 8 Interview Questions and Answers with examples:

In this tutorial, we have covered almost all important Java 8 interview questions and answers for Java Interview in 2020.

This post on JAVA 8 Interview Questions is prepared to help you understand the basic concepts of new Java 8 programming for interview purposes. All the important JAVA 8 concepts are explained here with examples for your easy understanding.

1) Tell the top features introduced in Java 8?

New features that are introduced in Java 8 are:

  • Lambda Expressions
  • Method References
  • Optional Class
  • Functional Interface
  • Default methods
  • Nashorn, JavaScript Engine
  • Stream API
  • Date API

2) Explain Functional Interfaces?

Functional Interface is an interface that has only single abstract method. The implementation of these interfaces is provided using a Lambda Expression which means that to use the Lambda Expression, you need to create a new functional interface or you can use the predefined functional interface of Java 8.
The annotation used for creating a new Functional Interface is “@FunctionalInterface”.

3) What is an optional class in java?

Optional class is a special wrapper class introduced in Java 8 which is used to avoid NullPointerExceptions. This final class is present under java.util package. NullPointerExceptions occurs when we fail to perform the Null checks.

4) Explain java default methods?

Default methods in java are the methods of Interface which has a body. These methods, use the default keywords. The use of these default methods is “Backward Compatibility” which means if JDK modifies any Interface (without default method) then the classes which implement this Interface will break.
On the other hand, if you add the default method in an Interface then you will be able to provide the default implementation. This won’t affect the implementing classes.

Syntax:
public interface questions{
default void print() {
System.out.println(“www.softwaretestinghelp.com”);
}
}

5) Explain the features of the Lambda Function?

Main features of the Lambda Function are as follows:
A method that is defined as Lambda Expression can be passed as a parameter to another method.
A method can exist standalone without belonging to a class.
There is no need to declare the parameter type because the compiler can fetch the type from the parameter’s value.
We can use parentheses when using multiple parameters but there is no need to have parenthesis when we use a single parameter.
If the body of expression has a single statement then there is no need to include curly braces.

6) Tell the difference between the Collection and Stream API?

Below is the list of difference between Collection and Stream API

Stream APICollection API
It was introduced in Java 8 Standard Edition version.It was introduced in Java version 1.2
There is no use of the Iterator and Spliterators.With the help of forEach, we can use the Iterator and Spliterators to iterate the elements and perform an action on each item or the element.
An infinite number of features can be stored.A countable number of elements can be stored.
Consumption and Iteration of elements from the Stream object can be done only once.Consumption and Iteration of elements from the Collection object can be done multiple times.
It is used to compute data.It is used to store data.

7) How to create Functional Interface in java?
Using @FunctionalInterface annotation we can create a Functional Interface.
Once you have defined the functional interface, you can have only one abstract method. Since you have only one abstract method, you can write multiple static methods and default methods.

Example:
@FunctionalInterface
interface MyFuncInterface {

public int multiply(int a, int b);

}
public class Java8FunInterDemo {

public static void main(String args[]) {
MyFuncInterface Total = (a, b) -> a * b;
// simple operation of multiplication of ‘a’ and ‘b’
System.out.println(“Result: “+Total.multiply(30, 60));
}
}

8) What is a SAM Interface in Java 8?

Java 8 FunctionalInterface is also known as SAM Interface. SAM stands for “Single Abstract Method”.

9) What is Method Reference in Java 8?

In Java 8, a new feature was introduced known as Method Reference. This is used to refer to the method of functional interface. It can be used to replace Lambda Expression while referring to a method.

For Example: If the Lambda Expression looks like

num -> System.out.println(num)
Then the corresponding Method Reference would be,

System.out::println
where “::” is an operator that distinguishes class name from the method name.

10) Why we should LocalDate, LocalTime, LocalDateTime instead of old date and time API ?

Below are the drawbacks of the old java date and time API:

Java.util.Date is mutable and is not thread-safe whereas the new Java 8 Date and Time API are thread-safe.
Java 8 Date and Time API meets the ISO standards whereas the old date and time were poorly designed.
It has introduced several API classes for a date like LocalDate, LocalTime, LocalDateTime, etc.
Performance vice Java 8 works faster than the old java date and time API.

11) Explain String:: Valueof Expression

It is a static method reference to the ValueOf method of the String class. System.out::println is a static method reference to println method of out object of System class.

It returns the corresponding string representation of the argument that is passed. The argument can be Character, Integer, Boolean, and so on.

12) Explain Predicate? What is the difference between a Predicate and a Function?

Predicate is a pre-defined Functional Interface. It is under java.util.function.Predicate package. It accepts only a single argument which is in the form as shown below,

Predicate<T>

PredicateFunction
It has the return type as Boolean.It has the return type as Object.
It is written in the form of Predicate< T> which accepts a single argument.It is written in the form of Function< T, R> which also accepts a single argument.
It is a Functional Interface which is used to evaluate Lambda Expressions. This can be used as a target for a Method Reference.It is also a Functional Interface which is used to evaluate Lambda Expressions. In Function< T, R>, T is for input type and R is for the result type. This can also be used as a target for a Lambda Expression and Method Reference.

13) Explain Stream API?

Stream API is a new feature added in Java 8. It is a special class that is used for processing objects from a source such as Collection.

14) Why we should use the Stream API?1

We Should use the Stream API because,
It supports aggregate operations which makes the processing simple.
It supports Functional-Style programming.
It does faster processing. Hence, it is apt for better performance.
It allows parallel operations.

15) Difference between limit and skip?

The limit() method is used to return the Stream of the specified size. For Example, If you have mentioned limit(5), then the number of output elements would be 5.

Example:

import java.util.stream.Stream
public class Java8 {
public static void main(String[] args) {
    Stream.of(0,1,2,3,4,5,6,7,8)
    .limit(6)         
    /*limit is set to 6, hence it will print the 
    numbers starting from 0 to 5 
    */
    .forEach(num->System.out.print("\n"+num));
}

}
skip() method is used to skip the element.

Let’s consider the following example. In the output, the elements are 6, 7, 8 which means it has skipped the elements till the 6th index (starting from 1).

import java.util.stream.Stream;
public class Java8 {
public static void main(String[] args) {
    Stream.of(0,1,2,3,4,5,6,7,8)
    .skip(6)
    /*
     It will skip till 6th index. Hence 7th, 8th and 9th
     index elements will be printed
     */
    .forEach(num->System.out.print("\n"+num));
}

}

16) How to use the current date and time using Java 8 Date and Time API?

The below program is written with the help of the new API introduced in Java 8. We have made use of LocalDate, LocalTime, and LocalDateTime API to get the current date and time.

In the first and second print statement, we have retrieved the current date and time from the system clock with the time-zone set as default. In the third print statement, we have used LocalDateTime API which will print both date and time.

class Java8 {
public static void main(String[] args) {
System.out.println(“Current Local Date: ” + java.time.LocalDate.now());
//Used LocalDate API to get the date
System.out.println(“Current Local Time: ” + java.time.LocalTime.now());
//Used LocalTime API to get the time
System.out.println(“Current Local Date and Time: ” + java.time.LocalDateTime.now());
//Used LocalDateTime API to get both date and time
}
}

17) Tell the difference between Intermediate and Terminal Operations in Stream?

All Stream operations are either Terminal or Intermediate.
Intermediate Operations are the operations that return the Stream so that some other operations can be carried out on that Stream. Intermediate operations do not process the Stream at the call site, hence they are called lazy.
These types of operations (Intermediate Operations) process data when there is a Terminal operation carried out. Examples of Intermediate operation are map and filter.

Terminal Operations initiate Stream processing. During this call, the Stream undergoes all the Intermediate operations. Examples of Terminal Operation are sum, Collect, and forEach.
In below program, we are first trying to execute Intermediate operation without Terminal operation. As you can see the first block of code won’t execute because there is no Terminal operation supporting.
The second block successfully executed because of the Terminal operation sum().

import java.util.Arrays;
class Java8 {
public static void main(String[] args) {
    System.out.println("Intermediate Operation won't execute");
    Arrays.stream(new int[] { 0, 1 }).map(i -> {
        System.out.println(i);
        return i;
        // No terminal operation so it won't execute
    });

    System.out.println("Terminal operation starts here");
    Arrays.stream(new int[] { 0, 1 }).map(i -> {
        System.out.println(i);
        return i;
        // This is followed by terminal operation sum()
    }).sum();
}
}

18) What is the difference between Stream’s findFirst() and findAny()?

As the name suggests, the findFirst() method is used to find the first element from the stream whereas the findAny() method is used to find any element from the stream.

The findFirst() is predestinarianism in nature whereas the findAny() is non-deterministic. In programming, Deterministic means the output is based on the input or initial state of the system.

19) What is the difference between Iterator and Spliterator?

These are the differences between Iterator and Spliterator.

IteratorSpliterator
It was introduced in Java version 1.2It was introduced in Java SE 8
It is used for Collection API.It is used for Stream API.
Some of the iterate methods are next() and hasNext() which are used to iterate elements.Spliterator method is tryAdvance().
We need to call the iterator() method on Collection Object.We need to call the spliterator() method on Stream Object.
Iterates only in sequential order.Iterates in Parallel and sequential order.

20) What is the Consumer Functional Interface?

Consumer Functional Interface is also a single argument interface (like Predicate and Function). It comes under java.util.function.Consumer. This does not return any value.

In the below program, we have made use of the accept method to retrieve the value of the String object.

import java.util.function.Consumer;
public class Java8 {
public static void main(String[] args)
Consumer str = str1 -> System.out.println(str1);
str.accept(“Saket”);
/* We have used accept() method to get the
value of the String Object
*/
}
}

21) What is the Supplier Functional Interface?

Supplier Functional Interface does not accept input parameters. It comes under java.util.function.Supplier. This returns the value using the get method.

Below we have made use of the get method to retrieve the value of the String object.

import java.util.function.Supplier;

public class Java8 {
public static void main(String[] args) {
Supplier str = () -> "Saket";
System.out.println(str.get());
/* We have used get() method to retrieve the
value of String object str.
*/
}
}

22) What is Nashorn in Java 8 and what its usage?

Nashorn in Java 8 is a Java-based engine for executing and evaluating JavaScript code.

23) What is the Difference Between Map and flatMap Stream Operation?

Map Stream operation gives one output value per input value whereas flatMap Stream operation gives zero or more output value per input value.

Map Example – Map Stream operation is generally used for simple operation on Stream such as the one mentioned below.

In this program, we have changed the characters of “Names” into the upper case using map operation after storing them in a Stream and with the help of the forEach Terminal operation, we have printed each element.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Map {
public static void main(String[] str) {
List Names = Arrays.asList("Saket", "Trevor", "Franklin", "Michael");    
List<String> UpperCase = Names.stream().map(String::toUpperCase).collect(Collectors.toList());
    // Changed the characters into upper case after converting it into Stream

    UpperCase.forEach(System.out::println);
    // Printed using forEach Terminal Operation
}

}

flatMap Example – flatMap Stream operation is used for more complex Stream operation.

Here we have carried out flatMap operation on “List of List of type String”. We have given input names as list and then we have stored them in a Stream on which we have filtered out the names which start with ‘S’.

Finally, with the help of the forEach Terminal operation, we have printed each element.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class flatMap {
public static void main(String[] str) {
List> Names = Arrays.asList(Arrays.asList(“Saket”, “Trevor”), Arrays.asList(“John”, “Michael”),
Arrays.asList(“Shawn”, “Franklin”), Arrays.asList(“Johnty”, “Sean”));

    /* Created a “List of List of type String” i.e. List<List<String>> 
       Stored names into the list
     */

    List<String> Start = Names.stream().flatMap(FirstName -> FirstName.stream()).filter(s -> s.startsWith("S"))
            .collect(Collectors.toList());

    /* Converted it into Stream and filtered 
        out the names which start with 'S'
     */

    Start.forEach(System.out::println);

    /*
     Printed the Start using forEach operation
     */
}

}
Output:

flatMap Stream operation

24) What is MetaSpace in Java 8?

In Java 8, a new feature was introduced to store classes. The area where all the classes that are stored in Java 8 are called MetaSpace. MetaSpace has replaced the PermGen.

Till Java 7, PermGen was used by Java Virtual Machine to store the classes. Since MetaSpace is dynamic as it can grow dynamically and it does not have any size limitation, Java 8 replaced PermGen with MetaSpace.

25) What is the difference between Java 8 Internal and External Iteration?

The difference between Internal and External Iteration is as below.

Internal Iteration External Iteration
It was introduced in Java 8 (JDK-8). It was introduced and practiced in the previous version of Java (JDK-7, JDK-6 and so on).
It iterates internally on the aggregated objects such as Collection. It iterates externally on the aggregated objects.
It supports the Functional programming style. It supports the OOPS programming style.
Internal Iterator is passive. External Iterator is active.
It is less erroneous and requires less coding. It requires little more coding and it is more error-prone.

26) What is JJS?
JJS is a command-line tool used to execute JavaScript code at the console. In Java 8, JJS is the new executable which is a JavaScript engine.

27) Explain ChronoUnits in Java 8?

ChronoUnits is the enum that is introduced to replace the Integer values that are used in the old API for representing the month, day, etc.

28) What is StringJoiner Class in Java 8? How can we achieve joining multiple Strings using StringJoiner Class?

In Java 8, a new class was introduced in the package java.util which was known as StringJoiner. Through this class, we can join multiple strings separated by delimiters along with providing prefix and suffix to them.

In the below program, we will learn about joining multiple Strings using StringJoiner Class. Here, we have “,” as the delimiter between two different strings. Then we have joined five different strings by adding them with the help of the add() method. Finally, printed the String Joiner.

import java.util.StringJoiner;
 
public class Java8 {
    public static void main(String[] args) {    
    StringJoiner stj = new StringJoiner(",");
    // Separated the elements with a comma in between.

    stj.add("Sachin");
    stj.add("Rathore");
    stj.add("Loves");
    stj.add("Java 8");
    stj.add("Java 9");

    // Added elements into StringJoiner “stj”

    System.out.println(stj);
}

}

29) Write a Java 8 program to sort an array and then convert the sorted array into Stream?

In this program, we have used parallel sort to sort an array of Integers. Then converted the sorted array into Stream and with the help of forEach, we have printed each element of a Stream.

import java.util.Arrays;
public class Java8 {
public static void main(String[] args) {
    int arr[] = { 99, 55, 203, 99, 4, 91 };
    Arrays.parallelSort(arr);
    // Sorted the Array using parallelSort()

    Arrays.stream(arr).forEach(n -> System.out.print(n + " "));
    /* Converted it into Stream and then
       printed using forEach */
}
}

30) Write a Java 8 program to find the number of Strings in a list whose length is greater than 5?

In this program, four Strings are added in the list using add() method, and then with the help of Stream and Lambda expression, we have counted the strings who has a length greater than 5.

import java.util.ArrayList;
import java.util.List;
public class Java8 {
public static void main(String[] args) {
List list = new ArrayList();
list.add("Saket");
list.add("Saurav");
list.add("Softwaretestinghelp");
list.add("Steve");   
 // Added elements into the List

    long count = list.stream().filter(str -> str.length() > 5).count();

    /* Converted the list into Stream and filtering out
       the Strings whose length more than 5
       and counted the length
       */
    System.out.println("We have " + count + " strings with length greater than 5");
}

}

Please see top core java interview question here

Leave a Reply 0

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