DEV Community

Cover image for Java 8: Functional programming interview questions
Hunter Johnson for Educative

Posted on • Originally published at educative.io

Java 8: Functional programming interview questions

The key contribution that Java 8 introduced to the Java programming model is functional programming. This article focuses on questions related to functional programming, and some other significant changes that the Java 8 release introduced.

We’ll go over examples of interview questions related to Lambda calculus, functional interfaces, and more to test your knowledge of these concepts.

We’ll cover:

Let’s get started!

Java 8 interview questions and answers

1. What important features were introduced in Java 8?

These are some of the core concepts and features included with the Java 8 release. Understanding these concepts will not only prepare you for common Java-related interview questions, but will also help you be a better programmer in general.
The most important features added were:

  • Lambda expressions are an anonymous, classless function.
  • Method references are shorthand notations of lambda expressions used to call methods.
  • Functional interfaces are interfaces with a single abstract method.
  • Default methods enabled backward compatibility by allowing developers to add new methods to an interface without needing to modify the implementation class.
  • Static methods belong only to the interface, so implementation of this method can only be written in the interface itself.
  • Stream APIs are used to perform aggregate operations on elements returned from various data sources (such as collections or arrays).
  • Date-Time APIs improved on the old design by making them more readable, and easier to use with differing time zones.

2. What is a lambda expression, and what is its ideal use case?

A lambda expression is a function that can be referenced and passed around as an object. Lambda expressions helped introduce the functional programming paradigm to Java. Most Java functions exist inside an object’s scope, but lambda expressions do not and can be called from anywhere in the program.

Lambda expressions are often used to express instances of single-method classes more clearly and compactly than if you used the syntax of anonymous classes.

3. Explain the syntax of a lambda expression.

A lambda expression consists of:

  • Arguments: Formal parameters enclosed in parentheses. A lambda expression can have zero or more parameters.
  • The array token ->: Points arguments to the body of the lambda expression.
  • Body: Contains expressions or statements. If there is only one statement, curly braces are not required.
(Arguments list)->{expression;} or
(Arguments list)->{statements;}
Enter fullscreen mode Exit fullscreen mode

4. Execute a thread using a lambda expression.

Here’s an example of how you would execute a thread using a lambda expression:

public class LambdaThread {
public static void main(String[] args) {
 New Thread(()->System.out.println("Executing thread")).start();
   }
} 
Enter fullscreen mode Exit fullscreen mode

5. What is a method reference?

A method reference is a type of lambda expression used to refer to the method of a functional interface.
Lambda expressions are used to create anonymous methods, but when you want to call an existing method, you can make reading your code easier by calling that method by its name. So, a method reference can be used to replace lambda expressions when calling existing methods.

6. What is a functional interface?

A functional interface in Java 8 is an interface that can only have one abstract method. Functional interfaces are also referred to as SAM interfaces, or, Single Abstract Method interfaces. However, they can contain any number of default or static methods.

The @FunctionalInterface annotation is optional and can be used to prevent functional interfaces from having more than one abstract method.

7. What are some commonly used functional interface types?

Java 8 introduced four types of functional interfaces:

  • Consumer: Accepts an argument, returns nothing.
  • Function: Accepts an argument, returns a value.
  • Predicate: Accepts an argument, returns a boolean value.
  • Supplier: Does not accept an argument, returns a value.

8. What is a default method? What is a static method?

Default:
The default method was introduced in Java 8 to allow for default implementations of methods within interfaces. This meant that existing interfaces could be backward compatible with their older versions. Lambda expressions could be used without having to provide the implementation code in the implementation class.

Default methods can be overridden by classes that implement these interfaces.

Static:
The static method introduced in Java 8 functions similarly to the default methods but cannot be overridden when implementing class.

They are associated with the class in which they exist and can be called without creating an instance of that class.

9. What conditions must be fulfilled to match a lambda

expression against a functional interface?

There are three conditions that must be satisfied:
The functional interface must only have one unimplemented method.
The parameters within the method must match the parameters of the lambda expression.
The return type of the method must match the return type of the lambda expression.

10. What is the Optional class?

Optional is a value-based class introduced in Java 8 as a container object that can use the boolean isPresent() method to check for a non-null value inside itself.

This can make your code easier to read because instead of returning a RuntimeException:

Exception in thread "main" java.lang.NullPointerException
Enter fullscreen mode Exit fullscreen mode

The Optional class can be used to run your program without crashing it by returning an alternate block of code that you specify.

Note: You must import java.util.package to use the Optional class.

11. What are the advantages of using Date-Time APIs introduced in Java 8?

The new Date-Time APIs are faster than their predecessors, thread-safe, and compliant with ISO standards.

Developers had previously struggled with writing code that accounted for differences in time zones. To solve this, Java 8 included separate classes for handling local date-time when the use of time zones was not required and zoned date-time for when they were.

12. What are some Date-Time APIs, and what do they do?

  • Local:
    LocalDate, LocalTime, and LocalDateTime are classes that represent the local date and time of the person using the program.

    • LocalDate: Displays date in (year, month, day (yyyy-MM-dd) format.
    • LocalTime: Displays time in (hour, minute, second, and nanosecond (HH-mm-ss-ns)) format.
    • LocalDateTime: Displays both date and time in (yyyy-MM-dd-HH-mm-ss-ns) format.
  • Zoned:

    • ZonedDateTime: Immutable class storing all date and time fields, and a time-zone that can be used with ZoneOffset to handle ambiguous local date-times.

13. Write a program that displays the current date and time.

Here’s one example of how you could implement this:

import java.time.LocalDateTime;

public class Main {
    public static void main(String[] args) {
        LocalDateTime exampleProgram = LocalDateTime.now();
        System.out.println(exampleProgram);
}
}

----> 2022-05-25T18:37:34.467
Enter fullscreen mode Exit fullscreen mode

14. What is the Stream API, and how is it used?

The Stream API is used to convey collections of objects or primitives from a data source through a “stream” that performs computational operations on the various data elements passing through.

Three main components of a Stream:

  • A data source.
  • A set of intermediate operations to process the data.
  • A sole terminal operation to return the result.

Streams are used alongside the Collectors class to filter and manipulate elements, making them ideal for projects that involve database operations, pipeline operations, or parallel processing. Streams function similarly to loops but are easier to read at a glance, and tend to be better at processing large data lists. For smaller data lists, loops are sufficient.

15. What is a collector?

When all computational operations in a stream have been performed on the elements passing through, a collector is used to combine the final results and return them as lists or strings.

To learn more about collection, check out Collections in Java on Educative, which walks you through one of the most important topics in Java programming.

The course covers:

  • How data is modified within collections.
  • How to sort a collection.
  • How to make a collection thread-safe.
  • And more!

16. What are intermediate operations, and what do they do?

Stream intermediate operations return another Stream as a result, allowing you to call multiple operations as a query. Intermediate operations are considered “lazy” because they do not evaluate until a terminal operation initiates.

  • map(): Returns the results of a Stream after a given function is applied to the elements of a Stream.
  • filter(): Returns a Stream consisting of elements that match a given predicate (another type of functional interface).
  • sorted(): Returns the elements of a Stream after they have been sorted.

Other intermediate operations include:

  • distinct()
  • flatMap()
  • limit()
  • peek()
  • skip()

17. What are terminal operations, and what do they do?

Terminal operations denote the end of a Stream and return the result.

  • collect(): Returns the collective result of all intermediate operations performed on the Stream.
  • forEach(): Accepts a consumer and iterates through each element of a Stream.
  • reduce(): Reduces the elements of a Stream and returns the result as a single value.
  • count(): Returns the number of elements in a Stream.
  • min(): Returns the smallest element from a Stream.
  • max(): Returns the greatest element from a Stream.

18. Collect Stream elements into a List using the toList() method.

Here's an example solution:

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

public class Main {
   public static void main(String[] args) {
       List<Integer> list = Stream.of(1, 2, 3).collect(Collectors.toList());  
   }
Enter fullscreen mode Exit fullscreen mode
import java.util.List; 
import java.util.stream.Stream;
import java.util.stream.Collectors;

public class Main {
   public static void main(String[] args) {
       List<Integer> list = Stream.of(1, 2, 3).collect(Collectors.toList());  
   }
}
Enter fullscreen mode Exit fullscreen mode

19. Determine the number of elements in a given Stream.

To find the number of elements in a given Stream, use the .count() operation.

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

public class Main {
   public static void main(String[] args) {
       List<Integer> list = Stream.of(1, 2, 3).collect(Collectors.toList());  
       Long count = list.stream().collect(Collectors.counting());
       System.out.print(count); 
   }
}

----> 3
Enter fullscreen mode Exit fullscreen mode

20. What is the random keyword used for?

In Java 8, the random keyword can be used to generate random values.

21. What is a supplier?

A Java 8 supplier is a common type of functional interface in the Standard Library that does not accept any parameters as arguments.

22. What is a consumer?

A Java 8 consumer is another common type of functional interface with a single argument.

Unlike a predicate, another single argument functional interface, a consumer accepts arguments but does not return any values.

23. What’s the syntax for a predicate interface?

Predicates are functional interfaces that accept an object and return a Boolean value.

The syntax for this is:

public boolean test(T object){
    Return boolean;
}
Enter fullscreen mode Exit fullscreen mode

24. What is functional programming?

  • Functional programming is a declarative programming paradigm where programs are constructed with sequential functions rather than statements.

  • Functions can be independent and reusable, allowing statements to execute in any order, regardless of the program state.

Wrapping up and additional resources

In summary, learning Java 8 is absolutely worth it if writing efficient, readable, reliable code sounds appealing to you. The popularity of Java 8 is another good reason to familiarize yourself with its concepts, as it’s likely that you’ll come across programs written in Java 8 at some point in your career.

Also, the core concepts introduced in Java 8 are great to know for anyone who wants to be a better, more versatile programmer that can collaborate in a broader range of Java projects.

At Educative, we’re passionate about advancing developers’ careers. That’s why we’ve created the following resources to help you master Java 8 and land the career of your dreams:

Happy Learning!

Continue learning about Java interview prep on Educative

Start a discussion

Do you have any helpful tips for the Java 8 interview? Was this article helpful? Let us know in the comments below!

Top comments (0)