Java 8 Flashcards

1
Q

What are the new features introduced in JAVA 8?

A

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 features, lots of feature enhancements are done under-the-hood, at both compiler and JVM level.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How will you sort a list of string using Java 8 lambda expression?

A

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

//sort using java 8
private void sortUsingJava8(List names) {
  Collections.sort(names, (s1, s2) -> s1.compareTo(s2));
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the characteristics of a Java 8 lambda expression?

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Why lambda expression is to be used?

A

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 for an anonymous class and gives a very simple yet powerful functional programming capability to Java.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What kind of variable you can access in a lambda expression?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are method references?

A

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)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Explain the System.out::println expression.

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are functional interfaces?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the purpose of BiConsumer functional interface?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the purpose of BinaryOperator functional interface?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the purpose of BiPredicate functional interface?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the purpose of BooleanSupplier functional interface?

A

It represents a supplier of Boolean-valued results.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the purpose of Consumer functional interface?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the purpose of DoubleBinaryOperator functional interface?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the purpose of DoubleConsumer functional interface?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the purpose of DoubleFunction functional interface?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What are default methods?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are static default methods?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How will you call a default method of an interface in a class?

A

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();                  
   }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How will you call a static method of an interface in a class?

A

Using name of the interface.

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

What is streams in Java 8?

A

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

22
Q

What is stream pipelining in Java 8?

A

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.

23
Q

What is the difference between Collections and Stream in Java8 ?

A

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

24
Q

What is the purpose of forEach method of stream in java 8?

A

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

25
Q

How will you print 10 random numbers using forEach of java 8?

A

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

What is the purpose of map method of stream in java 8?

A

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

27
Q

How will you print unique squares of numbers in java 8?

A

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

List numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
//get list of unique squares
List squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList())
28
Q

What is the purpose of filter method of stream in java 8?

A

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

29
Q

How will you print count of empty strings in java 8?

A

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

Liststrings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
//get count of empty string
int count = strings.stream().filter(string −> string.isEmpty()).count();
30
Q

What is the purpose of limit method of stream in java 8?

A

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

31
Q

How will you print 10 random numbers in java 8?

A

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

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

What is the purpose of sorted method of stream in java 8?

A

The ‘sorted’ method is used to sort the stream.

33
Q

How will you print 10 random numbers in a sorted order in java 8?

A

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

What is Parallel Processing in Java 8?

A

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 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.
35
Q

What are collectors in Java 8?

A

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.

Liststrings = Arrays.asList(“abc”, “”, “bc”, “efg”, “abcd”,””, “jkl”);
List 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);

36
Q

What are Statistics collectors in Java 8?

A

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

37
Q

How will you get the highest number present in a list using Java 8?

A

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

38
Q

How will you get the lowest number present in a list using Java 8?

A

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

39
Q

How will you get the sum of all numbers present in a list using Java 8?

A

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

40
Q

How will you get the average of all numbers present in a list using Java 8?

A

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

41
Q

What is Optional in Java8?

A

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.

42
Q

What is Nashorn in Java8?

A

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.

43
Q

What is jjs in JAVA8?

A

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

44
Q

Can you execute javascript code from java 8 code base?

A

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

45
Q

What is local datetime API in JAVA8?

A

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

46
Q

What is zoned datetime API in JAVA8?

A

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

47
Q

What is chromounits in java8?

A

java.time.temporal.ChronoUnit enum is added in Java 8 to replace the integer values used in old API to represent day, month, etc.

48
Q

How will you get the current date using local datetime api of java8?

A

Following code gets the current date using local datetime api −

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

How will you add 1 week to current date using local datetime api of java8?

A

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