Top 50 Java 8 Interview Questions You Must Prepare 19.Mar.2024

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.

It represents a supplier of long-valued results.

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

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

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

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

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

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

It represents a supplier of Boolean-valued results.

It represents an operation on a single long-valued operand that produces a long-valued result.

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

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

getMimeDecoder() method of Base64 class returns a Base64.Decoder that decodes using the MIME type base64 decoding scheme.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

It represents an operation on a single operand that produces a result of the same type as its operand.

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

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

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

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

getUrlDecoder() method of Base64 class returns a Base64.Decoder that decodes using the URL and Filename safe type base64 encoding scheme.

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

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

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

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(TemporalAdjusters.next(DayOfWeek.SATURDAY));

System.out.println("Second Saturday on : " + secondSaturday);

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.

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

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

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

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

It represents an operation on a single double-valued operand that produces a double-valued result.

It represents a supplier of double-valued results.

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

Following code gets the current date using local datetime api −

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

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.