Java 8 - Interview Questions

Q1.  What are new features introduced with Java 8 ?
Ans. Lambda Expressions , Interface Default and Static Methods , Method Reference , Parameters Name , Optional , Streams, Concurrency.

Q2.  What is a Lambda Expression ? What's its use ?
Ans. Its an anonymous method without any declaration. Lambda Expression are useful to write shorthand Code and hence saves the effort of writing lengthy Code.    It promotes Developer productivity, Better Readable and Reliable code.

Q3. What is a method reference?
Ans:  method reference is a Java 8 construct that can be used for referencing a method without invoking it. It is used for treating methods as Lambda Expressions,This way, the following code:

         1)      (o) -> o.toString();
         2)      Object::toString();
A method reference can be identified by a double colon separating a class or object name and the name of the method.
         1)      String::new;  (constructor reference)
         2)      String::valueOf;  (Static method reference)
         3)      str::toString;  ( bounded instance method reference)
         4)      String::toString; (Unbound instance method reference)

Q4.  What are Default Methods ?
Ans. With Java 8, We can provide method definitions in the Interfaces that gets carried down the classes implementing that interface in case they are not overridden by the Class. Keyword "default" is used to mark the default method.

Q5. What is StringJoiner ?
Ans. StringJoiner is a util method to construct a string with desired delimiter. This has been introduced with wef from Java 8.
Sample Code :
StringJoiner strJoiner = new StringJoiner(".");
strJoiner.add("Hello").add("Java 8");
System.out.println(strJoiner);
Result:- prints Hello Java8

Q6. Describe some of the functional interfaces in the standard library.

There are a lot of functional interfaces in the java.util.function package, the more common ones include but not limited to:

Function – it takes one argument and returns a result
Consumer – it takes one argument and returns no result (represents a side effect)
Supplier – it takes not argument and returns a result
Predicate – it takes one argument and returns a boolean
BiFunction – it takes two arguments and returns a result
BinaryOperator – it is similar to a BiFunction, taking two arguments and returning a result. The two arguments and the result are all of the same types

UnaryOperator – it is similar to a Function, taking two arguments and returning a result. The argument and the result are all of the same types.

No comments: