Java 8 interview questions and answers

In this article, we are going to discuss some important Java8 Interview Questions with Answers, Which are asked frequently for fresher candidates as well as Experienced.

We have already an article on Java8 Features.

Java 8 was released in 2014.

Java 8 is a release with new language features and library classes, Which are was present in other programming languages like python, but now it's available in java 8.

These features are towards achieving cleaner and more compact code, and some add new functionality, which makes Java stand like other programming languages in terms of features.

If you are new for java8 and want to install java8 on your machine, please follow the tutorial.

What Is a Method Reference?

You use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, it's often clearer to refer to the existing method by name.

Method references enable you to do this; they are compact, easy-to-read lambda expressions for methods that already have a name.

If your lambda expression is like this:

str -> System.out.println(str

then you can replace it with a method reference like this:

System.out::println

Four types of method references

1). Method reference to an instance method of an object – object::instanceMethod

2). Method reference to a static method of a class – Class::staticMethod

3). Method reference to an instance method of an arbitrary object of a particular type – Class::instanceMethod

4). Method reference to a constructor – Class:: new

What are Functional Interfaces in Java8?

There are many functional interfaces in the java.util.function package. Here is the list of frequently used Functional Interfaces.

1). Function – Takes one argument and returns a result.

2). Consumer – Takes one argument and returns no result (represents a side effect).

3). Supplier – Takes no argument and returns a result.

4). Predicate – Takes one argument and returns a boolean.

5). BiFunction – Takes two arguments and returns a result.

6). BinaryOperator – Same as BiFunction, taking two arguments and returning a result. The two arguments and the

result are all of the same types.

7).UnaryOperator – Same as Function, taking a single argument and returning a result of the same type.

What is Lambda Expression?

Lambda Expression is an anonymous function that accepts a set of input parameters and returns results.

It is a block of code without any name, with or without parameters, and with or without results. This block of code is executed on demand.

interface MyNumber { double getValue(); } public class LambdaDemo { public static void main(String[] args) { MyNumber myNum; myNum = () -> 123.45; System.out.println("A fixed value: " + myNum.getValue()); myNum = () -> Math.random() * 100; System.out.println("A random value: " + myNum.getValue()); System.out.println("Another random value: " + myNum.getValue()); } }

What is a Functional Interface? What is SAM Interface?

A Functional Interface is an interface, which contains only one abstract method. Functional Interface is also known as SAM Interface because it contains only one abstract method.

Runnable interface is a functional interface, so instead of

Thread thread = new Thread(new Runnable() { public void run() { System.out.println("Hello World!"); } });

we can use

Thread thread = new Thread(() -> System.out.println("Hello World!"));

interface SomeFunc&lt t &gt { T func(T t); } public class GenericFunctionalInterfaceDemo { public static void main(String[] args) { SomeFunc reverse = (str) -&gt { String result = ""; int i; for (i = str.length() - 1; i &gt= 0; i--) { result += str.charAt(i); } return result; }; System.out.println("Lambda reversed is " + reverse.func("Lambda")); System.out.println("Expression reversed is " + reverse.func("Expression")); SomeFunc&ltinteger&gt factorial = (n) -> { int result = 1; for (int i = 1; i &lt = n; i++) result = i * result; return result; }; System.out.println("The factoral of 3 is " + factorial.func(3)); System.out.println("The factoral of 5 is " + factorial.func(5)); } }

Is it possible to define our own Functional Interface?
What is @FunctionalInterface? What are the rules to define a Functional Interface?

Yes, We can define our own functional interfaces. 
We have to use @FunctionalInterface annotation to mark an interface as Functional Interface.
@FunctionalInterface interface display { public String display(); }

Rules to define a Functional Interface
  • Define an interface with only a single abstract method.
  • We cannot define more than one abstract method.
  • Use @FunctionalInterface annotation in the interface definition.
  • We can define other methods like Default methods, Static methods.
  • overriding java.lang.Object class’s method as an abstract method, which does not count as an abstract method.

What is Optional in Java 8? Why we have Java 8 Optional?

Optional is a final Class introduced as part of Java SE 8. It is defined in java.util package.

It is used to represent optional values that are either exist or not exist. It can contain either one value or zero value. If it contains a value, we can get it. Otherwise, we get nothing.

It is a bounded collection that is it contains at most one element only. It is an alternative to the “null” value.

Main Advantage of Optional is:

It is used to avoid null checks.
It is used to avoid "NullPointerException".

Java SE 8 New Features? Please list down it.

  • Stream API
  • Date and Time API
  • Interface Default Methods and Static Methods
  • Spliterator
  • Method and Constructor References
  • Collections API Enhancements
  • Concurrency Utils Enhancements
  • Fork/Join Framework Enhancements
  • Internal Iteration
  • Parallel Array and Parallel Collection Operations
  • Optional
  • Lambda Expressions
  • Functional Interfaces
  • Type Annotations and Repeatable Annotations
  • Method Parameter Reflection
  • Base64 Encoding and Decoding
  • IO and NIO2 Enhancements
  • 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

What is the difference and similarities between
Function and Predicate in java 8?

Difference:

The function returns an Object and it is a single argument function.
The predicate return type is boolean (i.e true or false) and it is also a single argument function.

Similarities:

Both are functional interfaces i.e both contain a single abstract method.

What is Nashorn in java 8?

Nashorn is the latest javascript engine released with java8. Before JDK 8, the javascript engine was based on Mozilla Rhino.

It provides better compliance with ECMA normalized javascript specifications and better runtime performance.

What are the defaults methods?

The default method are those methods in the interface which have the body and use default keywords. The default method are introduced in Java 8 mainly because of backward compatibility.

Example public interface Vehicle { void print(); default void move() { System.out.println("Vehicle is moving.."); } }

Can you provide some APIs of Java 8 Date and TIme?

LocalDate, LocalTime, and LocalDateTime are the Core API classes for Java 8. As the name suggests, these classes are local to the context of the observer. It denotes the current date and time in the context of Observer. You can see more examples here.

Given the list of numbers, remove the duplicate elements from the list

using java8 stream api we can remove the duplicate elements from the list

package com.javacodestuffs.java8.examples import java.util.List; import java.util.Set; import java.util.Arrays; import java.util.stream.Collectors; public class RemoveDuplicatesFromList { public static void main(String[] args) { Integer[] arr = new Integer[] { 9, 7, 11, 4, 33, 2, 34, 22, 31, 9, 33, 55, 4, 31, 25 }; List < Integer > listWithDuplicates = Arrays.asList(arr); Set < Integer > setWithoutDups = listWithDuplicates.stream().collect(Collectors.toSet()); setWithoutDups.forEach((i) ->System.out.print(" " + i)); } } output: $javac com/javacodestuffs/java8/examples/RemoveDuplicatesFromList.java $java -Xmx128M -Xms16M com/javacodestuffs/java8/examples/RemoveDuplicatesFromList 33 2 34 4 22 7 55 9 25 11 31

Given the list of students,
count number of students with 51 marks in Physics using java8?

List<Student> studentList = getStudentList(); long count = studentList.stream() .filter(e->e.getPhysics()> 51) .count(); System.out.println("Number of students with 51 marks in Physics are : "+count);

Given a list of employee, find maximum salary of employee,Using java8?

List<Employee> employeeList = getEmployeeList(); OptionalInt max = employeeList.stream(). mapToInt(Employee::getSalary).max(); if(max.isPresent()) System.out.println("Maximum Salar of Employee: "+max.getAsInt());

Given a list of employees,
sort all the employee on the basis of age,Using java8?

List<Employee> employeeList = getEmployeeList(); employeeList.sort((e1,e2)->e1.getAge()-e2.getAge()); employeeList.forEach(System.out::println);

In this article, we have seen the  Java 8 interview questions and answers with examples. All source code in the article can be found in the GitHub repository.