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.

When to use Interface and Abstract class in Java?


Please see detailed post here

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


Please see detailed post here

Top 5 Interface Interview Questions Answers.


Please see detailed post here

Top 5 Type Casting Interview Questions Answers.


Please see detailed post here

Top 10 Exception Handling Interview Questions Answers.


Please see detailed post here


You may also like to see


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.

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


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


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.

Difference between interface and abstract class in Java.

Difference between interface vs abstract class in Java.?


Difference between interface and abstract class in Java. interface is contract while abstract class is partial implementation.

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


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 and abstract class in Java? what is the difference between them?

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


When to use interface and abstract class in java with real time example. interface vs abstract class in oops. difference between interface and abstract class.

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 name "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 name "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.
 }
}

How Interface achieve Polymorphism.

Note:
Interface just speak about the contract capabilities and don't know anything about implementation.

Example: 
Interface can very well say that "I can get all available flights", "I can do booking" because they have that capability, but they don't know "How exactly to get all available flights", "How exactly to do booking" and this is the job of class that accepted Interface contract in other words it is the job of class that implements that interface.
Interface helps in achieving dynamic Polymorphism because it focus only on capabilities and don't care about implementation which implemented class MUST take care of as define in interface contract.
Interface very well knows what methods it is capable of calling, and it is sure that class that implements this interface definitely has given the body to those methods, so it blindly calls  

"interfaceReference.capableMethods()",  
(in our example: flightOperationsReference.getAllAvailableFlights())

It doesn't care, what object has been assigned to "interfaceReference", (it can be of any class that implemented it), but when interface calls "interfaceReference.capableMethods()",  "capableMethods()" method will definitely be called on class whose object has been assigned to "interfaceReference" and that is the contract that every implementer of interface should provide body to methods defined in interface.


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


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.

How to run two thread one after another in java

how to run two thread one after another in java.


How to run two thread one after another in java. To execute threads one after another it needs to be synchronized. wait notify notifyAll is useful.

This is the famous interview question for the beginners, 
Write a program that creates 3 threads and prints alternate values in sequence.

Input: 
We have three Threads, ThreadA, ThreadB and ThreadC each printing "A", "B" and "C" repectively.

Output:
 

A B C A B C A B C A ...... so on.

Printing Threads in Sequence in Java.


We have 3 threads as shown below,

ThreadA is printing "A" continuously. (ThreadA.java)
ThreadB is printing "B" continuously. (ThreadB.java) 
ThreadC is printing "C" continuously. (ThreadC.java)

If we will not synchronize above threads then the output order is not guaranteed and we may get output like 
A C B B B C A A B C A A C C .... or
A C C C C C A A B C B B B B .... or anything

but the desired output is A B C A B C A B C A B C A B C......

For this, we need to synchronize ThreadA, ThreadB and ThreadC? what does synchronize mean here? 
Synchronize in simple terms is to allocate a turn to ThreadA as when it should run, allocate a turn to ThreadB as when it should run, allocate a turn to ThreadC as when it should run.

We took one variable "flag" and synchronize 3 threads as below, 
If value of flag=1, then it is ThreadA's turn to print.
If value of flag=2, then it is ThreadB's turn to print.
If value of flag=3, then it is ThreadC's turn to print. 

Now question is,
what will ThreadA do if flag value is 2 or 3 ? ThreadA will wait() as it is not his turn.
what will ThreadB do if flag value is 1 or 3 ? ThreadB will wait() as it is not his turn..
what will ThreadC do if flag value is 1 or 2 ? ThreadC will wait() as it is not his turn.

Thread can call wait() method, but wait() method needs to be called on some object. 
In our case, we will create class "ResourceLock", which will be used as a lock for all 3 threads and wait() method will be called on object of "ResourceLock".

What is the task of ThreadA,
  1. ThreadA should first acquire lock on the object of "ResourceLock", 
  2. ThreadA should check whether value of flag is 1,
  3. If No, then wait().
    If Yes,
    then print "A" and set the flag value to "2" for marking ThreadB's task as next.
    Notify all the waiting threads by using notifyAll() method.
Once notified, all waiting Threads will be waked up, that is ThreadB and ThreadC will be awake now, but as the value of flag is 2, only ThreadB will be active and other Threads will again go in waiting state.


Java Program to execute Threads in sequential order.


 ThreadRunningInSequence.java

package javabypatel;

public class ThreadRunningInSequence {

    public static void main(String[] args) {

    	ResourceLock lock = new ResourceLock();

        ThreadA a=new ThreadA(lock);
        ThreadB b=new ThreadB(lock);
        ThreadC c=new ThreadC(lock);

        a.start();
        b.start();
        c.start();
    }
}
ThreadA.java
package javabypatel;

public class ThreadA extends Thread{

	ResourceLock lock;

	ThreadA(ResourceLock lock){
		this.lock = lock;
	}

	@Override
	public void run() {

		try{
			synchronized (lock) {

				for (int i = 0; i < 100; i++) {

					while(lock.flag!=1){
						lock.wait();
					}

					System.out.print("A ");
					Thread.sleep(1000);
					lock.flag = 2;
					lock.notifyAll();
				}

			}
		}catch (Exception e) {
			System.out.println("Exception 1 :"+e.getMessage());
		}

	}

}


ThreadB.java
package javabypatel;

public class ThreadB extends Thread{

	ResourceLock lock;

	ThreadB(ResourceLock lock){
		this.lock = lock;
	}

	@Override
	public void run() {

		try{
			synchronized (lock) {

				for (int i = 0; i < 100; i++) {

					while(lock.flag!=2){
						lock.wait();
					}

					System.out.print("B ");
					Thread.sleep(1000);
					lock.flag = 3;
					lock.notifyAll();
				}

			}
		}catch (Exception e) {
			System.out.println("Exception 2 :"+e.getMessage());
		}

	}
}

ThreadC.java
package javabypatel;

public class ThreadC extends Thread{

	ResourceLock lock;

	ThreadC(ResourceLock lock){
		this.lock = lock;
	}

	@Override
	public void run() {

		try{
			synchronized (lock) {

				for (int i = 0; i < 100; i++) {

					while(lock.flag!=3){
						lock.wait();
					}

					System.out.print("C ");
					Thread.sleep(1000);
					lock.flag = 1;
					lock.notifyAll();
				}

			}
		}catch (Exception e) {
			System.out.println("Exception 3 :"+e.getMessage());
		}

	}
}


ResourceLock.java
package javabypatel;
public class ResourceLock{
	public volatile int flag = 1;
}


You may also like to see


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.

Difference between wait notify notifyall example in Java.

Difference between wait notify notifyall example in Java.


Difference between wait notify notifyall example in Java. lets see difference between wait notify notifyall example using sample Java program.

wait() :
Thread on which wait() method is called will go to waiting state by releasing the monitor(here monitor is nothing but object of any class).
Note: This thread will wake up only if some other thread calls either notify or notifyAll on same monitor.

notify() :
Thread on which notify() method is called will wake up one thread who is waiting on same monitor.

notifyAll() :
Thread on which notifyAll() method is called will wake up all threads who is waiting on same monitor.
 

We will understand wait(), notify(), notifyAll() with the help of below program that creates 3 threads and prints alternate values in sequence.

Input: 
We have three Threads, ThreadA, ThreadB and ThreadC each printing "A", "B" and "C" repectively.

Output:
 

A B C A B C A B C A ...... so on.

Printing Threads in Sequence in Java.


We have 3 threads as shown below,

ThreadA is printing "A" continuously. (ThreadA.java)
ThreadB is printing "B" continuously. (ThreadB.java) 
ThreadC is printing "C" continuously. (ThreadC.java)

If we will not synchronize above threads then the output order is not guaranteed and we may get output like 
A C B B B C A A B C A A C C .... or
A C C C C C A A B C B B B B .... or anything

but the desired output is A B C A B C A B C A B C A B C......

For this, we need to synchronize ThreadA, ThreadB and ThreadC? what does synchronize mean here? 
Synchronize in simple terms is to allocate a turn to ThreadA as when it should run, allocate a turn to ThreadB as when it should run, allocate a turn to ThreadC as when it should run.

We took one variable "flag" and synchronize 3 threads as below, 
If value of flag=1, then it is ThreadA's turn to print.
If value of flag=2, then it is ThreadB's turn to print.
If value of flag=3, then it is ThreadC's turn to print. 

Now question is,
what will ThreadA do if flag value is 2 or 3 ? ThreadA will wait() as it is not his turn.
what will ThreadB do if flag value is 1 or 3 ? ThreadB will wait() as it is not his turn..
what will ThreadC do if flag value is 1 or 2 ? ThreadC will wait() as it is not his turn.

Thread can call wait() method, but wait() method needs to be called on some object. 
In our case, we will create class "ResourceLock", which will be used as a lock for all 3 threads and wait() method will be called on object of "ResourceLock".

What is the task of ThreadA,
  1. ThreadA should first acquire lock on the object of "ResourceLock", 
  2. ThreadA should check whether value of flag is 1,
  3. If No, then wait().
    If Yes,
    then print "A" and set the flag value to "2" for marking ThreadB's task as next.
    Notify all the waiting threads by using notifyAll() method.
Once notified, all waiting Threads will be waked up, that is ThreadB and ThreadC will be awake now, but as the value of flag is 2, only ThreadB will be active and other Threads will again go in waiting state.


Java Program to execute Threads in sequential order.


 ThreadRunningInSequence.java

package javabypatel;

public class ThreadRunningInSequence {

    public static void main(String[] args) {

     ResourceLock lock = new ResourceLock();

        ThreadA a=new ThreadA(lock);
        ThreadB b=new ThreadB(lock);
        ThreadC c=new ThreadC(lock);

        a.start();
        b.start();
        c.start();
    }
}
ThreadA.java
package javabypatel;

public class ThreadA extends Thread{

 ResourceLock lock;

 ThreadA(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=1){
      lock.wait();
     }

     System.out.print("A ");
     Thread.sleep(1000);
     lock.flag = 2;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 1 :"+e.getMessage());
  }

 }

}


ThreadB.java
package javabypatel;

public class ThreadB extends Thread{

 ResourceLock lock;

 ThreadB(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=2){
      lock.wait();
     }

     System.out.print("B ");
     Thread.sleep(1000);
     lock.flag = 3;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 2 :"+e.getMessage());
  }

 }
}

ThreadC.java
package javabypatel;

public class ThreadC extends Thread{

 ResourceLock lock;

 ThreadC(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=3){
      lock.wait();
     }

     System.out.print("C ");
     Thread.sleep(1000);
     lock.flag = 1;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 3 :"+e.getMessage());
  }

 }
}


ResourceLock.java
package javabypatel;
public class ResourceLock{
 public volatile int flag = 1;
}


You may also like to see


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.