Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Java 8 Interview Questions

Java is a very popular programming language and is very widely used. Java 8 was released in 2014 and a lot of new features were added to overcome the limitations of the previous versions. In this tutorial, we will discuss some of the most commonly asked interview questions about Java 8.

Q1. Briefly explain the new features added in Java 8

  • Lambda Expressions - Used to define a function that can be referenced as an object.
  • Functional Interface - Interfaces with just one abstract method.
  • Method References - Allow us to use functions as parameters for invoking a method.
  • Optional - A wrapper class used to check Null values.
  • Default Methods - Allows us to add implementation for methods inside an interface.
  • Stream API - Special iterator class that allows pipeline processing of data.
  • Date API - An improved API inspired by JodaTime.

Q2. Explain the advantages of Java 8?

  • Increased readability and reusability of code.
  • Lesser boilerplate code.
  • Higher stability.
  • Parallel execution of operations.
  • Compact code

Q3. What does Method Reference mean in Java 8?

Method referencing is a way of referring to a method without invoking it. Double colon(::) is used for method reference. Method referencing is used to treat methods as Lambda expressions.

Q4. What are Functional Interfaces?

A functional interface is an interface with exactly one abstract method. They are also known as SAM interfaces. SAM stands for Single Abstract Method. The @FunctionalInterface annotation can be used, but it is optional. There is no restriction on the number of default, static, and overridden methods. An example of a functional interface is shown below.

@FunctionalInterface
interface FunctionalDemo
{
	abstract public void someAbstractMethod();
	
	default public void defaultMethod()
	{
		System.out.print("Default");
	}
}

Q5. What is a Lambda Expression?

Lambda expression is an anonymous function that can be referenced and used as an object. The following are some of the key characteristics of Lambda expressions. Lambda expressions can also be used as parameters for other methods.

Q6. How will you create a Lambda Expression? Explain the basic syntax.

A Lambda expression contains three parts.

  • A parameter list is enclosed in round brackets().
  • The expression body is enclosed in curly braces{}.
  • Arrow symbol(->) to separate parameter list and body.

The code below shows a basic lambda expression.

interface DemoInterface{
	abstract void add(int i, int j);
}

public class Demo
{
	public static void main(String[] args) throws Exception
	{
		DemoInterface i = (int a, int b) -> {
			System.out.print("Sum is: " + (a + b));
		};
		i.add(10, 20);
	}
}


Sum is: 30

The following are some of the key characteristics of a Lambda expression.

  • Optional type declaration - we do not need to declare the type of the parameters. The compiler can infer the type from their values and usage.
  • Optional parentheses around parameters - if we only have a single parameter, then we don't need to enclose it in round brackets.
  • Optional curly braces - if the expression contains just a single line of code, then we don't need to enclose it in curly braces.
  • Optional return keyword - if the expression returns a value and it is wrapped in curly braces, then we don't need to use the return statement.

Q7. What are Java 8 Streams?

A Stream is like a sequence of objects which are obtained from a source, like Collections. They are used to perform aggregate operations on the data in a pipelined fashion. They are used to make the processing of data simpler and easier.

Q8. Explain a few features of the Date and Time API.

The new Date and Time API solves some of the drawbacks of the previous date API. The key features of the Date and Time API are mentioned below.

  • Classes are immutable
  • Provides thread safety to avoid concurrency issues.
  • Timezone support
  • Meets the ISO standards
  • Inspired by JodaTime
  • Support for Timezones

Q9. How will you fetch the current date and time using the LocalDate, LocalTime, and the LocalDateTime APIs?

We can use the now() method with all of these classes to fetch the current date and time.

import java.time.*;

public class Demo
{
	public static void main(String[] args) throws Exception
	{
		LocalDate currLocalDate = LocalDate.now();
		LocalTime currLocalTime = LocalTime.now();
		LocalDateTime currLocalDateTime = LocalDateTime.now();
		
		System.out.println("Local Date: " + currLocalDate);
        System.out.println("Local Time: " + currLocalTime);
        System.out.println("Local Date and Time: " + currLocalDateTime);
	}
}


Local Date: 2021-08-06
Local Time: 16:06:52.498893400
Local Date and Time: 2021-08-06T16:06:52.498893400

Q10. Explain Nashorn?

Nashorn is a new JavaScript processing engine that comes with Java 8. It replaces the Mozilla Rhino, which came with JDK 7. It provides better runtime performance. It also provides better compliance with ECMA (European Computer Manufacturers Association) normalized JavaScript specification.

Q11. What do you mean by Default Methods?

A method that has been implemented inside an interface is known as a Default Method. The default keyword is used in their declaration. They are added to Java 8 to provide "Backward Compatibility". This means that if the JDK modifies an interface, then the classes implementing it will break. But with the default method, there won't be any impact on the implementing classes.

interface DemoInterface
{
	abstract void print(int i, int j);
	abstract String concat(String s1, String s2);
	//Default method
	default void defaultMethod()
	{
		System.out.print("Default method called!");
	}
}

Q12. What is JJS?

JJS stands for Java JavaScript, and it is a command-line tool used to execute JavaScript in the console.

Q13. Explain the forEach() method with the help of an example.

The forEach() method is part of the Stream API. It is used to iterate over each element of a stream and perform an action. Let's try to add ten and print all elements of a stream using the forEach() method.

import java.util.stream.Stream;

public class Demo
{
	public static void main(String[] args) throws Exception
	{
		Stream s = Stream.of(1, 2, 3, 4, 5);
		s.forEach(i -> System.out.println((int)i + 10));
	}
}


11
12
13
14
15

Q14. What is the difference between PermGen and MetaSpace?

The PermGen, short for Permanent Generation, is the place where class information and metadata were stored before Java 8. It was a contiguous heap memory space and was fixed in size. MetaSpace was introduced in Java 8 and it provides a dynamic or resizable native memory to store class metadata. It improves the de-allocation of metadata and garbage collection and is free from size limitations.

Q15. How will you use Streams to find and print even numbers present in an array?

We can use the filter() method of streams to find the even numbers. Then, we can simply print the stream elements by using the forEach() method.

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

public class Demo
{
	public static void main(String[] args) throws Exception
	{
		List<Integer> list = Arrays.asList(7, 9, 10, 1, 2, 5, 12, 11, 3, 4);
		Stream<Integer> evenNums = list.stream().filter(i -> i % 2 == 0);
		evenNums.forEach(System.out::println);
	}
}


10
2
12
4

Q16. What is Spliterator in Java 8?

Spliterator is an iterator interface introduced in Java 8. Just like a normal iterator, it can iterate or traverse through each element of a collection or stream. Unlike normal iterators, Spliterator supports both parallel and sequential traversals.

Q17. What is the difference between Streams and Collections?

Stream Collection
Used for processing data. Used for storing data.
Can process an infinite number of elements. Can store a limited number of elements.
Elements cannot be accessed directly. Easier access of elements.

Q18. Explain Stream Pipelining in Java 8.

Pipelining is the concept of chaining together multiple operations. The operations can be of two types - intermediate operations and terminal operations. Intermediate operations return an instance of the stream and terminal operation is used to terminate the pipeline.

Q19. Explain Intermediate and Terminal Operations with the help of examples.

Stream pipelining is done by using the Intermediate and Terminal operations. Intermediate operations return an instance of the stream and are used for chaining multiple operations. Intermediate operations are lazy because they won't start execution until a terminal operation is invoked. Intermediate operations mostly use lambda expressions to process the stream. Some common intermediate operations are map, flatMap, filter, peek, etc.

Terminal operations, as the name suggests, are used to terminate the stream pipelining. They are used to start stream processing. Some common terminal operations include forEach(), forEachOrdered(), collect(), reduce(), etc.

For example, in the code below, we are first using two intermediate operations(map() and filter()) and then we are printing the result using the terminal forEach() method.

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

public class Demo
{
	public static void main(String[] args) throws Exception
	{
		List<String> list = Arrays.asList("Hello", "Hola", "Ola");
		list.stream().map(s -> s.toUpperCase())       //Intermediate
					 .filter(s -> s.startsWith("H"))  //Intermediate
					 .forEach(System.out::println);   //Terminal
	}
}


HELLO
HOLA

Q20. What is Optional, and why is it used?

The Optional is a container or wrapper class that can contain zero(null) or one value. This class includes methods to check if the value is present or not. This class is used as a return type for methods that might otherwise return null. The method would need to return an object instead of a value. This helps us in avoiding the NullPointerException.

Q21. What is the difference between a Predicate and a Function?

Both Predicate and Function are functional interfaces, and they are present in the java.util.function package. A Predicate is used to test something, while a Function is for more general-purpose. A Predicate returns true or false according to the test. Function, on the other hand, returns an object.

Q22. How can we add one year to the current date using the LocalDate and LocalDateTime API?

The plusYears() method is used to add the number of years to a LocalDate or LocalDateTime object. We also have plusDays() and plusMonths() methods to add days or months to our date. Use the minusYears(), minusMonths(), or minusDays() methods to subtract years or months, or days from the date.

import java.time.*;

public class Demo
{
	public static void main(String[] args) throws Exception
	{
		LocalDate currLocalDate = LocalDate.now();
		System.out.println("Current Date: " + currLocalDate);
		LocalDate dateAfterOneYear = currLocalDate.plusYears(1);
		System.out.println("Date after one year: " + dateAfterOneYear);
	}
}


Current Date: 2021-08-06
Date after one year: 2022-08-06

Summary

Java continues to be one of the most widely used programming languages, and one must be well-versed with the basics of Java to ace technical interviews. Java 8 introduced several new features, and in this tutorial, we discussed some of the most important topics concerning technical Java interviews.