Share this:

Top 113 Frequently Asked Java 8 Interview Question

1. What are the new features that are added in Java 8?
Answer: Java 8 ships with several new features and enhancements but the most significant are the following:

  • Lambda Expressions – It is termed as the new language feature and it allows the treating actions as the objects.
  • Method References – It helps in enabling to define the Lambda Expressions by referring to the various methods directly by using their names.
  • Optional – This is a class which is to provide a type-level solution for the representation of the optional values instead of using the null references.
  • Functional Interface – This is an interface which has maximum one abstract method and the implementation can be provided using a Lambda Expression for this interface.
  • Default methods – These methods are the methods which gives one’s the ability to add the full implementations in interfaces.
  • Nashorn, JavaScript Engine – It is known as the Java-based engine for the execution and evaluation of the JavaScript code.
  • Stream API – It is termed as the special iterator class which allows in processing collections of objects in a functional manner.
  • Date and Time API – It is an improved, immutable JodaTime-inspired Date API. Besides all these new features all others feature are in the path of compiler and the JVM also.

2. What makes Java SE 8 superior over others?
Answer: The features are as follows which makes it superior over others in Java SE 8.

  • It writes the parallel code.
  • It offers even more useable codes.
  • It has improved performance applications.
  • It has more readable and concise codes.
  • It supports writing database including promotions.

3. Do we need changes and reforms in Java?
Answer: Yes, we do need changes and reforms in Java language because of the following reasons.

  1. To make the best and efficient use of multi-million CPUs that are deployed at work throughout the world.
  2. To meet with the changes and up-gradation made in the technology hardware and software.
  3. To support the running of various kinds of applications.
  4. To create highly concurrent and scalable applications.
  5. To make use of all the functional programming features which are an integral part of the latest Java SE 8 computer language.

4. What is a Lambda Expression?
Answer: We can say that, a lambda expression is a function which can be referenced and passed around as an object. Lambda expressions are a function that introduces functional style processing in Java and helps in facilitating the writing of compact and easy-to-read code.

Due to this the lambda expressions are simply and natural replacement for same or anonymous classes as method arguments and one of their main uses is defining the inline implementations of the functional interfaces.

5. Define the main parts of a Lambda expression in Java Programming Language?
Answer: Three main parts of a Lambda expression are:

  • Parameter list: As the Lambda expression can have zero or more parameters. Parameter list is optional in case of Lambda.
  • Lambda arrow operator: It is termed as the Lambda arrow operator. It helps in separating the list of parameters and the body of Lambda.
  • Lambda expression body: The piece of code which the user wants to execute is written in the Lambda expression body.

6. Why we use Lambda Expression?
Answer:

  • It helps in providing the implementation of the Java 8 Functional Interface.
  • As we can see that the lambda expressions are a natural replacement for same or anonymous classes as a method argument.
  • Lambda Expressions helps in encapsulating by enabling user to encapsulate a single unit of behavior and then pass it to other code. We can use lambda expressions if we need a certain action performed on each element of a collection, when a process is completed, or when a process encounters an error.

7. What is the main theme behind the release of a new version of Java like Java 8?
Answer: The main theme of Java 8 is its support for the functional programming. With increase in Database size and growth of multi-code CPU servers, there is need for Java to support such large-scale systems. With new features of Java 8, it is possible to create functional programs to interact efficiently with Big Data systems. Support for Streams is very helpful in this regard.

Lambda expressions are very useful for cloud computing where we can pass code as data and run the same code on multiple servers. Optional is a best practice that is borrowed from Google Guava library for handling the exceptional cases. This has made programs more robust with support for edge cases.

8. What is a Functional Interface?
Answer: An Interface is termed as the functional interface if it contains exactly one abstract method. It can have any number of default, static methods but it contains only one abstract method. It also helps in declaring methods of the object class.

Functional Interface is also known as Single Abstract Method Interfaces or SAM Interfaces. A functional interface has the ability of extending another interface only when it does not have any abstract method. Java 8 helps in providing the predefined functional interfaces to deal with functional programming by making use of lambda and method references.

9. Can we define our own Functional Interface in Java? What is a Functional Interface? What are the rules needed to define a Functional Interface?
Answer: Yes, we can define our own Functional Interfaces in Java. We make use of the Java SE 8’s @ Functional Interface annotation for marking an interface as the Functional Interface. We need to follow some rules for defining a Functional Interface:

  • We are able to define an interface with one and only one abstract method not more than this.
  • We are also not able to define more than one abstract method.
  • Use @FunctionalInterface annotation in the interface definition.
  • In this we have the ability to define any number of other methods like Default methods, Static methods.
  • If we override java.lang.Object class’s method as an abstract method then it does not count as an abstract method.

10. Describe some of the Functional interfaces in the standard library.
Answer: The functional interfaces in the java.util.function package are as follows:

  • Function – It is the functional interface which takes one argument and then returns a result.
  • Consumer – It is the functional interface that takes one argument and returns no result.
  • Supplier – It is the functional interface that takes no argument and returns a result.
  • Predicate – It is the functional interface which takes one argument and returns a Boolean.
  • BiFunction – It is the functional interface which takes two arguments and returns a result.
  • BinaryOperator – It is the functional interface which is same as a BiFunction. It takes two arguments and returns a result. The two arguments and the result are all of the same types.
  • UnaryOperator – It is the functional interface which is same as a Function. It takes a single argument and returns a result of the same type.

11. Differentiate between the Functional interface and SAM interface?
Answer: There is no difference between Functional interface and SAM interface. The SAM interface or Single Abstract Method interface is a kind of Functional interface defined in Java SE 8 API.

12. Explain the differences and similarities between Function and Predicate in java 8 programming language?
Answer:

Differences:
Return Type: Function returns an Object and it is a single argument function. Predicate return type is boolean (i.e true or false) and it is also a single argument function.
Similarities: Both are functional interfaces i.e both contain single abstract method.

13. What are the guidelines that are needed to be followed in Functional Interface?
Answer: There are several guidelines stated below which are needed to be followed in Functional Interface.

  1. The interface should be defined with only one abstract method.
  2. Not more than one abstract can be defined.
  3. Making use of @Functionalinterface annotation in the interface definition.
  4. The override of the Java.lang.object class’s method will not be considered as an abstract method.
  5. Any methods can be used for defining a number.

14. What is a Method Reference?
Answer: Method reference is used for referring to a method of the functional interface. Method reference is defined as the compact and easy form of a lambda expression. Each time when you are using a lambda expression to just referring a method, you can replace your lambda expression with method reference.

15. What are the different kinds of Method References?
Answer: There are four kinds of method references:

KIND EXAMPLE
Reference to static method ContainingClass::staticMethodName
Reference to an instance method of a particular object ContainingObject::instanceMethodName
Reference to an instance method of an arbitrary object of a particular type ContainingType::methodName
Reference to a constructor ClassName::new

16. Is it possible for us to provide implementation of a method in a Java Interface?
Answer: Yes, it is possible to provide implementation of a method in a Java Interface as it was not possible before Java8. It has introduced the flexibility of providing implementation of a method in an interface.
There are two options for that:
1.     Default Method: We can give default implementation of a method.
2.     Static Method: We can create a static method in an interface and provide implementation

17. What is a default method in Java 8 and when do we make use of it?
Answer: A default method is a method with an implementation that can be found in an interface. We make use of a default method for the addition of a new functionality to an interface while also maintaining backward compatibility with classes that are already implementing the interface.

Generally, when we add a new abstract method to an interface then all the implementing classes will break until they implement the new abstract method. In Java 8, this problem has found its solution by making the use of default method. For example, Collection interface does not have  forEach  method declaration. Thus, due to the addition of such method will simply break the whole collections API.

Java 8 introduces the default method so that the Collection interface can have a default implementation of  forEach method  without the requirement of the classes implementing this interface to implement the same.

18. Why default methods in Interfaces are needed?
Answer: Default methods helps the user in enabling to add new functionality to the interfaces of the libraries and also ensures that the binary compatibility with code written for older versions of those interfaces. In a typical design based on the abstractions where an interface has one or more implementations and if one or more methods are being added to the interface then all the implementations will be forced to implement them too.

Otherwise, the design will just get break down so that the default interface methods are an efficient way to deal with this issue. This allow us to add new methods to an interface which are automatically available in the implementations. Therefore, there is no need in modifying the implementing classes. In this way the backward compatibility gets neatly preserved without having to refactor the implementers.

The default method is used for defining a method with a default implementation. We can override the default method and also to provide the more specific implementation for the method.

19. Why static methods in interface are needed?
Answer:The static interface methods helps in providing a simple mechanism which allows us to increase the degree of cohesion of a design by putting together all related methods in one single place without having the need to create an object.

Static methods in interfaces help in making possible to group related utility methods without having the need for creating artificial utility classes which are simply placeholders for static methods.

20. Differentiate between Iterator and Spliterator?
Answer: Difference between Iterator and Spliterator  are as follow:

  • Introduction: Iterator is first introduced in jdk 1.2 while Spliterator is introduced in jdk 1.8.
  • Use in API: Iterator is used for Collection API while Spliterator is used for Stream API.
  • Parallel programming: Iterator can be used for iterating the elements in Collection in sequential order while Spliterator can be used for iterating the Stream elements in parallel or sequential order.
  • Universal Iterator: Iteartor is universal iterator while Spliterator is not a universal iterator.

21. How does Internal Iteration work in Java 8?
Answer: In an Iterator, the fundamental question that comes in our mind is which party controls the iteration work in Java 8. When a collection is able to control the iterator, then it is termed as External Iteration. When the Iterator is able to control the iteration then it is called as Internal Iteration.

In case of the Internal Iteration, the Iterator applies the operation to all the elements in aggregate and the client hands over an operation to Iterator. Internal Iteration is easier for the implementations as the Iterator doesn’t need to store the state of the collection.

22. Differentiate between Internal and External Iterator?
Answer: Some of the differences between Internal and External Iterator are as follows:

  1. An Internal Iterator controls the iteration itself. An External Iterator collection controls the iteration.
  2. Internal Iterator can iterate elements in individually as well as in Bulk (like forEach). External iterator iterates element one by one.
  3. Internal Iterator does not have to iterate elements only sequentially. External Iterator always iterates sequentially.
  4. Internal Iterator supports declarative programming style that goes well with functional programming. External Iterator follows imperative style OOPS programming.
  5. Some people consider Internal Iterator code more readable than that of External Iterator.

23. Is Internal Iterator is advantageous over External Iterator in Java 8?
Answer:Yes, it is more advantageous then the external iterator. Some of the advantages of Internal Iterator are listed below:

  1. Internal Iterator is based on Functional programming; therefore it can work on declarative style code.
  2. There is no need to sequentially iterate elements in Internal Iterator.
  3. Code is more readable and concise in Internal Iterator.
  4. Internal Iterator supports concurrency and parallel processing.

24. What are the applications of Internal Iteration?
Answer: We need Internal Iterator in applications that require high performance, parallel processing, fast iteration and bulk operations support. In the case of Internal Iteration applications, we are not having much control over the iteration. The other features like parallel processing etc. become more important.

25. Explain the disadvantage of Internal Iteration over External Iteration?
Answer: Internal Iteration has many advantages over External Iteration. But it has one big disadvantage. Since Java API is responsible for iterating in Internal iterator, developer does not get any control over iteration.

26. What is Nashorn in java 8?
Answer: Nashorn is defined as the latest javascript engine that is released with java 8. Before jdk 8, the javascript engine was based on Mozilla Rhino. It provides better compliance with ECMA normalized javascript specification and better runtime performance.

27. What is a Stream in Java? How it is different from collection?
Answer: A stream is simply defined as an iterator whose role is to accept a set of actions to apply on each of the elements that it contains. The stream in Java represents a sequence of the objects from a source such as a collection which helps in supporting aggregate operations.

They were designed so that they can make collection processing simpler, easier and concise. Contrary to the collections, the logic of iteration is implemented inside the stream, so that we can make use of methods like map and flatMap for performing a declarative processing.

As the Stream API is fluent and also allows pipelining. Streams are distinct from the collections as the streams are inherently lazily loaded and processed.

28. What is a Stream pipelining in Java 8?
Answer: Stream pipelining is the concept of chaining operations together. This can be done by splitting the operations that can happen on a stream into two categories: intermediate operations and terminal operations.

Each intermediate operation in the stream pipelining is the operation which returns an instance of Stream itself when it runs an arbitrary number of intermediate operations. Therefore, set up for processing of data which forms a processing pipeline. There is a need of the terminal operation which returns a final value and terminates the pipeline.

29. Differentiate between Collection API and Stream API?

Collection API Stream API
It is available since Java 1.2 It is introduced in Java SE8.
It is used to store data that contains a set of objects. It is used for computation of data that involves computation on a set of objects.
In this API we are able to use both spliterator and Iterator to iterate the elements. We can use forEach to perform an action for each element. In this API we are not able to use spliterator and Iterator to iterate the elements.
It is used for storing limited number of elements. It is used for storing either limited number or infinite number of elements.
Collection API uses External iteration concept to iterate elements such as the iterator. Stream API uses external iteration concept for the iteration of the elements using forEach methods.
Collection Objects are constructed Eagerly. Stream Objects are constructed lazily.
We add elements to Collection objects only after it is computed completely. We add elements to Stream objects without any prior computation. That means stream objects are computed on-
demand.
In this API we are having the ability to iterate and consume elements from a collection object at any number of times. In this API we are having ability to iterate and consume elements from a stream object only once.

30. What is optional in Java?
Answer: Optional is a container object in Java that is used to contain not-null objects. Optional object is used for representing null with the absent value. This optional class has various utility methods for facilitating the code to handle values as ‘available’ or ‘not available’ instead of checking the null values. It is introduced in Java 8 and also similar to what Optional is in Guava.

The purpose of the Optional class is to provide a type-level solution for representation of optional values instead of using the null references.

31. Describe the advantages of Java 8 optional?
Answer:

  • In this the null checks are not required.
  • No more NullPointerException at run-time.
  • We can develop a clean and neat APIs.
  • No more Boilerplate code is needed.

32. What is Collectors class in Java 8?
Answer: Collectors are known as the final class that extends the Objectclass. It helps in providing the reduction of the operations like accumulating elements into the collections, summarizing elements according to various criteria, etc. Collectors perform the reduction operations. It helps in combining the results of the processing ongoing on the elements of the stream like collecting the elements into collections, summarizing the elements according to the different criteria. Collectors return the list or a string. As a result, the readability is increased. Static import used here is static import java.util.stream.Collectors.*;

33. What is StringJoiner?
Answer: StringJoiner belongs to the java.util package and it is used for combining the different strings into a single string with delimiters, and also with the prefixes and suffixes. It uses the two different constructors for this purpose. The constructors are called as the Public StringJoiner(CharSequence delimiter) and Public StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix).

34. What is the use of Java 8 Stringjoiner class?
Answer: Java programming language had added a new final class StringJoiner in the java.util package. It is used for the construction of a sequence of characters that are separated by a delimiter. Now, we can create a string by passing delimiters like a comma(,), hyphen(-) etc.

35. How Java 8 supports Multiple Inheritance?
Answer: In Multiple Inheritance a class can inherit behavior from more than one parent classes. Prior to Java 8, a class can implement multiple interfaces but extend only one class. In Java 8, we are having the method implementation within an interface. So an interface behaves like an Abstract class. Now if we implement more than one interface with method implementation in a class, it means we are inheriting behavior from multiple abstract classes. That is how we get Multiple Inheritance in Java 8.

36. What is Diamond Problem in inheritance? How Java 8 solves this problem?
Answer: A Diamond Problem is a Multiple Inheritance problem. In Java 8, it takes place when a Class extends more than one Interface which has same method implementation (Default method). To counter with this problem, Java 7 and the earlier versions does not support methods implementation in interface and also they don’t support Multiple Inheritance. Java 8 has introduced some new features like it has introduced the default methods to support the Multiple Inheritance with some limitations.

37. What is jjs?
Answer: In Java 8 programming language, jjs is defined as the new executable or command line tool which is used for executing Javascript code at the console.

38. What is the difference between Terminal and Intermediate options?

Intermediate Terminal
The intermediate operation help in producing the stream pipelining. Terminal operation terminates the pipeline.
The intermediate operations are the operations that can be chained multiple times on a stream. Terminal operations cannot be chained various times.
Intermediate operations are the operations which cannot be evaluated independently and they need a terminal operation for their evaluation. Terminal Operations can be evaluated independently.

39. What is spliterator in Java 8?
Answer: A Spliterator is one of the types of Java8 Iterator in java util package which traverses and partitions the elements of a source in Java into another Spliterator. A source of the spliterator may be a collection or an IO channel or a generator function.

40. Differentiate between map and flatmap stream operation in Java 8 Programming Language?

Map Flat Map
In the case of Map, for one input value we get one output value. In case of flat Map, for one input value we gets the arbitrary number.

41. Explain the sequential and parallel stream in Java 8?
Answer: Parallel streams are the streams which help in dividing the provided venture into many and run them in unique threads and make use of a couple of cores of the computer. On the other hand, sequential streams work just like for-loop.

The duties which are supplied to the streams are usually the iterative operations performed on the factors of a series or array or from different dynamic sources. In case of Parallel execution of streams they run iterations which are more than one, concurrently in the extraordinary accessible cores.

42. Explain local date-time API in Java 8?
Answer: In the case of new data-time API, one of the classes is the Local Date-Time API where there is no problem like the handling of the time-zones. Programmers or users make use of this API where there is no need of time zones. Local Date-Time API is also defined in the package java.time.

43. What are features of Java 8 Date-Time API over the old date and Calender classes?
Answer: Here are some of the challenges faced by developers with earlier Java versions:

  • It was having poor API design (for example, months start with 1 and days start with 0).
  • It was not considered as thread safe.
  • There is no consistency within the java.util and java.sql classes.
  • There is no support for internationalization and time zone.

The new Date and Time API has been introduced in Java SE 8 with the following features:

  • The improved API design has the ability of clearly separating the human- readable date time and machine time.
  • The new Date and Time API helps in making all the classes immutable that is safe and best suited for the multithreaded environment.
  • The new Date and Time API has more clarity in the API design level. The methods in this are clearly defined and perform the same action in all classes.
  • The API has the ability to define a separate class for Date, Time, DateTime, Timestamp, TimeZone, and so on but the new Date and Time API works with the ISO-8601 calendar. However, we can also use the API with non-ISO calendars as well.

44. What are the basic ideas behind the Date/Time API of Java 8 Programming Language?
Answer: There are some basic ideas behind the Date/Time API of Java 8:

  1. Immutable-value classes: The new API avoids thread safety and concurrency issues by ensuring that all the core classes are immutable   and represent well-defined values.
  2. Domain-driven design: The new API is modeled on precise domain with classes that represent different use cases for Date and Time.
  3. The emphasis on domain-driven design offers benefits like clarity and understandability.
  4. Separation of chronologies: The new API allows people to work with different calendar systems. It supports the needs of users in different areas of the world likes Japan or Thailand that don’t follow ISO-8601.

45. Describe the advantages of new Date and Time API in Java 8 over old Date API?
Answer: The advantages of Java 8 Date Time API over old Date API are as follows:
1. Concurrency: Existing Date Time classes (such as java.util.Date and SimpleDateFormatter) are not thread-safe. This does not work well in concurrent applications. In new Date Time API, developer does not have to deal with concurrency issues while writing datehandling code.

2. Better Design: Date/Time classes prior to Java 8 have poor API design. For example, years in java.util.Date start at 2000, months start at 1, and days start at 0. It is not an innovative idea. Java 8 Date Time API handles this problem very well and efficiently.

3. No need for 3rd Party Libraries: With the popularity of third-party Date/Time libraries like Joda Time, Java has to make its native Date/Time API comparable. Now we can use the Java API instead of using 3rd party libraries.

46. Is it possible to get current time by using the Date/Time API of Java 8 Programming Language?
Answer: In Java 8 we have the option of using Clock class to get the current time. Instead of using old method System.currentTimeMillis(), we can create a Clock object and call millis() method to get the current time in milliseconds. We can also call instant() method on Clock object to get the current time in a readable format.

47. What do you understand by the term Chromounits in Java 8?
Answer: The Chromounit was added in Java 8 to replace the value of an integer which was used in old API for representing the month, day, year, etc. unit is defined in the java.time.temporal.ChronoUnit.

48. What is Type interference in Java 8?
Type interference is defined as the feature of Java which gives the capability to the compiler at each method invocation and that is corresponding announcement for determining the type of arguments. Java provides multiplied model of type inference in Java 8.

49. What are the Parameters for Evaluating Java programmers?
Answer: Some of the parameters for evaluating Java programmers are as follows:

  • Analyse the application of functional paradigm or OOPs.
  • View the number of lines in code and determine if it could have been shorter.
  • Examine the type of data structure used for problem-solving.
  • We have to check that if the codes are easy to read, understand, and maintain.
  • We should evaluate if the codes are having the quality of extensibility.
  • Assess the quality of the Build Scripts.
  • We must also check for the quality, readability and coverage of unit tests.

50. What are various ways of creating Optional?
Answer:

  • Optional.empty() – This method is used for creating optional which will return an empty Optional object.
  • Optional.of() – This method will return an Optional of object passed as an argument to of method. It also returns an Optional with the specified present non-null value.
  • Optional.ofNullable() – This method returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.

51. What are the methods that are available in Optional?
1. isPresent() – This method will return true if the object is present into an Optional object.
if(graphicsCard.isPresent()){
System.out.println(graphicsCard.get());
}
2. get() – This method works if a value is present in this Optional, returns the value, otherwise throws NoSuchElementException. GraphicsCardnewCard=graphicsCard.get();
3. ifPresent – This method works if a value is present, invoke the specified consumer with the value, otherwise do nothing.
graphicsCard.ifPresent(System.out::println);
4. orElse(T other) – This method return the value if present, otherwise returns the object passed as a parameter. Internals of orElse method in Java 8 Optional class.
publicTorElse(Tother){
returnvalue!=null?value:other;
}

GraphicsCardnewCard=graphicsCard.orElse(newGraphicsCard());
5. orElseThrow – This method returns the contained value, if present, otherwise throws an exception to be created by the provided supplier.
GraphicsCardnewCard=graphicsCard.orElseThrow(IllegalArgumentException::new);

52. Differentiate between Optional.of() and Optional.ofNullable() ?
Optional.of() versus Optional.ofNullable()

Optional.of() will return the object of Optional without null check.
We should look at the interns of Optional.of() method:
publicstatic<T>Optional<T>of(Tvalue){
returnnewOptional<>(value);
}

Optional.ofNullable() will return the object of Optional with a null check. If this method gets the null as an input then this method will return the empty Optional otherwise it returns an Optional with the specified present non-null value. We should look at the interns of Optional.ofNullable() method:
publicstatic<T>Optional<T>ofNullable(Tvalue){
returnvalue==null?empty():of(value);
}
Optional.of() should be used when we are sure that Optional will never have a null object and it will contain the object value or it will be empty but it will not be null. Optional.of() can also throw a NullPointerEception if the Optional is created with a null value.
Optional.ofNullable()- is used when there are chances that the object might be null.

53. What are repeating annotations?
Answer: Java 8 Programming Language has introduced a new Java language feature regarding the annotations. We are now able to repeat an annotation multiple times on a type declaration.

54. What are Type Annotations? Name some common Type Annotations?
Answer: In addition to use the annotations on type declarations, we can now apply the annotations whenever we use types.
Following are some examples of Type annotations
@NonNull
@ReadOnly
@Regex,
@Tainted
@Untainted

55. What is a Consumer?
Answer: Consumer is a functional interface added in Java 8 that has a single abstract method accept(). A consumer is used when you want to perform an operation that takes a parameter but doesn’t return anything.

56. What is a Supplier?
Answer: Supplier is a functional interface with a single abstract method get(). A Supplier is used when we need to generate the instances without taking any input.

57. Differentiate between Predicate, Supplier and Consumer in Java 8?
Answer: The differences between Predicate, Supplier and Consumer in Java 8 Programming Language are as follows:

  • Predicate is an anonymous function that accepts one argument and returns a result.
  • Supplier is an anonymous function that accepts no argument and returns a result.
  • Consumer is an anonymous function that accepts one argument and returns no result.

58. Differentiate between an interface with default method and an abstract class in Java 8?
Answer: An interface having a default method seems to be same as an Abstract class in Java. But there are subtle differences between these two that are as follows:

  1. Instance variable: An interface cannot have instance variables. An abstract class can have instance variables.
  2. Constructor: An interface cannot have a constructor. An abstract class can have constructor.
  3. Concrete Method: An interface cannot have concrete methods other than default method. An abstract class is having the ability for defining concrete methods with implementation.
  4. Lambda: An interface with exactly one default method can be used for lambda expression. We cannot use abstract class for lambda expression.

59. Does Java 7 support Type Inference?
Answer: Yes, Java 7 supports Type Inference. In Java 8, Oracle has enhanced the Type Inference concept. Now it can be used to define Lambda expressions, functions and Method references.

60. Which method in Optional helps in providing with the fallback mechanism in case of null value?
Answer: In case, an Optional has null value, we can use orElseGet() method as fallback mechanism. If we implement orElseGet() method, it will be invoked when the value of Optional is null.

61. How can we analyze the dependencies in Java classes and packages?
Answer: Java 8 usually comes with a new command line tool jdeps which helps in analyzing the package-level and class-level dependencies to the programmer. We can pass a jar file name or a class name as an argument to this tool. It will list all the dependencies of that jar or class.

62. What are the JVM arguments that are introduced by Java 8?
Answer: In Java 8, PermGen space of ClassLoader has been removed. PermGen has been replaced with MetaSpace. Now we have the ability to set the initial and maximum size of the MetaSpace. The JVM options -XX:PermSize and –XX:MaxPermSize are replaced by –
XX:MetaSpaceSize and -XX:MaxMetaspaceSize respectively in Java 8.

63. Define the characteristics of a Lambda Expression?
Answer: Lambda expression has below mentioned characteristics:
1) Optional type declaration:
Optional type declaration states that when we are declaring the Lambda argument on the left side of the lambda then the type (of argument) is not required to declare. Compiler itself infer them from their values. For example:

  1. int param -> { body.. }
  2. param -> { body.. }

Both are valid.

2) Optional parentheses :
Optional parentheses states that parentheses are not required in case only one single parameter is declared in Lambda. For Example :

  1. param -> { body.. }
  2. (param) -> { body.. }

Both are valid statements.
3) Optional curly braces :
It states that curly braces around lambda body is not required if the expressions part only has a single statement. For example :

  • param – > statement
  • param – > {statement;}

Both are valid expressions.
4) Optional return statement :
It states that if a lambda expression returns a value and the value is wrapped inside curly braces then the return statement is not required.

  1. (x, y) – > {return x+y;}
  2. (x, y) – > {x+y;}

Both are valid and equal.

64. What is a SAM Interface?
Answer: SAM interface stands for Single Abstract Method interface. It is the other name for Functional interface. SAM has only one abstract method. Java 8 had released many functional interfaces.

65. Are the abstract classes still useful?
Answer: Abstract classes can still do more in comparison to Java 8 interfaces:

  1. Abstract class can have a constructor. The interface has no constructors to be invoked by the descendants.
  2. Abstract classes are more structured and can hold a state. In comparison, Interface methods are all public, field members are all constant. You may want to restrict access privileges of methods and/or make them operate on non-constant state.
  3. A child class can call upon the abstract class method(s) by super, while it can not do so on default interface methods.
  4. Type clarity: You can only extend one class. This makes it clearer what your object is and how to use it.

66. Do we have PermGen in Java 8? Are you aware of MetaSpace?
Answer: Until Java 7 the JVM makes use of an area termed as PermGen to store the classes. PermGen got removed in Java 8 and it is replaced by the MetaSpace.

Major advantage of MetaSpace over permgen:
PermGen was fixed in term of maximum size and can not grow dynamically but Metaspace can grow dynamically and do not have any size constraint.

67. What is the advantage of Metaspace over PermGen?
Answer: PerGen was fixed in size and could not grow dynamically, while Metaspace can grow dynamically and does have any type of size constraint.

68. Difference between Stream’s findFirst() and findAny()?
Answer: findFirst in a stream will always return the first element from the stream whereas findAny is allowed to choose any element from the stream. findFirst has a deterministic behavior whereas findAny has a nondeterministic behavior.

69. Explain the System.out::println expression.
Answer: System.out::println method is defined as the static method reference to the println method of object of the System class.

70. What is the purpose of BiConsumer functional interface?
Answer: It helps in representing an operation that accepts two input arguments and returns no result.

71. What is the purpose of BiFunction functional interface?
Answer: It represents a function that accepts two arguments and produces a result.

72. What is the purpose of BinaryOperator functional interface?
Answer: It helps in representing an operation upon two operands of the same type which produces a result of the same type as the operands.

73. What is the purpose of BiPredicate functional interface?
Answer: It represents a predicate (Boolean-valued function) of two arguments.

74. What is the purpose of BooleanSupplier functional interface?
Answer: It represents a supplier of Boolean-valued results.

75. What is the purpose of Consumer functional interface?
Answer: It helps in representing an operation which accepts a single input argument and returns no result.

76. What is the purpose of DoubleBinaryOperator functional interface?
Answer: It helps in the representation of an operation upon two double-valued operands and that produces a double-valued result.

77. What is the purpose of DoubleConsumer functional interface?
Answer: It helps in representing an operation that accepts a single double-valued argument and then returns no result.

78. What is the purpose of DoubleFunction functional interface?
Answer: It represents a function that accepts a double-valued argument and produces a result.

79. What is the purpose of DoublePredicate functional interface?
Answer: It represents a predicate (Boolean-valued function) of one double-valued argument.

80. What is the purpose of DoubleSupplier functional interface?
Answer: It represents a supplier of double-valued results.

81. What is the purpose of DoubleToIntFunction functional interface?
Answer: It represents a function that accepts a double-valued argument and produces an int-valued result.

82. What is the purpose of DoubleToLongFunction functional interface?
Answer: It helps in representing a function which accepts a double-valued argument and produces a long-valued result.

83. What is the purpose of DoubleUnaryOperator functional interface?
Answer: It represents an operation on a single double-valued operand that produces a double- valued result.

84. What is the purpose of Function functional interface?
Answer: It represents a function that accepts one argument and produces a result.

85. What is the purpose of IntBinaryOperator functional interface?
Answer: It helps in the representation of an operation upon two int-valued operands and produces an int-valued result.

86. What is the purpose of IntConsumer functional interface?
Answer: It helps in the representation of an operation which accepts a single int-valued argument and returns no result.

87. What is the purpose of IntFunction<R> functional interface?
Answer: It represents a function that accepts an int-valued argument and produces a result.

88. What is the purpose of IntPredicate functional interface?
Answer: It represents a predicate (Boolean-valued function) of one int-valued argument.

89. What is the purpose of IntSupplier functional interface?
Answer: It represents a supplier of int-valued results.

90. What is the purpose of IntToDoubleFunction functional interface?
Answer: It helps in the representation of a function that accepts an int-valued argument and that produces a double-valued result.

91. What is the purpose of IntToLongFunction functional interface?
It helps in the representation of a function that accepts an int-valued argument and that produces a long-valued result.

92. What is the purpose of IntUnaryOperator functional interface?
Answer: It represents an operation on a single int-valued operand that produces an int-valued result.

93. What is the purpose of LongBinaryOperator functional interface?
Answer: It represents an operation upon two long-valued operands and produces a long-valued result.

94. What is the purpose of LongConsumer functional interface?
Answer: It helps in the representation of an operation that accepts a single long-valued argument and returns no result.

95. What is the purpose of LongFunction<R> functional interface?
Answer: It represents a function that accepts a long-valued argument and produces a result.

96. What is the purpose of LongPredicate functional interface?
Answer: It helps in the representation of a predicate (Boolean-valued function) of one long-valued argument.

97. What is the purpose of LongSupplier functional interface?
Answer: It represents a supplier of long-valued results.

98. What is the purpose of LongToDoubleFunction functional interface?
Answer: It helps in the representation of a function which accepts a long-valued argument and that produces a double-valued result.

99. What is the purpose of LongToIntFunction functional interface?
Answer: It helps in the representation of a function which accepts a long-valued argument and that produces an int-valued result.

100. What is the purpose of LongUnaryOperator functional interface?
Answer: It represents an operation on a single long-valued operand that produces a long-valued result.

101. What is the purpose of ObjDoubleConsumer functional interface?
Answer: It represents an operation that accepts an object-valued and a double-valued argument, and returns no result.

102. What is the purpose of ObjIntConsumer functional interface?
Answer: It represents an operation that accepts an object-valued and an int-valued argument, and returns no result.

103. What is the purpose of ObjLongConsumer functional interface?
Answer: It represents an operation that accepts an object-valued and a long-valued argument, and returns no result.

104. What is the purpose of Predicate functional interface?
Answer:It represents a predicate (Boolean-valued function) of one argument.

105. What is the purpose of Supplier functional interface?
Answer: It represents a supplier of results.

106. What is the purpose of ToDoubleBiFunction functional interface?
Answer: It helps in the representation of a function that accepts two arguments and that produces a double-valued result.

107. What is the purpose of ToDoubleFunction functional interface?
Answer: It represents a function that produces a double-valued result.

108. What is the purpose of ToIntBiFunction functional interface?
Answer: It represents a function that accepts two arguments and produces an int-valued result.

109. What is the purpose of ToIntFunction functional interface?
Answer: It represents a function that produces an int-valued result.

110. What is the purpose of ToLongBiFunction functional interface?
Answer: It helps in representation of a function that accepts two arguments and produces a long- valued result.

111. What is the purpose of ToLongFunction functional interface?
Answer: It represents a function that produces a long-valued result.

112. What is the purpose of UnaryOperator functional interface?
Answer: It represents an operation on a single operand that produces a result of the same type as its operand.

113. Is it possible to list the numbers and remove the duplicate elements in the list using Java SE 8 features?
Answer: Yes, we can list the numbers and remove the duplicate elements in the list by applying stream and then collecting it to set using Collections.toSet() method.

 

The above 113 Top  Java 8 interview questions were compiled to help freshers and experienced Java 8 professionals to help in their job interviews. Please go through these frequently asked Java 8 interview questions to get better prepared for your next interview.

Share this: