In this Post we have collected and explained the Most important Interview questions related to Java 8. We have covered almost all types of interview questions related to Java 8 newly added features. Some important topics that we have covered are lambda expressions, functional interfaces, default methods, streams, etc.
This post will help you to prepare and answers all Java 8 interview questions that can be asked during your interview. These Java 8 questions and answers are helpful for freshers as well as experienced who is preparing for an interview as Java developer.
Let us start Preparing.
Java 8 interview questions
Q1). Tell us some newly added features in Java 8.
Ans:
Some newly added Features of Java 8 are Lambda Expression, Functional Interface, Stream API, Default Method, Method References, Date Time API, Optional Class, Nashorm, and JavaScript Engine.
Short Explanations
Lambda Expression: lambda expression is a block of code that takes parameters and returns a value. We can refer to Lambda Expression as an object.
Functional Interfaces: It is an interface that contains only one abstract method.
Method References: Method References allow us to call the Class method by its name. “::” denotes method reference.
Default method: It is a method in the interface that implementation is not required in the class implementing that interface.
Stream API: Stream API is a sequence of objects used to process Collections.
Date Time API: It is introduced to overcome old Date drawbacks like new Date Time API is thread safe.
Optional: It is a Wrapper class to check the null value.
Nashorn, JavaScript Engine: Nashorn is an improved javascript engine to replace the existing Rhino.
Q2). What is Default Method in Java 8?
Ans:
the default method is a method inside the interface with the keyword default. It is a type of non-abstract method.
As we know an interface can have only abstract methods without a body. And we need a separate class for the implementation of interface methods. If we add a new method then we have to add the implementation of the newly added method in the class implementing the same interface.
To overcome this issue, Java 8 has introduced the concept of default methods. In interface, a default method can have its body so we don’t need to add its implementation in the class implementing the same interface.
Default Method Example:
interface DefaultInterface
{
// abstract method of interface
public void cube(int a);
// default method of interface
default void display()
{
System.out.println("This is default method");
}
}
class Main implements DefaultInterface
{
// need to add the implementation of
//cube abstract method
public void cube(int a)
{
System.out.println(a*a*a);
}
public static void main(String args[])
{
Main obj = new Main();
obj.cube(5);
// default method executed
//no need to add implementation
obj.display();
}
}
Output
125
This is default method
Q3). Can We Override Default Method in Java?
Ans: Yes, we can override the default method in Java.
Q4). What is Static Interface Methods in Java 8 ?
Ans:
Java 8 provided us with a feature to define and implement static methods in interfaces.
As we know the static method belongs to the class, not to a particular object. We can call the method using the interface name preceding the method name.
Static Method Example:
interface StaticInterface {
// static method in interface
static void staticMethod()
{
System.out.println("This is static Method can call by Interface");
}
}
// Implementation Class
public class Main implements StaticInterface {
public static void main(String[] args)
{
// Calling the static
//direcly using interface name
StaticInterface.staticMethod();
}
}
Output
This is static Method can call by Interface
Q5). What is the Lambda Expression in Java 8.
Ans:
Lambda expression is a function without a name. It is also known as an anonymous function as it does not have type information by itself. Lambda expression is executed on-demand. It is used with collection to perform operations like iteration, filter, extracting data, etc. The return type of the anonymous function is the same as that of the body expression.
As lambda expressions are similar to anonymous functions, they can only be applied to a single abstract method of Functional Interface. It will infer the return type, type, and several arguments from the signature of the abstract method of functional interface.
Basic Structure/Syntax of a Lambda Expression
FunctionalInterface fi = (String name) -> {
System.out.println(name);
return name;
}
Lambda expression is divided into three parts
1. List of Arguments/Params:
(String name)
Params or Parameters are passed in () round brackets. Lambda expression can have zero, one, two, or more params. Declaring the type of parameter is optional. It can be inferred from the context.
2. Arrow Token:
->
Arrow token is a lambda arrow operator which separates the parameters from the body. It points the list of arguments to the body.
3. Expression/Body:
{
System.out.println("Hello "+name);
return "Hello "+name;
}
The body contains the expressions or statements. If we have more than one line then we will use {} curly braces. the return type of the anonymous function is the same as that of the body expression.
Features of a lambda expression
- Lambda expressions can be passed as a parameter to another method.
- Lambda expressions can be standalone without belonging to any class.
Arraylist Iteration Using Lambda Expression
import java.util.*;
class Main{
public static void main(String args[]){
List<String> arr = Arrays.asList("quescol","interview");
arr.forEach(s->System.out.println(s));
}
}
Output
quescol
interview
Q6) What is String::valueOf Expression means?
Ans: String::valueOf is an example of a method reference. Here, String is class and valueOf is a static method of String class.
Here the valueOf() method will take input and will return a string representation of the value.
Program to demonstrate String::valueOf
public class Main{
public static void main(String args[])
{
int value=50;
String str=String.valueOf(value);
System.out.println(str+10);
}
}
Output
5010
Here int value is converted into String using valueOf() method.
Q7). What is Optional in Java 8? What is it best used for?
Ans :
In Java 8, Optional is a newly introduced class in java.util package to eliminate too many null checks. Optional comes with some built-in functions like isPresent(),ofNullable(), empty(), of() etc.
Optional Example Java 8
import java.util.Optional;
public class Main {
public static void main(String[] args)
{
String[] words = new String[10];
words[5] = "quescol";
if (Optional.ofNullable(words[5]).isPresent()) {
String word = words[5].toLowerCase();
System.out.print(word);
}
else
System.out.println("Word is null");
}
}
Output
quescol
Q8) What is Stream in Java 8?
Ans:
Stream API is introduced newly in Java 8 to process the Collection object.
Stream is not a data structure or it does not store any data, It just provides a convenient way to operate with data source and make its processing faster.
There are two methods to generate a Stream
1). stream() − Returns a sequential stream considering collection as its source.
2). parallelStream() − Returns a parallel Stream considering collection as its source.
There are two types of operation performed on Stream
1). Intermediate operation : it contains methods like map(), filter() and Sorted().
2). Terminal Operation : It contains methods like contains(), forEach() and reduce().
Example of Stream API
import java.util.*;
import java.util.stream.Collectors;
class Student{
int id;
String name;
int roll;
public Student(int id, String name, int roll) {
this.id = id;
this.name = name;
this.roll = roll;
}
}
public class Main {
public static void main(String[] args) {
List<Student> studentsList = new ArrayList<Student>();
studentsList.add(new Student(1,"Mayank",2));
studentsList.add(new Student(2,"Nishant",1));
studentsList.add(new Student(3,"Subhesh",3));
List<Integer> studentsListOutput =studentsList.stream()
.filter(s -> s.roll >= 2)
.map(s->s.roll)
.collect(Collectors.toList());
System.out.println(studentsListOutput);
}
}
Output
[2, 3]
Q9) What Data Source a Stream can Process?
Ans:
A Stream can process the following data:
- A collection
- An Array
- An I/O channel
Q10) Tell me Some Intermediate Operations of Stream API?
Ans:
- Filter(Predicate<T>) – This method takes the condition and returns only the satisfying condition.
- map(Funtion<T, R>) – This method returns a new Stream as a return value. It is used when we want to convert stream X into stream Y.
- distinct() – distinct() method returns a stream that consist distinct elements in a stream.
- limit(long maxsize) – It is a terminal operation that returns a stream of elements in a given size.
- skip(long start) – It discards the element till given in the skip function.
Q11) What new feature added in new Date and Time API in Java 8?
Ans:
- In Java 8, the new Data Time API is Thread-safe.
- New Java 8 API have Domain-driven design.
- It allows developers to work with different calendaring systems like Japan or Thailand or India without extra burden.
- All packages are based on the ISO-8601 calendar system
Q12) What is LocalDate in Java 8?
Ans:In Java 8, LocalDate is an immutable date-time object that is used to represent a date. The default format of LocalDate is year-month-day.
Some important function of LocalDate are getDayOfMonth(), getDayOfWeek(), getMonth(), getYear() etc.
Example of LocalDate Program
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
System.out.println("Date: "+date);
System.out.println("Days Of Month: "+date.getDayOfMonth());
System.out.println("Day Of Week: "+date.getDayOfWeek());
System.out.println("Month Name: "+date.getMonth());
System.out.println("Year: "+date.getYear());
}
}
Output
Date: 2023-07-06
Days Of Month: 6
Day Of Week: THURSDAY
Month Name: JULY
Year: 2023
Q13). What is LocalTime in Java 8?
Ans:In Java 8, LocalTime is an immutable date-time object that is used to represent a time. The default format of LocalTime is an hour-minute-second.
Some important function of LocalTime are plusHours(), minusHours(), plusMinutes(), minusMinutes() etc.
Example of LocalTime Program
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
LocalTime time = LocalTime.now();
System.out.println("Current Time: "+time);
System.out.println("Added one hour : "+time.plusHours(1));
System.out.println("Minus one hour: "+time.minusHours(1));
System.out.println("Added 5 minutes: "+time.plusMinutes(5));
System.out.println("Minus 5 minutes: "+time.minusMinutes(5));
}
}
Output
Current Time: 12:32:08.335274
Added one hour : 13:32:08.335274
Minus one hour: 11:32:08.335274
Added 5 minutes: 12:37:08.335274
Minus 5 minutes: 12:27:08.335274
Q14) What is the LocalDateTime example in Java 8?
Ans:
In Java 8, LocalDateTime is an immutable date-time object that is used to represent a date-time. Default format of
LocalDateTime is year-month-day-hour-minute-second.
Some important functions of LocalDateTime are plusDays(),minusDays(), now() etc.
Example of Java 8 LocalDateTime
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println("Date Time: " + now);
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formatDateTime = now.format(format);
System.out.println("Formated Date Time: " + formatDateTime);
System.out.println("Date Time Plus One: " + now.plusDays(1));
System.out.println("Date Time Minus One: " + now.minusDays(2));
}
}
Output
Date Time: 2023-07-06T12:32:48.641509
Formated Date Time: 06-07-2023 12:32:48
Date Time Plus One: 2023-07-07T12:32:48.641509
Date Time Minus One: 2023-07-04T12:32:48.641509
Q15). What is the Difference between Predicate and Function?
Ans:
- A predicate can take one parameter that represents the input type or return type. The function takes two parameters one represents input type and the second represents return type.
- The predicate has one test() function which means “test this function” Whereas the function has one apply() function means “apply this function”.
- Predicate returns only Boolean value but Function can return any value.
- If we want to perform some conditional checks we go with Predicates. But if we want to perform some operation, we should go with Function.
Predicate Example Java 8
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
Predicate<Integer> predicate = i -> (i < 10);
System.out.println(predicate.test(5));
}
}
Output
true
Function Example Java 8
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<String, Integer> function = x -> x.length();
System.out.println(function.apply("Hello Function"));
}
}
Output
14
Q16). Difference between findFirst() and findAny()?
Ans:
- findFirst() returns the first element from List that meets the given criteria, while
- findAny() function returns any element from the list that will meet the criteria. This feature is very useful when we work with a parallel stream.
Example to demonstrate findFirst() and findAny()
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("A","B","C","D","E");
Optional<String> resultFindAny = list.stream().findAny();
Optional<String> resultFindFirst = list.stream().findFirst();
System.out.println(resultFindAny.get());
System.out.println(resultFindFirst.get());
}
}
Output
A
A
Q17). Tell us the Steps to Create a Functional Interface.
Ans: To Create Functional Interface Java 8 Provided @FunctionalInterface Annotation.
After adding annotation on Interface, It can have only one abstract method and can have multiple static and default methods.
Java Program to Create Functional Interface
@FunctionalInterface
interface CustomFunctionalInterface {
void display();
}
public class Main {
public static void main(String[] args) {
CustomFunctionalInterface functionalInterface = () -> {
System.out.println("Functional Interface Example");
};
functionalInterface.display();
}
}
Output
Functional Interface Example
Functional Interface Program to Calculate Cube
@FunctionalInterface
interface Cube {
int calculate(int x);
}
public class Main {
public static void main(String[] args) {
int a = 10;
Cube c = (int x) -> x * x * x;
int ans = c.calculate(a);
System.out.println(ans);
}
}
Output
1000
Q18). What is Method Reference in Java 8?
Ans:
Java 8 has added a new feature Method Reference. Method Reference refers to the method of functional interface.
Example to demonstrate Method Reference
If our Lambda Expression is written below
str -> System.out.println(str)
Method Reference will be like
System.out::println
“::” is the symbol that used in method reference.
Method Reference Example
import java.util.Collection;
import java.util.Arrays;
class Main {
public static void main(String args[])
{
Collection collection = Arrays.asList("Hello","Method","Reference");
collection.forEach(System.out::println);
}
}
Output
Hello
Method
Reference
Q19). What are the Differences between limit and skip in Java 8?
Ans:
- Limit() method is used to return the stream of a given size. Suppose if we have written limit(10) it means total 10 output will be returned only.
- skip() method is used to return stream after skipping the index starting from 0 to given index. Skip(5) means skip element from starting(0) to 5 elements i.e. index 4.
limit() example Java 8
import java.util.stream.*;
class Main {
public static void main(String args[])
{
Stream.of(0,1,2,3,4,5,6,7,8,9)
.limit(5)
.forEach(num->System.out.print(num+"\n"));
}
}
Output
0
1
2
3
4
skip() example Java 8
import java.util.stream.*;
class Main {
public static void main(String args[])
{
Stream.of(0,1,2,3,4,5,6,7,8)
.skip(5)
.forEach(num->System.out.print(num+"\n"));
}
}
Output
5
6
7
8
Q20). Difference between Intermediate and Terminal Operations in Stream.
Ans:
Generally, Stream operations are either Terminal or Intermediate operations. Intermediate Operations return the Stream to perform other operations on it.
- Intermediate Operations process data when there is a Terminal operation carried out.
- Some intermediate operations are map(), filter(), distinct(), sorted(), limit(), skip().
- As an Intermediate return stream value, Terminal Operation returns non-stream values like primitive, object, or collection, or It will return nothing.
- There might be multiple intermediate operations, but a stream can have only one terminal operation.
- Some Terminal Operation are forEach(), toArray(), reduce(), collect(), min(), max(), count(), anyMatch(), allMatch(), noneMatch(), findFirst(), findAny() etc.
Feature | Intermediate Operations | Terminal Operations |
---|---|---|
Type of Operation | Transformative. They take a stream and return a new stream. | Consumptive. They produce a result or a side-effect from a stream. |
Statefulness | Can be stateful or stateless. | Always consume the stream, closing it. |
Return Type | Always return a Stream<T>. Allows chaining with other intermediate operations. | Vary depending on the operation; can be an Optional, a boolean, a value, or void. |
Execution | Lazily executed. Intermediate operations do not run until a terminal operation is invoked. | Trigger the processing of the stream pipeline and close it. |
Examples | map, filter, distinct, sorted | forEach, collect, reduce, anyMatch |
Example of Intermediate & Terminal Operation
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String args[]) {
List<Integer> arr = Arrays.asList(1,2,3,4,5);
List<Integer> output = arr.stream().map(x -> x * x).collect(Collectors.toList());
System.out.println(output);
}
}
Output
[1, 4, 9, 16, 25]
Q21). What is Nashorn in Java 8?
Ans:
In Java 8, Nashorn is added as the new default JavaScript engine for the JVM.
Q22). Difference Between Map and flatMap Stream Operation?
Ans:
map() and flatMap() are used when we have to map the elements of a collection to a certain function and then we need to return the stream which contains the updated results.
Map() produces one output for each input in the stream, whereas the flatMap() produces zero or more output for each input.
One-to-one mapping occurs in a map() but flatmap() allows one-to-many mapping.
Example of map()
import java.util.*;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args)
{
List<String> animal = Arrays.asList("cat","dog","monkey");
List list = animal.stream()
.map(s -> s.length())
.collect(Collectors.toList());
System.out.println("Character count of each String : " + list);
}
}
Output
Character count of each String : [3, 3, 6]
Example of flatMap()
import java.util.*;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args)
{
List<List<Integer> > arr = Arrays.asList(
Arrays.asList(1, 2),Arrays.asList(3, 4), Arrays.asList(5, 6));
System.out.println("Our 2D List :" + arr);
List<Integer> flatList
= arr.stream()
.flatMap(list -> list.stream())
.collect(Collectors.toList());
System.out.println("flatMap Output after flatten : "
+ flatList);
}
}
Output
Our 2D List :[[1, 2], [3, 4], [5, 6]]
flatMap Output after flatten : [1, 2, 3, 4, 5, 6]
Q23). What is MetaSpace in Java 8?
Ans:
MetaSpace is replaced with old PermGen memory space. It is used to how efficiently store the class.
The difference between MetaSpace with PermGen is, MetaSpace is able to increase its size dynamically.
Q24). Tell me something about StringJoiner Class in Java 8.
Ans:
StringJoiner is a new class added in Java 8 under java.util package.
It is used to join multiple strings separated by delimiters along with providing prefix and suffix to them.
Program to demonstrate StringJoiner
import java.util.*;
import java.util.StringJoiner;
import java.util.Arrays;
public class Main {
public static void main(String[] args)
{
List<String> arr= Arrays.asList("Ram","Shyam","Alice","Bob");
StringJoiner sj = new StringJoiner(",");
sj.add(arr.get(0)).add(arr.get(1)).add(arr.get(2));
System.out.println(sj);
}
}
Output
Ram,Shyam,Alice
Q25). Write a Program to add any prefix and suffix to the String in Java 8?
Ans:
To write a program in Java to add prefixes and suffixes in a given String we will use StringJoiner newly added in Java 8.
We will add “[“ and “]” as a prefix and suffix.
Program to add prefixes and suffix
import java.util.*;
import java.util.StringJoiner;
import java.util.Arrays;
public class Main {
public static void main(String[] args)
{
List<String> arr= Arrays.asList("Ram","Shyam","Alice","Bob");
StringJoiner sj = new StringJoiner(",","[","]");
sj.add(arr.get(0)).add(arr.get(1)).add(arr.get(2));
System.out.println(sj);
}
}
Output
[Ram,Shyam,Alice]
Q26). Print ten random numbers using forEach?
Ans:
Below is the program to generate 10 random numbers using forEach. Here we are using a Random class to generate a Random number.
Program to generate a random number
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
}
}
Output
-1542135975
418648077
1291667511
1956535422
805649755
-233920670
-8083929
-1654932449
-1616561678
1477724508
Q27). How you can print the highest number in Array?
Ans:
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> numArray = Arrays.asList(3,5,1,9,22);
int max = numArray.stream().max(Integer::compare).get();
System.out.println("maximum number is " + max );
}
}
Output
maximum number is 22
Q28). Print Current date, time, and date time using Java 8 Date and Time API.
Ans:
class Main {
public static void main(String[] args) {
System.out.println("Current Date: " + java.time.LocalDate.now());
System.out.println("Current Time: " + java.time.LocalTime.now());
System.out.println("Current Date and Time: " + java.time.LocalDateTime.now());
}
}
Output
Current Date: 2023-07-06
Current Time: 12:43:14.649560
Current Date and Time: 2023-07-06T12:43:14.650403