• Articles
  • Tutorials
  • Interview Questions

Java 8 Interview Questions and Answers

CTA

Java is a multi-discipline and most demanded language. With average salaries ranging from ₹4 to ₹15 lakhs per annum in India, Java professionals enjoy competitive compensation. The demand for Java skills is expected to continue growing as there are over 144000+ open jobs in India, offering numerous career opportunities. Mastery of core Java concepts, frameworks, and technologies will make you stand out when getting ready for this competitive job market.

Table of content

Basic Java 8 Features Interview Questions for Freshers

1. What are some of the important features that are introduced in Java 8?

There are many features important for development using Java that were implemented in Java 8. Some of these features are as follows:

  • Lambda expressions
  • Default methods for interfaces
  • Functional interface
  • Stream API
  • Data API

2. What is a lambda expression?

Within Angular, the view embodies the graphical user interface (UI) of an application. Its primary role involves presenting the data sourced from the component and managing user interactions. Constructed through HTML templates, the view dynamically renders and adjusts its content to the component’s data and the application’s logic.

The following is the structure of a lambda expression:

(Argument List) ->{expression;} or
(Argument List) ->{statements;}

3. What are the most important advantages of using Java 8?

The introduction of Java 8 has been proven to be very helpful for programmers in the following ways:

  • Code is now highly readable
  • More reusability of code
  • Code size is now very compact
  • Minimum boilerplate code
  • Easier testability methods
  • Parallel execution and operations

4. Describe the syntax of a lambda expression.

Lambda expressions can be divided into three parts as shown in the below syntax:

//Lambda expression
(int a, int b) -> { System.out.println(a+b); return a+b;}
  1. Arguments: A lambda expression can have zero or more arguments at any point in time.
  2. Array token: It is used to point to the body of the expression.
  3. Body: The body consists of expressions and statements. Braces are not required if it has only a single statement.

5. What is the use of the @FunctionalInterface annotation?

This annotation is used in functional interfaces to add more readability to the code as an informative aspect. However, it does not affect the runtime or the semantics of the code.

Check out our video on Java 8 Interview Questions, designed especially for beginners:

Video Thumbnail

6. What is the syntax of a lambda expression in Java 8?

The syntax of a lambda expression comprises three components:

  1. Argument list: It can be empty or non-empty as per the functionality.
  2. Arrow token: This is -> symbol that separates arguments from the body.
  3. Body: Contains expressions or statements for the logic. Curly braces are optional for a single-statement body.

For example:

(args) -> { // body }

Java 8 Features Interview Questions for Experienced (2 to 5 Years)

7. What is the meaning of functional interfaces in Java 8?

Functional interfaces in Java 8 are interfaces having a single abstract method.

Following are the three types of methods that can be present:

Get 100% Hike!

Master Most in Demand Skills Now!

8. What is the use of the String::ValueOf expression in Java 8?

String::ValueOf is a simple static method referencing the valueOf method, belonging to the class ‘String.’

Next up on this Java8 Interview Questions and Answers post, we have to check out an important concept regarding the interface.

9. Differentiate between a predicate and a function in Java 8.

Predicate Function
Returns True or False Returns an object
Used as an assignment target for lambda expressions Can be used for both lambda expressions and method references

10. What are default methods in Java 8?

Default methods are the interfaces in Java 8 that make use of the ‘default’ keyword. Default methods are added to Java 8 to give users the functionality and ability to use backward compatibility.

11. What are the core API classes for date and time in Java 8?

There are three main core API classes for date and time in Java 8 as given below:

  • LocalDate
  • LocalTime
  • LocalDateTime

Java 8 Interview Questions for 2 to 3 Years of Experience

12. Is it possible to create a custom functional interface in Java 8?

Yes, Java 8 supports the creation of a custom functional interface.

The following example denotes the creation of an interface called ‘CustInterface’ as shown:

package org.arpit.java2blog;
public interface CustInterface{

void print();
default void printColor()
{
System.out.println("Printing the color");
}
}

The main class can be created as shown below:

package org.arpit.java2blog.constructor;
public class FunctionalIntefaceMain {
public static void main(String[] args)
{
FunctionalIntefaceMain pMain=new FunctionalIntefaceMain();
pMain.printForm(() -> System.out.println("Printing form"));
}
public void printForm(CustInterface c)
{
c.print();
}
}

When the program runs, it prints out the ‘printing form’ message to the screen. It is very vital that you learn Java with the programming approach.

13. What is the meaning of method reference in Java 8?

Method references are used in Java 8 to refer to methods of functional interfaces. It can be considered as a short-code version of using a lambda expression.

The following is the expression for a method reference:

Class::methodname

14. How can you create custom functional interfaces in Java 8?

We can create custom functional interfaces by adding the @FunctionalInterface annotation to any interface with a single abstract method. It can contain default and static methods too. This allows leveraging lambda expressions for desired functionality.
For example:

@FunctionalInterface

interface CustomFI
{
void customMethod();
default void defaultMethod()
{
// default implementation
}
}

15. What is the difference between intermediate and terminal operations in streams?

Intermediate operations return stream instances, allowing further operations. Examples are filter(), map(), peek(), etc.
Terminal operations mark the end of stream processing and return the final result. Examples are forEach(), count(), collect(), etc.

Java 8 Features Interview Questions for 4 to 5 Years Experience

16. What is the easiest way to print the current date and time using the new APIs in Java 8?

The ‘now’ method, which is a part of LocalDate, can be used to get the current date as shown below:

LocalDate currentDate = LocalDate.now();
System.out.println(currentDate);

Similarly, it can also be used to get the current time:

LocalTime currentTime = LocalTime.now();
System.out.println(currentTime);

17. What were the issues that were fixed with the new Date and Time API of Java 8?

With the older versions of Java, java.util.The date was mutable. This means it has absolutely no thread safety.

Also, java.text.SimpleDateFormat was not thread-safe in the older versions. The older Date and Time API was difficult to understand for programmers in terms of readability too.

18. What are PermGen and Metaspace in Java 8?

The Java Virtual Machine has been using PermGen for class storage until Java 7. It is now superseded by Metaspace.

Metaspace has a huge advantage over PermGen that makes the former grow dynamically without any constraint, while PermGen has a fixed maximum size.

19. Differentiate between intermediate and terminal operations in Java 8.

Intermediate Operation Terminal Operation
Used for the transition to a new state Used to end the process under execution
Lazy execution of code, i.e., code is not executed as soon as it is encountered Not lazy; code is immediately executed upon encounter

20. Can the following piece of code compile successfully?

@FunctionalInterface
public interface Function2<T, U, V> {
public V apply(T t, U u);
default void count() {
    // increment counter
}
}

Yes, the code can compile and execute without any errors. It uses functional interface specifications when the single abstract method is being defined.

21. When do you use the Stream API in Java 8?

Key scenarios where the Stream API is helpful are parallel processing, working with large data sets, lambdas usage, chaining operations with pipelines, eliminating explicit for loops through internal iterations, etc.

22. How are collectors used in Java 8 Streams?

Collectors provide recipes for accumulating elements from a Stream into a summary result, e.g. ,toList(), joining(), etc. They are most commonly used with the terminal collect() operation, which returns aggregated results based on the collector chosen.

Advanced Java 8 Interview Questions (6 to 10 Years)

23. What is the use of the peek() method in streams?

peek() allows debugging or logging in pipeline stages without impacting actual stream behavior. It is useful for examining stream content at various pipeline stages, especially in complex transformations.

24. What is Nashorn in Java 8?

Nashorn is a newly introduced JavaScript processing engine that came bundled with Java 8. It provides tighter compliances with ECMA JavaScript specifications and has runtime performance that beats Rhino, its predecessor.

25. What is the use of the optional keyword in Java 8?

The optional keyword is used in Java 8 to avoid the occurrence of the NullPointerException.

An optional object can be created easily using the empty() static method as shown below:

@Test

public void whenCreatesEmptyOptional_thenCorrect() {

Optional empty = Optional.empty();

assertFalse(empty.isPresent());

}

26. What is stream pipelining used for?

Stream pipelining is a concept that is implemented in Java 8 so that users can chain more than one operation at a time. This works on the principle of splitting the operation into two categories:

  • Intermediate operations: Return the instance of the stream when running
  • Terminal operations: Used to terminate the operation and return the final value

Next up on this set of top Java 8 interview questions and answers, let us check out the intermediate-level questions.

27. What is JJS in Java 8?

JJS is the common line tool that comes packaged with Java 8. It is used to run JavaScript code seamlessly using just the console.

Java 8 Interview Questions for 6 to 7 Years of Experience

28. What is the code to sort strings using the Java 8 lambda expression?

The below piece of code sorts strings using the lambda expression:

//Sorting using Java 8 lambda expression
private void sortUsingJava8(List<String> names) {

Collections.sort(names, (s1, s2) -> s1.compareTo(s2));

}

29. Is it possible to call a static method of any interface in a class using Java 8?

Yes, it is possible to call a static method in a class by making use of the name as shown below:

interface Vehicle {
static void lightsOn() {
System.out.println("Turning on Lights!");
}
}

class Car implements Vehicle {
public void print() {
Vehicle.lightsOn();
}
}

Next up in this Blog on Java 8 Interview Questions for the experienced, we have to check out an important concept regarding keywords.

30. Can you briefly explain the working of the random keyword in Java 8?

The random keyword, as the name suggests, is used to generate random values for computations and operations in Java 8.

The following piece of code is used to print out 20 random numbers using the forEach loop:

Random random = new Random();
random.ints().limit(20).forEach(System.out::println);

31. What are collectors in Java 8?

Collectors are mainly used to combine the final result after the processing of elements in a stream. They are used to return lists or strings.

The following piece of code denotes how collectors work:

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");

List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

System.out.println("Filtered List: " + filtered);

String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));

System.out.println("Merged String: " + mergedString);

 

32. What are the common functional interface types in Java 8?

Some common functional interface types present in the java.util.function package are:

  1. Consumer<T>: Accepts an input, operates on it, but returns no result.
  2. Supplier<T>: Returns a result but does not accept any input.
  3. Predicate<T>: Accepts input and returns a boolean.
  4. Function<T,R>: Accepts one argument, operates on it and returns a result.
  5. UnaryOperator<T>: A variant of Function that operates on and returns the same type.

33. What is the difference between the map() and flatMap() methods?

map() transforms each element into another object one-to-one. flatMap() maps each element to a stream of objects and flattens into a new single stream.

Java 8 Interview Questions for 8 to 10 Years of Experience

34. What is the easiest way to print the sum of all of the numbers present in a list using Java 8?

In Java 8, the following code is used to print the sum of all of the numbers that are present in a list:

List<Integer> numbers = Arrays.asList(5, 4, 10, 12, 87, 33, 75);
IntSummaryStatistics stats = integers.stream().mapToInt((x) −> x).summaryStatistics();
System.out.println("Sum of all numbers : " + stats.getSum());

35. Can JavaScript code be executed from Java 8 codebase?

Yes, JavaScript code can be easily executed using a codebase by making use of ScriptEngineManger. This is used to interpret the code in Java 8.

Certification in Full Stack Web Development

36. When is an ideal situation to use the Stream API in Java 8?

The Stream API in Java 8 can be effectively used if the Java project calls for the following operations:

  1. Perform database operations
  2. Execute operations lazily
  3. Write functional-style programming
  4. Perform parallel processing
  5. Use pipeline operations
  6. Use internal iteration

37. How can you print the date of the next occurring Wednesday using Java 8?

The following piece of code prints the next occurring Wednesday in the calendar:

//Print the next occurring Wednesday
LocalDate today = LocalDate.now();
LocalDate nextWednesday = 
today.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));
System.out.println("Next Wednesday on : " + nextWednesday);

38. Which class implements the encoder used for encoding byte data in Java 8?

In Java 8, the static class Base64.Encoder is utilized to implement an encoder that makes it effortless to encode byte data using the Base64 encoding scheme.

39. How is a Base64 decoder created in Java 8?

The getDecoder() method, which is a part of the Base64 class, is used to return a Base64.Decoder. This decodes by making use of the Base64 encoding scheme.

40. How is a Base64 encoder that encodes URLs created in Java 8?

The getUrlEncoder() method, again a part of the Base64 class, is used to encode the URLs.

41. How to find and remove duplicate elements from a stream?

Duplicate elements can be eliminated from a stream by using distinct() or collecting results into a set, which removes duplicates by design.
For example:

list.stream().distinct().collect(Collectors.toList());

42. What are the differences between collections and streams in Java?

Collections in Java are an in-memory data structure that holds the value of the current data structure, whereas a stream is not a data structure; streams take input from collections, arrays, or I/O sources.

Java 8 Interview Questions for 11 to 12 Years of Experience

43. What is a supplier in Java 8?

A supplier is a simple functional interface in Java 8 that does not take in any argument. It is used as an assignment target when making use of lambda expressions.

The following is an example that denotes the usage of a supplier:

import java.util.function.Supplier;
public class Java8SupplierExample {
public static void main(String[] args) {
Supplier<String> supplier= ()-> "HelloLearners";
System.out.println(supplier.get());
}
}

44. What is a consumer in Java 8?

Similar to a predicate, a consumer is a functional interface with a single argument in Java 8. However, unlike a predicate, a consumer does not return any value and is commonly used for lambda expressions. Below is an example code snippet that demonstrates the usage of the consumer interface to print a string:

import java.util.function.Consumer;

public class Java8ConsumerExample {

    public static void main(String[] args) {

        Consumer<String>; consumerString = s -> System.out.println(s);

        consumerString.accept("HelloWorld");

    }

}

In the given code snippet, there is a consumer named consumerString which accepts a String parameter and prints it using the System.out.println statement. The accept method is used to pass the string “HelloWorld” to the consumer, resulting in the output “HelloWorld” being displayed on the console.

Next up on this set of top Java 8 interview questions and answers, let us check out the advanced-level questions.

45. Differentiate between findFirst() and findAny() in the Stream API of Java 8.

findFirst() findAny()
Always returns the first element from a stream Can choose any element present in the stream
Deterministic behavior Non-deterministic behavior

46. Differentiate between Collection API and Stream API in Java 8.

Collection API Stream API
Helps store object data Helps in the computation of data
Stores a limited number of elements Can store an unlimited number of elements
Eager execution Lazy execution

47. What is the meaning of a Spliterator in Java 8?

Spliterator is a newly introduced iterator interface for Java 8. It is very efficient and handles API-related operations seamlessly across the runtime environment.

48. Differentiate between Spliterator and a regular iterator in Java 8.

Spliterator Iterator
Introduced with Java 8 Present since Java 1.2
Used in Stream API Used in Collection API
Helps in the iteration of streams in a parallel and sequential order Iterates collections in a sequential order only
Example: tryAdvance() Examples: next() and hasNext()

49. Can you name the common types of functional interfaces in the standard library?

There are many functional interface types in the standard library, and some of them are as follows:

  • BiFuction
  • BinaryOperator
  • Consumer
  • Predicate
  • Supplier
  • UnaryOperator

50. What are the similarities between map and flatMap stream operations in Java 8?

Both the map and flatMap operations are types of intermediate stream operations. They accept a function as input and utilize this function to perform different actions on the stream elements.

51. Can you give examples of intermediate operations in Java 8?

The examples that are widely used in intermediate operations are:

  • Distinct()
  • Limit(long n)
  • Filter(Predicate)
  • Map(Function)
  • skip(long n)

52. What are some of the examples of terminal operations in Java 8?

Following are some of the examples of terminal operations in Java 8:

  • Count
  • Min
  • Max
  • Reduce
  • toArray
  • anymatch
  • allMatch

53. What is the easiest way to find and remove duplicate elements from a list using Java 8?

Duplicate elements can be listed and removed easily by applying stream operations and performing a collection, later using the Collections.toSet() method. This should remove all of the duplicate elements present in the list.

54. What is the use of the peek() method in Java 8?

The peek() method is a part of the stream class in Java 8, which is used to see actions performed through a stream pipeline. Peeking can be done at every step to print messages about the code being executed onto the console.

Peeking has a wide amount of usage when efficiency is a requirement, when debugging code with the lambda expression, or when performing stream processing.

55. What is the syntax of a predicate interface in Java 8?

Predicate is a functional interface used in Java to take in an object and return a Boolean value.

The following is the syntax of a predicate function:

public boolean test(T object){
return boolean;
}

56. What is the easiest way to convert an array into a stream in Java 8?

Any array in Java 8 can be converted into a stream easily using the stream class. The creation of a stream using a factory method is as shown below:

String[] testarray = {"Hello", "Intellipaat", "learners"};
Stream numbers = Stream.of(testarray);
numbers.forEach(System.out::println);

Next up on this set of top Java 8 interview questions and answers, we have to check out questions that are dependent on your learning and experience.

57. Why do you think you are the right fit for this Java Developer role?

This is a very commonly asked question in a Java 8 interview. With this, the interviewer wants to understand your proficiency in Java and how you want to take it up for your career path and growth.

It would be advantageous to answer this question based on your interests in Java programming and how you plan to use it to the best of your abilities when you join the firm.

58. Do you have any past work experience in a production environment involving Java?

This question has a high probability of coming up if you are an experienced developer getting interviewed. Make sure to answer it to the best of your abilities and provide an honest answer about your experience with Java development in a production environment.

59. Do you have any experience working in the same industry as ours?

This is a question based on the type of company you have applied for. There are a variety of industries that make use of Java 8 for their respective requirements. Understanding the job description and what is expected of you will help you in answering this question, alongside talking about any working experience you have previously in the same field.

If you are transitioning from another industry, it is essential to articulate your strategy for assimilating into the new environment and leveraging your strengths effectively.

60. Do you have any certification to boost your candidature for this Java Developer role?

Having a certification from a reputed organization will add a lot of weightage to your resume, alongside providing you in-depth knowledge about the technology you want to master.

With such a certification comes industry-level projects to work on, which will help you immensely to prove to the interviewer that you have put in a solid amount of time and effort to master the technology.

Obtaining certification in a specific technology will contribute to the credibility of your career progression. It will provide a substantial advantage in terms of knowledge, learning, and competitive edge when facing interviews.

Java 8 Coding Interview Questions

61. Write a code to sort a List of Strings by their length using Stream API.

List names = Arrays.asList("Kartik", "batra", "karan", "Rishi", "Jon");

names.stream()
.sorted((s1, s2) -> Integer.compare(s1.length(), s2.length()))
.forEach(System.out::println);

This first obtains a Stream from the list of strings. The sorted method applies a custom Comparator implemented using a lambda expression. It compares the lengths of two strings, s1 and s2. Finally, we print each string using Each terminal operation.

62. How to implement a Runnable interface in Java 8 using a lambda expression?

We can implement the run() method of Runnable using a lambda expression as:

Runnable task = () -> {
// Write code that needs to be executed in thread
};
new Thread(task).start();

This implements the functional interface Runnable using lambda, featuring empty args and a run method body inside curly braces. Then we pass the task Runnable to a Thread instance to start execution.

63. Write code to sum integers in a List using reduce() operator.

List numbers = Arrays.asList(5,3,7,10);

int sum = numbers.stream().reduce(0, (a,b) -> a+b);

System.out.println(sum); //prints 25

The identity element is initialized to 0, and lambda expression implements adder logic. This accumulates the sum progressively using reduce.

Java 8 Tricky Interview Questions

64. Can we define a static method in a functional interface in Java 8?

Yes, it is perfectly valid to define static methods inside functional interfaces. Since Java 8, interfaces can contain both default and static methods. The single abstract method rule applies only to non-static, non-default methods.
Defining static methods allows the interface to provide helper utilities to implementers without needing to inherit a class.

65. Is this Stream pipeline written correctly?

names.stream()
.filter(Objects::isNull)
.map(String::toUpperCase)
.forEach(System.out::println);

No, the above code has an issue. The stream is first filtered to contain only null names using filter(). Calling toUpperCase on a null String would throw a NullPointerException. The filter should be moved after the map() operation to avoid this scenario.

66. What is the output of the following pipeline operation?

Stream.of(1, 1, 3, 2, 4, 3)
.peek(System.out::print)
.limit(3)
.distinct()
.forEach(System.out::print);

The output of the above pipeline is:

1113123

The peek() operation prints the stream elements as they pass through the pipeline.
Next, limit(3) limits the size of the stream to the first 3 elements. So the stream becomes (1, 1, 3).
Now distinct() removes any duplicates and passes on (1, 3) forward.
The final forEach prints the distinct elements (1, 3).
Because of the interleaved peek, it prints “1113123.” The peek executes before the limit, printing initial elements before truncation.

Java 8 Developer Salary Trends

CTA

Currently, Java developers are one of the highest-paid software professionals in India. With strong demand for Java skills both from IT services companies and product based startups, Java developer salaries have grown rapidly over the past 5 years.

Depending on their exact role and years of experience, Java developers make $117,000 per year in the USA. While in India, they can make between ₹5 lakh per annum for junior roles up to ₹30 lakh or more for lead and principal architect-level positions. Geography also plays a major role, with Mumbai, Bangalore, and Gurgaon/Delhi NCR paying some of the highest Java salaries in the country.

Here is an overview of the typical Java developer salary in India, mapped to roles and experience levels:

Job Role Experience Salary Range
Junior Java Developer 0-2 years ₹5 lakh – ₹8 lakh per annum
Java Developer 2-5 years ₹8 lakh – ₹12 lakh per annum  
Senior Java Developer 5-10 years ₹10 lakh – ₹20 lakh per annum
Lead Java Architect 10-15 years ₹15 lakh – ₹30 lakh per annum
Principal/Chief Architect 15+ years ₹28 lakh – ₹49 Lakh per annum

Nowadays, additional factors like specialized skills in cutting-edge technologies, freelancing billing rates, etc. also impact Java developers’ earning potential. 

Java 8 Developer Job Trends

  • Global Demand: Java developers continue to be one of the most in-demand tech professionals worldwide. There are over 357,000+ Java jobs in the United States, with job postings growing over 13% year-over-year.  
  • Regional Trends: In the APAC region, India has the highest number of Java job openings currently, with over 122000+ Java jobs in India posted by companies of all sizes, and job postings are growing at an enormous rate in the country.
  • Skills in Demand: Along with core Java skills, companies are looking for developers proficient in Java frameworks like Spring Boot, Hibernate, and Struts. Knowledge of microservices, Docker containers, and cloud platforms is also in high demand now.

Java 8 Developer Job Opportunities

There are multiple job roles in Java. Here are a few of them:

Job Role Description
Junior Java Developer Works on module development under the guidance of senior developers. It focuses on core Java, data structures, and databases.
Java Developer Builds applications and systems end-to-end. Proficient in Java, Spring, Hibernate, and web services.
Senior Java Developer Leads project development and code reviews. Deep expertise in architecture and advanced Java EE technologies.
Java Tech Lead Owns delivery for the entire product development lifecycle. Provides guidance to developers and testers in a team.
Java Architect Develops overall software architectures and high-level technical designs. Ensures the scalability and performance of complex systems.

Java 8 Developer Roles & Responsibilities

According to a job description posted by Tata Consultancy Services on Linkedin: 

Roles and Responsibilities:

  • Hands-on experience in Java 8 and Spring Boot (primary skills).
  • Secondary skills required: SQL and one database, such as Oracle or MongoDB.
  • Well versed in Lambda expressions.
  • Experience in Docker, Kubernetes, /OpenShift is also expected.
  • Enterprise application development experience using CI/CD pipelines.
  • Good command of code version management.
  • Experience in unit testing frameworks.
  • Agile development experience.
  • Roles require interaction with developers distributed across locations.
  • Good communication skills and good analytical skills.

I hope reviewing these commonly asked Java interview questions gives you a solid foundation to prepare and build confidence. Intellipaat offers a well-rounded Java Certification Course to expand your Programming skills.

Course Schedule

Name Date Details
Python Course 30 Nov 2024(Sat-Sun) Weekend Batch View Details
07 Dec 2024(Sat-Sun) Weekend Batch
14 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.