Top Java 8 Interview Questions and Answers

By | September 29, 2021
Java 8 Interview Questions

Java is one of the most popular and widely used programming languages, and many organizations use it for web, desktop and mobile app development which makes Java Developers always in demand. Now with so many high-level programming languages in the market, Java core developers provide a new version of Java every year. These new versions or updates do not change the complete syntax, they are only supposed to bring new features in Java, and most of the new versions only bring new features for the advanced Java Developer or solve some previous version bugs.

Top Java 8 Interview Questions

The current version of Java is Java 14, but here we have provided the Java 8 Interview questions and Answers because Java 8 is the most used and stable Java version and most of the organizations use it for their projects.


Question: Name the new features which were introduced in Java 8.


  • Lambda Expression
  • Default methods in the interface
  • Functional Interface
  • Optional
  • Method references
  • Date API
  • Stream API
  • Nashorn, JavaScript Engine
  • javac Enhancements
  • JVM Changes
  • Java 8 Compact Profiles: compact1,compact2,compact3
  • JDBC 4.2
  • JAXP 1.6
  • Java DB 10.10
  • Networking
  • Security Changes

Question: What are the major advantages of using Java 8?


  • Compact coding
  • Increase code reusability
  • Testable code
  • Utilize current Multi-core CPUs Efficiently
  • Reduce Boilerplate

Question: What is Lambda expression?

Answer: Lambda expression is one of the new features of Java 8, and it is also known as Anonymous functions. Lambda Expression provides an easy and concise way to write the user-defined function in a single line. It comprises the set of parameters and function body, and we can call it without a name.

Lambda Expression Syntax:

(Argument List) ->{function body;}

Lambda Expression Example:

 public class ThreadSample {
 public static void main(String[] args) {
  // old way
  new Thread(new Runnable() {
   public void run() {
    System.out.println("Thread is started");
  // using lambda Expression
  new Thread(()->System.out.println("Thread is started")).start();


Question: Explain the syntax of Lambda Expression.

Answer:  Lambda expression is divided into 3 parts Arguments, Array token and Function body or statement.

Argument: The lambda expression is similar to the user-defined function with no name, and as a function, it can accept zero or more than 0 arguments.

Array token: Array token is a special symbol which represents by -> sing and it acts as a separator between the arguments and function body.

Body: Body contains the expression or statement and it resides in curly braces.


(int a,int b)-> {a+b};

Here a and b are two integer arguments, -> symbol is the array token and a+b is the function body or statement.

Question: What is the Type of Lambda Expression?

Answer: In other high-level programming languages which give support for first class function, there the type of a lambda expression is a function, but the Java 8 has represented Lambda Expression as an object, and when we define a lambda expression it must be bound to a particular object type which is known as functional interface.

Question: Give some advantages of Lambda Expressions.


  • Increase code Conciseness.
  • Reduce the code bloat.
  • Increase code readability
  • Eliminate the use of unnecessary variables.
  • Increase code reusability.
  • Simplified variable scope
  • Less boilerplate codes.

Question: What is the target type of a lambda expression?

Answer: The functional interface for which the Lambda Expression has been invoked become its target type.


interface TT 
   // interface body
TT le = (x,y) -> {//};

here TT is the target type of lambda expression le.

Question: What is StringJoiner?

Answer: StringJoiner is the new class introduced in Java 8 which is used to join the string using a delimiter. We can also use prefix and suffix with StringJoiner to add a specific string at the beginning and end of the string.


StringJoiner joiner = new StringJoiner(",", PREFIX, SUFFIX); 

Question: What are the functional Interfaces?

Answer: Functional Interfaces first introduced in Java 8, which allow the user to define exactly one abstract method inside the interface. These interfaces are also known as Single Abstract Method Interface (SAM interface).

To create a functional interface in java we can either use lambda expressions, method references or constructor references.

Question: Relate lambda expression with functional interfaces.

Answer: Using the lambda expression, we can apply the abstract method in an interface to create a functional interface.

Question: Why do we need Functional Interface in Java?

Answer: In Java 8 functional interface introduced to implement the concept of Lambda expression, so an abstract method can be implemented via a Lambda expression.

Question: How can you create your own functional interface?

Answer: However, java can implicitly identify functional interface but we can also annotate it with @FunctionalInterface.


interface CustomFunctionalInterface {
   void display();
public class FunctionInterfaceLambdaTest {
   public static void main(String args[]) {
      // Using Anonymous inner class
      CustomFunctionalInterface test1 = new CustomFunctionalInterface() {
         public void display() {
            System.out.println("Display using Anonymous inner class");
      // Using Lambda Expression
      CustomFunctionalInterface test2 = () -> {    // lambda expression
         System.out.println("Display using Lambda Expression");

Question: Is it necessary to mention the annotation @FunctionalInterface to define a functional interface?

Answer: Even if we do not mention the @FunctionalInterface, the compiler would not throw any error, so it’s completely on the developer whether he/she mention the annotation or not, but it’s a good practice to mention the annotation.

If we mention an interface with @FuntionalInterface and try to create more than one abstract method then the compiler would throw an error.

Question: What is the key difference between collections and stream API?

Answer: Collection is used to store and group the data in a proper data structure whereas the stream is used to perform data operations on that data.

Question: Mention some of the Limitations of Stream API in Java 8?


  • If we use a parallel stream when lambda expressions are stateful, this could result in a random response.
  • A Stream cannot be used later once it has been consumed.
  • There are too many complex methods in Stream API which make it hard to learn.

Question: What is Spliterator?

Answer: Basically, it is an Iterator like java Iterator and ListIterator, which is used to iterate elements from a collection, I/O channel or Generator functions. It is introduced in java 8, defied as an interface in Java collection API and reside in java.util package.

It uses tryAdvance() method to iterate in multiple Threads for parallel processing and forEachRemaining() method for single Thread.

Question: What is the key difference between Iterator and Spliterator?

Answer: We can use the Spliterator with Stream whereas we can only use iterator with collections. Spliterator gives support for sequential and parallel iteration whereas iterator support only sequential iteration.

Question: Comment on method reference in Java 8.

Answer: Method reference feature introduced in Java 8, and it is used to refer method of functional interface. It can also be considered as an easy and compact form of the lambda expression.


interface Sayable{ 
    void say(); 

public class MethodReference { 
    public static void saySomething(){ 
        System.out.println("Static Method."); 
    public static void main(String[] args) { 
        // Referring static method 
        Sayable sayable = MethodReference::saySomething; 
        // Calling interface method 

Question: How to access the name of the parameter?

Answer: In java 8 we have a class java.lang.reflect.Parameter which helps us to get the information related to the parameters name and its modifiers.

Question: What is Optional class in Java 8?

Answer: In Java 8 to avoid the NullPointerException developer introduced Optional class in java.util.package. With Optional class, we can write readable and compact code without using too many null checks. With it, we can specify the alternative values to return or alternative code to run.


import java.util.Optional;  
public class Optional_Class{  
    public static void main(String[] args) {  
        String[] words = new String[10];  
        Optional<String> checkNull = 
        if (checkNull.isPresent()) {  
            String word = words[5].toLowerCase();  
        } else 
            System.out.println("Null Word");  

Question: Name the method provided by the option for the fallback mechanism in case of a null value.

Answer: Somehow if there is a null value in optional then we use the orElseGet() method as a fallback mechanism.

Question: Comment on the Static method in the Interface.

Answer: Inside an Interface, if we define a method with a static keyword then it would be considered as a static method. The static method contains the full definition of the method, and the class which implement the interface cannot override the interface static method.

Question: What are default methods?

Answer: The concept of default method introduced in Java 8 which allow the interface to have methods without affecting the class that implement the interface.

To define a default method in an interface we use the default keyword and the class which implement the interface can access the default method with the class instance, and using the class itself the user can also override the default method.


public interface Story {
    default void tell(){
        System.out.println("story telling");

public class People implements Story{
    public static void main(String[] args){
        People person = new People();


Question: Why do we require Default methods?

Answer: In earlier versions of java when we do not have the default methods, we have to use the abstract method in the interface. The main problem with the abstract methods and interface were, the code has to be provided in the class which is implementing the interface if there a new method introduced in the interface. To solve this problem and improve the backward compatibility of class with interface default methods introduced.

Question: What is the difference between Predicate and Functions?

Answer: The Predicate interface accepts an argument and returns a Boolean value, whereas the function interface returns an object value.

The predicate has a method test() which test the passed argument and test for the condition, whereas Function has a method apply() which apply logic on the passed argument.


Predicate<T>:  Here T represent the object type of the input or argument.

Function <T, R>: Here T is the type of the object pass to the function and R is the type of return object


Function<String, Integer> length = str -> str.length();
Predicate gt_lt = i -> i>0 ;

Question: What is the major difference between Internal and External iterator?

Answer: The external iterator is controlled by the programmer whereas the internal iterator is controlled by the iterator itself. Internal Iterator reduces the error probability, make the code more readable and useless code whereas there is more possibility that user can commit some error with the external iterator.

Question: Name the drawbacks of old date-time APIs, which were solved with Java 8.


  • Unsafe Threads: Before Java 8, java.util.Date was mutable and not thread-safe, but with Java 8 new date-time APIs, we get immutable and safer thread date APIs.
  • Few Operation: There were limited operations and methods for the old Date APIs, but with new Java 8 date APIs we get many new operations. 

Question: Name some Data and Time APIs of Java 9.


  • LocalDate/LocalTime and LocalDateTime API : These APIs used when we do not require time zone.
  • ZonedDateTime API: We use this API when we require time zone.
  • Period and Duration: These APIs Deal with the amount of time.
  • ChronoUnit: ChronoUnit is used to replace integer values which used in old APIs to represent the date, month and year.
  • TemporalAdjuster: for date related operation we use this API.

Question: How can we get the difference between two dates?

Answer:  To get the difference between two days or to get the duration between two dates we can use the java 8 Period Class.


Period duration = Period.between(date_1, date_2);

Question: Name the method introduced in Java 8 to process Arrays on multi-core machines.

Answer:  New arrays Parallel method introduce in java 8 for parallel processing of Arrays on the multi-core machines and these methods are:

  • parallelSetAll()
  • parallelSort()

Question: What is diamond Problem of multiple inheritance?

Answer: Consider this C++ class for example:

class A {
     void fun() { ... }
class B extends A {}
class C extends A {}
class D extends B, C {}

Here the class D can access the class A method fun(), but if the class B and C override the fun() method in their scope then the ambiguity will arrive in method resolution by Class D. This ambiguity of method accessing can lead to a trap in multiple inheritance which is known as diamond problem.

Question: How the Java 8 update deal with the diamond problem of Multiple inheritance?

Answer: Java 8 interface set some rule for multiple inheritance in order to tackle the diamond problem.

  • The inherited method from a class would be given priority over the default method inherited from an interface.
  • Derived interfaces take higher precedence than the interfaces higher-up in the inheritance hierarchy.
  • After following the above two rules if still, the problem arise then implementing class has to override the method.

Question: Write a code to get the current date and time using Java 8 date and time APIs.


import java.time.*;
import java.time.format.DateTimeFormatter;

public class Date {
public static void GetTimeandDate()
    LocalDate date =;     // the current date
    System.out.println("the current date is "+date);
    LocalTime time =;     // the current time
    System.out.println("the current time is "+ time);

    // Main Function
    public static void main(String[] args) 
        GetTimeandDate (); // calling the method

Question: What is Metascpace?

Answer: Metaspace is the new concept introduced in Java 8 to replace the concept of PermGen (Permanent Generation) memory space. In Java 8 developer introduced a new memory space known as Metaspace which handles the memory allocation of the classes, and gives better results for the native memory region grow to automatically.

Question: What is PermGem? do we still have it in Java 8?

Answer: We do not have PermGem in Java 8, it got replaced by the Metaspace. PermGen stands for Permanent Generation and it is a special heap space, which is separated from the main memory heap. Before Java 8 the Java Virtual Machine would use PermGen to keep track of the loaded class and to store all the static content in the memory section.

Question: Use only Java 8 APIs, and write code for this statement- “You have given a list of students and you need to filter out all the students whose marks are greater than 1000 and you also need to print their name”.


//essential imports
import java.util.ArrayList;
import java.util.List;

//Code Logic
List<String> StudentsFilter =>s.Marks()>1000).map(Students::Names).collect(Collectors.toList());

Question: With the help of Java 8 APIs write code to solve this statement- “You have given a list of Students, print the number of students who get marks less than 400.”


//Code Logic

List<Students> StudentsList = createStudentsList();
long count =>s.Marks()>25).count();

System.out.println("There are  " +count +"students who score less than 500");

Question: With the help of Java 8 APIs write a code to solve this statement- “You have given a list of Students, find all the students with name Luffy.”


//Code Logic

List<Students> StudentsList = createStudentsList();
Optional<Students> s =>s.Name().equalsIgnoreCase("Luffy")).findAny();

Question: With the help of Java 8 APIs write a code to solve this statement- “You have given a list of Students, you need to find the student which score the highest marks.”


List<Students> StudentsList = createStudentsList();
OptionalInt highest =;

       System.out.println("The highest score is: "+ highest.getAsInt());

Question: With the help of Java 8 APIs write a code to solve this statement- “You have given a list of Students, sort all the students based on their rank.”


List<Students> StudentsList = createStudentsList();

Question: With the help of Java 8 APIs write a code to solve this statement- “you have given a list of Students, now join all the students name with a comma(,).”


//Code logic

List<Students> StudentsList = createStudentsList();
List<String> StudentsNames =;
String names = String.join(",", StudentsNames);
System.out.println("All Students : "+names);

Question: With the help of Java 8 APIs write a code to solve this statement- “You have given a list of Students, group them all by their names ”


//Essential Imports
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//Code Logic
List<Students> StudentsList = createStudentsList();
Map<String, List<Students>> map =;
map.forEach((name,Student_List)->System.out.println("Name: "+name+" ==>"+ Student_List));

Question: What is the difference between Intermediate and terminal operations in stream?

Answer: If a stream operation returns another stram as a result then it would be an Intermediate stream operation.

If a stream returns non-stream value such as primitive or object or collection or return nothing then it would be considered as a terminal stream operation.

Examples of Intermediate Operations:

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

Examples of terminal Operations:

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

Question: With the help of Java 8 APIs write a code to solve this statement- “You have given a list of numbers, you need to remove all the duplicates element from the list ”


import java.util.Arrays;
import java.util.List;
import java.util.Set;
public class OnlyUniqueElements {
                public static void main(String[] args)
                  Integer[] lis=new Integer[]{20,40,70,90,20,20,40,80,70,50,60,10};
                  List<Integer> List_with_Duplicate = Arrays.asList(lis);

                   Set<Integer> Set_without_dups =;
                   Set_without_dups.forEach((i)->System.out.print(" "+i));

Question: What is the difference between findFirst() and findAny()?

Answer: The findAny() method help us to find any element from a Stream, we use it when we do not concern about the element order, and this method return an Optional instance.

The findFirst() method find the first element in the stream, we use this method when we want to find the first element from the sequence, or when we concern with the element order in the sequence.

Question: With the help of Java 8 APIs write a code to solve this statement-  “you have given a list of numbers, you need to square them and filter out the number which is greater than 20000 and then you also need to find their average”


import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;

public class Squares_Average {
    public static void main(String[] args)
         Integer[] lis=new Integer[]{122,250,223,679,500,770,340,382};
         List<Integer> list = Arrays.asList(lis);
        //calculating average
        OptionalDouble average =>n*n).filter(n->n>10000).average();
             //printing average as double
             System.out.println("Your Result is: "+average.getAsDouble());                     

Question: Why do we use Optional class in Java 8?

Answer: To tackle the problem of NullPointerException in Java 8 we use the Optional class.

Question: What is predicate function in interface?

Answer: Predicate in interface represents the generic functional interface which accepts a single argument and return the result as a boolean value. It resides in the java.util.function package.

Question: What is Consumer interface in java 8?

Answer: Consumer interface is a functional interface which resides in java.util.function package, and these functional methods accept one argument and do not return any value.


Consumer<String> consumerStr=s->{ System.out.println(s); };

Question: What is supplier function interface?

Answer:  Supplier interface is a functional interface which is a part of java.utils.function package, these functional methods does not accept any argument value but return an object value using the get() method.


Here we have provided the top Java 8 interview questions and answers, by far Java 8 is one of the most stable versions of Java and many organizations still use it for their project and currently running applications. Java 8 also play a major role in Java updates, because it introduced many new features in Java and show that Java can be more than an Object-oriented programming language.

People are also reading:

Leave a Reply

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