Prepare Interview

Exams Attended

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address
Check our LIVE MOCK INTERVIEWS

Java 8 Interview Questions and Answers

Test your skills through the online practice test: Java 8 Quiz Online Practice Test

Experienced / Expert level questions & answers

Ques 1. How lambda expression and functional interfaces are related?

Lambda expressions can only be applied to abstract method of functional interface.
For example:
Runnable has only one abstract method called run, so it can be used as below:
// Using lambda expression
Thread t1=new Thread(
  ()->System.out.println("In Run method")
);

Here we are using Thread constructor which takes Runnable as parameter. As you can see we did not specify any function name here, as Runnable has only one abstract method, java will implicitly create anonymous Runnable and execute run method.
It will be as good as below code.
Thread t1=new Thread(new Runnable() { 
   @Override
   public void run() {
      System.out.println("In Run method");
   }
});

Is it helpful? Add Comment View Comments
 

Ques 2. Can you create your own functional interface?

Yes, you can create your own functional interface. Java can implicitly identify functional interface but you can also annotate it with @FunctionalInterface.
Example:
Create interface named "Readable" as below:
public interface Readable {
    void read();
    default void readBook()
    {
        System.out.println("Reading the book.");
    }
}

Create main class named "MyFunctionalInteface":
public class MyFunctionalInteface {
    public static void main(String[] args)
    {
        MyFunctionalInteface myFuncInterface = new MyFunctionalInteface();
        myFuncInterface.readMyBook(() -> System.out.println("Reading my book"));
    }
    public void readMyBook(Readable p)
    {
        p.read();
    }
}

When you run above program, you will get below output:
Reading my book

As you can see, since Readable has only one abstract method called read(), we were able to call it using lambda expression.

Is it helpful? Add Comment View Comments
 

Ques 3. What is method reference in java 8?

Method reference is used refer method of functional interface. It is nothing but compact way of lambda expression.You can simply replace lambda expression with method reference.
Syntax:
class::methodname

Is it helpful? Add Comment View Comments
 

Ques 4. What the issues with Old Date and time API before Java 8? Date and Time API differences between Java 8 and earlier Java version.

Issues with old Date and Time API:
  • Thread Safety: You might be already aware that java.util.Date is mutable and not thread safe. Even java.text.SimpleDateFormat is also not Thread-Safe. New Java 8 date and time APIs are thread safe.
  • Performance: Java 8 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.

Is it helpful? Add Comment View Comments
 

Ques 5. Do we have PermGen in Java 8? What is MetaSpace in Java 8?

Until Java 7, JVM used an area called PermGen to store classes. It got removed in Java 8 and replaced by MetaSpace.
Major advantage of MetaSpace over permgen:
PermGen was fixed in term of maximum size and can not grow dynamically but Metaspace can grow dynamically and do not have any size constraint.

Is it helpful? Add Comment View Comments
 

Ques 6. Difference between Intermediate and terminal operations in Stream.

Java 8 Stream supports both intermediate and terminal operation.
  • Intermediate operations are lazy in nature and do not get executed immediately. Terminal operations are not lazy, they are executed as soon as encountered.
  • Intermediate operation is memorized and is called when terminal operation is called.
  • All Intermediate operations return stream as it just transforms stream into another and terminal operation don't.

Is it helpful? Add Comment View Comments
 

Ques 7. Given the list of numbers, remove the duplicate elements from the list.

See the following code:

Integer[] arr=new Integer[]{1,2,3,4,3,2,4,2};
List<Integer> listWithDuplicates = Arrays.asList(arr);
Set<Integer> setWithoutDups = listWithDuplicates.stream().collect(Collectors.toSet());
setWithoutDups.forEach((i)->System.out.print(" "+i));

Is it helpful? Add Comment View Comments
 

Ques 8. Difference between Stream 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 has deterministic behavior whereas findAny is nondeterministic behavior.

Is it helpful? Add Comment View Comments
 

Ques 9. What is consumer function interface?

It is a functional interface defined in java.util.function package. It contains an abstract accept() and a default andThen() method. It can be used as the assignment target for a lambda expression or method reference.
Consumer is single argument functional interface which does not return any value.

public static void main(String[] args) {  
   Consumer<String> consumerString = s->System.out.println(s);
   consumerString.accept("John");
}
 
We have created consumer object which takes String object as input and print it. It is simple use of Consumer interface to print String.
Output:
John

Is it helpful? Add Comment View Comments
 

Ques 10. What is predicate function interface?

Predicate is single argument function which returns true or false. It has test method which returns boolean. Usually, it used to apply in a filter for a collection of objects.

public static void main(String[] args) {
Predicate<Integer> predicate = i -> i > 100;
boolean greaterCheck = predicate.test(200);
System.out.println("is 200 greater than 100: "+greaterCheck);
}

Output:
is 200 greater than 100: true

Is it helpful? Add Comment View Comments
 

Ques 11. What Is a Stream? How Does It Differ from a Collection?

  • In simple terms, a stream is an iterator whose role is to accept a set of actions to apply on each of the elements it contains.
  • The stream represents a sequence of objects from a source such as a collection, which supports aggregate operations. They were designed to make collection processing simple and concise. Contrary to the collections, the logic of iteration is implemented inside the stream, so we can use methods like map and flatMap for performing a declarative processing.
  • And yet another important distinction from collections is that streams are inherently lazily loaded and processed.
  • Another difference is that the Stream API is fluent and allows pipelining:  
    • int sum = Arrays.stream(new int[]{1, 2, 3})
        .filter(i -> i >= 2)
        .map(i -> i * 3)
        .sum();

Is it helpful? Add Comment View Comments
 

Ques 12. What Is the Difference Between Map and flatMap Stream Operation?

  • There is a difference in signature between map and flatMap. Generally speaking, a map operation wraps its return value inside its ordinal type while flatMap does not.
  • For example, in Optional, a map operation would return Optional<String> type while flatMap would return String type.
  • So after mapping, one needs to unwrap (read “flatten”) the object to retrieve the value whereas, after flat mapping, there is no such need as the object is already flattened. The same concept is applied to mapping and flat mapping in Stream.
  • Both map and flatMap are intermediate stream operations that receive a function and apply this function to all elements of a stream.
  • The difference is that for the map, this function returns a value, but for flatMap, this function returns a stream. The flatMap operation “flattens” the streams into one.

Is it helpful? Add Comment View Comments
 

Ques 13. What is Stream Pipelining in Java 8?

  • Stream pipelining is the concept of chaining operations together. This is done by splitting the operations that can happen on a stream into two categories: intermediate operations and terminal operations.
  • Each intermediate operation returns an instance of Stream itself when it runs, an arbitrary number of intermediate operations can, therefore, be set up to process data forming a processing pipeline.
  • There must then be a terminal operation which returns a final value and terminates the pipeline.

Is it helpful? Add Comment View Comments
 

Ques 14. What does the flatmap() function do? why you need it?

The flatmap function is an extension of the map function. Apart from transforming one object into another, it can also flatten it.
For example, if you have a list of the list but you want to combine all elements of lists into just one list. In this case, you can use flatMap() for flattening. At the same time, you can also transform an object like you do use map() function.

public static void main(String[] args) {
            String[][] data = new String[][]{{"a", "b"}, {"c", "d"}, {"e", "f"}};
            //Stream<String[]>
            Stream<String[]> temp = Arrays.stream(data);
            //Stream<String>, GOOD!
            Stream<String> stringStream = temp.flatMap(x -> Arrays.stream(x));
            Stream<String> stream = stringStream.filter(x -> "a".equals(x.toString()));
            stream.forEach(System.out::println);
       }

Is it helpful? Add Comment View Comments
 

Ques 15. What is the parallel Stream? How can you get a parallel stream from a List?

A parallel stream can parallel execute stream processing tasks. For example, if you have a parallel stream of 1 million orders and you are looking for orders worth more than 1 million, then you can use a filter to do that.
Unlike sequential Stream, the parallel Stream can launch multiple threads to search for those orders on the different part of Stream and then combine the result.
In short, the parallel Stream can paralyze execution.

Is it helpful? Add Comment View Comments
 

Most helpful rated by users:

Related differences

Java 7 vs Java 8Java 8 vs Java 9

Related interview subjects

JUnit interview questions and answers - Total 24 questions
Spring Framework interview questions and answers - Total 53 questions
Java Design Patterns interview questions and answers - Total 15 questions
Java 17 interview questions and answers - Total 20 questions
Core Java interview questions and answers - Total 306 questions
Tomcat interview questions and answers - Total 16 questions
Apache Wicket interview questions and answers - Total 26 questions
Java Applet interview questions and answers - Total 29 questions
JAXB interview questions and answers - Total 18 questions
JMS interview questions and answers - Total 64 questions
Log4j interview questions and answers - Total 35 questions
Struts interview questions and answers - Total 84 questions
RMI interview questions and answers - Total 31 questions
Apache Camel interview questions and answers - Total 20 questions
JDBC interview questions and answers - Total 27 questions
Java 11 interview questions and answers - Total 24 questions
JPA interview questions and answers - Total 41 questions
EJB interview questions and answers - Total 80 questions
GWT interview questions and answers - Total 27 questions
Kotlin interview questions and answers - Total 30 questions
Glassfish interview questions and answers - Total 8 questions
Google Gson interview questions and answers - Total 8 questions
Java 21 interview questions and answers - Total 21 questions
JSP interview questions and answers - Total 49 questions
J2EE interview questions and answers - Total 25 questions
Apache Tapestry interview questions and answers - Total 9 questions
Java Swing interview questions and answers - Total 27 questions
Java Mail interview questions and answers - Total 27 questions
Hibernate interview questions and answers - Total 52 questions
JSF interview questions and answers - Total 24 questions
Java 8 interview questions and answers - Total 30 questions
Java 15 interview questions and answers - Total 16 questions
JBoss interview questions and answers - Total 14 questions
Web Services interview questions and answers - Total 10 questions
RichFaces interview questions and answers - Total 26 questions
Servlets interview questions and answers - Total 34 questions
Java Beans interview questions and answers - Total 57 questions
Spring Boot interview questions and answers - Total 50 questions
©2023 WithoutBook