Showing posts with label java 8. Show all posts
Showing posts with label java 8. Show all posts

Thursday, January 25, 2018

Java 8 Interview Questions

In this post you will learn some frequently asked java 8 interview questions and answers for freshers and experienced as well. 

1. What are the new features added in Java 8?

Ans: Lambda Expressions:

Lambdas are anonymous functions that capture the variables of its surrounding context. They can be used to treat code as data, or, as an example, to be referenced and used as an ordinary object and passed as argument an to methods and constructors.

Functional interfaces: Functional interfaces are plain old Java interfaces with only one abstract method.

Method References: Method references are also Lambda Expressions. When all a Lambda Expression does is to invoke one method or constructor, you can substitute for a much simpler syntax called Method Reference.

Stream API: a special iterator class that allows the processing of data in a declarative way. Streams can also leverage multi-core architectures without you having to write a single line of multi-threaded code. Writing parallel code is hard and error-prone, as we all know.

Default Methods: Interfaces can now contain implementation code, this is called default methods. It allows an Interface to have methods added to them without having to worry about classes who implement this interface.

2.What are main advantages of using Java 8?
Ans:
  • More compact code
  • Less boiler plate code
  • More readable and reusable code
  • More testable code
  • Parallel operations 
3. Can you create your own functional interface?
Yes, you can create your own functional interface. Java can implicitly identify functional interface but you can also annotate it with @FunctionalInterface.
Example:
Create interface named “Display” as below

public interface display {
void display();
default void displayColor()
{
System.out.println("display Color copy");
}
}
now Create main class named “FunctionalIntefaceMain”
class FunctionalIntefaceMain {

public static void main(String[] args)
{
FunctionalIntefaceMain pMain=new FunctionalIntefaceMain();
pMain.displayForm(() -> System.out.println("displayable form"));
}
public void printForm(display d)
{
d.display();
}
}
Output:
displayable form

5. What are method references?

Ans:
When all a lambda expression does is call one single method from an object or a class, or even a constructor, it can be expressed in a much less verbose way called Method Reference. So, method references are a syntax sugar to create lambda expressions that only invoke one method or constructor.

Syntax:
class::methodname

6.What is Optional?How can you use it?
Ans:

Java 8 has introduced new class Called Optional. This class is basically introduced to avoid NullPointerException in java.Optional class encapsulates optional value which is either present or not.It is a wrapper around object and can be use to avoid NullPointerExceptions.

7. What is the difference between Predicate and Function?
Ans:

Both are functional interfaces.
Predicate<T> is single argument function and either it returns true or false.This can be used as the assignment target for a lambda expression or method reference.
Function<T,R> is also single argument function but it returns an Object.Here T denotes type of input to the function and R denotes type of Result.

8.What is the difference between an interface with a default method and an abstract class?

Ans: Java 8 brought the concept of default methods or method implementations in an Interface. So one might ask what is the difference between an interface and an abstract class now.
Abstract classes can have many things that an interface cannot, like constructors and instance variables. Abstract classes, even if they have only one abstract method, can’t be used as functional interfaces, which seems pretty obvious but it is always better to make it clear.

9.What happens if you create an Interface that extends another interface which contains a Default Method?
Ans:
If an interface that contains a default method is extended, there are three options:

  1. The child interface does not mention the default method: The effect is that the default method is inherited;
  2. The child interface redeclares the method: The method then becomes abstract;
  3. The child interface redefines the method: The effect is that the new method overrides the one from the super interface
10.Do we have PermGen in Java 8? Are you aware of MetaSpace?
Ans:
Until Java 7, JVM used an area called PermGen to store classes. It got removed in Java 8 and replaced by MetaSpace.
Major advantage of MetaSpace over permgen:
PermGen was fixed in term of maximum size and can not grow dynamically but Metaspace can grow dynamically and do not have any size constraint.

11. What are Interface Static Methods in Java 8 ? How are they invoked?

Ans: Java 8 added the possibility to create static methods in interfaces. Neither the interfaces that extend an interface with a static method nor the classes that implement it, inherit this static method, it is necessary to invoke them explicitly using the interface name, just like any other static method: NameOfInteface.staticMethod();
A static method can only be invoked directly by the implementation methods (either static or default) from the defining interface.

12. Explain Java 8-Internal vs. External Iteration?
Ans:
External Iterators- This Iterator is also known as active iterator or explicit iterator. For this type of iterator the control over iteration of elements is with the programmer. Which means that the programmer define when and how the next element of iteration is called.
Internal Iterators- This Iterator is also known as passive iterator, implicit iterator or callback iterator. For this type of iterator the control over the iteration of elements lies with the iterator itself. The programmer only tells the iterator "What operation is to be performed on the elements of the collection". Thus the programmer only declares what is to be done and does not manage and control how the iteration of individual elements take place.

13.What is :: (double colon) operator in Java 8?
Ans:
Usually we use lambda expressions to create anonymous methods which return us the desired output. But sometimes lambda expressions do nothing but call an existing method. Because this lambda expression calls an existing method, method reference can be used here instead of Lambda function. Method reference is described using :: (double colon) symbol.




Wednesday, February 8, 2017

Java 8 Stream API

In this article we will understand and learn about Stream API in Java 8 Version. This is one of core concept in Core Java. Java 8 brings new abilities to work with Collections,in the form of a brand new Stream API. This new functionality is provided by the java.util.stream package. 

The Stream API offers easy filtering,counting and mapping of Collections as well as different ways to get slices and subsets of information out of them. The Stream API allows shorter and more elegant code for working with collections.

Stream represents a sequence of objects. A stream operates on data source,such as an array or Collections. A stream never provides storage for the data. It simply moves the data,possibly filtering,sorting on that data in the process.

The Stream API defines several stream interfaces, which are packaged in java.util.stream

BaseStream is a generic interface declared like this:

interface BaseStream<T, S extends BaseStream<T,S>>

In the above T specifies the type of elements in the stream, and S represents the type of stream that extends BaseStream. BaseStream extends AutoCloseable interface,thus a stream can be managed in try-with-resources statement.

How to obtain a Stream:

You can obtain a stream in a number of ways. Perhaps the most common is when a stream is obtained for a collection. In JDK 8, the Collection interface has been expanded to include two methods that obtain a stream from a collection. The first is stream() as shown below

default Stream<E>stream()

The second method is

 default Stream<E>parallelStream()

A stream can be obtained from an array by use of the static stream() method,which was added to the arrays class by JDK 8. 

static <T> Stream<T> stream(T[ ] array)

This method returns a sequential stream to the elements in array. For example, given an
array called addresses of type Address, the following obtains a stream to it:
 

Stream<Address> addrStrm = Arrays.stream(addresses); 

Lets start with a short example. We will use this data model in all examples:

Class Author{
String name;

int countOfBooks;
}
class Book{
String name;
int year;
Author author;
}
Let's imagine that we need to print all authors in a books collection who wrote a book after 2010. How would we do it in Java 7?

for(Book book:books){
if(book.author!=null&&book.year>2010)
{
System.out.println(book.author.name);
}
}

In Java 8 how would we do that same problem above:

books.stream().filter(book ->book.year>2010)
//filter out books published in or before 2010

.map(Book::getAuthor)//get the list of authors from the list

.map(Author::getName//get the list of names for remaining authors 

.forEach(System.out::println)//print the value of each remaining element

It is only one expression that is the method stream() on any Collection returns a Stream object encapsulating all the elements of that collection. This can be manipulated with different modifiers from the Stream API, such as filter() and map(). Each modifier returns a new Stream Object  with the results of the modification,which can be further manipulated. The forEach() method allows us to perform some action for each instance of the resulting stream.

The Stream API helps developers look at java collections from a new angle. Imagine now that we need to get a Map of available languages in each country. How would this be implemented in Java 7?

Map<String, Set<String>>CountryToSetOfLanguages=new HashMap<>();

for(Locale locale:Locale.getAvailableLocales())
{
String country=locale.getDisplayCountry();

if(!countryToSetOfLanguages.containsKey(country))
{
countryToSetOfLanguages.put(country,new HashSet<>());
}
countryToSetOfLanguages.get(country).add(locale.getDisplayLanguage());
}

In java 8 the above same will be rewritten below:

import java.util.stream.*;
import static java.util.stream.Collectors.*;
.........
........
Map<String, Set<String>>CountryToSetOfLanguages=Stream.of(Locale.getAvailableLocales()).collect(groupingBy(Locale::getDisplayCountry,mapping(
Locale::getDisplayLanguage,toSet())));

The method collect() allows us to collect the results of a stream in different ways. Here,we can see that it firstly groups by country,and then maps each group by language(groupinBy() and toSet() are both static methods from the Collectors class).




 

Sunday, November 20, 2016

Java 8 Default method with example

In this page we will learn why Java 8 interfaces included default method, In the earlier post we were discussed Java 7 new feature, now,we will learn why Java 8 added default methods in Java 8. Prior to Java 8 an interface could not define any implementation whatsoever. That means all methods are abstract methods in interface,containing no body. But in JDK 8 has changed this by adding new capability to interface called default method. That means an interface can provide method body by using default method.

Use of Default Method:

Prior to Java 8, you could use abstract and all regular classes to provide  static and default methods. All the methods in interface should be overridden by implementing classes.You can not add new method in an interface without modifying all the implementations. The default method would solve this problem by supplying an implementation if no other implementation is explicitly provided. Thus, the addition of default method will not cause preexisting code to break.

 An interface default method is defined similar to a way a method is defined by a class. The main difference is that the declaration is preceded by a keyword default



Let us look at sample interface as follows: 

Interface sample
{
getSalary();//this is normal interface method declaration

default String getName();//this is a default method for interface in Java 8
{
return "default String";
}

 In the above code sample interface declared two methods namely getSalary() it is a standard interface declaration methods, second methods is getName() which newly added in the java 8,notice that syntax you should declare default keyword before method name and it contains body,so it returns default String. Therefore, it is not necessary for an implementing class to override it.


Example:

interface sample
{
public int getSalary();//this is normal interface method declaration

default String getName()//this is a default method for interface in Java 8
{
return "default String";
}
class sampleImp implements sample
{
public int getSalary()//you need to implement this only in the class
{
return 20000;
}
class Test
{
public static void main(String args[])
{
sampleImp si=new sampleImp();
si.getNumer();//you have to call explicitly since it it is implemented by class sampleImp
si.getString();// you need to call this also because default implementation
}


Output:
 20000
default String

In the above example, the default implementation of getName() automatically used. It was not necessary to define in sampleImp class. 

If we want different String you can override getName(),it it possible to implementing class to define its own implementation of a default method.

Example:

class sampleImp implements sample
{
public int getSalary()
{
return 20000;
}
public String getName()
{
return "hello java 8";
}

 Resolving Default method conflicts:

If a class implements two interfaces,one of which has default method and other default or not with same name and parameter type,by this time you must resolve the conflict. So to understand this we will take an example

Suppose we have an interface Person with  getId() method

public interface Person{
String getName();

default int getId()
{
return 0;
}

Another interface called Dempartment also with same method as getId()

public interface Department{
String getName();
default int getId()
{
return 0;
}

Now what happens if you form a class that implements both of them?

public class Employee implements Person,Department
{
---------
---------
}

In the above example class inherits two getId() methods provided by Person and Department interfaces. Here Java compiler does not choose one over the other. The compiler reports and leaves up to you to resolve ambiguity. So to resolve this conflict, provide a getId() method in the Employee class and either implement your own Id.

Example:

public class Employee implements Person and Department
{
public int getId()
{
return Department.super.getId();
---------------------------
---------------------------
}
}
Note:  In the above example super keyword lets you call super type method. Based on our requirement we should specify which supertype we want.



High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...