Java 8-Interview Quetion
Java 8-Interview Quetion
Stream API Abstract layer that provides pipeline processing of the data.
Wrapper class to check the null values and helps in further processing based
Optional
on the value.
JVM
Functional Interfaces are an interface with only one abstract method. Due to which it is also known
as the Single Abstract Method (SAM) interface. It is known as a functional interface because it wraps
a function as an interface or in other words a function is represented by a single abstract method of
the interface.
Functional interfaces can have any number of default, static, and overridden methods. For declaring
Functional Interfaces @FunctionalInterface annotation is optional to use. If this annotation is used
for interfaces with more than one abstract method, it will generate a compiler error.
return msg;
@Override
// Method Override
@Override
System.out.println(“Hello World”);
System.out.println(fi.HelloWorld());
System.out.println(fi.CustomMessage(“Hi”));
fi.bar();
A functional interface cannot extend another interface with abstract methods as it will void the rule
of one abstract method per functional interface. E.g:
interface Parent {
It can extend other interfaces which do not have any abstract method and only have the default,
static, another class is overridden, and normal methods. For eg:
interface Parent {
System.out.println("Hello");
}
@FunctionalInterface
A method in the interface that has a predefined body is known as the default method. It uses the
keyword default. default methods were introduced in Java 8 to have 'Backward Compatibility in case
JDK modifies any interfaces. In case a new abstract method is added to the interface, all classes
implementing the interface will break and will have to implement the new method. With default
methods, there will not be any impact on the interface implementing classes. default methods can
be overridden if needed in the implementation. Also, it does not qualify as synchronized or final.
Static methods, which contains method implementation is owned by the interface and is invoked
using the name of the interface, it is suitable for defining the utility methods and cannot be
overridden.
Some of the famous pre-defined functional interfaces from previous Java versions are Runnable,
Callable, Comparator, and Comparable. While Java 8 introduces functional interfaces like Supplier,
Consumer, Predicate, etc. Please refer to the java.util.function doc for other predefined functional
interfaces and its description introduced in Java 8.
Runnable: use to execute the instances of a class over another thread with no arguments and no
return value.
Callable: use to execute the instances of a class over another thread with no arguments and it either
returns a value or throws an exception.
Comparator: use to sort different objects in a user-defined order
Operator: Perform a reduction type operation that accepts the same input types.
What is the lambda expression in Java and How does a lambda expression relate to a functional
interface?
Lambda expression is a type of function without a name. It may or may not have results and
parameters. It is known as an anonymous function as it does not have type information by itself. It is
executed on-demand. It is beneficial in iterating, filtering, and extracting data from a collection.
As lambda expressions are similar to anonymous functions, they can only be applied to the 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.
System.out.println("Hello "+name);
1. List of Arguments/Params:
(String name)
A list of params is passed in () round brackets. It can have zero or more params. Declaring the type of
parameter is optional and can be inferred for the context.
2. Arrow Token:
->
Arrow token is known as the lambda arrow operator. It is used to separate the parameters from the
body, or it points the list of arguments to the body. 3. Expression/Body:
System.out.println("Hello "+name);
return "Hello "+name;
A body can have expressions or statements. {} curly braces are only required when there is more
than one line. In one statement, the return type is the same as the return type of the statement. In
other cases, the return type is either inferred by the return keyword or void if nothing is returned.
Below are the two significant features of the methods that are defined as the lambda expressions:
Type interface is available even in earlier versions of Java. It is used to infer the type of argument by
the compiler at the compile time by looking at method invocation and corresponding declaration.
What are the types and common ways to use lambda expressions?
A lambda expression does not have any specific type by itself. A lambda expression receives type
once it is assigned to a functional interface. That same lambda expression can be assigned to
different functional interface types and can have a different type.
For e.g.:
It is a static method reference to method Valueof() of class String. It will return the string
representation of the argument passed.
Optional is a container type which may or may not contain value i.e. zero(null) or one(not-null)
value. It is part of java.util package. There are pre-defined methods like isPresent(), which returns
true if the value is present or else false and the method get(), which will return the value if it is
present.
return Optional.of(word.toUpperCase());
else {
It encapsulates optional values, i.e., null or not-null values, which helps in avoiding null checks,
which results in better, readable, and robust code It acts as a wrapper around the object and returns
an object instead of a value, which can be used to avoid run-time NullPointerExceptions.
A Stream, which represents a sequence of data objects & series of operations on that data is a data
pipeline that is not related to Java I/O Streams does not hold any data permanently.
The key interface is java.util.stream.Stream<T>. It accepts Functional Interfaces so that lambdas can
be passed. Streams support a fluent interface or chaining. Below is the basic stream timeline marble
A data source
Set of Intermediate Operations to process the data source
Single Terminal Operation that produces the result
Components of Stream
Intermediate Operations:
Terminal Operations:
What is the stateful intermediate operation? Give some examples of stateful intermediate
operations.
To complete some of the intermediate operations, some state is to be maintained, and such
intermediate operations are called stateful intermediate operations. Parallel execution of
these types of operations is complex.
For Eg: sorted() , distinct() , limit() , skip() etc.
Sending data elements to further steps in the pipeline stops till all the data is sorted for
sorted() and stream data elements are stored in temporary data structures.
collect() - Collects single result from all elements of the stream sequence.
reduce() - Produces a single result from all elements of the stream sequence
Search/Query operations
Stream processing will be stopped, as and when the result can be determined.
Iterative operations
forEach() - Useful to do something with each of the Stream elements. It accepts a consumer.
findFirst() findAny()
Returns the first element in the Stream Return any element from the Stream
Collections are the source for the Stream. Java 8 collection API is enhanced with the default methods
returning Stream<T> from the collections.
Collections Streams
Data structure holds all the data No data is stored. Have the capacity to process an infinite number
elements of elements on demand
What is the feature of the new Date and Time API in Java 8?
What are the important packages for the new Data and Time API?
java.time
dates
times
Instants
durations
time-zones
periods
Java.time.format
Java.time.temporal
java.time.zone
LocalDate
LocalTime
LocalDateTime
Nashorn is a JavaScript processing engine that is bundled with Java 8. It provides better
compliance with ECMA (European Computer Manufacturers Association) normalized
JavaScript specifications and better performance at run-time than older versions.
As part of Java 8, JJS is a command-line tool that helps to execute the JavaScript code in the console.
Below is the example of CLI commands:
JAVA>jjs
jjs> print("Hello, Java 8 - I am the new JJS!")
Hello, Java 8 - I am the new JJS!
jjs> quit()
>>