Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Java8_LatestInterviewQuestions

Java 8 introduced several key features including Lambda expressions, Functional Interfaces, and the Stream API, which enhance code readability and reusability. It also replaced PermGen with MetaSpace for better memory management and introduced the Optional class to handle null values more effectively. Additionally, Java 8 supports method references and various pre-defined functional interfaces to streamline functional programming.

Uploaded by

akshusphalle
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java8_LatestInterviewQuestions

Java 8 introduced several key features including Lambda expressions, Functional Interfaces, and the Stream API, which enhance code readability and reusability. It also replaced PermGen with MetaSpace for better memory management and introduced the Optional class to handle null values more effectively. Additionally, Java 8 supports method references and various pre-defined functional interfaces to streamline functional programming.

Uploaded by

akshusphalle
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Java 1.

8 features

1. Describe the newly added features in Java 8?

Feature Name Description


Lambda expression A function that can be shared or referred to as an object.
Functional Interfaces Single abstract method interface.
Method References Uses function as a parameter to invoke a method.
It provides an implementation of methods within interfaces enabling 'Interface
Default method
evolution' facilities.
Stream API Abstract layer that provides pipeline processing of the data.
New improved joda-time inspired APIs to overcome the drawbacks in previous
Date Time API
versions
Wrapper class to check the null values and helps in further processing based on
Optional
the value.
Nashorn, JavaScript An improvised version of JavaScript Engine that enables JavaScript executions
Engine in Java, to replace Rhino.
13) What are the types of method references in Java?

3. What are the significant advantages of Java 8?


 Compact, readable, and reusable code.

 Less boilerplate code.

 Parallel operations and execution.

 Can be ported across operating systems.

 High stability.

 Stable environment.

 Adequate support

4. What is MetaSpace? How does it differ from PermGen?


PremGen: MetaData information of classes was stored in PremGen (Permanent-Generation) memory
type before Java 8. PremGen is fixed in size and cannot be dynamically resized. It was a contiguous
Java Heap Memory.
MetaSpace: Java 8 stores the MetaData of classes in native memory called 'MetaSpace'. It is not a

contiguous Heap Memory and hence can be grown dynamically which helps to overcome the size

constraints. This improves the garbage collection, auto-tuning, and de-allocation of metadata.

5. What are functional or SAM interfaces?

Functional Interfaces are an interface with only one abstract method. Due to which it is also known as
the Single Abstract Method (SAM) 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.
6. Can a functional interface extend/inherit another interface?
A functional interface cannot extend another interface with abstract methods as it will void the rule of
one abstract method per functional interface.

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.

7. What is the default method, and why is it required?

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.

8. What are static methods in Interfaces?


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

9. What are some standard Java pre-defined functional interfaces?


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,

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
Comparable: use to sort objects in the natural sort order

10. What are the various categories of pre-defined function interfaces?


Function: To transform arguments in returnable value.
Predicate: To perform a test and return a Boolean value.
Consumer: Accept arguments but do not return any values.
Supplier: Do not accept any arguments but return a value.
Operator: Perform a reduction type operation that accepts the same input types

11. 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

Java 8 Interview Questions for Experienced


1. What is the basic structure/syntax of a lambda expression?
FunctionalInterface fi = (String name) -> {
System.out.println("Hello "+name);
return "Hello "+name;
}

Lambda expression can be divided into three distinct parts as below:


1. List of Arguments/Params: (String name)
2. Arrow Token: -->
3. Expression/Body: { System.out.println("Hello "+name); return "Hello "+name; }

2. What are the features of a lambda expression?


Below are the two significant features of the methods that are defined as the lambda expressions:
1) Lambda expressions can be passed as a parameter to another method.
2) Lambda expressions can be standalone without belonging to any class
. What is a type interface?
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

5. In Java 8, what is Method Reference?


Method reference is a compact way of referring to a method of functional interface. It is used to refer to
a method without invoking it. :: (double colon) is used for describing the method reference. The syntax
is class::methodName
For e.g.:
Integer::parseInt(str) \\ method reference
str -> Integer.ParseInt(str); \\ equivalent lambda

6. What does the String::ValueOf expression mean?


It is a static method reference to method Valueof() of class String. It will return the string representation
of the argument passed

7. What is an Optional class?


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.
8. What are the advantages of using the Optional class?
Below are the main advantage of using the Optional class:
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

9. What are Java 8 streams?


A stream is an abstraction to express data processing queries in a declarative way.
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.

10. What are the main components of a Stream?


Components of the stream are:
 A data source
 Set of Intermediate Operations to process the data source
 Single Terminal Operation that produces the result

15) What are the two types of common operations of Java Streams?

ava Stream holds two different types of operations that are:


Intermediate operations: Intermediate operations are the operations that return a stream so that the
user can chain various intermediate operations without using semicolons, as we do in other
programming languages like Scala.
Terminal operations: The terminal operations are the operations that are mainly void and null, and if
not null, these operations return a non-stream as a result.

16) What are the differences between Collections and Streams?


S.
Collections Streams
N.
1. Collection API is open to use since Java SE Streams API were included in Java SE 8.
1.2.
The collections framework is used to store Streams are used in computing data. In simple
2. data. In simple words, it is used to store a set of words, it is used in the computation of a set of
objects. objects.
In Collections API, the iteration of elements
can be done with the help of both the
In the Streams API, the users are not allowed to
Spliterator and Iterator. The forEach() method
3. iterate the elements of the stream using the
can also be used by the user to perform a
Spliterator and Iterator.
method on every element which is in the
stream.
If the users want to do the processing on the
It is used to save an infinite quantity of
4. elements of the Collections, then at that
elements.
moment, Streams API is used.
Collections API uses the external iteration idea Stream API does internal iteration to iterate the
5. to iterate the elements of the stream, such as elements of the stream. Streams API uses the
the Iterator. forEach() method to do the internal iteration.
The objects of the Collections API are not
The objects of the Streams API are lazily
6. lazily constructed. The objects of the
constructed.
Collections are constructed eagerly.
In the Streams, when the stream object is
In the Collections, when the collection object is computed entirely, then only the user can add
7. computed entirely, then only the user can add elements to the object of the stream. In simple
elements to the object of the collection. words, we can say that the Streams objects are
computed on the demand of the user.
Whenever a user is using the Collections API, Whenever a user is using the Streams API, they
8. they can iterate and use elements from the can iterate and use elements from the object of
object of the collection at any number of times. the stream only a single time.
16) What are the differences between Collections and Streams?
S.
Collections Streams
N.
Collection API is open to use since Java SE
1. Streams API were included in Java SE 8.
1.2.
The collections framework is used to store Streams are used in computing data. In simple
2. data. In simple words, it is used to store a set of words, it is used in the computation of a set of
objects. objects.
In Collections API, the iteration of elements
can be done with the help of both the
In the Streams API, the users are not allowed to
Spliterator and Iterator. The forEach() method
3. iterate the elements of the stream using the
can also be used by the user to perform a
Spliterator and Iterator.
method on every element which is in the
stream.
If the users want to do the processing on the
It is used to save an infinite quantity of
4. elements of the Collections, then at that
elements.
moment, Streams API is used.
Collections API uses the external iteration idea Stream API does internal iteration to iterate the
5. to iterate the elements of the stream, such as elements of the stream. Streams API uses the
the Iterator. forEach() method to do the internal iteration.
The objects of the Collections API are not
The objects of the Streams API are lazily
6. lazily constructed. The objects of the
constructed.
Collections are constructed eagerly.
7. In the Collections, when the collection object is In the Streams, when the stream object is
computed entirely, then only the user can add
computed entirely, then only the user can add elements to the object of the stream. In simple
elements to the object of the collection. words, we can say that the Streams objects are
computed on the demand of the user.
Whenever a user is using the Collections API, Whenever a user is using the Streams API, they
8. they can iterate and use elements from the can iterate and use elements from the object of
object of the collection at any number of times. the stream only a single time.

17) Explain some of the Intermediate operations which are used commonly in the
Java programming language?
Some of the Intermediate operations that are used commonly in the Java are:
Stream.filter(): The Java Stream filter() method is one of the significant operations under intermediate
operations. The filter() method accepts a Predicate to separate all components of the stream. It is under
intermediate operations because it enables the users to call another stream operation (for example -
Stream.forEach() method) on the result. The predicate should declare true if the component is to be
introduced in the final Stream, and the Predicate will reflect false if the component should not be
included in the final stream.
Stream.map(): The intermediate operation Stream.map(), with the help of the given function,
transforms each component in the stream into some other object. In simple words, the Stream.map()
operation converts the element of a stream into something else. It takes the given function and applies
that function to every element of the stream, which at the end returns a stream of the values that are
produced by the parameter function. Stream.map() also supports the user to create a calculation on the
data inside a Java stream. For example, if a user has a list of strings, the user can transform each string
from the given list to uppercase, lowercase, or to a substring of the original string and something
entirely else.
Stream.sorted(): The Java Stream sorted() method is also an intermediate operation or method. This
sorted() operation returns a classified (or we can say the sorted) view of the stream. The components in
the stream are sorted in a usual manner unless the user passes or uses a custom Comparator if they want
to sort the stream in a different way.

18) Explain some of the Terminal operations which are used commonly in the Java
programming language?
Some of the Terminal operations which are used commonly in the Java programming language are:
Stream.forEach(): The Java Stream forEach() method or operation is one of the terminal operations in
which starts the internal iteration of the components in the stream. In simple words, the Java Stream
forEach() method helps in repeating over all of the components of a stream and execute some process
on each of them. The forEach() method returns nothing, or we can say void. The process to be
performed on the elements of the stream is transferred as the Java lambda expression.
Stream.collect(): The Java Stream.collect() method is practiced to take elements from a stream and
save all of them in a group. Stream collect() is a method to get away from the environment of streams
and receive a solid combination of values, like an array list or a list. The Java Stream collect() method
is a terminal operation that starts the internal iteration of elements and collects the elements in the
stream in a collection or object of some kind.
Stream anyMatch(): The anyMatch() method of Java stream is also one of the terminal operations that
inputs a single Predicate or condition as a parameter and starts the internal iteration of the Stream. The
anyMatch() method implements the Predicate parameter to every component of the Stream. If the given
Predicate reflects true for any of the components of the stream, the anyMatch() method yields true. If
no elements match the Predicate, anyMatch() will return false.
Stream allMatch(): The allMatch() method of Java stream is also one of the terminal operations that
inputs a single Predicate or condition as a parameter and starts the internal iteration of the Stream. The
allMatch() method implements the Predicate parameter to every component of the Stream. If the given
Predicate reflects true for all of the components of the stream, the allMatch() method yields true. If not
all the elements match the Predicate, the allMatch() will return false.
Stream noneMatch(): The noneMatch() method of Java stream is also one of the terminal operations
that inputs a single Predicate or condition as a parameter and starts the internal iteration of the Stream.
The noneMatch() method implements the Predicate parameter to every component of the Stream. The
noneMatch() method will return true if no elements are matched by the Predicate and will return false if
one or more elements are matched with the predicate.
Stream.count(): The Java Stream count() method is also a terminal operation that reflects the number
of components present in the stream. The number of elements present in the stream is produced and
returned in the form of a long return type. In simple words, the Java Stream count() method starts the
internal iteration of the elements in the Stream and counts the elements present in it.
Stream.reduce(): The Java Stream reduce() method is also a terminal operation that helps in reducing
all the components of the stream to only a single component. The reduce() method performs a
reduction on the components of the stream with the provided function. The result of the reduce()
method is an Optional (Optional is a process of restoring a nullable T reference with a non-null value),
which holds the reduced value of the stream.
20) What are the major points of differentiation between the Iterator and the
Spliterator?

Difference Iterator Spliterator


The Iterator was introduced in The Spliterator was introduced in Java SE
Introduction
Java SE 1.2. 1.8.
In Collections API, the Iterator is
API uses In Streams API, the Spliterator is used.
used.
The user can iterate the Stream The user can iterate the Stream elements
Parallel
elements in sequential order with both parallelly as well as in sequential order
Programming
the help of Iterator. with the help of Spliterator.
Universal Iterator can be called as a Spliterator cannot be called as a universal
Iterator universal iterator. iterator.

17. How are Collections different from 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 of
elements elements on demand
External Iteration Internal Iteration
Can be processed any number of
Traversed only once
times
Elements are easy to access No direct way of accessing specific elements
Is a data store Is an API to process the data
18. What is the feature of the new Date and Time API in Java 8?
 Immutable classes and Thread-safe
 Timezone support
 Fluent methods for object creation and arithmetic
 Addresses I18N issue for earlier APIs
 Influenced by popular joda-time package
 All packages are based on the ISO-8601 calendar system

6. How are functional interfaces and Lambda Expressions related?


Lambda expressions are applied only to the functional interface’s abstract method.

11. List some Java 8 Date and Time API’s


The core API classes are:

LocalDate
LocalTime
LocalDateTime

23) Explain the use of the Optional in Java SE 8?

Java 8 has launched a unique class, Optional in java.util package. It can assist in drafting a clean code
without practicing multiple null tests. By working with Optional, we can define substitute values to
restore or alternate code to run. This makes the code more understandable because the actions which
were deceived are now obvious to the developer.
Optional can also be defined as an object of container which might contains or not contain a non-null
value. You need to import the java.util package to run this class. If the situation exists, isPresent () will
return true and get () will return the value. Additional methods based on the presence or absence of a
value obtained are introduced, such as orElse (), which provides the default value when the value is not
present, and ifPresent (), which creates a chunk of code when the value is present. This is the category
based on the number, that is, their cases:
Final and immutable (though may include references to mutable objects).
Acknowledged even individually based on equals(), not based on reference equation(==).
Do not have available constructors.

14. Describe the more commonly found functional interfaces in the standard
library.
Although many functional interfaces exist, these are the one's users most likely encounter:

Function. Takes one argument and returns a result


Consumer. Takes one argument and returns no result
Supplier. Takes a not argument and returns a result
Predicate. Takes one argument and returns a boolean
BiFunction. Takes two arguments and returns a result
BinaryOperator. It’s like a BiFunction, except it takes two arguments and returns a result, and they
are all the same type
UnaryOperator. It’s like a Function, but it takes a single argument and returns a result of the same
type

15. What is a stream, and how does it differ from a collection?


A stream is an iterator whose function is to accept a set of actions and apply them to each of the
elements it contains. A stream represents an object sequence from a collection or other source that
supports aggregate operations. Unlike collections, iteration logic implements inside the stream.

Also, streams are inherently lazily loaded and processed, unlike collections.

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.

17. What is jjs in Java 8?


Jis is the new executable or command-line tool used at the console to execute JavaScript code.
12. Is it possible to create a custom functional interface in Java 8?
Yes, Java 8 supports the creation of a custom functional interface.
packageorg.arpit.java2blog.constructor;
publicclassFunctionalIntefaceMain {
publicstaticvoidmain(String[] args)
{
FunctionalIntefaceMain pMain=newFunctionalIntefaceMain();
pMain.printForm(() -> System.out.println("Printing form"));
}
publicvoidprintForm(CustInterface c)
{
c.print();
}
}

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.

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.

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
3 publicvoidwhenCreatesEmptyOptional_thenCorrec
 t() {
4 Optional<String> empty = Optional.empty();
 assertFalse(empty.isPresent());
5 }

6

7

8

9

26. What is stream pipelining used for?


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

code to sort strings using the Java 8 lambda expression?


Collections.sort(names, (s1, s2) -> s1.compareTo(s2));}
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.
List<String>strings = Arrays.asList("abc", "", "bc", "efg");

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.

How to find and remove duplicate elements from a stream?


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

5. 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

intermediate operations in Java 8?


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

terminal operations in Java 8?


Count
Min
Max
Reduce
toArray
anymatch
allMatch

25) Define PermGen and MetaSpace. Also mention the points


of differentiation between PermGen and MetaSpace?

PermGen is known as the memory space which is used for collecting class data like byte code, static
variables, and many more. The space allocated to PermGen is by default 64Mb. The PermGen can also
be attuned with the help of -XXMaxPermSize.
In Java SE 8, the PermGen process area was restored with MetaSpace. Java developers have transferred
permGem to the unique consciousness in the original OS, which is now commonly known as
MetaSpace. MetaSpace can auto-enhance its capacity, by default. In MetaSpace, the classes can store
and discharge during the total life sentence of the Java Virtual Machine (JVM).
Differences between PermGen and MetaSpace
Basic: PermGen is the memory operation for saving class data like a static variable, byte
code, etc. In Java SE 8, the PermGen purpose section was substituted with MetaSpace.
Default Memory Allocation: The space allocated to PermGen is by default 64Mb. In
metaSpace, it can, by default, auto increase its size.
Tuned-up Memory Flag: PermGen can be harmonized by applying-XXMaxPermSize. In
metaSpace, we can reduce the upper bound of the memory by -XX: MaxMetaspaceSize.
Memory Area - PermGen is a unique Heap space. Since the introduction of Java SE 8,
MetaSpace is now including a separate storage space in the original Operation System (OS).

Internal and External iteration of Java SE 8?


Internal Iteration External Iteration
Internal Iteration was advanced in the latest External Iteration was advanced and used in the
older versions of Java, that are, Java SE 7, Java SE 6
version of Java, i.e., Java SE 8(JDK-8).
and so on.
In internal iteration, the iteration is done
In external iteration, the iteration is done externally
internally on the different objects. For
on the different objects.
example - Streams.
Internal iteration works in the Functional External iteration works in the Object-Oriented
programming style. programming style (OOPS).
Internal Iterator can be called as passive in
External Iterator can be called as active in nature.
nature.
There are less chances of errors in Internal
There are more chances of errors in External
iteration. But internal iteration requires more
iteration. But external iteration requires less coding.
coding.

finds the minimum and maximum number of a Stream?


Integer maximum= Stream.of(1, 2, 3, 4, 5, 6)
.max(Comparator.comparing(Integer::valueOf))
.get();
Integer minimum = Stream.of(1, 2, 3, 4, 5, 6)
.min(Comparator.comparing(Integer::valueOf))
.get();

joining multiple Strings using StringJoiner Class?


StringJoiner joiner = new StringJoiner(",");
joiner.add("Gaurav");
joiner.add("Tanmay");
joiner.add("Harsh");
joiner.add("Abhishek");
joiner.add("Aakash");
System.out.println(joiner);

Java 8 program modifying the string by adding prefix and


suffix to it?
In this program, we will add delimiter "," in between the two
distinguished given strings. Also, we have given "(" and ")" brackets
as prefix and suffix. According to the question, we have to join many
different strings. For this, we will take the help of add() method in
order to add them. Finally, after that we will print the String
Joiner.
// Separated the elements with a comma in between. //Added a prefix "(" and a suffix ")"
StringJoiner joiner = new StringJoiner(",", "(", ")");
joiner.add("Anubhav");
joiner.add("Gaurav");
joiner.add("Tanmay");
joiner.add("Nikhil");
joiner.add("Harsh"); // Added elements into StringJoiner "joiner"
System.out.println(joiner); }

You might also like