Java 8: Functional programming interview questions
Tags: java, career, functional, programming
Published: 2022-05-25 19:57:56

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**:
* [Interview questions](#questions)
    * [1. What important features were introduced with Java 8?](#important-features)
    * [2. What is a lambda expression, and what is its ideal use case?](#lambda-use-case)
    * [3. Explain the syntax of a lambda expression.](#lambda-syntax)
    * [4. Execute a thread using a lambda expression.](#execute-thread) 
    * [5. What is a method reference?](#what-is-method-reference)
    * [6. What is a functional interface?](#what-is-functional-interface)
    * [7. What are some commonly used functional interface types?](#common-functional-interface-types)
    * [8. What is a `default` method? What is a `static` method?](#default-static-methods) 
    * [9. What conditions must be fulfilled to match a lambda expression against a functional interface?](#match-lambda-to-interface)
    * [10. What is the `Optional` class?](#optional-class)
    * [11. In what ways did the Date-Time APIs improve?](#date-time-api-improvements)
    * [12. What are some Date-Time APIs, and what do they do?](#date-time-apis) 
    * [13. Write a program that displays the current date and time.](#display-current-date-and-time)
    * [14. What is the Stream API, and how is it used?](#stream-api)
    * [15. What is a collector?](#collector)
    * [16. What are intermediate operations, and what do they do?](#intermediate-operations) 
    * [17. What are terminal operations, and what do they do?](#terminal-operations)
    * [18. Collect Stream elements into an array list using the `toList()` method.](#collect-stream-elements-into-array)
    * [19. Determine the number of elements in a given Stream.](#stream-count)
    * [20. What is the `random` keyword used for?](#random-keyword)
    * [21. What is a supplier?](#supplier)
    * [22. What is a consumer?](#consumer)
    * [23. What's the syntax for a predicate interface?](#predicate-interface-syntax)
    * [24. What is functional programming?](#functional-programming) 
* [Wrap up and additional resources](#wrapup)

Let’s get started!

<a name="questions"></a>

## Java 8 interview questions and answers

<a name="important-features"></a>
### 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. 

<a name="lambda-use-case"></a>
### 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. 

<a name="lambda-syntax"></a>
### 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;}
```

<a name="execute-thread"></a>
### 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();
   }
} 
```
<a name="what-is-method-reference"></a>
### 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.

<a name="what-is-functional-interface"></a>
### 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. 

<a name="common-functional-interface-types"></a>
### 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. 

<a name="default-static-methods"></a>
### 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. 

<a name="match-lambda-to-interface"></a>
###  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. 

<a name="optional-class"></a>
### 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
```
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.

<a name="date-time-api-improvements"></a>
### 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. 

<a name="date-time-apis"></a>
### 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. 

<a name="display-current-date-and-time"></a>
### 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
```

<a name="stream-api"></a>
### 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.

<a name="collector"></a>
### 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!

<a name="intermediate-operations"></a>
### 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()`

<a name="terminal-operations"></a>
### 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.

<a name="collect-stream-elements-into-array"></a>
### 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());  
   }
```

```
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());  
   }
}
```
<a name="stream-count"></a>
### 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
```

<a name="random-keyword"></a>
### 20. What is the `random` keyword used for?

In Java 8, the `random` keyword can be used to generate random values.
 
<a name="supplier"></a>
### 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. 

<a name="consumer"></a>
### 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. 

<a name="predicate-interface-syntax"></a>
### 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;
}
```

<a name="functional-programming"></a>
### 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. 

<a name="wrapup"></a>
## 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: 

* Ready to crack your knuckles and dig into some advanced interview prep? Give [Decode the Coding Interview in Java: Real-World Examples](https://www.educative.io/courses/decode-coding-interview-java?aid=5082902844932096&utm_source=google&utm_medium=paid&utm_campaign=decode_coding_interview&utm_content=extensions&utm_term=&utm_campaign=DSA+I+Java+I+Target+Geos&utm_source=adwords&utm_medium=ppc&hsa_acc=5451446008&hsa_cam=16058966280&hsa_grp=132258797505&hsa_ad=579257327975&hsa_src=g&hsa_tgt=dsa-1599320231466&hsa_kw=&hsa_mt=&hsa_net=adwords&hsa_ver=3&gclid=CjwKCAiAo4OQBhBBEiwA5KWu_4jpWPXE-9v-gpN_eKW0hsEmhMyeRY0njSKMkx75l2DigdnIrYKMaxoC9SQQAvD_BwE?eid=5082902844932096) a try on Educative. 
* New to Java and not sure where to start? Try [Learn Java from Scratch](https://www.educative.io/courses/learn-java-from-scratch?eid=5082902844932096) on Educative, this is our course geared towards complete beginners and only takes about 12 hours to complete! 

*Happy Learning!*

### Continue learning about Java interview prep on Educative

* [The complete guide to Java interview questions and interview prep](https://www.educative.io/blog/top-java-interview-questions?eid=5082902844932096).

* [Java Multithreading & Concurrency: Cracking senior interviews](https://www.educative.io/blog/java-multithreading-and-concurrency-what-to-know-for?eid=5082902844932096)

* [Ace the top 15 Java algorithm questions for coding interviews](https://www.educative.io/blog/ace-top-15-java-algorithm-questions?eid=5082902844932096)

### 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!