Skip to main content

Design Patterns/Algorithm/OOP Design Principle

Design Pattern

Question : What is Factory Design Pattern in Java?
Factory pattern is one of most used design pattern in Java. This type of design pattern comes under creational pattern.

In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.

Implementation
We're going to create a Shape interface and concrete classes implementing the Shape interface. A factory class ShapeFactory is defined as a next step.


FactoryPatternDemo, our demo class will use ShapeFactory to get a Shape object. It will pass information (CIRCLE / RECTANGLE / SQUARE) to ShapeFactory to get the type of object it needs.

Step 1
Create an interface.

Shape.java

public interface Shape {
   void draw();
}

Step 2
Create concrete classes implementing the same interface.

Rectangle.java

public class Rectangle implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}
Square.java

public class Square implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Square::draw() method.");
   }
}
Circle.java

public class Circle implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Circle::draw() method.");
   }
}

Step 3
Create a Factory to generate object of concrete class based on given information.

ShapeFactory.java

public class ShapeFactory {

   //use getShape method to get object of type shape 
   public Shape getShape(String shapeType){
      if(shapeType == null){
         return null;
      }
      if(shapeType.equalsIgnoreCase("CIRCLE")){
         return new Circle();
         
      } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
         return new Rectangle();
         
      } else if(shapeType.equalsIgnoreCase("SQUARE")){
         return new Square();
      }
      
      return null;
   }
}
Step 4
Use the Factory to get object of concrete class by passing an information such as type.

FactoryPatternDemo.java

public class FactoryPatternDemo {

   public static void main(String[] args) {
      ShapeFactory shapeFactory = new ShapeFactory();

      //get an object of Circle and call its draw method.
      Shape shape1 = shapeFactory.getShape("CIRCLE");

      //call draw method of Circle
      shape1.draw();

      //get an object of Rectangle and call its draw method.
      Shape shape2 = shapeFactory.getShape("RECTANGLE");

      //call draw method of Rectangle
      shape2.draw();

      //get an object of Square and call its draw method.
      Shape shape3 = shapeFactory.getShape("SQUARE");

      //call draw method of circle
      shape3.draw();
   }

}

Question : What is Abstract Factory Design Pattern in Java?
Answer : Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. This type of design pattern comes under creational pattern.

In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern.

Question:What is Builder design pattern in Java? When do you use Builder pattern ?
Answer : Builder pattern builds a complex object using simple objects and using a step by step approach. This type of design pattern comes under creational pattern.

A Builder class builds the final object step by step. This builder is independent of other objects.

Step 1

Meal.java

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

public class Meal {
   private List<Item> items = new ArrayList<Item>();

   public void addItem(Item item){
      items.add(item);
   }

   public float getCost(){
      float cost = 0.0f;
   
      for (Item item : items) {
         cost += item.price();
      }
      return cost;
   }

   public void showItems(){
 
      for (Item item : items) {
         System.out.print("Item : " + item.name());
         System.out.print(", Packing : " + item.packing().pack());
         System.out.println(", Price : " + item.price());
      }
   }
}

Step 2
Create a MealBuilder class, the actual builder class responsible to create Meal objects.

MealBuilder.java

public class MealBuilder {

   public Meal prepareVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new VegBurger());
      meal.addItem(new Coke());
      return meal;
   }

   public Meal prepareNonVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new ChickenBurger());
      meal.addItem(new Pepsi());
      return meal;
   }
}

Step 3
BuiderPatternDemo uses MealBuider to demonstrate builder pattern.

BuilderPatternDemo.java

public class BuilderPatternDemo {
   public static void main(String[] args) {
 
      MealBuilder mealBuilder = new MealBuilder();

      Meal vegMeal = mealBuilder.prepareVegMeal();
      System.out.println("Veg Meal");
      vegMeal.showItems();
      System.out.println("Total Cost: " + vegMeal.getCost());

      Meal nonVegMeal = mealBuilder.prepareNonVegMeal();
      System.out.println("\n\nNon-Veg Meal");
      nonVegMeal.showItems();
      System.out.println("Total Cost: " + nonVegMeal.getCost());
   }
}

Question:What is Singleton pattern in Java? 
Answer : Singleton pattern in Java is a pattern which allows only one instance of Singleton class available in whole application. java.lang.Runtime is good example of Singleton pattern in Java.
Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational.

This pattern involves a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.

Implementation
We're going to create a SingleObject class. SingleObject class have its constructor as private and have a static instance of itself.

SingleObject class provides a static method to get its static instance to outside world. SingletonPatternDemo, our demo class will use SingleObject class to get a SingleObject object.

Step 1
Create a Singleton Class.

SingleObject.java

public class SingleObject {

   //create an object of SingleObject
   private static SingleObject instance = new SingleObject();

   //make the constructor private so that this class cannot be
   //instantiated
   private SingleObject(){}

   //Get the only object available
   public static SingleObject getInstance(){
      return instance;
   }

   public void showMessage(){
      System.out.println("Hello World!");
   }
}
Step 2
Get the only object from the singleton class.

SingletonPatternDemo.java

public class SingletonPatternDemo {
   public static void main(String[] args) {

      //illegal construct
      //Compile Time Error: The constructor SingleObject() is not visible
      //SingleObject object = new SingleObject();

      //Get the only object available
      SingleObject object = SingleObject.getInstance();

      //show the message
      object.showMessage();
   }
}

Question : How to support Lazy loading without any racing issue?
Answer : We can use the Bill Pugh solution


public class BillPughSingleton {

       private BillPughSingleton() {
       }

       private static class LazyHolder {
              private static final BillPughSingleton INSTANCE = new BillPughSingleton();
       }

       public static BillPughSingleton getInstance() {
              return LazyHolder.INSTANCE;
       }
}

What is Prototype Pattern?
Answer : Prototype pattern refers to creating duplicate object while keeping performance in mind. This type of design pattern comes under creational pattern.

This pattern involves implementing a prototype interface which tells to create a clone of the current object. This pattern is used when creation of object directly is costly. For example, an object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls.
We're going to create an abstract class Shape and concrete classes extending the Shape class. A class ShapeCache is defined as a next step which stores shape objects in a Hashtable and returns their clone when requested.

PrototypPatternDemo, our demo class will use ShapeCache class to get a Shape object.

Step 1
Create an abstract class implementing Clonable interface.

Step 2
Create concrete classes extending the above class.
public abstract class Shape implements Cloneable {
private String id;
protected String type;
   
abstract void draw();
public Object clone() {
      Object clone = null;
      
      try {
         clone = super.clone();
         
      } catch (CloneNotSupportedException e) {
         e.printStackTrace();
      }
      
      return clone;
   }
}

Step 3
Create concrete classes extending the above class.

Rectangle.java

public class Rectangle extends Shape {

   public Rectangle(){
     type = "Rectangle";
   }

   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}
Square.java

public class Square extends Shape {

   public Square(){
     type = "Square";
   }

   @Override
   public void draw() {
      System.out.println("Inside Square::draw() method.");
   }
}
Circle.java

public class Circle extends Shape {

   public Circle(){
     type = "Circle";
   }

   @Override
   public void draw() {
      System.out.println("Inside Circle::draw() method.");
   }
}

Step 4
Create a class to get concrete classes from database and store them in a Hashtable.

ShapeCache.java

import java.util.Hashtable;

public class ShapeCache {
   private static Hashtable<String, Shape> shapeMap  = new Hashtable<String, Shape>();

   public static Shape getShape(String shapeId) {
      Shape cachedShape = shapeMap.get(shapeId);
      return (Shape) cachedShape.clone();
   }

   // for each shape run database query and create shape
   // shapeMap.put(shapeKey, shape);
   // for example, we are adding three shapes
   
   public static void loadCache() {
      Circle circle = new Circle();
      circle.setId("1");
      shapeMap.put(circle.getId(),circle);

      Square square = new Square();
      square.setId("2");
      shapeMap.put(square.getId(),square);

      Rectangle rectangle = new Rectangle();
      rectangle.setId("3");
      shapeMap.put(rectangle.getId(), rectangle);
   }
}

Step 5
PrototypePatternDemo uses ShapeCache class to get clones of shapes stored in a Hashtable.

PrototypePatternDemo.java

public class PrototypePatternDemo {
   public static void main(String[] args) {
      ShapeCache.loadCache();

      Shape clonedShape = (Shape) ShapeCache.getShape("1");
      System.out.println("Shape : " + clonedShape.getType());

      Shape clonedShape2 = (Shape) ShapeCache.getShape("2");
      System.out.println("Shape : " + clonedShape2.getType());

      Shape clonedShape3 = (Shape) ShapeCache.getShape("3");
      System.out.println("Shape : " + clonedShape3.getType());
   }
}

Question : What is decorator pattern in Java? Can you give an example of Decorator pattern?
Answer : Decorator pattern allows a user to add new functionality to an existing object without altering its structure. This type of design pattern comes under structural pattern as this pattern acts as a wrapper to existing class.
This pattern creates a decorator class which wraps the original class and provides additional functionality keeping class methods signature intact.
We are demonstrating the use of decorator pattern via following example in which we will decorate a shape with some color without alter shape class.

public interface Window {
       public void draw();

}

public class BasicWindow implements Window {
       @Override
       public void draw() {
              System.out.println("Basic window Rendered");
       }
}

public abstract class WindowDecorator implements Window {
       public Window window;

       public abstract void addWindowFeature();

       public WindowDecorator(Window window) {
              super();
              this.window = window;
       }

}

public class DecorateWithBorder extends WindowDecorator {
       private Window window;
       public DecorateWithBorder(Window win){
              super(win);
              this.window = win;
       }

       @Override
       public void draw() {
              window.draw();
              this.addWindowFeature();
       }

       @Override
       public void addWindowFeature() {
              System.out.println("Added the Border");
       }

}

public class DecorateWithLeftScrollBar extends WindowDecorator {
       private Window window;
       public DecorateWithLeftScrollBar(Window win){
              super(win);
              this.window = win;
       }

       @Override
       public void draw() {
              window.draw();
              this.addWindowFeature();
       }

       @Override
       public void addWindowFeature() {
              System.out.println("Added the Left Scroll Bar");
       }

}

public class DecorateWithRightScrollBar extends WindowDecorator {
       private Window window;
       public DecorateWithRightScrollBar(Window win){
              super(win);
              this.window = win;
       }

       @Override
       public void draw() {
              window.draw();
              this.addWindowFeature();
       }

       @Override
       public void addWindowFeature() {
              System.out.println("Added the Right Scroll Bar");
       }

}


public class DecoratorDemo {
       public static void main(String[] args) {
              Window window = new DecorateWithRightScrollBar( new DecorateWithLeftScrollBar(new DecorateWithBorder(new BasicWindow())));
              window.draw();
       }
}


What is Facade pattern?
Answer: Facade pattern hides the complexities of the system and provides an interface to the client using which the client can access the system. This type of design pattern comes under structural pattern as this pattern adds an interface to existing system to hide its complexities.

This pattern involves a single class which provides simplified methods required by client and delegates calls to methods of existing system classes.
We are going to create a Shape interface and concrete classes implementing the Shape interface. A facade class ShapeMaker is defined as a next step.

ShapeMaker class uses the concrete classes to delegate user calls to these classes. FacadePatternDemo, our demo class, will use ShapeMaker class to show the results.

Step 1
Create a facade class.

ShapeMaker.java

public class ShapeMaker {
   private Shape circle;
   private Shape rectangle;
   private Shape square;

   public ShapeMaker() {
      circle = new Circle();
      rectangle = new Rectangle();
      square = new Square();
   }

   public void drawCircle(){
      circle.draw();
   }
   public void drawRectangle(){
      rectangle.draw();
   }
   public void drawSquare(){
      square.draw();
   }
}

Step 2
Use the facade to draw various types of shapes.

FacadePatternDemo.java

public class FacadePatternDemo {
   public static void main(String[] args) {
      ShapeMaker shapeMaker = new ShapeMaker();

      shapeMaker.drawCircle();
      shapeMaker.drawRectangle();
      shapeMaker.drawSquare();
   }

}

Question : What is flyweight pattern ?
Answer : Flyweight pattern is primarily used to reduce the number of objects created and to decrease memory footprint and increase performance. This type of design pattern comes under structural pattern as this pattern provides ways to decrease object count thus improving the object structure of application.

Flyweight pattern tries to reuse already existing similar kind objects by storing them and creates new object when no matching object is found. We will demonstrate this pattern by drawing 20 circles of different locations but we will create only 5 objects. Only 5 colors are available so color property is used to check already existing Circle objects.

Question : What is Strategy Design Pattern in Java?
Answer : Strategy pattern in quite useful for implementing set of related algorithms e.g. compression algorithms, filtering strategies etc. Strategy design pattern allows you to create Context classes, which uses Strategy implementation classes for applying business rules. This pattern follow open closed design principle and quite useful in Java. One example of Strategy pattern from JDK itself is a Collections.sort() method and Comparator interface, which is a strategy interface and defines strategy for comparing objects. Because of this pattern, we don't need to modify sort() method (closed for modification) to compare any object, at same time we can implement Comparator interface to define new comparing strategy (open for extension).

Question : What is State design Pattern in Java?

Question : What is Composite design Pattern in Java?

Question : What is Template method design Pattern in Java
Answer : In Template pattern, an abstract class exposes defined way(s)/template(s) to execute its methods. Its subclasses can override the method implementation as per need but the invocation is to be in the same way as defined by an abstract class. This pattern comes under behavior pattern category.
Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
Base class declares algorithm 'placeholders', and derived classes implement the placeholders.
Two different components have significant similarities, but demonstrate no reuse of common interface or implementation. If a change common to both components becomes necessary, duplicate effort must be expended.

Question : When to use Strategy Design Pattern in Java?

Question : What is Proxy pattern in Java?
Answer : In proxy pattern, a class represents functionality of another class. This type of design pattern comes under structural pattern.

In proxy pattern, we create object having original object to interface its functionality to outer world.

Implementation
We are going to create an Image interface and concrete classes implementing the Image interface. ProxyImage is a a proxy class to reduce memory footprint of RealImage object loading.

ProxyPatternDemo, our demo class, will use ProxyImage to get an Image object to load and display as it needs.

Step 1
Create an interface.

Image.java

public interface Image {
   void display();
}

Step 2
Create concrete classes implementing the same interface.

RealImage.java

public class RealImage implements Image {

   private String fileName;

   public RealImage(String fileName){
      this.fileName = fileName;
      loadFromDisk(fileName);
   }

   @Override
   public void display() {
      System.out.println("Displaying " + fileName);
   }

   private void loadFromDisk(String fileName){
      System.out.println("Loading " + fileName);
   }
}

ProxyImage.java

public class ProxyImage implements Image{

   private RealImage realImage;
   private String fileName;

   public ProxyImage(String fileName){
      this.fileName = fileName;
   }

   @Override
   public void display() {
      if(realImage == null){
         realImage = new RealImage(fileName);
      }
      realImage.display();
   }
}

Step 3
Use the ProxyImage to get object of RealImage class when required.

ProxyPatternDemo.java

public class ProxyPatternDemo {

   public static void main(String[] args) {
      Image image = new ProxyImage("test_10mb.jpg");

      //image will be loaded from disk
      image.display();
      System.out.println("");
   
      //image will not be loaded from disk
      image.display();
   }

}

Question : What is Observer design pattern in Java? When do you use Observer pattern in Java?
Answer : Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
Encapsulate the core (or common or engine) components in a Subject abstraction, and the variable (or optional or user interface) components in an Observer hierarchy.
The "View" part of Model-View-Controller.

Question : Difference between Strategy and State design Pattern in Java?
Answer :  State design pattern is used to define and mange state of object, while Strategy pattern is used to define a set of interchangeable algorithm and let's client to choose one of them. So Strategy pattern is a client driven pattern while Object can manage there state itself.

Question:When to use Composite design Pattern in Java? Have you used previously in your project?
Answer : Composite pattern is used where we need to treat a group of objects in similar way as a single object. Composite pattern composes objects in term of a tree structure to represent part as well as whole hierarchy. This type of design pattern comes under structural pattern as this pattern creates a tree structure of group of objects.
This pattern creates a class that contains group of its own objects. This class provides ways to modify its group of same objects.
We are demonstrating use of composite pattern via following example in which we will show employees hierarchy of an organization.
Implementation
We have a class Employee which acts as composite pattern actor class. CompositePatternDemo, our demo class will use Employee class to add department level hierarchy and print all employees.

Step 1
Create Employee class having list of Employee objects.

Employee.java

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

public class Employee {
   private String name;
   private String dept;
   private int salary;
   private List<Employee> subordinates;

   // constructor
   public Employee(String name,String dept, int sal) {
      this.name = name;
      this.dept = dept;
      this.salary = sal;
      subordinates = new ArrayList<Employee>();
   }

   public void add(Employee e) {
      subordinates.add(e);
   }

   public void remove(Employee e) {
      subordinates.remove(e);
   }

   public List<Employee> getSubordinates(){
     return subordinates;
   }

   public String toString(){
      return ("Employee :[ Name : " + name + ", dept : " + dept + ", salary :" + salary+" ]");
   }
}

Step 2
Use the Employee class to create and print employee hierarchy.

CompositePatternDemo.java

public class CompositePatternDemo {
   public static void main(String[] args) {
 
      Employee CEO = new Employee("John","CEO", 30000);

      Employee headSales = new Employee("Robert","Head Sales", 20000);

      Employee headMarketing = new Employee("Michel","Head Marketing", 20000);

      Employee clerk1 = new Employee("Laura","Marketing", 10000);
      Employee clerk2 = new Employee("Bob","Marketing", 10000);

      Employee salesExecutive1 = new Employee("Richard","Sales", 10000);
      Employee salesExecutive2 = new Employee("Rob","Sales", 10000);

      CEO.add(headSales);
      CEO.add(headMarketing);

      headSales.add(salesExecutive1);
      headSales.add(salesExecutive2);

      headMarketing.add(clerk1);
      headMarketing.add(clerk2);

      //print all employees of the organization
      System.out.println(CEO);
   
      for (Employee headEmployee : CEO.getSubordinates()) {
         System.out.println(headEmployee);
       
         for (Employee employee : headEmployee.getSubordinates()) {
            System.out.println(employee);
         }
      }
   }
}


Question: When to use Template method design Pattern in Java?
Answer : Template pattern outlines an algorithm in form of template method and let subclass implement individual steps. Key point to mention, while answering this question is that template method should be final, so that subclass can not override and change steps of algorithm, but same time individual step should be abstract, so that child classes can implement them.

Question:Difference between Decorator and Proxy pattern in Java?
Answer:Decorator pattern is used to implement functionality on already created object, while Proxy pattern is used for controlling access to object. One more difference between Decorator and Proxy design pattern is that, Decorator doesn't create object, instead it get object in it's constructor, while Proxy actually creates objects.

Question:When to use Setter and Constructor Injection in Dependency Injection pattern?
Answer: Use Setter injection to provide optional dependencies of an object, while use Constructor injection to provide mandatory dependency of an object, without which it can not work. This question is related to Dependency Injection design pattern and mostly asked in context of Spring framework, which is now become an standard for developing Java application. Since Spring provides IOC container, it also gives you way to specify dependencies either by using setter methods or constructors.

Question: When to use Adapter pattern in Java? Have you used it before in your project?
Answer : Use Adapter pattern when you need to make two class work with incompatible interfaces. Adapter pattern can also be used to encapsulate third party code, so that your application only depends upon Adapter, which can adapt itself when third party code changes or you moved to a different third party library. By the way this Java design pattern question can also be asked by providing actual scenario.

public class Volt {
       public int volt;
       public Volt(int volt) {
              super();
              this.volt = volt;
       }
       public int getVolt() {
              return volt;
       }
       public void setVolt(int volt) {
              this.volt = volt;
       }
}

public interface Socket {
       public Volt getVolt();
       public int ConversionFactor();
}

public class AmericanSocket implements Socket{
       public Volt getVolt(){
              return new Volt(120);
       }

       @Override
       public int ConversionFactor() {
              return 1;
       }     
}

public class IndianSocket implements Socket{
       public Volt getVolt(){
              return new Volt(240);
       }
      
       @Override
       public int ConversionFactor() {
              return 2;
       }     
}


public interface SocketAdapter {
       public Volt get120Volt();
       public Volt get12Volt();
       public Volt get3Volt();
}

public class SocketAdpaterImpl implements SocketAdapter {
       Socket socket = null;
       public SocketAdpaterImpl(Socket socket) {
              this.socket = socket;
       }
       @Override
       public Volt get120Volt() {
              Volt  v = socket.getVolt();
              int volts = v.getVolt()/socket.ConversionFactor();
              v.setVolt(volts);
              return v;
       }

       @Override
       public Volt get12Volt() {
              Volt  v = socket.getVolt();
              int volts = v.getVolt()/socket.ConversionFactor()/10;
              v.setVolt(volts);
              return v;
       }

       @Override
       public Volt get3Volt() {
              Volt  v = socket.getVolt();
              int volts = v.getVolt()/socket.ConversionFactor()/10/4;
              v.setVolt(volts);
              return v;
       }
}

public class AdpaterDemo{
       public static void main(String[] args) {
              {
                     SocketAdpaterImpl adpaterImpl = new SocketAdpaterImpl(new IndianSocket());
                     System.out.println(adpaterImpl.get3Volt().getVolt());
                     System.out.println(adpaterImpl.get12Volt().getVolt());
                     System.out.println(adpaterImpl.get120Volt().getVolt());
                    
              }
              {
                     SocketAdpaterImpl adpaterImpl = new SocketAdpaterImpl(new AmericanSocket());
                     System.out.println(adpaterImpl.get3Volt().getVolt());
                     System.out.println(adpaterImpl.get12Volt().getVolt());
                     System.out.println(adpaterImpl.get120Volt().getVolt());
                    
              }
             
       }
      
}

Question: Can you write code to implement producer consumer design pattern in Java?
Answer: Producer consumer design pattern is a concurrency design pattern in Java which can be implemented using multiple way. if you are working in Java 5 then its better to use Concurrency util to implement producer consumer pattern instead of plain old wait and notify in Java.  Here is a good example of implementing producer consumer problem using BlockingQueue in Java.
BlockingQueue amazingly simplifies implementation of Producer-Consumer design pattern by providing outofbox support of blocking on put() and take(). Developer doesn't need to write confusing and critical piece of wait-notify code to implement communication. BlockingQuue is an interface and Java 5 provides different implantation like ArrayBlockingQueue and LinkedBlockingQueue , both implement FIFO order or elements, while ArrayLinkedQueue is bounded in nature LinkedBlockingQueue is optionally bounded. here is a complete code example of Producer Consumer pattern with BlockingQueue. Compare it with classic wait notify code, its much simpler and easy to understand.

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ProducerConsumerPattern {

    public static void main(String args[]){

     //Creating shared object
     BlockingQueue sharedQueue = new LinkedBlockingQueue();

     //Creating Producer and Consumer Thread
     Thread prodThread = new Thread(new Producer(sharedQueue));
     Thread consThread = new Thread(new Consumer(sharedQueue));

     //Starting producer and Consumer thread
     prodThread.start();
     consThread.start();
    }

}

//Producer Class in java
class Producer implements Runnable {

    private final BlockingQueue sharedQueue;

    public Producer(BlockingQueue sharedQueue) {
        this.sharedQueue = sharedQueue;
    }

    @Override
    public void run() {
        for(int i=0; i<10; i++){
            try {
                System.out.println("Produced: " + i);
                sharedQueue.put(i);
            } catch (InterruptedException ex) {
                Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

}

//Consumer Class in Java
class Consumer implements Runnable{

    private final BlockingQueue sharedQueue;

    public Consumer (BlockingQueue sharedQueue) {
        this.sharedQueue = sharedQueue;
    }

    @Override
    public void run() {
        while(true){
            try {
                System.out.println("Consumed: "+ sharedQueue.take());
            } catch (InterruptedException ex) {
                Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }


}

Output:
Produced: 0
Produced: 1
Consumed: 0
Produced: 2
Consumed: 1
Produced: 3
Consumed: 2
Produced: 4
Consumed: 3
Produced: 5
Consumed: 4
Produced: 6
Consumed: 5
Produced: 7
Consumed: 6
Produced: 8
Consumed: 7
Produced: 9
Consumed: 8
Consumed: 9

You see Producer Thread  produced number and Consumer thread consumes it in FIFO order because blocking queue allows elements to be accessed in FIFO.

OOP Design Principal


Question:What is Open closed design principle in Java?
Answer : Open closed design principle is one of the SOLID principle defined by Robert C. Martin, popularly known as Uncle Bob. This principle advises that a code should be open for extension but close for modification. At first this may look conflicting but once you explore power of polymorphism, you will start finding patterns which can provide stability and flexibility of this principle. One of the key example of this is State and Strategy design pattern, where Context class is closed for modification and new functionality is provided by writing new code by implementing new state of strategy. See this article to know more about Open closed principle.

Question:  Can you give an example of  SOLID design principles in Java?
Answer : There are lots of SOLID design pattern which forms acronym SOLID, following is the list of SOLID design principles for Java programmer  to answer this Java interview question.

DRY (Don't repeat yourself): Our first object oriented design principle is DRY, as name suggest DRY (don't repeat yourself) means don't write duplicate code, instead use Abstraction to abstract common things in one place. If you have block of code in more than two place consider making it a separate method, or if you use a hard-coded value more than one time make them public final constant. Benefit of this Object oriented design principle is in maintenance. It's important  not to abuse it, duplication is not for code, but for functionality . It means, if you used common code to validate OrderID and SSN it doesn’t mean they are same or they will remain same in future. By using common code for two different functionality or thing you closely couple them forever and when your OrderID changes its format , your SSN validation code will break. So beware of such coupling and just don’t combine anything which uses similar code but are not related.

Encapsulate What Changes: Only one thing is constant in software field and that is "Change", So encapsulate the code you expect or suspect to be changed in future. Benefit of this OOPS Design principle is that Its easy to test and maintain proper encapsulated code. If you are coding in Java then follow principle of making variable and methods private by default and increasing access step by step e.g. from private to protected and not public. Several of design pattern in Java uses Encapsulation, Factory design pattern is one example of Encapsulation which encapsulate object creation code and provides flexibility to introduce new product later with no impact on existing code.

Open Closed Design Principle : Classes, methods or functions should be Open for extension (new functionality) and Closed for modification. This is another beautiful SOLID design principle, which prevents some-one from changing already tried and tested code. Ideally if you are adding new functionality only than your code should be tested and that's the goal of Open Closed Design principle. By the way, Open Closed principle is "O" from SOLID acronym.

Single Responsibility Principle (SRP) : Single Responsibility Principle is another SOLID design principle, and represent  "S" on SOLID acronym. As per SRP, there should not be more than one reason for a class to change, or a class should always handle single functionality. If you put more than one functionality in one Class in Java  it introduce coupling between two functionality and even if you change one functionality there is chance you broke coupled functionality,  which require another round of testing to avoid any surprise on production environment.

Dependency Injection or Inversion principle : Don't ask for dependency it will be provided to you by framework. This has been very well implemented in Spring framework, beauty of this design principle is that any class which is injected by DI framework is easy to test with mock object and easier to maintain because object creation code is centralized in framework and client code is not littered with that.There are multiple ways to  implemented Dependency injection like using  byte code instrumentation which some AOP (Aspect Oriented programming) framework like AspectJ does or by using proxies just like used in Spring. See this example of IOC and DI design pattern to learn more about this SOLID design principle. It represent "D" on SOLID acronym.

Favor Composition over Inheritance : Always favor composition over inheritance ,if possible. Some of you may argue this, but I found that Composition is lot more flexible than Inheritance. Composition allows to change behavior of a class at runtime by setting property during runtime and by using Interfaces to compose a class we use polymorphism which provides flexibility of to replace with better implementation any time. Even Effective Java advise to favor composition over inheritance.

Liskov Substitution Principle (LSP) : According to Liskov Substitution Principle, Subtypes must be substitutable for super type i.e. methods or functions which uses super class type must be able to work with object of sub class without any issue". LSP is closely related to Single responsibility principle and Interface Segregation Principle. If a class has more functionality than subclass might not support some of the functionality ,and does violated LSP. In order to follow LSP SOLID design principle, derived class or sub class must enhance functionality, but not reduce them. LSP represent  "L" on SOLID acronym.

Interface Segregation principle (ISP): Interface Segregation Principle stats that, a client should not implement an interface, if it doesn't use that. This happens mostly when one interface contains more than one functionality, and client only need one functionality and not other.Interface design is tricky job because once you release your interface you can not change it without breaking all implementation. Another benefit of this design principle in Java is, interface has disadvantage to implement all method before any class can use it so having single functionality means less method to implement.

Programming for Interface not implementation : Always program for interface and not for implementation this will lead to flexible code which can work with any new implementation of interface. So use interface type on variables, return types of method or argument type of methods in Java. This has been advised by many Java programmer including in Effective Java and head first design pattern book.

Delegation principle : Don't do all stuff  by yourself,  delegate it to respective class. Classical example of delegation design principle is equals() and hashCode() method in Java. In order to compare two object for equality we ask class itself to do comparison instead of Client class doing that check. Benefit of this design principle is no duplication of code and pretty easy to modify behavior.

All these object oriented design principle helps you write flexible and better code by striving high cohesion and low coupling. Theory is first step, but what is most important is to develop ability to find out when to apply these design principle. Find out, whether we are violating any design principle and compromising flexibility of code, but again as nothing is perfect in this world, don't always try to solve problem with design patterns and design principle they are mostly for large enterprise project which has longer maintenance cycle.


Question:What is difference between Abstraction and Encapsulation in Java?
Answer : Abstraction and Encapsulation in Java are two important Object oriented programming concept and they are completely different to each other. Only similarity between Abstraction and Encapsulation is that they are OOPS concept, other than that they mean two different things. Abstraction represent taking out the behavior from How exactly its implemented, one example of abstraction in Java is interface while Encapsulation means hiding details of implementation from outside world so that when things change no body gets affected. One example of Encapsulation in Java is private methods; clients  don't care about it, You can change, amend or even remove that method  if that method is not encapsulated and it were public all your clients would have been affected. Apart from this main difference in behavior here are couple of more differences between Abstraction and Encapsulation in Java.
Following are more differences between Abstraction vs Encapsulation in Java and OOPS(Object Oriented programming) concept.

  • First difference between Abstraction and Encapsulation is that, Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using private, package-private and protected access modifier.
  • Encapsulation is also called data hiding.
  • Design principles "programming for interface than implementation" is based on abstraction and "encapsulate whatever changes" is based upon Encapsulation.
Question : Give an example where you prefer abstract class over interface ?
Answer : This is common but yet tricky design interview question. both interface and abstract class follow "writing code for interface than implementation" design principle which adds flexibility in code, quite important to tackle with changing requirement. here are some pointers which help you to answer this question:

1. In Java you can only extend one class but implement multiple interface. So if you extend a class you lost your chance of extending another class.

2. Interface are used to represent adjective or behavior e.g. Runnable, Clonable, Serializable etc, so if you use an abstract class to represent behavior your class can not be Runnable and Clonable at same time because you can not extend two class in Java but if you use interface your class can have multiple behavior at same time.

3. On time critical application prefer abstract class is slightly faster than interface.

4. If there is a genuine common behavior across the inheritance hierarchy which can be coded better at one place than abstract class is preferred choice. Some time interface and abstract class can work together also where defining function in interface and default functionality on abstract class.

To learn more about interface in Java check my post 10 things to know about Java interfaces

Question : Design a Vending Machine which can accept different coins, deliver different products?
Answer : This is an open design question which you can use as exercise, try producing design document, code and Junit test rather just solving the problem and check how much time it take you to come to solution and produce require artifacts, Ideally this question should be solve in 3 hours, at least a working version.

Question:  You have a Smartphone class and will have derived classes like IPhone, AndroidPhone, WindowsMobilePhone can be even phone names with brand, how would you design this system of Classes.
Answer : This is another design pattern exercise where you need to apply your object oriented design skill to come with a design which is flexible enough to support future products and stable enough to support changes in existing model.

Question : When do you overload a method in Java and when do you override it?
Answer : Rather a simple question for experienced designer in Java. if you see different implementation of a class has different way of doing certain thing than overriding is the way to go while overloading is doing same thing but with different input. method signature varies in case of overloading but not in case of overriding in java.

Question : Design ATM Machine?
Answer : We all use ATM (Automated Teller Machine) , Just think how will you design an ATM ? for designing financial system one must requirement is that they should work as expected in all situation. so no matter whether its power outage ATM should maintain correct state (transactions), think about locking, transaction, error condition, boundary condition etc. even if you not able to come up exact design but if you be able to point out non functional requirement, raise some question , think about boundary condition will be good progress.


Question : You are writing classes to provide Market Data and you know that you can switch to different vendors overtime like Reuters, wombat and may be even to direct exchange feed , how do you design your Market Data system.
Answer : This is very interesting design interview question and actually asked in one of big investment bank and rather common scenario if you have been writing code in Java. Key point is you will have a MarketData interface which will have methods required by client e.g. getBid(), getPrice(), getLevel() etc and MarketData should be composed with a MarketDataProvider by using dependency injection. So when you change your MarketData provider Client won't get affected because they access method form MarketData interface or class.

Question : Why is access to non-static variables not allowed from static methods in Java
Answer : You can not access non-static data from static context in Java simply because non-static variables are associated with a particular instance of object while Static is not associated with any instance. You can also see my post why non static variable are not accessible in static context for more detailed discussion.

Question : Design a Concurrent Rule pipeline in Java?
Answer : Concurrent programming or concurrent design is very hot now days to leverage power of ever increasing cores in advanced processor and Java being a multi-threaded language has benefit over others. Do design a concurrent system key point to note is thread-safety, immutability, local variables and avoid using static or instance variables. you just to think that one class can be executed by multiple thread a same time, So best approach is that every thread work on its own data, doesn't interfere on other data and have minimal synchronization preferred at start of pipeline. This question can lead from initial discussion to full coding of classes and interface but if you remember key points and issues around concurrency e.g. race condition, deadlock, memory interference, atomicity, ThreadLocal variables  etc you can get around it.

What is Generalization, Specialization, Realization and Dependency?
Answer: The Generalization and Specialization relationships are both reciprocal and hierarchical. In other words, Generalization and specialization are the inverse of each other. It only differs in the design process.
Generalization is a bottom-up design process whereas Specialization is a top-down design process.
They both belong to inheritance.
Like Parrot and Sparrow specialize Bird, and Bird generalizes from Parrot and Sparrow. These relationships are hierarchical because they create a relationship tree.
If we are moving down in the hierarchy we will get Specialization and if we will go up in the hierarchy then we will get Generalization.  In java, Generalization can relate to the “extends” keyword

Note: - Generalization is the process of extracting common features from two or more classes, and combining them into a generalized super class. Common features can be attributes, associations, or methods.
Finally we can say, a super class is a generalization of its subclass (es). Inversely, a subclass is a Specialization of its super class.

Realization in Java
Realization is the relationship between the class and the interface. It is achieved using the “implements” keyword in Java. A realization relationship connector appears as a dashed line with an unfilled arrowhead.

http://www.javatechtipssharedbygaurav.com/


J2EE design pattern

Question : What is context object Design Pattern.
Answer : when you want to avoid using protocol-specific system information outside of its relevant context, then we can use Context Object pattern that allows efficient processing of requests by propagating context information between different middleware layers. Using this pattern, a layer/session propa-gates per-request information required by the next layer/session in a context object, which eliminates the need for (1) per-request state within each layer and (2) lock-ing/synchronization to access per-request information across different layers. e.g. in Struts framework the client data submitted from the form is wrapped under ActionForm, similarly Spring MVC we can the form data into the POJO, and then propagate to the service then repository.

Question : What is Front Controller Architecture?
Answer : The front controller design pattern is used to provide a centralized request handling mechanism so that all requests will be handled by a single handler. This handler can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers. Following are the entities of this type of design pattern.
Front Controller - Single handler for all kinds of requests coming to the application (either web based/ desktop based).
Dispatcher - Front Controller may use a dispatcher object which can dispatch the request to corresponding specific handler.
View - Views are the object for which the requests are made. 

Question : What is Design Pattern - Intercepting Filter Pattern?
Answer : The intercepting filter design pattern is used when we want to do some pre-processing / post-processing with request or response of the application. Filters are defined and applied on the request before passing the request to actual target application. Filters can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers. Following are the entities of this type of design pattern.
Filter - Filter which will performs certain task prior or after execution of request by request handler.
Filter Chain - Filter Chain carries multiple filters and help to execute them in defined order on target.
Target - Target object is the request handler

Question : What is Service Locator Pattern Design Pattern ?
Answer : The service locator design pattern is used when we want to locate various services using JNDI lookup. Considering high cost of looking up JNDI for a service, Service Locator pattern makes use of caching technique. For the first time a service is required, Service Locator looks up in JNDI and caches the service object. Further lookup or same service via Service Locator is done in its cache which improves the performance of application to great extent.
Following are the entities of this type of design pattern.
Service - Actual Service which will process the request. Reference of such service is to be looked upon in JNDI server.
Context / Initial Context - JNDI Context carries the reference to service used for lookup purpose.
Service Locator - Service Locator is a single point of contact to get services by JNDI lookup caching the services.
Cache - Cache to store references of services to reuse them
Client - Client is the object that invokes the services via ServiceLocator.

Question : What is Transfer Object Design Pattern
Answer : The Transfer Object pattern is used when we want to pass data with multiple attributes in one shot from client to server. Transfer object is also known as Value Object. Transfer Object is a simple POJO class having getter/setter methods and is serializable so that it can be transferred over the network. It does not have any behavior. Server Side business class normally fetches data from the database and fills the POJO and send it to the client or pass it by value. For client, transfer object is read-only. Client can create its own transfer object and pass it to server to update values in database in one shot.
Following are the entities of this type of design pattern.
Business Object - Business Service fills the Transfer Object with data.
Transfer Object - Simple POJO having methods to set/get attributes only.
Client - Client either requests or sends the Transfer Object to Business Object

Question : What is DAO Design Pattern?
Answer : Data Access Object Pattern or DAO pattern is used to separate low level data accessing API or operations from high level business services.
Following are the participants in Data Access Object Pattern.
Data Access Object Interface - This interface defines the standard operations to be performed on a model object(s).
Data Access Object concrete class - This class implements above interface. This class is responsible to get data from a data source which can be database / xml or any other storage mechanism.
Model Object or Value Object - This object is simple POJO containing get/set methods to store data retrieved using DAO class.

What is Business Delegate Pattern?
Answer : Business Delegate Pattern is used to decouple presentation tier and business tier. It is basically use to reduce communication or remote lookup functionality to business tier code in presentation tier code.
In business tier we have following entities.
Client - Presentation tier code may be JSP, servlet or UI java code.
Business Delegate - A single entry point class for client entities to provide access to Business Service methods.
LookUp Service - Lookup service object is responsible to get relative business implementation and provide business object access to business delegate object.
Business Service - Business Service interface. Concrete classes implement this business service to provide actual business implementation logic.


Real world Java examples of GoF design patterns
Abstract factory (recognizeable by creational methods returning the factory itself which in turn can be used to create another abstract/interface type)
javax.xml.parsers.DocumentBuilderFactory#newInstance()
javax.xml.transform.TransformerFactory#newInstance()
javax.xml.xpath.XPathFactory#newInstance()

Builder (recognizeable by creational methods returning the instance itself)
java.lang.StringBuilder#append() (unsynchronized)
java.lang.StringBuffer#append() (synchronized)
java.nio.ByteBuffer#put() (also on CharBuffer, ShortBuffer, IntBuffer, LongBuffer, FloatBuffer and DoubleBuffer)
javax.swing.GroupLayout.Group#addComponent()
All implementations of java.lang.Appendable

Factory method (recognizeable by creational methods returning an implementation of an abstract/interface type)
java.util.Calendar#getInstance()
java.util.ResourceBundle#getBundle()
java.text.NumberFormat#getInstance()
java.nio.charset.Charset#forName()
java.net.URLStreamHandlerFactory#createURLStreamHandler(String) (Returns singleton object per protocol)

Prototype (recognizeable by creational methods returning a different instance of itself with the same properties)
java.lang.Object#clone() (the class has to implement java.lang.Cloneable)

Singleton (recognizeable by creational methods returning the same instance (usually of itself) everytime)
java.lang.Runtime#getRuntime()
java.awt.Desktop#getDesktop()

Structural patterns

Adapter (recognizeable by creational methods taking an instance of different abstract/interface type and returning an implementation of own/another abstract/interface type which decorates/overrides the given instance)
java.util.Arrays#asList()
java.io.InputStreamReader(InputStream) (returns a Reader)
java.io.OutputStreamWriter(OutputStream) (returns a Writer)
javax.xml.bind.annotation.adapters.XmlAdapter#marshal() and #unmarshal()

Bridge (recognizeable by creational methods taking an instance of different abstract/interface type and returning an implementation of own abstract/interface type which delegates/uses the given instance)
None comes to mind yet. A fictive example would be new LinkedHashMap(LinkedHashSet<K>, List<V>) which returns an unmodifiable linked map which doesn't clone the items, but uses them. The java.util.Collections#newSetFromMap() and singletonXXX() methods however comes close.

Composite (recognizeable by behavioral methods taking an instance of same abstract/interface type into a tree structure)
java.awt.Container#add(Component) (practically all over Swing thus)
javax.faces.component.UIComponent#getChildren() (practically all over JSF UI thus)

Decorator (recognizeable by creational methods taking an instance of same abstract/interface type which adds additional behaviour)
All subclasses of java.io.InputStream, OutputStream, Reader and Writer have a constructor taking an instance of same type.
java.util.Collections, the checkedXXX(), synchronizedXXX() and unmodifiableXXX() methods.
javax.servlet.http.HttpServletRequestWrapper and HttpServletResponseWrapper

Facade (recognizeable by behavioral methods which internally uses instances of different independent abstract/interface types)
javax.faces.context.FacesContext, it internally uses among others the abstract/interface types LifeCycle, 

ViewHandler, NavigationHandler and many more without that the enduser has to worry about it (which are however overrideable by injection).
javax.faces.context.ExternalContext, which internally uses ServletContext, HttpSession, HttpServletRequest, HttpServletResponse, etc.

Flyweight (recognizeable by creational methods returning a cached instance, a bit the "multiton" idea)
java.lang.Integer#valueOf(int) (also on Boolean, Byte, Character, Short and Long)

Proxy (recognizeable by creational methods which returns an implementation of given abstract/interface type which in turn delegates/uses a different implementation of given abstract/interface type)
java.lang.reflect.Proxy
java.rmi.*, the whole API actually.

The Wikipedia example is IMHO a bit poor, lazy loading has actually completely nothing to do with the proxy pattern at all.
Behavioral patterns

Chain of responsibility (recognizeable by behavioral methods which (indirectly) invokes the same method in another implementation of same abstract/interface type in a queue)
java.util.logging.Logger#log()
javax.servlet.Filter#doFilter()

Command (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been encapsulated by the command implementation during its creation)
All implementations of java.lang.Runnable
All implementations of javax.swing.Action

Interpreter (recognizeable by behavioral methods returning a structurally different instance/type of the given instance/type; note that parsing/formatting is not part of the pattern, determining the pattern and how to apply it is)
java.util.Pattern
java.text.Normalizer
All subclasses of java.text.Format
All subclasses of javax.el.ELResolver

Iterator (recognizeable by behavioral methods sequentially returning instances of a different type from a queue)
All implementations of java.util.Iterator (thus among others also java.util.Scanner!).
All implementations of java.util.Enumeration

Mediator (recognizeable by behavioral methods taking an instance of different abstract/interface type (usually using the command pattern) which delegates/uses the given instance)
java.util.Timer (all scheduleXXX() methods)
java.util.concurrent.Executor#execute()
java.util.concurrent.ExecutorService (the invokeXXX() and submit() methods)
java.util.concurrent.ScheduledExecutorService (all scheduleXXX() methods)
java.lang.reflect.Method#invoke()

Memento (recognizeable by behavioral methods which internally changes the state of the whole instance)
java.util.Date (the setter methods do that, Date is internally represented by a long value)
All implementations of java.io.Serializable
All implementations of javax.faces.component.StateHolder

Observer (or Publish/Subscribe) (recognizeable by behavioral methods which invokes a method on an instance of another abstract/interface type, depending on own state)
java.util.Observer/java.util.Observable (rarely used in real world though)
All implementations of java.util.EventListener (practically all over Swing thus)
javax.servlet.http.HttpSessionBindingListener
javax.servlet.http.HttpSessionAttributeListener
javax.faces.event.PhaseListener

State (recognizeable by behavioral methods which changes its behaviour depending on the instance's state which can be controlled externally)
javax.faces.lifecycle.LifeCycle#execute() (controlled by FacesServlet, the behaviour is dependent on current phase (state) of JSF lifecycle)

Strategy (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been passed-in as method argument into the strategy implementation)
java.util.Comparator#compare(), executed by among others Collections#sort().
javax.servlet.http.HttpServlet, the service() and all doXXX() methods take HttpServletRequest and HttpServletResponse and the implementor has to process them (and not to get hold of them as instance variables!).
javax.servlet.Filter#doFilter()

Template method (recognizeable by behavioral methods which already have a "default" behaviour definied by an abstract type)
All non-abstract methods of java.io.InputStream, java.io.OutputStream, java.io.Reader and java.io.Writer.
All non-abstract methods of java.util.AbstractList, java.util.AbstractSet and java.util.AbstractMap.
javax.servlet.http.HttpServlet, all the doXXX() methods by default sends a HTTP 405 "Method Not Allowed" error to the response. You're free to implement none or any of them.

Visitor (recognizeable by two different abstract/interface types which has methods definied which takes each the other abstract/interface type; the one actually calls the method of the other and the other executes the desired strategy on it)
javax.lang.model.element.AnnotationValue and AnnotationValueVisitor
javax.lang.model.element.Element and ElementVisitor

javax.lang.model.type.TypeMirror and TypeVisitor

http://www.javacoderz.com/javacoderz/datastructure

Algorithm

Question : List down complexity of common data structure.
Answer

Data Structure
Time Complexity
Space Complexity

Average
Worst
Worst

Access
Search
Insertion
Deletion
Access
Search
Insertion
Deletion

O(1)
O(n)
O(n)
O(n)
O(1)
O(n)
O(n)
O(n)
O(n)
O(n)
O(n)
O(1)
O(1)
O(n)
O(n)
O(1)
O(1)
O(n)
O(n)
O(n)
O(1)
O(1)
O(n)
O(n)
O(1)
O(1)
O(n)
O(n)
O(n)
O(1)
O(1)
O(n)
O(n)
O(1)
O(1)
O(n)
O(log(n))
O(log(n))
O(log(n))
O(log(n))
O(n)
O(n)
O(n)
O(n)
O(n log(n))
O(1)
O(1)
O(1)
O(1)
O(n)
O(n)
O(n)
O(n)
O(n)
O(log(n))
O(log(n))
O(log(n))
O(log(n))
O(n)
O(n)
O(n)
O(n)
O(n)
-
O(log(n))
O(log(n))
O(log(n))
-
O(n)
O(n)
O(n)
O(n)
O(log(n))
O(log(n))
O(log(n))
O(log(n))
O(log(n))
O(log(n))
O(log(n))
O(log(n))
O(n)
O(log(n))
O(log(n))
O(log(n))
O(log(n))
O(log(n))
O(log(n))
O(log(n))
O(log(n))
O(n)
-
O(log(n))
O(log(n))
O(log(n))
-
O(log(n))
O(log(n))
O(log(n))
O(n)
O(log(n))
O(log(n))
O(log(n))
O(log(n))
O(log(n))
O(log(n))
O(log(n))
O(log(n))
O(n)

Array Sorting Algorithms
Algorithm
Time Complexity
Space Complexity

Best
Average
Worst
Worst
O(n log(n))
O(n log(n))
O(n^2)
O(log(n))
O(n log(n))
O(n log(n))
O(n log(n))
O(n)
O(n)
O(n log(n))
O(n log(n))
O(n)
O(n log(n))
O(n log(n))
O(n log(n))
O(1)
O(n)
O(n^2)
O(n^2)
O(1)
O(n)
O(n^2)
O(n^2)
O(1)
O(n^2)
O(n^2)
O(n^2)
O(1)
O(n)
O((nlog(n))^2)
O((nlog(n))^2)
O(1)
O(n+k)
O(n+k)
O(n^2)
O(n)
O(nk)
O(nk)
O(nk)
O(n+k)
Graph Operations
Node / Edge Management
Storage
Add Vertex
Add Edge
Remove Vertex
Remove Edge
Query
O(|V|+|E|)
O(1)
O(1)
O(|V| + |E|)
O(|E|)
O(|V|)
O(|V|+|E|)
O(1)
O(1)
O(|E|)
O(|E|)
O(|E|)
O(|V|^2)
O(|V|^2)
O(1)
O(|V|^2)
O(1)
O(1)
O(|V| |E|)
O(|V| |E|)
O(|V| |E|)
O(|V| |E|)
O(|V| |E|)
O(|E|)
Heap Operations
Type
Time Complexity

Heapify
Find Max
Extract Max
Increase Key
Insert
Delete
Merge

-
O(1)
O(1)
O(n)
O(n)
O(1)
O(m+n)

-
O(n)
O(n)
O(1)
O(1)
O(1)
O(1)

O(n)
O(1)
O(log(n))
O(log(n))
O(log(n))
O(log(n))
O(m+n)

-
O(1)
O(log(n))
O(log(n))
O(1)
O(log(n))
O(log(n))

-
O(1)
O(log(n))
O(1)
O(1)
O(log(n))
O(1)



Question : What is the time complexity of HashMap.containsKey() in java?
Answer
: For containsKey() is just a get() that throws away the retrieved value, it's O(1) (assuming the hash function works properly, again).
Generally O(1), but if we using bad hashCode function we need add more elements to one bucket and it can be O(n) in worst case.

Question : Compare the complexity between, HashSet vs. TreeSet vs. LinkedHashSet
Answer
: HashSet is Implemented using a hash table. Elements are not ordered. The add, remove, and contains methods have constant time complexity O(1).
TreeSet is implemented using a tree structure(red-black tree in algorithm book). The elements in a set are sorted, but the add, remove, and contains methods has time complexity of O(log (n)). It offers several methods to deal with the ordered set like first(), last(), headSet(), tailSet(), etc.
LinkedHashSet is between HashSet and TreeSet. It is implemented as a hash table with a linked list running through it, so it provides the order of insertion. The time complexity of basic methods is O(1).

Question : What is the algorithm diffrence between Collections.sort and Arrays.sort?
Answer
: Collections.sort uses merge sort  But Arrays.sort uses quick sort.

Question : Compare quick sort vs Merge Sort?
Answer : Merge sort generally performs less comparisons than quick sort both worst case and on average. If performing a comparison is costly, merge sort will definitely have the upper hand in terms of speed.
Merge sort requires more memory: As shown in the video, merge sort uses the whole upper shelf. Quick sort on the other hand puts only one ball at a time on the upper shelf.
Quick sort is generally believed to faster in common real-life settings. This is mainly due to its lower memory consumption which usually affects time performance as well.
Note that in the video both algorithms do something obviously wasteful. When merge sort merges two balls it can merge them in place, and not move them to the upper shelf and then push them back. This will save it about 2 seconds. Quick sort doesn't really need to push the buttons it pushes when a pivot is placed back (it made sense in the match against bubble sort). This will save it about 3.5 seconds. So after these improvements, quick sort will be a bit faster.

Question : What is the time complexity of the Binary Search?
Answer : Look at the below table for the data.

Class
Search algorithm
Worst case performance
O(log n)
Best case performance
O(1)
Average case performance
O(log n)
Worst case space complexity
O(1)


Question : Compare the sorting algorithm
Answer : below is the compariosn between all popular sorting algorithm.


ALGORITHM
WORSTCASE RUNNING TIME
AVERAGE RUNNING TIME
OBSERVATIONS
Bubble sort
O (n2)
O (n2)
Adjacent pairs are compared
and swapped if they are in the
wrong order.
Can be efficient for very small
and nearly sorted lists. Easy to
implement. Almost never used.
Merge sort
O (n log n)
O (n log n)
Repeatedly divides the list
into sub-lists until each list
contains just one item, then
repeatedly merges the lists to
produce a single (sorted) list.
Fast. Very commonly used.
Quick sort
O (n2)
O (n log n)
Repeatedly divides the list into
two sub-lists based on a pivot
value until all lists contain a
single value (or no values).
Sorted sub-lists are concatenated around their pivot values
to eventually form the complete, sorted list. Fast. Very
commonly used.
Heap sort
O (n log n)
O (n log n)
Creates a heap data structure
from the list, then repeatedly
extracts the largest value into
an array until all values are
removed from the heap. The
heap speeds searches while
constructing the sorted array.
Insertion sort
O (n2)
O (n2)
Iterates over a list, removing
elements and inserting them
into their sorted location in
another list. Faster than quick
sort for very small arrays.

























Comments

Popular posts from this blog

NodeJS

Question : Why You should use Node JS? Answer :  Following are the major factor influencing the use of the NodeJS Popularity : The popularity can be important factor, as it has more user base and hence solution  of any common problem faced by developer can found easily online, without any professional help. JavaScript at all levels of the stack :  A common language for frontend and backend offers several potential benefits: The same programming staff can work on both ends of the wire Code can be migrated between server and client more easily Common data formats (JSON) exist between server and client Common software tools exist for server and client Common testing or quality reporting tools for server and client When writing web applications, view templates can be used on both sides Leveraging Google's investment in V8 Engine. Leaner, asynchronous, event-driven model Microservice architecture Question : example of node JS code? Answer :  const fs = require('fs'); const uti

Kubernetes

What is Kubernetes? Kubernetes is a portable, extensible, open-source platform for managing containerized workloads and services, that facilitates both declarative configuration and automation. It has a large, rapidly growing ecosystem.  The name Kubernetes originates from Greek, meaning helmsman or pilot. Google open-sourced the Kubernetes project in 2014. Kubernetes combines over 15 years of Google’s experience running production workloads at scale with best-of-breed ideas and practices from the community. Why you need Kubernetes and what it can do? Containers are a good way to bundle and run your applications. In a production environment, you need to manage the containers that run the applications and ensure that there is no downtime. For example, if a container goes down, another container needs to start. Wouldn’t it be easier if this behavior was handled by a system? That’s how Kubernetes comes to the rescue! Kubernetes provides you with a framework to run distributed systems resi

Spring Interview Question - Version 3.5

Spring Overview Question :   What is Spring? Answer : Spring is an open source development framework for Enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make Java EE development easier to use and promote good programming practice by enabling a POJO based programming model.   Question : What are benefits of Spring Framework? Answer :   Lightweight : Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.   Inversion of control (IOC) : Loose coupling is achieved in Spring, with the Inversion of Control technique. The objects give their dependencies instead of creating or looking for dependent objects.   Aspect oriented (AOP) : Spring supports Aspect oriented programming and separates application business logic from system services.   C