How Hashmap works internally in Java with Diagram

How HashMap works in Java.



This is the famous interview question for the beginners as well as for experienced, So Let's see what it is all about.

Hashmap is very popular data structure and found useful for solving many problems due to O(1) time complexity for both get and put operation.
Before getting into Hashmap internals, Please read Hashmap basics and Hashcode.

Internal working of Get and Put operation.


Hashmap store objects in key-value pair in a table.
   1. Objects are stored by method hashmap.put(key, value) and
   2. Objects are retrieved by calling hashmap.get(key) method.

For detail explanation on hashmap get and put API, Please read this post How Hashmap put and get API works.

Put Operation


Hashmap works on principle of hashing and internally uses hashcode as a base, for storing key-value pair.
With the help of hashcode, Hashmap stores objects and retrieves it in constant time O(1).


Lets recap "Employee Letter Box" example, we saw in last post on Hashcode.


How Hashcode and Equals works in Java Hashmap

How Hashcode and Equals works in Java Hashmap.



This is the famous interview question for the beginners as well as for experienced, So Let's see what it is all about.

Hashmap is very popular data structure and found useful for solving many problems due to O(1) time complexity for both get and put operation.
Before getting into Hashmap internals, Please read Hashmap basics and Hashcode.

Before going into details of Hashcode and Equals method, lets first understand how Get and Put
method of Hashmap works internally and it will help you understand where this two method come in picture.

Internal working of Get and Put operation.


Hashmap store objects in key-value pair in a table.
   1. Objects are stored by method hashmap.put(key, value) and
   2. Objects are retrieved by calling hashmap.get(key) method.

For detail explanation on hashmap get and put API, Please read this post How Hashmap put and get API works.

Put Operation


Hashmap works on principle of hashing and internally uses hashcode as a base, for storing key-value pair.
With the help of hashcode, Hashmap stores objects and retrieves it in constant time O(1).


Lets recap "Employee Letter Box" example, we saw in last post on Hashcode.


What is Thread in Java with example.

What is Thread in Java with example.



Java Thread is an independent path of execution within a program which can run in parallel with other existing Threads.

Lets try to understand above line with simple scenario and it will be more clear:

Threads in Real time scenario:
Suppose you want to count the population of a India, how will you approach? 

Note: There are 29 states in India.

Approach 1:


First approach is, you start with first state and count population of that state then you will start second state and so on for all 29 states. 
Once you have population of all the states, just sum the population count of all States.

Imagine the time it will take for you to do this as you are alone and you have to count population state by state.
 

Approach 2:

Second approach is, you called 29 people to help you out and you distributed the task of population count to 29 person, each person taking care of individual state. 
  1. Person 1 will take care of population count for State 1. 
  2. Person 2 will take care of population count for State 2 and so on.
Once you have population count of all the states, just sum the population count received from all 29 person and you are done.

Imagine the time it will take for you to do this as compared to Approach 1, surely it will be much less.

So that is what Thread does. In above scenario, you can consider 29 persons as 29 Threads who are doing their respective task of population count.


It is possible that Person 1 may finish population count for State 1 assigned to it much early than Person 2 doing population count for State 2 because State 1 might be small.
Person 2 will continue doing his task even after Person 1 finished early. 


In the similar way, Say If you have 2 Threads say Thread 1 and Thread 2. Thread 1 may complete its job early and Thread 2 will continue doing its job even after Thread 1 is done and they both execute separately. 

Now to relate it with Threads:
When you have task like above that needs to be run in parallel for faster processing at that time Threading will come in picture.

You can say, Java Threads helps creating multiple independent path of execution within a program which can run parallely.
Application Example: 
In Java, when a program requires more than one task to execute in parallel, say for example, 
  1. Reading a data from a local file.
  2. Reading a data from remote connection.

When both of above task need to be executed in parallel at that time Threading will come in picture.
So Java Threads helps creating multiple independent path of execution within a program which can run in parallel.

You may also like to see


Compress a given string in-place and with constant extra space.

Check whether a given string is an interleaving of String 1 and String 2.

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord.

Serialize and Deserialize a Binary Tree

Advanced Multithreading Interview Questions In Java



Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

How Hashmap works in Java

How HashMap works in Java.



This is the famous interview question for the beginners as well as for experienced, So Let's see what it is all about.

Hashmap is very popular data structure and found useful for solving many problems due to O(1) time complexity for both get and put operation.
Before getting into Hashmap internals, Please read Hashmap basics and Hashcode.

Internal working of Get and Put operation.


Hashmap store objects in key-value pair in a table.
   1. Objects are stored by method hashmap.put(key, value) and
   2. Objects are retrieved by calling hashmap.get(key) method.

For detail explanation on hashmap get and put API, Please read this post How Hashmap put and get API works.

Put Operation


Hashmap works on principle of hashing and internally uses hashcode as a base, for storing key-value pair.
With the help of hashcode, Hashmap stores objects and retrieves it in constant time O(1).


Lets recap "Employee Letter Box" example, we saw in last post on Hashcode.


Quartz Scheduler Cron Trigger example in Java

Quartz Scheduler Cron Trigger example in Java.


Integration of Quartz scheduler with Spring boot. Java Quartz scheduler cron expression example. Spring quartz scheduler postgresql database example.

Quartz Scheduler:  
  1. Quartz is a richly featured, open source Job scheduling library. 
  2. Quartz can be used to create simple or complex schedules for executing multiple jobs. 
  3. Using quartz library, job can be schedule which can be executed instantly or to be executed later point of time. 
  4. Quartz also accepts cron expression using which complex jobs can be scheduled like
    "Run job after every 5 minutes" or "Run job every week on monday at 3 PM" etc.
Spring boot:
  1. Spring boot is (Spring + Configuration) bundle which helps you to develop application faster.
  2. Spring boot take care of many configurations and helps developer focus on business. 
  3. It includes an embedded tomcat (or jetty) server.

Configure Quartz Scheduler In Web Application Java

Integrating Quartz Scheduler In Web Application Java.


Integration of Quartz scheduler with Spring boot. Java Quartz scheduler cron expression example. Spring quartz scheduler postgresql database example.

Quartz Scheduler:  
  1. Quartz is a richly featured, open source Job scheduling library. 
  2. Quartz can be used to create simple or complex schedules for executing multiple jobs. 
  3. Using quartz library, job can be schedule which can be executed instantly or to be executed later point of time. 
  4. Quartz also accepts cron expression using which complex jobs can be scheduled like
    "Run job after every 5 minutes" or "Run job every week on monday at 3 PM" etc.
Spring boot:
  1. Spring boot is (Spring + Configuration) bundle which helps you to develop application faster.
  2. Spring boot take care of many configurations and helps developer focus on business. 
  3. It includes an embedded tomcat (or jetty) server.

Quartz Scheduler Tutorial In Java with Example.

Quartz Scheduler Tutorial In Java with Example.


Integration of Quartz scheduler with Spring boot. Java Quartz scheduler cron expression example. Spring quartz scheduler postgresql database example.

Quartz Scheduler:  
  1. Quartz is a richly featured, open source Job scheduling library. 
  2. Quartz can be used to create simple or complex schedules for executing multiple jobs. 
  3. Using quartz library, job can be schedule which can be executed instantly or to be executed later point of time. 
  4. Quartz also accepts cron expression using which complex jobs can be scheduled like
    "Run job after every 5 minutes" or "Run job every week on monday at 3 PM" etc.
Spring boot:
  1. Spring boot is (Spring + Configuration) bundle which helps you to develop application faster.
  2. Spring boot take care of many configurations and helps developer focus on business. 
  3. It includes an embedded tomcat (or jetty) server.

Quartz Scheduler + Spring Boot Example

Quartz Scheduler + Spring Boot Example.


Integration of Quartz scheduler with Spring boot. Java Quartz scheduler cron expression example. Spring quartz scheduler postgresql database example.

Quartz Scheduler:  
  1. Quartz is a richly featured, open source Job scheduling library. 
  2. Quartz can be used to create simple or complex schedules for executing multiple jobs. 
  3. Using quartz library, job can be schedule which can be executed instantly or to be executed later point of time. 
  4. Quartz also accepts cron expression using which complex jobs can be scheduled like
    "Run job after every 5 minutes" or "Run job every week on monday at 3 PM" etc.
Spring boot:
  1. Spring boot is (Spring + Configuration) bundle which helps you to develop application faster.
  2. Spring boot take care of many configurations and helps developer focus on business. 
  3. It includes an embedded tomcat (or jetty) server.

Insertion Sort in Java

Insertion Sort in Java


Insertion sort is simple sorting algorithm that sorts the complete array by picking one element at a time and shifting it at its right place.

Lets understand above line in more details with the help of an example. Given a array of integers, Sort it using Insertion sort.  

Lets understand what is the input and the expected output.

Linear Search Algorithm in Java

Linear Search Algorithm in Java OR
Sequential Search Algorithm in Java

Linear search is a searching algorithm which sequentially searches element in an array.

In this algorithm, elements of array is scanned one by one and check if it is matching with element to search and if found return true else return false.

Lets understand the problem statement graphically and it will be more clear,  



How Binary search Algorithm works in Java

How Binary search Algorithm works in Java.

Binary search is a technique for searching an element from sorted array.

Let's understand Binary Search Algorithm with the help of an example, 
You will be given a sorted array and an element, find whether element is present in array or not.
 

Binary Search in Java

Binary Search in Java.

Binary search is a technique for searching an element from sorted array.

Let's understand Binary Search with the help of an example,
You will be given a sorted array and an element, find whether element is present in array or not.
Lets understand the problem statement graphically and it will be more clear,  
 

Find element in a sorted array

Binary Search in Sorted Array OR
Given a sorted array, Search a given element in array.


Searching an element in a sorted array.
You will be given a sorted array and an element, you need to find whether element is present in array or not.

Lets understand the problem statement graphically and it will be more clear,  
 

Static Polymorphism in Java with Program

Static Polymorphism, Static Binding, Compile time Polymorphism,
Method Overloading.


Polymorphism is one of the most important OOPS concept. The word "Polymorphism" means, "one name having many forms".

Please note, Polmorphism is just a concept that describes the ability of a method to behave differently at different situation, but is actually achieved either by Method Overloading(Static Polymorphism) or by Method Overriding(Dynamic Polymorphism).

More details on Polymorphism concept with example: here
 
Types of Polymorphism

  1. Static Polymorphism - Static Binding - Compile time Polymorphism - Method Overloading
  2. Dynamic Polymorphism - Dynamic Binding - Run time Polymorphism - Method Overriding  
Lets understand Static Polymorphism in more details with example.

What is Polymorphism in Java with example.

What is Polymorphism in Java with example.


Polymorphism is one of the most important OOPS concept that means "one name having many forms".

Polymorphism is Greek word which means "Many Forms", If we break the word, we will get,
Polymorphism = (Poly + Morphism) = Many + Forms.

 Lets understand above line in more details with example.

Interface example in Java

Interface example in Java with Program?


Interface is used in a situation,
  1. When you know the contract methods but don't know anything about the implementation.
  2. Your contract implementation can change in future.
  3. You want to achieve dynamic polymorphishm and loose coupling that is by just changing one line of code, you should be able to switch between contract implementer.
Lets understand above points in more details:


Interface example in Java.

When to use Interface and Abstract class with Real example: here
When to use Interface in Java: here

Example 1

Lets say we want to start a service like "makemytrip.com" or "expedia.com",  where we are responsible for displaying the flights from various flight service company and place an order from customer. 
Lets keep our service as simple as, 
  1. Displaying flights available from vendors like "AirIndia", "Emirates" and "JetAirways".
  2. Place and order for seat to respective vendor.
Remember, In this application, we don't own any flight. we are just a middle man/aggregator.
Lets see how to design it.

FlightService Interface
interface FlightService{
 void getAllFlights();
 void doBooking();
}
Emirates Implementation
class Emirates implements FlightService{
 @Override
 public void doBooking() {
  System.out.println("Do booking in Emirates way");
 }
 @Override
 public void getAllFlights() {
  System.out.println("Get flights in Emirates way");
 }
}
JetAirways Implementation
class JetAirways implements FlightService{
 @Override
 public void doBooking() {
  System.out.println("Do booking in JetAirways way");
 }
 @Override
 public void getAllFlights() {
  System.out.println("Get flights in JetAirways way");
 }
}

AirIndia Implementation
class AirIndia implements FlightService{
 @Override
 public void doBooking() {
  System.out.println("Do booking in AirIndia way");
 }
 @Override
 public void getAllFlights() {
  System.out.println("Get flights in AirIndia way");
 }
}

InterfaceTest.java

import java.util.ArrayList;
import java.util.List;

public class InterfaceTest {
 
 private static FlightManager flightManager = new FlightManager();
 
 public static void main(String[] args) {
  
  loadVendors();
  
  System.out.println("Get all flights...");
  for (FlightService fs: flightManager.getListVendors()) {
   fs.getAllFlights();
  }
  
  System.out.println("Do booking.");
  for (FlightService fs: flightManager.getListVendors()) {
   fs.doBooking();
  }
 }
 
 private static void loadVendors(){
  flightManager.addVendor(new Emirates());
  flightManager.addVendor(new AirIndia());
  flightManager.addVendor(new JetAirways());
 }
}
FlightManager.java
import java.util.ArrayList;
import java.util.List;

class FlightManager{
 private List<FlightService> listVendors = null;
 
 public FlightManager() {
  listVendors = new ArrayList<FlightService>();
 }
 
 public void addVendor(FlightService fs){
  this.listVendors.add(fs);
 }
 
 public List<FlightService> getListVendors() {
  return listVendors;
 }
 
}

Example 2

Lets say we have a requirement to Sort array but don't know which sorting algorithm to use because it depends on the nature of array.
  1. If the data set is small and nearly sorted then Insertion sort works well.  
  2. If we are working on big size array and have space constraint then Merge sort works very well.
So each sorting algorithm is fit for particular use cases.
How to design our sorting application which helps other application to sort integer array.

Sort.java
interface Sort{
 int[] sort(int[] arr);
}
MergeSort.java
class MergeSort implements Sort{
 @Override
 public int[] sort(int[] arr) {
  System.out.println("Sort array using Merge sort algorithm");
  return arr;
 }
}
InsertionSort.java
class InsertionSort implements Sort{
 @Override
 public int[] sort(int[] arr) {
  System.out.println("Sort array using Insertion sort algorithm");
  return arr;
 }
}
QuickSort.java
class QuickSort implements Sort{
 @Override
 public int[] sort(int[] arr) {
  System.out.println("Sort array using Quick sort algorithm");
  return arr;
 }
}
InterfaceTest.java
public class InterfaceTest {
 
 public static void main(String[] args) {
  int choice = 2; // user choice
  
  Sort sortObj = null;
  if(choice == 1){
   sortObj = new InsertionSort();
  
  }else if(choice == 2){
   sortObj = new QuickSort();
  
  }else if(choice == 3){
   sortObj = new MergeSort();
  }
  
  //common line used for all types of sorting
  //which algorithm will be called for sorting that depends on which object is passed to sortObj reference.
  sortObj.sort(new int[]{3,2,1}); 
 }
}

Example 3

Assume, you are writing a web service for Filtering data. 
Example: In Amazon.com, you can filter the product, By Color, By Material, By Brand, By Price and so on.
Similarly, assume your application also has such type of filtering where user can filter listing by multiple criteria. 
Also, application can be accessed by,
  1. Desktop browser which sends filter data in XML format.
    
       abc
       1000
       5000
       blue
    
  2. Mobile app which sends filter data in JSON format.
    {
      "filterData": {
        "brand": "abc",
        "priceFrom": "1000",
        "priceTill": "5000",
        "color": "blue"
      }
    }
    
How will you design your application in this scenario where user can provide input data in XML and JSON format. 
While designing application, think of future requirements as well, today there are 2 formats, tomorrow application clients can send data in multiple format like CSV etc, so handle those cases as well.
For this example, try to give a try by yourself. In case if you find difficulty in implementing, see below.
interface Parser{
 Object parse(String filterString);
}
class JSONParser implements Parser{
 @Override
 public Object parse(String filterString) {
  System.out.println("Parsing JSON string and returning Object");
  return null;
 }
}
class XMLParser implements Parser{
 @Override
 public Object parse(String filterString) {
  System.out.println("Parsing XML string and returning Object");
  return null;
 }
}
class CSVParser implements Parser{
 @Override
 public Object parse(String filterString) {
  System.out.println("Parsing CSV string and returning Object");
  return null;
 }
}

public class InterfaceTest {
 
 public static void main(String[] args) {
  
  String requestCameFrom = "mobile"; //request coming from
  String filterData = "null"; //Filter data coming from UI, can be XML, JSON, CSV etc.
  
  
  Parser parser = null;
  if(requestCameFrom.equals("mobile")){
   parser = new JSONParser();
  
  }else if(requestCameFrom.equals("desktop")){
   parser = new XMLParser();
  }
  
  parser.parse(filterData); 
 }
}

You may also like to see


When to use Interface in java with example

Interface Vs Abstract class in Java OOPS.

Top Java Interface Interview Questions and Answers

When to use interface and abstract class in Java? what is the difference between them?

 

Java Multithreading and Concurrency Interview Questions and Answers with Example

Advanced Multithreading Interview Questions In Java

How ConcurrentHashMap works and ConcurrentHashMap interview questions.


Enjoy !!!! 
If you find any issue in post or face any error while implementing, Please comment.

When to use Interface in java with example

When to use Interface in java with example?


Interface is used in a situation,
  1. When you know the contract methods but don't know anything about the implementation.
  2. Your contract implementation can change in future.
  3. You want to achieve dynamic polymorphishm and loose coupling that is by just changing one line of code, you should be able to switch between contract implementer.
Lets understand above points in more details:


Interface in Java.

When to use Interface and Abstract class with Real example: 
http://javabypatel.blogspot.in/2017/07/when-to-use-abstract-class-and-interface-difference-between-them.html



When you know the contract methods but don't know anything about the implementation

Lets say we want to start a service like "makemytrip.com" or "expedia.com",  where we are responsible for displaying the flights from various flight service company and place an order from customer. 
Lets keep our service as simple as, 
  1. Displaying flights available from vendors like "AirIndia", "Emirates" and "JetAirways".
  2. Place and order for seat to respective vendor.
Remember, In this application, we don't own any flight. we are just a middle man/aggregator and our task is to first enquire "AirIndia", then enquire "Emirates" and at last enquire "JetAirways" about the list of flights available and later if customer opts for booking then inform the respective flight vendor to do booking.


For this, first we need to tell "AirIndia", "Emirates" and "JetAirways" to give us list of flights, internally how they are giving the list that we don't care.
  1. This means I only care for method name "getAllFlights()"

    "getAllFlights()" from
    "AirIndia" may have used SOAP service to return list of flights.
    "getAllFlights()" from "Emirates" may have used REST service to return list of flights.
    "getAllFlights()" from
    "
    JetAirways" may have used CORBA service to return list of flights.

    but we don't care how it is internally implemented and what we care is the contract method "
    getAllFlights" that all the flight vendor should provide and return list of flights.

  2. Similarly, for booking I only care for method name "doBooking()" that all vendors should have, internally how this vendors are doing booking that I don't care.

To conclude: We know contract.
So we can say that we know the contract that irrespective of who the Flight vendor is, you need "getAllFlights()" and "doBooking()" method from them to run our aggregator service.

Your contract implementation can change in future. 
Say we want to develop some business application which require usage of Database and we choose to use Oracle. So we will design something like below,


We are using Oracle database and all our layers are binded to use OracleDatabaseManager to fetch data using Oracle database.

Now, say tomorrow we plan to change our database to Postgresql, We will end up changing all our layers, which is wrong. If we need to change all our layers, imagine testing and development efforts required. 

So how our design should be which can sustain future changes ? Interface will come to rescue.
Instead of using calling concrete implementation menthods in service layer, we should call contract methods of interface which doesn't know anything about implementation.

In this appraoch, Service layer doesn't care as which implementation we are using.
So in future if we switch from Oracle to PostgreSQL or to any vendor, Service layer will have no impact and it will remain as it is because it calls interface contract methods which doesn't care about implementation.

Only change required is in Database layer which is also a minimal change.
Also, this design helps us adding more vendor as an when required without disturbing the existing vendor implementation.


You want to achieve dynamic polymorphishm and loose coupling that is by just changing one line of code, you should be able to switch between contract implementer.

From above point, you can see, by only changing the middle layer, we are able to switch database implementation to different vendor without disturbing service layer.

So we can say that our application or our service layer is not tightly coupled with database layer instead both layer works on contract which make them loosely coupled and changes on one layer doesn't affect another layer as contract still remains same.


You may also like to see


Interface example in Java with Program

Interface Vs Abstract class in Java OOPS.

Top Java Interface Interview Questions and Answers

When to use interface and abstract class in Java? what is the difference between them?

 

Java Multithreading and Concurrency Interview Questions and Answers with Example

Advanced Multithreading Interview Questions In Java

How ConcurrentHashMap works and ConcurrentHashMap interview questions.


Enjoy !!!! 
If you find any issue in post or face any error while implementing, Please comment.

Top 20 Java Interview Questions and Answers.

Top 20 Java Interview Questions and Answers.


Top 20 Java Interview Questions and Answers. Frequently asked core Java Interview Questions and Answers for freshers and experienced.

List of Top Java Interview Questions and Answers for freshers and experienced.

Top 25 Java Concurrency Interview Questions Answers for Freshers and Experienced.


Question 1. What are Threads in Java?

In Java, when a program requires more than one task to execute in parallel, say for example,
  1. Reading a data from a local file.
  2. Reading a data from remote connection.
When both of above task need to be executed in parallel at that time Threading will come in picture.
So Java Threads helps creating multiple independent path of execution within a program which can run parallely.  

Read local csv file in Angular2

Reading local csv file in Angular2.


Read local csv file in Angular2 with example. upload .csv file in javascript. Display CSV or text file using JavaScript, JQuery, Bootstrap and Angular2.


We will Read, Parse and Display .csv file records in Angular2.



N Queens Problem in Java - Backtracking

N Queens Problem in Java using Backtracking


N Queen problem is of placing N queens on an N×N chessboard so that no two queens attack each other.

Let us first understand what we want to achieve? what is the input and what is the expected output?

You are given a chess board of N * N size, you have to place N Queens on a chess board in such a way that no queens are attacking each other.

Note: Queens attacks on same row, on same column as well as diagonally.

Sample Input and output for 4 * 4 chess board


Kadane's Algorithm in Java.

Kadane's Algorithm in Java to find Largest Sum Contiguous Subarray.

Kadane's Algorithm in Java. Kadane's Algorithm to solve maximum sum subarray problem.

The maximum subarray problem is the task of finding the contiguous subarray within a one-dimensional array of numbers which has the largest sum.

Real time example of abstract class and interface in Java project.

Real time example of abstract class and interface in Java project.?


Real time example of abstract class and interface in java projects. abstract class real world example. real time example of Interface in java.

This is very popular interview question for the beginners as well for experienced. 

interface Vs abstract class in Java.


Interface: 
Interface is used when you want to define a contract and you don't know anything about implementation. (here it is total abstraction as you don't know anything.)
Abstract class:
Abstract class is used when you know something and rely on others for what you don't know.(here it is partial abstraction as some of the things you know and some you don't know.)
Now, Let's understand above difference between Interface and Abstract class with real world project example.

When to use Interface
Scenario, 
Consider we want to start a service like "makemytrip.com" or "expedia.com",  where we are responsible for displaying the flights from various flight service company and place an order from customer. 
Lets keep our service as simple as, 
  1. Displaying flights available from vendors like "airasia", "british airways" and "emirates".
  2. Place and order for seat to respective vendor.

How should we design our application considering interfaces and abstract class? In this scenario, interface is useful or abstract class?

Remember, In this application, we don't own any flight. we are just a middle man/aggregator and our task is to first enquire "airasia", then enquire "british airways" and at last enquire "emirates" about the list of flights available and later if customer opts for booking then inform the respective flight vendor to do booking.


For this, first we need to tell "airasia", "british airways" and "emirates" to give us list of flights, internally how they are giving the list that we don't care.
  1. This means I only care for method "getAllAvailableFlights()"

    "getAllAvailableFlights()" from
    "airasia" may have used SOAP service to return list of flights.
    "getAllAvailableFlights()" from "british airways" may have used REST service to return list of flights.
    "getAllAvailableFlights()" from
    "emirates"
    may have used CORBA service to return list of flights.

    but we don't care how it is internally implemented and what we care is the contract method "
    getAllAvailableFlights" that all the flight vendor should provide and return list of flights.

  2. Similarly, for booking I only care for method "booking()" that all vendors should have, internally how this vendors are doing booking that I don't care.

To conclude: We know contract.
So we can say that we know the contract that irrespective of who the Flight vendor is, we need "getAllAvailableFlights()" and "booking()" method from them to run our aggregator service.
In this situation, Interface is useful because we are not aware of the implementation of all the 2 methods required, and what we know is the contract methods that vendor(implementer) should provide. so due to this total abstraction and for defining the contract, interface is useful in this place.
Technically, we need to design our interface somewhat like below,

FlightOpeartions.java(Contract)
interface FlightOpeartions{
 void getAllAvailableFlights();
 void booking(BookingObject bookingObj);
}
BookingObject.java
class BookingObject{}
BritishAirways.java (Vendor 1)
class BritishAirways implements FlightOpeartions{

 public void getAllAvailableFlights(){
           //get british airways flights in the way 
           //they told us to fetch flight details.
 }

 public void booking(BookingObject flightDetails){  
          //place booking order in a way British airways 
          //told us to place order for seat.
 }

}
Emirates.java (Vendor 2)
class Emirates implements FlightOpeartions{

 public void getAllAvailableFlights(){
         //get Emirates flights in the way 
         //they told us to fetch flight details.
 }

 public void booking(BookingObject flightDetails){  
         //place booking order in a way Emirates airways
         //told us to place order for seat.
 }
}



When to use Abstract class
Scenario, 
Consider we want to start a service like Bulk SMS sender, where we take orders from various telecom vendors like Airtel, France Telecom, Vodafone etc.

For this, we don't have to setup your own infrastructure for sending SMS like Mobile towers but we need to take care of government rules like after 9PM, we should not send promotional SMS, we should also not send SMS to users registered under Do Not Disturb(DND) service etc. Remember, we need to take care of government rules for all the countries where we are sending SMS.

Note: for infrastructure like towers, we will be relying on vendor who is going to give us order.
Example, In case of,
Vodafone request us for bulk messaging, in that case we will use Vodafine towers to send SMS.
Airtel request us for bulk messaging, in that case we will use Airtel towers to send SMS.
What our job is to manage Telecom Regulations for different countries where we are sending SMS.
 
So what all methods we require would be somewhat like below,
 
 public void eastablishConnectionWithYourTower(){
    //connect using vendor way.
    //we don't know how, candidate for abstract method 
 }
 
 public void sendSMS(){
    eastablishConnectionWithYourTower();
    checkForDND();
    checkForTelecomRules();  
    //sending SMS to numbers...numbers.
    destroyConnectionWithYourTower()
 }
 
 public void destroyConnectionWithYourTower(){
    //disconnect using vendor way. 
    //we don't know how, candidate for abstract method
 }
 
 public void checkForDND(){
    //check for number present in DND.
 }
 
 public void checkForTelecomRules(){
    //Check for telecom rules.
 }
 

Out of above 5 methods, 
  1. Methods we know is "sendSMS()", "checkForDND()", "checkForTelecomRules()".
  2. Methods we don't know is "eastablishConnectionWithYourTower()", "destroyConnectionWithYourTower()".
we know how to check government rules for sending SMS as that is what our job is but
we don't how to eastablish connection with tower and how to destroy connection with tower because this is purely customer specific, airtel has its own way, vodafone has its own way etc.

So in the given scenario, we know some methods but there also exist some methods which are unknown and depends on customers.

In this case, what will be helpful, abstarct class or interface?
In this case, Abstract class will be helpful, because you know partial things like "checkForDND()", "checkForTelecomRules()" for sending sms to users but we don't know how to eastablishConnectionWithTower() and destroyConnectionWithTower() and need to depend on vendor specific way to connect and destroy connection from their towers.
Let's see how our class will look like,
abstract class SMSSender{
 
 abstract public void eastablishConnectionWithYourTower();
 
 public void sendSMS(){
  /*eastablishConnectionWithYourTower();
  checkForDND();
  checkForTelecomRules();  
  
  sending SMS to numbers...numbers.*/
 }

 abstract public void destroyConnectionWithYourTower();

 public void checkForDND(){
  //check for number present in DND.
 }
 public void checkForTelecomRules(){
  //Check for telecom rules
 }
}


class Vodafone extends SMSSender{

 @Override
 public void eastablishConnectionWithYourTower() {
  //connecting using Vodafone way
 }

 @Override
 public void destroyConnectionWithYourTower() {
  //destroying connection using Vodafone way
 }
 
}

class Airtel extends SMSSender{

 @Override
 public void eastablishConnectionWithYourTower() {
  //connecting using Airtel way
 }

 @Override
 public void destroyConnectionWithYourTower() {
  //destroying connection using Airtel way
 }
 
}


So to summarize, 

For Interface:

Interface is used when you don't know anything about implementation but know the contract that implementer should have to accomplish the task.

For Abstract class:

Abstract class is used when you know partial implementation, where say out of 5 methods, you know implementation of 3 methods and don't know implemenatation of 2 methods in that case 2 methods will be abstract and you need to rely on implementer as a contract to must provide body of abstract methods to accomplish the task.

 

You may also like to see


When to use Interface in java with example

Interface Vs Abstract class in Java OOPS.

Top Java Interface Interview Questions and Answers

When to use interface and abstract class in Java? what is the difference between them?

 

Java Multithreading and Concurrency Interview Questions and Answers with Example

Advanced Multithreading Interview Questions In Java

How ConcurrentHashMap works and ConcurrentHashMap interview questions.


Enjoy !!!! 
If you find any issue in post or face any error while implementing, Please comment.

Interface Vs Abstract class in Java OOPS.

Interface Vs Abstract class in Java OOPS?


Interface Vs Abstract class in java oops. top difference between Interface and Abstract class in java. both is used to achieve polymorphism.

This is very popular interview question for the beginners as well for experienced. 


interface Vs abstract class in Java.


Let's first understand the biggest difference between Interface and Abstract class and later will see other differences: 

When to use interface and abstract class in Java?

Interface: 
Interface is used when you want to define a contract and you don't know anything about implementation. (here it is total abstraction as you don't know anything.)
Abstract class:
Abstract class is used when you know something and rely on others for what you don't know.(here it is partial abstraction as some of the things you know and some you don't know.)
Now, Let's understand above difference between Interface and Abstract class with real world project example.

When to use Interface
Scenario, 
Consider we want to start a service like "makemytrip.com" or "expedia.com",  where we are responsible for displaying the flights from various flight service company and place an order from customer. 
Lets keep our service as simple as, 
  1. Displaying flights available from vendors like "airasia", "british airways" and "emirates".
  2. Place and order for seat to respective vendor.

How should we design our application considering interfaces and abstract class? In this scenario, interface is useful or abstract class?

Remember, In this application, we don't own any flight. we are just a middle man/aggregator and our task is to first enquire "airasia", then enquire "british airways" and at last enquire "emirates" about the list of flights available and later if customer opts for booking then inform the respective flight vendor to do booking.


For this, first we need to tell "airasia", "british airways" and "emirates" to give us list of flights, internally how they are giving the list that we don't care.
  1. This means I only care for method "getAllAvailableFlights()"

    "getAllAvailableFlights()" from
    "airasia" may have used SOAP service to return list of flights.
    "getAllAvailableFlights()" from "british airways" may have used REST service to return list of flights.
    "getAllAvailableFlights()" from
    "emirates"
    may have used CORBA service to return list of flights.

    but we don't care how it is internally implemented and what we care is the contract method "
    getAllAvailableFlights" that all the flight vendor should provide and return list of flights.

  2. Similarly, for booking I only care for method "booking()" that all vendors should have, internally how this vendors are doing booking that I don't care.

To conclude: We know contract.
So we can say that we know the contract that irrespective of who the Flight vendor is, you need "getAllAvailableFlights()" and "booking()" method from them to run our aggregator service.
In this situation, Interface is useful because we are not aware of the implementation of all the 2 methods required, and what we know is the contract methods that vendor(implementer) should provide. so due to this total abstraction and for defining the contract, interface is useful in this place.
Technically, we need to design our interface somewhat like below,

FlightOpeartions.java(Contract)
interface FlightOpeartions{
 void getAllAvailableFlights();
 void booking(BookingObject bookingObj);
}
BookingObject.java
class BookingObject{}
BritishAirways.java (Vendor 1)
class BritishAirways implements FlightOpeartions{

 public void getAllAvailableFlights(){
           //get british airways flights in the way 
           //they told us to fetch flight details.
 }

 public void booking(BookingObject flightDetails){  
          //place booking order in a way British airways 
          //told us to place order for seat.
 }

}
Emirates.java (Vendor 2)
class Emirates implements FlightOpeartions{

 public void getAllAvailableFlights(){
         //get Emirates flights in the way 
         //they told us to fetch flight details.
 }

 public void booking(BookingObject flightDetails){  
         //place booking order in a way Emirates airways
         //told us to place order for seat.
 }
}



When to use Abstract class
Scenario, 
Consider we want to start a service like Bulk SMS sender, where we take orders from various telecom vendors like Airtel, France Telecom, Vodafone etc.

For this, we don't have to setup your own infrastructure for sending SMS like Mobile towers but we need to take care of government rules like after 9PM, we should not send promotional SMS, we should also not send SMS to users registered under Do Not Disturb(DND) service etc. Remember, we need to take care of government rules for all the countries where we are sending SMS.

Note: for infrastructure like towers, we will be relying on vendor who is going to give us order.
Example, In case of,
Vodafone request us for bulk messaging, in that case we will use Vodafine towers to send SMS.
Airtel request us for bulk messaging, in that case we will use Airtel towers to send SMS.
What our job is to manage Telecom Regulations for different countries where we are sending SMS.
 
So what all methods we require would be somewhat like below,
 
 public void eastablishConnectionWithYourTower(){
    //connect using vendor way.
    //we don't know how, candidate for abstract method 
 }
 
 public void sendSMS(){
    eastablishConnectionWithYourTower();
    checkForDND();
    checkForTelecomRules();  
    //sending SMS to numbers...numbers.
    destroyConnectionWithYourTower()
 }
 
 public void destroyConnectionWithYourTower(){
    //disconnect using vendor way. 
    //we don't know how, candidate for abstract method
 }
 
 public void checkForDND(){
    //check for number present in DND.
 }
 
 public void checkForTelecomRules(){
    //Check for telecom rules.
 }
 

Out of above 5 methods, 
  1. Methods we know is "sendSMS()", "checkForDND()", "checkForTelecomRules()".
  2. Methods we don't know is "eastablishConnectionWithYourTower()", "destroyConnectionWithYourTower()".
we know how to check government rules for sending SMS as that is what our job is but
we don't how to eastablish connection with tower and how to destroy connection with tower because this is purely customer specific, airtel has its own way, vodafone has its own way etc.

So in the given scenario, we know some methods but there also exist some methods which are unknown and depends on customers.

In this case, what will be helpful, abstarct class or interface?
In this case, Abstract class will be helpful, because you know partial things like "checkForDND()", "checkForTelecomRules()" for sending sms to users but we don't know how to eastablishConnectionWithTower() and destroyConnectionWithTower() and need to depend on vendor specific way to connect and destroy connection from their towers.
Let's see how our class will look like,
abstract class SMSSender{
 
 abstract public void eastablishConnectionWithYourTower();
 
 public void sendSMS(){
  /*eastablishConnectionWithYourTower();
  checkForDND();
  checkForTelecomRules();  
  
  sending SMS to numbers...numbers.*/
 }

 abstract public void destroyConnectionWithYourTower();

 public void checkForDND(){
  //check for number present in DND.
 }
 public void checkForTelecomRules(){
  //Check for telecom rules
 }
}


class Vodafone extends SMSSender{

 @Override
 public void eastablishConnectionWithYourTower() {
  //connecting using Vodafone way
 }

 @Override
 public void destroyConnectionWithYourTower() {
  //destroying connection using Vodafone way
 }
 
}

class Airtel extends SMSSender{

 @Override
 public void eastablishConnectionWithYourTower() {
  //connecting using Airtel way
 }

 @Override
 public void destroyConnectionWithYourTower() {
  //destroying connection using Airtel way
 }
 
}


So to summarize, 

For Interface:

Interface is used when you don't know anything about implementation but know the contract that implementer should have to accomplish the task.

For Abstract class:

Abstract class is used when you know partial implementation, where say out of 5 methods, you know implementation of 3 methods and don't know implemenatation of 2 methods in that case 2 methods will be abstract and you need to rely on implementer as a contract to must provide body of abstract methods to accomplish the task.


Other differences between interface and abstract class in Java.

No abstract class interface
1 Abstract class can have both abstract methods (incomplele. methods without body) and non-abstract methods(complete. methods with body). Interface can only have abstract methods till Java 7.
In Java 8, Interface can have non-abstract default and static methods.
2 Abstract class can extends only one class and can implements multiple interfaces. Interface can only extends other interfaces.

You may also like to see


When to use Interface in java with example

Real time Interface examples in Java with Program

Top Java Interface Interview Questions and Answers

When to use interface and abstract class in Java? what is the difference between them?

 

Java Multithreading and Concurrency Interview Questions and Answers with Example

Advanced Multithreading Interview Questions In Java

How ConcurrentHashMap works and ConcurrentHashMap interview questions.


Enjoy !!!! 
If you find any issue in post or face any error while implementing, Please comment.