100% found this document useful (1 vote)
424 views

100 - Java 8 Interview Questions & Answers

The document contains 45 questions and answers about Java 8 features like lambda expressions, method references, functional interfaces, and stream API. Some key points covered are: - Lambda expressions add functional processing capabilities and can access effectively final variables. - Method references provide a simpler way to refer to methods by name. - Streams API facilitates pipeline processing of data. - Functional interfaces define a single abstract method for lambda expressions to implement.

Uploaded by

Radheshyam Nayak
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
424 views

100 - Java 8 Interview Questions & Answers

The document contains 45 questions and answers about Java 8 features like lambda expressions, method references, functional interfaces, and stream API. Some key points covered are: - Lambda expressions add functional processing capabilities and can access effectively final variables. - Method references provide a simpler way to refer to methods by name. - Streams API facilitates pipeline processing of data. - Functional interfaces define a single abstract method for lambda expressions to implement.

Uploaded by

Radheshyam Nayak
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 15

Hi Team,

#JAVA 8 INTERVIEW QUESTIONS & ANSWERS


Question 1. What Are The New Features Introduced In Java 8?

Answer :

There are dozens of features added to Java 8, the most significant ones are
mentioned below -

Lambda expression - Adds functional processing capability to Java.


Method references - Referencing functions by their names instead of invoking them
directly. Using functions as parameter.
Default method - Interface to have default method implementation.
New tools - New compiler tools and utilities are added like 'jdeps' to figure out
dependencies.
Stream API - New stream API to facilitate pipeline processing.
Date Time API - Improved date time API.
Optional - Emphasis on best practices to handle null values properly.
Nashorn, JavaScript Engine - A Java-based engine to execute JavaScript code.
Along with these new featuers, lots of feature enhancements are done under-the-
hood, at both compiler and JVM level.

Question 2. How Will You Sort A List Of String Using Java 8 Lambda Expression?

Answer :

Following code sorts a list of string using Java 8 lambda expression:

//sort using java 8


private void sortUsingJava8(List<String> names){
Collections.sort(names, (s1, s2) -> s1.compareTo(s2));
}

Question 3. What Are The Characteristics Of A Java 8 Lambda Expression?

Answer :

A lambda expression is characterized by the following syntax - parameter ->


expression body

Following are the important characteristics of a lambda expression -

Optional type declaration - No need to declare the type of a parameter. The


compiler can inference the same from the value of the parameter.
Optional parenthesis around parameter - No need to declare a single parameter in
parenthesis. For multiple parameters, parentheses are required.
Optional curly braces - No need to use curly braces in expression body if the body
contains a single statement.
Optional return keyword - The compiler automatically returns the value if the body
has a single expression to return the value.
Curly braces are required to indicate that expression returns a value.

Question 4. Why Lambda Expression Is To Be Used?

Answer :

Lambda expressions are used primarily to define inline implementation of a


functional interface, i.e., an interface with a single method only.
In the above example, we've used various types of lambda expressions to define the
operation method of MathOperation interface.
Then we have defined the implementation of sayMessage of GreetingService.

Lambda expression eliminates the need of anonymous class and gives a very simple
yet powerful functional programming capability to Java.

Question 5. What Kind Of Variable You Can Access In An Lambda Expression?

Answer :

Using lambda expression, you can refer to final variable or effectively final
variable (which is assigned only once).
Lambda expression throws a compilation error, if a variable is assigned a value the
second time.

Question 6. What Are Method References?

Answer :

Method references help to point to methods by their names. A method reference is


described using :: (double colon) symbol.
A method reference can be used to point the following types of methods -

Static methods
Instance methods
Constructors using new operator (TreeSet::new)

Question 7. Explain The System.out::println Expression?

Answer :

System.out::println method is a static method reference to println method of out


object of System class.

Question 8. What Are Functional Interfaces?

Answer :

Functional interfaces have a single functionality to exhibit. For example, a


Comparable interface with a single method 'compareTo' is used for comparison
purpose. Java 8 has defined a lot of functional interfaces to be used extensively
in lambda expressions.

Question 9. What Is The Purpose Of Biconsumer<t,u> Functional Interface?

Answer :

It represents an operation that accepts two input arguments, and returns no result.

Question 10. What Is The Purpose Of Bifunction<t,u,r> Functional Interface?

Answer :

It represents a function that accepts two arguments and produces a result.


Question 11. What Is The Purpose Of Binaryoperator<t> Functional Interface?

Answer :

It represents an operation upon two operands of the same type, producing a result
of the same type as the operands.

Question 12. What Is The Purpose Of Bipredicate<t,u> Functional Interface?

Answer :

It represents a predicate (Boolean-valued function) of two arguments.

Question 13. What Is The Purpose Of Booleansupplier Functional Interface?

Answer :

It represents a supplier of Boolean-valued results.

Question 14. What Is The Purpose Of Consumer<t> Functional Interface?

Answer :

It represents an operation that accepts a single input argument and returns no


result.

Question 15. What Is The Purpose Of Doublebinaryoperator Functional Interface?

Answer :

It represents an operation upon two double-valued operands and producing a double-


valued result.

Question 16. What Is The Purpose Of Doubleconsumer Functional Interface?

Answer :

It represents an operation that accepts a single double-valued argument and returns


no result.

Question 17. What Is The Purpose Of Doublefunction<r> Functional Interface?

Answer :

It represents a function that accepts a double-valued argument and produces a


result.

Question 18. What Is The Purpose Of Doublepredicate Functional Interface?

Answer :

It represents a predicate (Boolean-valued function) of one double-valued argument.

Question 19. What Is The Purpose Of Doublesupplier Functional Interface?

Answer :
It represents a supplier of double-valued results.

Question 20. 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.

Question 21. What Is The Purpose Of Doubletolongfunction Functional Interface?

Answer :

It represents a function that accepts a double-valued argument and produces a long-


valued result.

Question 22. 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.

Question 23. What Is The Purpose Of Function<t,r> Functional Interface?

Answer :

It represents a function that accepts one argument and produces a result.

Question 24. What Is The Purpose Of Intbinaryoperator Functional Interface?

Answer :

It represents an operation upon two int-valued operands and produces an int-valued


result.

Question 25. What Is The Purpose Of Intconsumer Functional Interface?

Answer :

It represents an operation that accepts a single int-valued argument and returns no


result.

Question 26. What Is The Purpose Of Intfunction<r> Functional Interface?

Answer :

It represents a function that accepts an int-valued argument and produces a result.

Question 27. What Is The Purpose Of Intpredicate Functional Interface?

Answer :

It represents a predicate (Boolean-valued function) of one int-valued argument.

Question 28. What Is The Purpose Of Intsupplier Functional Interface?

Answer :
It represents a supplier of int-valued results.

Question 29. What Is The Purpose Of Inttodoublefunction Functional Interface?

Answer :

It represents a function that accepts an int-valued argument and produces a double-


valued result.

Question 30. What Is The Purpose Of Inttolongfunction Functional Interface?

Answer :

It represents a function that accepts an int-valued argument and produces a long-


valued result.

Question 31. 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.

Question 32. What Is The Purpose Of Longbinaryoperator Functional Interface?

Answer :

It represents an operation upon two long-valued operands and produces a long-valued


result.

Question 33. What Is The Purpose Of Longconsumer Functional Interface?

Answer :

It represents an operation that accepts a single long-valued argument and returns


no result.

Question 34. What Is The Purpose Of Longfunction<r> Functional Interface?

Answer :

It represents a function that accepts a long-valued argument and produces a result.

Question 35. What Is The Purpose Of Longpredicate Functional Interface?

Answer :

It represents a predicate (Boolean-valued function) of one long-valued argument.

Question 36. What Is The Purpose Of Longsupplier Functional Interface?

Answer :

It represents a supplier of long-valued results.

Question 37. What Is The Purpose Of Longtodoublefunction Functional Interface?

Answer :
It represents a function that accepts a long-valued argument and produces a double-
valued result.

Question 38. What Is The Purpose Of Longtointfunction Functional Interface?

Answer :

It represents a function that accepts a long-valued argument and produces an int-


valued result.

Question 39. 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.

Question 40. What Is The Purpose Of Objdoubleconsumer<t> Functional Interface?

Answer :

It represents an operation that accepts an object-valued and a double-valued


argument, and returns no result.

Question 41. What Is The Purpose Of Objintconsumer<t> Functional Interface?

Answer :

It represents an operation that accepts an object-valued and an int-valued


argument, and returns no result.

Question 42. What Is The Purpose Of Objlongconsumer<t> Functional Interface?

Answer :

It represents an operation that accepts an object-valued and a long-valued


argument, and returns no result.

Question 43. What Is The Purpose Of Predicate<t> Functional Interface?

Answer :

It represents a predicate (Boolean-valued function) of one argument.

Question 44. What Is The Purpose Of Supplier<t> Functional Interface?

Answer :

It represents a supplier of results.

Question 45. What Is The Purpose Of Todoublebifunction<t,u> Functional Interface?

Answer :

It represents a function that accepts two arguments and produces a double-valued


result.

Question 46. What Is The Purpose Of Todoublefunction<t> Functional Interface?


Answer :

It represents a function that produces a double-valued result.

Question 47. What Is The Purpose Of Tointbifunction<t,u> Functional Interface?

Answer :

It represents a function that accepts two arguments and produces an int-valued


result.

Question 48. What Is The Purpose Of Tointfunction<t> Functional Interface?

Answer :

It represents a function that produces an int-valued result.

Question 49. What Is The Purpose Of Tolongbifunction<t,u> Functional Interface?

Answer :

It represents a function that accepts two arguments and produces a long-valued


result.

Question 50. What Is The Purpose Of Tolongfunction<t> Functional Interface?

Answer :

It represents a function that produces a long-valued result.

Question 51. What Is The Purpose Of Unaryoperator<t> Functional Interface?

Answer :

It represents an operation on a single operand that produces a result of the same


type as its operand.

Question 52. What Are Default Methods?

Answer :

With java 8, an interface can have default implementation of a function in


interfaces.

Question 53. What Are Static Default Methods?

Answer :

An interface can also have static helper methods from Java 8 onwards.

public interface vehicle {


default void print(){
System.out.println("I am a vehicle!");
}
static void blowHorn(){
System.out.println("Blowing horn!!!");
}
}
Question 54. How Will You Call A Default Method Of An Interface In A Class?

Answer :

Using super keyword along with interface name.

interface Vehicle {
default void print(){
System.out.println("I am a vehicle!");
}
}
class Car implements Vehicle {
public void print(){
Vehicle.super.print();
}
}

Question 55. How Will You Call A Static Method Of An Interface In A Class?

Answer :

Using name of the interface.

interface Vehicle {
static void blowHorn(){
System.out.println("Blowing horn!!!");
}
}
class Car implements Vehicle {
public void print(){
Vehicle.blowHorn();
}
}

Question 56. What Is Streams In Java 8?

Answer :

Stream represents a sequence of objects from a source, which supports aggregate


operations.

Question 57. What Is Stream Pipelining In Java 8?

Answer :

Most of the stream operations return stream itself so that their result can be
pipelined. These operations are called intermediate operations and their function
is to take input, process them, and return output to the target. collect() method
is a terminal operation which is normally present at the end of the pipelining
operation to mark the end of the stream.

Question 58. What Is The Difference Between Collections And Stream In Java8 ?

Answer :

Stream operations do the iterations internally over the source elements provided,
in contrast to Collections where explicit iteration is required.

Question 59. What Is The Purpose Of Foreach Method Of Stream In Java 8?


Answer :

Stream has provided a new method 'forEach' to iterate each element of the stream.

Question 60. How Will You Print 10 Random Numbers Using Foreach Of Java 8?

Answer :

The following code segment shows how to print 10 random numbers using forEach.

Random random = new Random();


random.ints().limit(10).forEach(System.out::println);

Question 61. What Is The Purpose Of Map Method Of Stream In Java 8?

Answer :

The 'map' method is used to map each element to its corresponding result.

Question 62. How Will You Print Unique Squares Of Numbers In Java 8?

Answer :

The following code segment prints unique squares of numbers using map.

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

//get list of unique squares

List<Integer> squaresList = numbers.stream().map( i ->


i*i).distinct().collect(Collectors.toList());

Question 63. What Is The Purpose Of Filter Method Of Stream In Java 8?

Answer :

The 'filter' method is used to eliminate elements based on a criteria.

Question 64. How Will You Print Count Of Empty Strings In Java 8?

Answer :

The following code segment prints a count of empty strings using filter.

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


//get count of empty string
int count = strings.stream().filter(string -> string.isEmpty()).count();

Question 65. What Is The Purpose Of Limit Method Of Stream In Java 8?

Answer :

The 'limit' method is used to reduce the size of the stream.

Question 66. How Will You Print 10 Random Numbers In Java 8?

Answer :
The following code segment shows how to print 10 random numbers.

Random random = new Random();


random.ints().limit(10).forEach(System.out::println);

Question 67. What Is The Purpose Of Sorted Method Of Stream In Java 8?

Answer :

The 'sorted' method is used to sort the stream.

Question 68. How Will You Print 10 Random Numbers In A Sorted Order In Java 8?

Answer :

The following code segment shows how to print 10 random numbers in a sorted order.

Random random = new Random();


random.ints().limit(10).sorted().forEach(System.out::println);

Question 69. What Is Parallel Processing In Java 8?

Answer :

parallelStream is the alternative of stream for parallel processing. Take a look at


the following code segment that prints a count of empty strings using
parallelStream.

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


//get count of empty string
int count = strings.parallelStream().filter(string -> string.isEmpty()).count();
//It is very easy to switch between sequential and parallel streams.

Question 70. What Are Collectors In Java 8?

Answer :

Collectors are used to combine the result of processing on the elements of a


stream. Collectors can be used to return a list or a string.

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);

Question 71. What Are Statistics Collectors In Java 8?

Answer :

With Java 8, statistics collectors are introduced to calculate all statistics when
stream processing is being done.

Question 72. How Will You Get The Highest Number Present In A List Using Java 8?

Answer :
Following code will print the highest number present in a list.

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


IntSummaryStatistics stats = integers.stream().mapToInt((x) ->
x).summaryStatistics();
System.out.println("Highest number in List : " + stats.getMax());

Question 73. How Will You Get The Lowest Number Present In A List Using Java 8?

Answer :

Following code will print the highest number present in a list.

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


IntSummaryStatistics stats = integers.stream().mapToInt((x) ->
x).summaryStatistics();
System.out.println("Lowest number in List : " + stats.getMin());

Question 74. How Will You Get The Sum Of All Numbers Present In A List Using Java
8?

Answer :

Following code will print the sum of all numbers present in a list.

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


IntSummaryStatistics stats = integers.stream().mapToInt((x) ->
x).summaryStatistics();
System.out.println("Sum of all numbers : " + stats.getSum());

Question 75. How Will You Get The Average Of All Numbers Present In A List Using
Java 8?

Answer :

Following code will print the average of all numbers present in a list.

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


IntSummaryStatistics stats = integers.stream().mapToInt((x) ->
x).summaryStatistics();
System.out.println("Average of all numbers : " + stats.getAverage());

Question 76. What Is Optional In Java8?

Answer :

Optional is a container object which is used to contain not-null objects. Optional


object is used to represent null with absent value. This class has various utility
methods to facilitate code to handle values as 'available' or 'not available'
instead of checking null values. It is introduced in Java 8 and is similar to what
Optional is in Guava.

Question 77. What Is Nashorn In Java8?

Answer :

With Java 8, Nashorn, a much improved javascript engine is introduced, to replace


the existing Rhino. Nashorn provides 2 to 10 times better performance, as it
directly compiles the code in memory and passes the bytecode to JVM. Nashorn uses
invokedynamics feature, introduced in Java 7 to improve performance.

Question 78. What Is Jjs In Java8?

Answer :

For Nashorn engine, JAVA 8 introduces a new command line tool, jjs, to execute
javascript codes at console.

Question 79. Can You Execute Javascript Code From Java 8 Code Base?

Answer :

Yes! Using ScriptEngineManager, JavaScript code can be called and interpreted in


Java.

Question 80. What Is Local Datetime Api In Java8?

Answer :

Local - Simplified date-time API with no complexity of timezone handling.

Question 81. What Is Zoned Datetime Api In Java8?

Answer :

Zoned - Specialized date-time API to deal with various timezones.

Question 82. What Is Chromounits In Java8?

Answer :

java.time.temporal.ChronoUnit enum is added in Java 8 to replace the integer values


used in old API to represent day, month, etc.

Question 83. How Will You Get The Current Date Using Local Datetime Api Of Java8?

Answer :

Following code gets the current date using local datetime api -

//Get the current date


LocalDate today = LocalDate.now();
System.out.println("Current date: " + today);

Question 84. How Will You Add 1 Week To Current Date Using Local Datetime Api Of
Java8?

Answer :

Following code adds 1 week to current date using local datetime api -

//add 1 week to the current date


LocalDate today = LocalDate.now();
LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
System.out.println("Next week: " + nextWeek);

Question 85. How Will You Add 1 Month To Current Date Using Local Datetime Api Of
Java8?
Answer :

Following code adds 1 month to current date using local datetime api:

//add 1 month to the current date


LocalDate today = LocalDate.now();
LocalDate nextMonth = today.plus(1, ChronoUnit.MONTHS);
System.out.println("Next month: " + nextMonth);

Question 86. How Will You Add 1 Year To Current Date Using Local Datetime Api Of
Java8?

Answer :

Following code adds 1 year to current date using local datetime api -

//add 1 year to the current date


LocalDate today = LocalDate.now();
LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
System.out.println("Next year: " + nextYear);

Question 87. How Will You Add 10 Years To Current Date Using Local Datetime Api Of
Java8?

Answer :

Following code adds 10 years to current date using local datetime api -

//add 10 years to the current date


LocalDate today = LocalDate.now();
LocalDate nextDecade = today.plus(1, ChronoUnit.DECADES);
System.out.println("Date after ten year: " + nextDecade);

Question 88. How Will You Get Next Tuesday Using Java8?

Answer :

Following code gets next tuesday using java8 -

//get the next tuesday


LocalDate today = LocalDate.now();
LocalDate nextTuesday = today.with(TemporalAdjusters.next(DayOfWeek.TUESDAY));
System.out.println("Next Tuesday on : " + nextTuesday);

Question 89. How Will You Get Second Saturday Of Next Month Using Java8?

Answer :

Following code gets second saturday of next month using java8 -

//get the second saturday of next month

LocalDate firstInYear = LocalDate.of(date1.getYear(),date1.getMonth(), 1);

LocalDate secondSaturday =
firstInYear.with(TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY)).with(TemporalAdj
usters.next(DayOfWeek.SATURDAY));
System.out.println("Second Saturday on : " + secondSaturday);

Question 90. How Will You Get The Instant Of Current Date In Terms Of Milliseconds
Using Java8?

Answer :

Following code gets the instant of current date in terms of milliseconds -

//Get the instant of current date in terms of milliseconds

Instant now = currentDate.toInstant();

Question 91. How Will You Get The Instant Of Local Date Time Using Time In Of
Milliseconds Using Java8?

Answer :

Following code gets the instant of local date time using time in of milliseconds -

Instant now = currentDate.toInstant();


ZoneId currentZone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(now, currentZone);
System.out.println("Local date: " + localDateTime);

Question 92. How Will You Get The Instant Of Zoned Date Time Using Time In Of
Milliseconds Using Java8?

Answer :

Following code gets the instant of zoned date time using time in of milliseconds -

Instant now = currentDate.toInstant();


ZoneId currentZone = ZoneId.systemDefault();
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(now, currentZone);
System.out.println("Zoned date: " + zonedDateTime);

Question 93. Which Class Implements A Decoder For Decoding Byte Data Using The
Base64 Encoding Scheme In Java8?

Answer :

static class Base64.Decoder - This class implements a decoder for decoding byte
data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.

Question 94. Which Class Implements An Encoder For Encoding Byte Data Using The
Base64 Encoding Scheme In Java8?

Answer :

static class Base64.Encoder - This class implements an encoder for encoding byte
data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.

Question 95. How Will You Create A Base64 Decoder?

Answer :

getDecoder() method of Base64 class returns a Base64.Decoder that decodes using the
Basic type base64 encoding scheme.

Question 96. How Will You Create A Base64 Encoder?

Answer :

getEncoder() method of Base64 class returns a Base64.Encoder that encodes using the
Basic type base64 encoding scheme.

Question 97. How Will You Create A Base64 Decoder That Decodes Using The Mime Type
Base64 Encoding Scheme?

Answer :

getMimeDecoder() method of Base64 class returns a Base64.Decoder that decodes using


the MIME type base64 decoding scheme.

Question 98. How Will You Create A Base64 Encoder That Encodes Using The Mime Type
Base64 Encoding Scheme?

Answer :

getMimeEncoder() method of Base64 class returns a Base64.Encoder that encodes using


the MIME type base64 encoding scheme.

Question 99. How Will You Create A Base64 Decoder That Decodes Using The Url And
Filename Safe Type Base64 Encoding Scheme?

Answer :

getUrlDecoder() method of Base64 class returns a Base64.Decoder that decodes using


the URL and Filename safe type base64 encoding scheme.

Question 100. How Will You Create A Base64 Encoder That Encodes Using The Url And
Filename Safe Type Base64 Encoding Scheme?

Answer :

getUrlEncoder() method of Base64 class returns a Base64.Encoder that encodes using


the URL and Filename safe type base64 encoding scheme.

You might also like