April 26, 2016

Java Design Pattern Interview Questions & Answers

What are Design Patterns?
Design patterns are tried and tested way to solve particular design issues by various programmers in the world. Design patterns are extension of code reuse.

Design patterns versus frameworks
Are design patterns the same thing as frameworks? The answer to that is NO. Design patterns are more like general guidelines on how to solve specific programming problems, but they do not specify the detailed code that’s necessary to solve those problems.

Name types of Design Patterns?
  • Creational Patterns - These design patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using new opreator. This gives program more flexibility in deciding which objects need to be created for a given use case. e.g Singleton, Factory pattern.
  • Structural Patterns - These design patterns concern class and object composition. (Composition is a 'has-a' relationship e.g Room 'has-a' Chair.) Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities. Structural design patterns are concerned with how classes and objects can be composed, to form larger structures.e.g Private Class Data, Decorator etc.
  • Behavioral Patterns - These design patterns are specifically concerned with communication between objects. e.g Template Method, Visitor, Iterator, Observer etc.
What is Singleton pattern?
Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

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.

There are many classes in JDK which is implemented using Singleton pattern like : Java.lang.Runtime with getRuntime() method, Java.awt.Toolkit with getDefaultToolkit() and Java.awt.Desktop with getDesktop() etc.

How can you create Singleton class in java?
It is two step process. First, make the constructor private so that new operator cannot be used to instantiate the class. Return an object of the object if not null otherwise create the object and return the same via a method.

What are the difference between a static class and a singleton class?
a. A static class can not implement interfaces where a singleton class can.
b. All members of a static class are static but for a Singleton class it is not a requirement.
c. A static class get initialized when it is loaded so it can not be lazily loaded where a singleton class can be lazily loaded.
d. A static class object is stored in stack whereas singlton class object is stored in heap memory space.
e. We can clone the object of Singleton but, we can not clone the static class object.

Can we create a clone of a singleton object?
Yes.

How to prevent cloning of a singleton object?
Throw exception within the body of clone() method.

What is double checked locking in Singleton?
Double checked locking is a technique to prevent creating another instance of Singleton when call to getInstance() method is made in multi-threading environment.
public static Singleton getInstance(){
     if(_INSTANCE == null){
         synchronized(Singleton.class){
         //double checked locking - because second check of Singleton instance with lock
                if(_INSTANCE == null){
                    _INSTANCE = new Singleton();
                }
            }
         }
     return _INSTANCE;
}

Explain in singleton pattern whether it is better to make the whole getinstance() method synchronized or just critical section is enough? Which one is preferable?
Synchronization of whole getinstance() method is costly and is only needed during the initialization on singleton instance, to stop creating another instance of Singleton.  Therefore it is better to only synchronize critical section and not the whole method.

What is lazy and early loading of Singleton and how will you implement it?
As there are many ways to implement Singleton like using double checked locking or Singleton class with static final instance initialized during class loading. Former is called lazy loading because Singleton instance is created only when client calls getInstance() method while later is called early loading because Singleton instance is created when class is loaded into memory.

How do you prevent for creating another instance of Singleton during serialization?
You can prevent this by using readResolve() method, since during serialization readObject() is used to create instance and it return new instance every time but by using readResolve you can replace it with original Singleton instance.

ALSO READ: Serialization of Singleton class..

How many ways you can write Singleton Class in Java?
a. Singleton by synchronizing getInstance() method
b. Singleton with public static final field initialized during class loading.
c. Singleton generated by static nested class, also referred as Singleton holder pattern.
d. From Java 5 on-wards using Enums

How to create singleton class in Java using ENUM?
Though Singleton pattern in Java exists from long time Enum Singletons are relatively new concept and in practice from Java 5 onward after introduction of Enum as keyword and feature.

public enum MySingleton{
  INSTANCE; 
  public void doIt(){
    System.out.println("Singleton using Enum");
  }

}

By this way you ca create a singleton class using enum, if you want you can declare instance variable and instance method inside it. If you are using any instance method than you need to ensure thread-safety of that method if at all it affect the state of object. By default creation of Enum instance is thread safe but any other method on Enum is developers responsibility.

Whenever you want instance of singleton class, call MySingleton.INSTANCE. It is much easier than calling getInstance() method on Singleton.

Why Enum Singleton are better in Java?

1). Enum Singleton are easy to write and Enum instance is thread-safe.

#Suppose you want to implement singleton class with double checked locking, then you need to write getInstance() method as:

public MySingletonDoubleCheckedLocking getInstance(){
    if(INSTANCE == null){
        synchronized(MySingletonDoubleCheckedLocking.class){
                if(INSTANCE == null){
                    INSTANCE = new MySingletonDoubleCheckedLocking();
                }
            }
         }
     return INSTANCE;
}


#There is one more way to create a singleton class in Java, by using static factory method.In this Singleton instance is static and final variable, it is initialized when class is first loaded into memory so creation of instance is inherently thread-safe. You can call MyStaticSingleton.getSingleton() to get access of this class.

public class MyStaticSingleton{
    //initailzed during class loading
    private static final MyStaticSingleton INSTANCE = new MyStaticSingleton();

    //to prevent creating another instance of MyStaticSingleton
    private MyStaticSingleton(){}

    public static MyStaticSingleton getSingleton(){
        return INSTANCE;
    }
}


In both the above ways we need to write so many line of codes in getInstance(), but with Enum Singleton pattern we can have that in just one line because creation of Enum instance is thread-safe and guaranteed by JVM.

2). Enum Singletons handled Serialization by themselves.
If you are using conventional way to create a singleton class and implement serializable interface, then you need to take extra care because readObject() method always return a new instance just like constructor in Java. You need to add readResolve() method in the singleton class, which discards the newly created instance by replacing with Singleton. e.g:

private Object readResolve(){
    return INSTANCE;
}


This can become even more complex if your Singleton Class maintain state, as you need to make them transient, but with Enum Singleton, Serialization is guaranteed by JVM.

What are the problems with enum as singleton?
  • enums do not support lazy loading.
  • Though it’s very very rare but if you changed your mind and now want to convert your singleton to multi-ton, enum would not allow this.

Give an example scenario where you will use singleton pattern.
Assume what we are writing an application that needs to log events in a log file. Logging is done with timestamp. We do not want to have more than one instances of Logger otherwise the log file will be created with every instance. In this case, we use Singleton pattern and instantiate the logger when the first request comes or when the server is started.

Mention what is the limitation of using singleton pattern?
The singleton pattern ensures that a class has only one instance and to provide a global point of access to it. But at the same time this becomes its limitation as most classes in an application you will need to create multiple instances.

Name some of the design patterns which are used in JDK library.
# Decorator pattern is used by Wrapper classes.
# Singleton pattern is used by Runtime, Calendar classes.
# Factory pattern is used by Wrapper class like Integer.valueOf.
# Observer pattern is used by event handling frameworks like swing, awt.

What is Factory method Design Pattern?
It is one of most used design pattern in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.

The factory pattern is preferred in the following cases: A class does not know which class of objects it must create or a factory pattern can be used where we need to create an object of any one of sub-classes depending on the data provided.


Factory pattern can be used:
  • When a class does not know which class of objects needs to create
  • When class specifies its sub-classes to specify which objects to create
  • In programming language, you can use factory pattern where you have to create an object of any one of sub-classes depending on the given data.
What is the benefit of Factory pattern?
Factory pattern encapsulates the implementation details and underlying implementation can be changed without any impact on caller api.

Example of Factory Design Pattern:

Step 1).
public interface Shape {
   void draw();
}


Step 2).
public class Rectangle implements Shape {
   @Override
   public void draw() {
      System.out.println("**Inside Rectangle draw() method.");
   }
}

public class Square implements Shape {
   @Override
   public void draw() {
      System.out.println("**Inside Square draw() method.");
   }
}

public class Circle implements Shape {
   @Override
   public void draw() {
      System.out.println("**Inside Circle draw() method.");
   }
}


Step 3).
public class ShapeFactory {   
    public Shape getShape(String shapeType){
      if(shapeType == null){
         return null;
      }       
      else if(shapeType.equalsIgnoreCase("CIRCLE")){
         return new Circle();
        
      } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
         return new Rectangle();
        
      } else if(shapeType.equalsIgnoreCase("SQUARE")){
         return new Square();
      } else
      {
         return null;
      }
   }
}


Step 4).
public class FactoryPatternDemo {
   public static void main(String[] args) {
      ShapeFactory shapeFactory = new ShapeFactory();
      Shape shape1 = shapeFactory.getShape("CIRCLE");
      shape1.draw();

      Shape shape2 = shapeFactory.getShape("RECTANGLE");
      shape2.draw();
     
      Shape shape3 = shapeFactory.getShape("SQUARE");
      shape3.draw();
   }
}


Output of FactoryPatternDemo is:
**Inside Circle draw() method.
**Inside Circle draw() method.
**Inside Circle draw() method.


What is Abstract Factory pattern?
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 as this pattern provides one of the best ways to create an object. 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.

Abstract factory pattern provides abstraction one level higher than factory pattern. It encapsulates a group of individual factories.
Step 1).
public interface Shape {
   void draw();
}

Step 2).
public class Rectangle implements Shape {
   @Override
   public void draw() {
      System.out.println("**Inside Rectangle draw() method.");
   }
}

public class Square implements Shape {
   @Override
   public void draw() {
      System.out.println("**Inside Square draw() method.");
   }
}

public class Circle implements Shape {
   @Override
   public void draw() {
      System.out.println("**Inside Circle draw() method.");
   }
}

Step 3).
public interface Color {
   void fill();
}

Step 4).
public class Red implements Color {
   @Override
   public void fill() {
      System.out.println("**Inside Red fill() method.");
   }
}

public class Green implements Color {
   @Override
   public void fill() {
      System.out.println("**Inside Green fill() method.");
   }
}

public class Blue implements Color {
   @Override
   public void fill() {
      System.out.println("**Inside Blue fill() method.");
   }
}

Step 5).
public abstract class AbstractFactory {
   abstract Color getColor(String color);
   abstract Shape getShape(String shape) ;
}

Step 6).
public class ShapeFactory extends AbstractFactory{   
    public Shape getShape(String shapeType){
      if(shapeType == null){
         return null;
      }       
      else if(shapeType.equalsIgnoreCase("CIRCLE")){
         return new Circle();
        
      } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
         return new Rectangle();
        
      } else if(shapeType.equalsIgnoreCase("SQUARE")){
         return new Square();
      } else
      {
         return null;
      }
   }
}

@Override
   Color getColor(String color) {
      return null;
}

public class ColorFactory extends AbstractFactory {   
   @Override
   public Shape getShape(String shapeType){
      return null;
   }
  
   @Override
   Color getColor(String color) {  
      if(color == null){
         return null;
      }         
      else if(color.equalsIgnoreCase("RED")){
         return new Red();        
      }else if(color.equalsIgnoreCase("GREEN")){
         return new Green();        
      }else if(color.equalsIgnoreCase("BLUE")){
         return new Blue();
      } else
      {     
        return null;
      }
   }
}

Step 7).
public class FactoryProducer {
   public static AbstractFactory getFactory(String choice){
  
      if(choice.equalsIgnoreCase("SHAPE")){
         return new ShapeFactory();
        
      }else if(choice.equalsIgnoreCase("COLOR")){
         return new ColorFactory();
      }
     
      return null;
   }
}

Step 8).
public class AbstractFactoryPatternDemo {
   public static void main(String[] args) {
      AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE");
      Shape shape1 = shapeFactory.getShape("CIRCLE");
      shape1.draw();

      Shape shape2 = shapeFactory.getShape("RECTANGLE");
      shape2.draw();
      Shape shape3 = shapeFactory.getShape("SQUARE");
      shape3.draw();

      AbstractFactory colorFactory = FactoryProducer.getFactory("COLOR");
      Color color1 = colorFactory.getColor("RED");
      color1.fill();
      Color color2 = colorFactory.getColor("Green");
      color2.fill();
      Color color3 = colorFactory.getColor("BLUE");
      color3.fill();
   }
}

Output of the AbstractFactoryPatternDemo :
**Inside Circle draw() method.
**Inside Rectangle draw() method.
**Inside Square draw() method.
**Inside Red fill() method.
**Inside Green fill() method.
**Inside Blue fill() method.


What is the difference between factory design pattern and abstract factory design pattern?
Both are creational design patterns. Factory pattern is said to be there if there is method in a class that is used to create class instances. Any class can have factory methods. Using abstract factory pattern, an instance of a class is created that has only factory methods.

What is MVC pattern?
MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application's concerns.
  • The model represents the state (data) and business logic of the application.
  • The view module is responsible to display data i.e. it represents the presentation.
  • The controller module acts as an interface between view and model. It intercepts all the requests i.e. receives input and commands to Model / View to change accordingly.

What is Decorator pattern?
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.

It is used to modify the functionality of an object at runtime. At the same time other instances of the same class will not be affected by this, so individual object gets the modified behavior.  e.g Adapter Pattern, Bridge Pattern, Composite Pattern.

Decorator Design Pattern in Java API
  • java.io.BufferedReader;
  • java.io.BufferedWriter;
  • java.io.FileReader;
  • java.io.Reader; 

e.g BufferedReader decorates InputStreamReader.

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
//where 'System.in' is an InputStream object

  • InputStreamReader(InputStream in): Bridge from byte streams to character streams. InputSteamReader reads bytes and translates them into characters using the specified character encoding.
  • BufferedReader(Reader in): read text from a character stream and buffer characters in order to provide efficient reading methods(e.g., readLine())
Step 1).
public interface Shape {
   void draw();
}

Step 2).
public class Rectangle implements Shape {
   @Override
   public void draw() {
      System.out.println("Shape is Rectangle");
   }
}

public class Circle implements Shape {
   @Override
   public void draw() {
      System.out.println("Shape is Circle");
   }
}

Step 3).
public abstract class ShapeDecorator implements Shape {
   protected Shape decoratedShape;
   public ShapeDecorator(Shape decoratedShape){
      this.decoratedShape = decoratedShape;
   }
   public void draw(){
      decoratedShape.draw();
   }   
}

Step 4).
public class RedShapeDecorator extends ShapeDecorator {
   public RedShapeDecorator(Shape decoratedShape) {
      super(decoratedShape);       
   }

   @Override
   public void draw() {
      decoratedShape.draw();          
      setRedBorder(decoratedShape);
   }
   private void setRedBorder(Shape decoratedShape){
      System.out.println("Border Color is set as Red");
   }
}

Step 5).
public class DecoratorPatternDemo {
   public static void main(String[] args) {
      Shape circle = new Circle();
      Shape redCircle = new RedShapeDecorator(new Circle());
      Shape redRectangle = new RedShapeDecorator(new Rectangle());
      circle.draw();
      redCircle.draw();
      redRectangle.draw();
   }
}

Output of DecoratorPatternDemo:
Shape is Circle
Shape is Circle
Border Color is set as Red
Shape is Rectangle
Border Color is set as Red


What is Bridge pattern?
Bridge pattern comes under structural pattern as it decouples implementation class and abstract class by providing a bridge structure between them. It is used when we need to decouple an abstraction from its implementation so that the two can vary independently.

This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes independent from interface implementer classes. Both types of classes can be altered structurally without affecting each other.
 Step 1).
public interface DrawAPI {
   public void drawCircle(int radius, int x, int y);
}

Step 2).
public class RedCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle in red color with radius= " + radius + ", x= " + x + ", y=" + y );
   }
}

public class GreenCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle in green color with radius= " + radius + ", x= " + x + ", y=" + y );
   }
}

Step 3).
public abstract class Shape {
   protected DrawAPI drawAPI;
 
   protected Shape(DrawAPI drawAPI){
      this.drawAPI = drawAPI;
   }
   public abstract void draw();  
}

Step 4).
public class Circle extends Shape {
   private int x, y, radius;

   public Circle(int x, int y, int radius, DrawAPI drawAPI) {
      super(drawAPI);
      this.x = x;
      this.y = y;
      this.radius = radius;
   }

   public void draw() {
      drawAPI.drawCircle(radius,x,y);
   }
}

Step 5).
public class BridgePatternDemo {
   public static void main(String[] args) {
      Shape redCircle = new Circle(100,100, 10, new RedCircle());
      Shape greenCircle = new Circle(100,100, 10, new GreenCircle());

      redCircle.draw();
      greenCircle.draw();
   }
}

What is Adapter pattern?
Adapter pattern comes under structural pattern as this pattern combines the capability of two independent interfaces. It works as a bridge between two incompatible interfaces. This pattern involves a single class which is responsible to join functionalities of independent or incompatible interfaces. For example a card reader which acts as an adapter between memory card and a laptop. You plugin the memory card into card reader and card reader into the laptop so that memory card can be read via laptop.

What is Template pattern?
Template pattern comes under behavior pattern category. In this pattern, an abstract class exposes defined way(s) or template(s) to execute its methods. The 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.

The AbstractClass contains the templateMethod(), which should be made final so that it cannot be overridden. This template method makes use of other operations available in order to run the algorithm, but is decoupled for the actual implementation of these methods. All operations used by this template method are made abstract, so their implementation is deferred to subclasses.

The ConcreteClass implements all the operations required by the templateMethod that were defined as abstract in the parent class. There can be many different ConcreteClasses. 

Let’s understand this pattern with an example, suppose we want to provide an algorithm to build a house. The steps need to be performed to build a house are – building foundation, building pillars, building walls and windows. The important point is that the we can’t change the order of execution because we can’t build windows before building the foundation. So in this case we can create a template method that will use different methods to build the house.

Now building the foundation for a house is same for all type of houses, whether its a wooden house or a glass house. So we can provide base implementation for this, if subclasses want to override this method, they can but mostly it’s common for all the types of houses.

What is Observer design pattern in Java? When do you use Observer pattern in Java?
It falls under behavioral pattern category, as name suggest it’s used to observe things. Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically.

Object which is being observed is refereed as Subject and classes which observe subject are called Observer.

Step 1).
public abstract class Observer {
   protected Subject subject;
   public abstract void update();
}

Step 2).
import java.util.ArrayList;
import java.util.List;
public class Subject {   
   private List observers = new ArrayList();
   private int state;

   public int getState() {
      return state;
   }

   public void setState(int state) {
      this.state = state;
      notifyAllObservers();
   }

   public void attach(Observer observer){
      observers.add(observer);       
   }

   public void notifyAllObservers(){
      for (Observer observer : observers) {
         observer.update();
      }
   }    
}

Step 3). Create concrete observer classes
public class BinaryObserver extends Observer{

   public BinaryObserver(Subject subject){
      this.subject = subject;
      this.subject.attach(this);
   }

   @Override
   public void update() {
      System.out.println( "Binary String= " + Integer.toBinaryString(subject.getState() ) );
   }
}

public class HexaObserver extends Observer{

   public HexaObserver(Subject subject){
      this.subject = subject;
      this.subject.attach(this);
   }

   @Override
   public void update() {
      System.out.println( "Hex String= " + Integer.toHexString( subject.getState() ).toUpperCase() );
   }
}

public class OctalObserver extends Observer{

   public OctalObserver(Subject subject){
      this.subject = subject;
      this.subject.attach(this);
   }

   @Override
   public void update() {
     System.out.println( "Octal String= " + Integer.toOctalString( subject.getState() ) );
   }
}

Step 4).
public class ObserverPatternDemo {
   public static void main(String[] args) {
      Subject subject = new Subject();

      new HexaObserver(subject);
      new OctalObserver(subject);
      new BinaryObserver(subject);

      System.out.println("First state change= 15");   
      subject.setState(15);
      System.out.println("Second state change= 10");   
      subject.setState(10);
   }
}

Output of ObserverPatternDemo:
First state change= 15
Hex String= F
Octal String= 17
Binary String= 1111
Second state change= 10
Hex String= A
Octal String= 12
Binary String= 1010


Builder Design Pattern comes under creational pattern, it builds a complex object using simple objects and using a step by step approach. A Builder class builds the final object step by step. This builder is independent of other objects.

Constructors in Java are used to create object and can take parameters required to create object. Problem starts when we create a complex Object from constructor with lot of parameters, some of them may be mandatory and others may be optional.

Consider a class which is used to create Pizza, now you need number of item like crust, cheeze, sauces, toppings to create Pizza. Many of them are mandatory and some of them are optional like green olives or spinach alfredo sauce etc. If we are going to have overloaded constructor for different kind of Pizza then there will be many constructor and even worst they will accept many parameter.

So the problem is that:
1. There will be too many constructors to maintain.
2. It will error prone because many fields has same type e.g. two types of sauce in different quantity (you might put wrong quantity of sauce abd compiler will not complain since the 'type' is same).

You can partially solve this problem by creating Pizza and then adding ingredients later, but that will impose another problem of leaving Object on inconsistent state during building, ideally Pizza should not be available until its created.

These problems can be solved by using Builder design pattern in Java. Builder design pattern not only improves readability but also reduces chance of error by adding ingredients explicitly and making object available once fully constructed.

public class Pizza {
    private final int spinachAlfredoSauce, ranchSauce;
    private final double cheese, pizzacrust;
    private final double bananaPeppersToppings, ripeOlivesToppings, greenOlivesToppings;
   
    public Pizza(Builder builder) {
        this.spinachAlfredoSauce = builder.spinachAlfredoSauce;
        this.ranchSauce = builder.ranchSauce;
        this.cheese = builder.cheese;
        this.pizzacrust = builder.pizzacrust;
        this.bananaPeppersToppings = builder.bananaPeppersToppings;
        this.ripeOlivesToppings = builder.ripeOlivesToppings;
        this.greenOlivesToppings = builder.greenOlivesToppings;
    }

    @Override
    public String toString() {
        return "Pizza [spinachAlfredoSauce=" + spinachAlfredoSauce
                + ", ranchSauce=" + ranchSauce + ", cheese=" + cheese
                + ", pizzacrust=" + pizzacrust + ", bananaPeppersToppings="
                + bananaPeppersToppings + ", ripeOlivesToppings="
                + ripeOlivesToppings + ", greenOlivesToppings="
                + greenOlivesToppings + "]";
    }

    public static class Builder
    {
        private int spinachAlfredoSauce, ranchSauce;
        private double cheese, pizzacrust;
        private double bananaPeppersToppings, ripeOlivesToppings, greenOlivesToppings;
       
        public Builder spinachAlfredoSauce(int spinachAlfredoSauce) {
            this.spinachAlfredoSauce = spinachAlfredoSauce;
            return this;
        }
        public Builder ranchSauce(int ranchSauce) {
            this.ranchSauce = ranchSauce;
            return this;
        }
        public Builder cheese(double cheese) {
            this.cheese = cheese;
            return this;
        }
        public Builder pizzacrust(double pizzacrust) {
            this.pizzacrust = pizzacrust;
            return this;
        }
        public Builder bananaPeppersToppings(double bananaPeppersToppings) {
            this.bananaPeppersToppings = bananaPeppersToppings;
            return this;
        }
        public Builder ripeOlivesToppings(double ripeOlivesToppings) {
            this.ripeOlivesToppings = ripeOlivesToppings;
            return this;
        }
        public Builder greenOlivesToppings(double greenOlivesToppings) {
            this.greenOlivesToppings = greenOlivesToppings;
            return this;
        }
       
        public Pizza build() {
            return new Pizza(this);
        }       
    }
   
    public static void main(String args[]) {        
        Pizza pizza=new Pizza.Builder().pizzacrust(3.5).cheese(2.5).greenOlivesToppings(.7).build();
         System.out.println(pizza);
    }
}

Disadvantages of Builder Design pattern
is verbose and code duplication as Builder needs to copy all fields from Original or Item class.

Advantages
of Builder Design pattern are:
1). more maintainable if number of fields required to create object is more than 4 or 5.
2). less error-prone as user will know what they are passing because of explicit method call.
3). more robust as only fully constructed object will be available to client.
 


A class instance can be created using new operator. Why should we use creational design patterns to create objects?
Using new operator to create objects is a valid approach but it's like hard coding the object type. If we are 100% sure that our object will be of the same class all the time, then we use new operator to create an object. In scenarios where the nature of the object can change according to the nature of the program, we use creational design patterns which offer flexible approach for creating class instances

Which design pattern is used to get a way to access the elements of a collection object in sequential manner?
Iterator pattern is used to get a way to access the elements of a collection object in sequential manner.

When service locator pattern is used?
When we want to locate various services using JNDI we use service locator pattern.

Mention which design pattern will be helpful to add new functionality to an existing object?
A decorator pattern allows a user to add new functionality to an existing object without changing its structure.

Mention which pattern is useful when one has to pass data with multiple attributes in one shot from client to server?

Transfer Object Pattern is useful when one has to pass data with multiple attributes in one shot from client to the server.

What is SOLID principle in Java?
1). Single Responsibility Principle : One class should have one and only one responsibility. We should write, change and maintain a class for only one purpose.
2). Open Closed Principle : Software components should be open for extension, but closed for modification. It means that your classes should be designed such a way that whenever fellow developers wants to change the flow of control in specific conditions in application, all they need to extend your class and override some functions and that’s it. If other developers are not able to design desired behavior due to constraints put by your class, then you should reconsider changing your class.
3). Liskov’s Substitution Principle : Derived types must be completely substitutable for their base types. It means that the classes fellow developer created by extending your class should be able to fit in application without failure. i.e. if a fellow developer poorly extended some part of your class and injected into framework/ application then it should not break the application or should not throw fatal exceptions.
4). Interface Segregation Principle : It is applicable to interfaces as single responsibility principle holds to classes. Clients should not be forced to implement unnecessary methods which they will not use. e.g: If you created an interface Reportable and added two methods generateExcel() and generatedPdf(). Now another developer wants to use this interface but he intend to use reports only in PDF format and not in excel. He will have to implement two methods, out of which one is extra burden put on him by designer of software. Either he will implement another method or leave it blank. Which is wrong. Instead of one interface, we should create two interfaces by breaking the existing one. They should be like PdfReportable and ExcelReportable. This will give the flexibility to user to use only required functionality only.
5). Dependency Inversion Principle : Depend on abstractions, not on concretions. We should design our software in such a way that various modules can be separated from each other using an abstract layer to bind them together.

-K Himaanshu Shuklaa..

April 25, 2016

Serialization Interview Questions and Answers for Experienced Developers

What is Serialization in Java?
Serialization is a process by which you can save or transfer the state of an object by converting it to a byte stream.

During Serialization, the Object is converted into a binary format ,which can be persisted into disk or sent over network to any other running Java virtual machine. During deserialization the reverse process is performed by creating object from binary stream.

April 24, 2016

JDBC Interview Questions And Answers

What is JDBC?
JDBC (Java Database Connectivity) is a Java API that is used to connect and execute query to the database. JDBC API uses jdbc drivers to connects to the database.

What are the common JDBC API components?
JDBC API consists of following interfaces and classes DriverManager, Driver, Connection, Statement, ResultSet, SQLException.

What is a JDBC DriverManager?
JDBC DriverManager is a class that manages a list of database drivers. It matches connection requests from the java application with the proper database driver using communication subprotocol.

What is a JDBC Driver?
JDBC driver is an interface enabling a Java application to interact with a database. To connect with individual databases, JDBC requires drivers for each database. The JDBC driver gives out the connection to the database and implements the protocol for transferring the query and result between client and database.

What is a connection?

Connection interface consists of methods for contacting a database. The connection object represents communication context.

What is a statement?
Statement encapsulates an SQL statement, which is passed to the database to be parsed, compiled, planned and executed.

What is a ResultSet?
These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data. The java.sql.ResultSet interface represents the result set of a database query.

What are types of ResultSet?
There are three constants which when defined in result set can move cursor in resultset backward, forward and also in a particular row.
  • ResultSet.TYPE_FORWARD_ONLY − The cursor can only move forward in the result set.
  • ResultSet.TYPE_SCROLL_INSENSITIVE − The cursor can scroll forwards and backwards, and the result set is not sensitive to changes made by others to the database that occur after the result set was created.
  • ResultSet.TYPE_SCROLL_SENSITIVE − The cursor can scroll forwards and backwards, and the result set is sensitive to changes made by others to the database that occur after the result set was created.
What are the main steps in java to make JDBC connectivity?

1. Register or Load the JDBC driver: Class.forName() is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.
Class.forName("com.mysql.jdbc.Driver");


2. Make connection
String url = "jdbc:oracle:thin:@localhost:1632:DEVROOT32";
Properties props = new Properties();
props.setProperty("user", "scott");
props.setProperty("password", "tiger");
Connection conn = DriverManager.getConnection(url,props);


3. Get Statement object: From connection object we can get statement object which is used to query the database
String sql ="select sysdate as current_day from dual";
PreparedStatement preStatement = conn.prepareStatement(sql);



4.  Execute the Query:Using statement object we execute the SQL or database query and get result set from the query.
ResultSet result = preStatement.executeQuery();

5. Close the connection

What are JDBC driver types?
There are four types of JDBC drivers
  • JDBC-ODBC Bridge plus ODBC driver − also called Type 1 calls native code of the locally available ODBC driver.
  • Native-API, partly Java driver − also called Type 2 calls database vendor native library on a client side. This code then talks to database over network.
  • JDBC-Net, pure Java driver − also called Type 3 the pure-java driver that talks with the server-side middleware that then talks to database.
  • Native-protocol, pure Java driver − also called Type 4 the pure-java driver that uses database native protocol.
What are different types of Statement?
There are three types of statement:
1. Statement: It’s a commonly used for getting data from database useful when we are using static SQL statement at runtime and it will not accept any parameter.
Statement stmt = conn.createStatement(sqlquery);
ResultSet rs = stmt.executeQuery();

2. PreparedStatement: When we are using same SQL statement multiple time its is useful and it will accept parameter at runtime.
String SQL = "select * from student WHERE student_id = ?";
PreparedStatement  pstmt = conn.prepareStatement(SQL);
ResultSet rs = pstmt.executeQuery();

3. Callable Statement: When we want to access stored procedures then callable statement are useful and they also accept runtime parameter. It is called like this
CallableStatement cs = con.prepareCall("{call calculate_annualincome}");
ResultSet rs = cs.executeQuery();

What is the difference between Statement and PreparedStatement interface?
In case of Statement, query is complied each time whereas in case of PreparedStatement, query is complied only once. So performance of PreparedStatement is better than Statement.

What is connection Pooling?
It is the mechanism by which we reuse the recourse like connection objects  which are needed to make connection with database. In this mechanism client are not required every time make new connection and then interact with database instead of that connection objects are stored in connection pool and client will get it from there. so it’s a best way to share a server resources among the client and enhance the application performance.

What does the Class.forName("MyClass") do?
  • Loads the class MyClass.
  • Execute any static block code of MyClass.
  • Returns an instance of MyClass.
What are the differences between setMaxRows(int) and SetFetchSize(int)?
setFetchSize(int) defines the number of rows that will be read from the database when the ResultSet needs more rows. setFetchSize(int) affects how the database returns the ResultSet data.

setMaxRows(int)
method of the ResultSet specifies how many rows a ResultSet can contain at a time. setMaxRows(int) affects the client side JDBC object.

How  do you prevent SQL Injection in Java Code?
In SQL Injection attack, malicious user pass SQL meta-data combined with input which allowed them to execute sql query of there choice.

PreparedStatement can be used to avoid SQL injection in Java code. Use of the PreparedStatement for executing SQL queries not only provides better performance but also shield your Java and J2EE application from SQL Injection attack. All the parameters passed as part of place-holder will be escaped automatically by JDBC Driver.

-K Himaanshu Shuklaa..

April 22, 2016

Madhuri shoots barefoot for the opening act of So You Think You Can Dance..

Everyone is aware of Madhuri’s love for dance. She believes that dance is an art and she has carved her niche in it. Madhuri Dixit who will be soon seen as the judge on &TV’s latest offering ‘So You Think You Can Dance - Ab India Ki Bari’ has done something phenomenal for the show. Read on to know more!

Tiger Shroff joins &TV’s 'So You Think You Can Dance'..


The new Baaghi in town, Tiger Shroff dropped by on the sets of &TV’s upcoming dance reality show SO YOU THINK YOU CAN DANCE. The actor showed off his cool dance moves and impressed everyone with his ‘Street’ style of dancing.

April 21, 2016

BARC Ratings (Impressions)- Week 15, 2016

  
In week 15 (9-15 April, 2016) of the BARC Ratings, Star Plus continued to be the most watched Hindi GEC. Colors remained at No.2 followed by Zee TV at No.3. Life OK took a leap to the fourth spot from seventh in week 14. Sony Pal remained at No.5.

April 15, 2016

Difference between Stack vs Heap in Java

1). Heap memory is used by java runtime to allocate memory to Objects and JRE classes. Whenever we create any object, it’s always created in the Heap space. Garbage Collection runs on the heap memory to free the memory used by objects that doesn’t have any reference. Any object created in the heap space has global access and can be referenced from anywhere of the application.

Java Stack memory is used for execution of a thread. They contain method specific values that are short-lived and references to other objects in the heap that are getting referred from the method. Stack memory is always referenced in LIFO (Last-In-First-Out) order. Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method. As soon as method ends, the block becomes unused and become available for next method.

A Fairy Tale Visit To Neuschwanstein Castle!!

Neuschwanstein Castle has been on my bucket list for ages because of its mesmerizing aura, breathtaking views and incredible artworks. That's why for me this visit was very, very thrilling. The kind of excitement where I let out little screams in complete anticipation.😻

April 13, 2016

All About jQuery..

What is jQuery?
Its a'lightweight' javascript library. With jQuery we, 'write less, and do more'.  jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation. jQuery run exactly the same in all major browsers, including Internet Explorer 6.

The jQuery library contains the following features:
# HTML/DOM manipulation
# CSS manipulation
# HTML event methods
# Effects and animations
# AJAX
# Utilities

Download jquery-1.12.2.min.js from jQuery.com, add the .js in your page. e.g


< head>
< script src="jquery-1.12.2.min.js">< /script>
< /head>
NOTE: type="text/javascript" is not added inside the < script>

jQuery CDN : If you don't want to download and host jQuery yourself, you can include it from a CDN (Content Delivery Network). Both Google and Microsoft host jQuery.

Google CDN:
< head>
< script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">< /script>
< /head>

Microsoft CDN:
< head>
< script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.2.min.js">< /script>
< /head>


jQuery Syntax
Basic syntax is: $(selector).action()
$ sign to define/access jQuery
(selector) to "query (or find)" HTML elements
jQuery action() to be performed on the element(s)

e.g:
$(this).hide() : hides the current element.
$("p").hide() : hides all elements.
$(".test").hide() : hides all elements with class="test".
$("#test").hide() : hides the element with id="test".

Document Ready Event
All jQuery methods are written inside a document ready event to prevent any jQuery code from running before the document is finished loading (is ready). Else, the method might fail, e.g:
  •     Trying to hide an element that is not created yet
  •     Trying to get the size of an image that is not loaded yet
$(document).ready(function(){
   // jQuery methods go here...
}); 


or use the shorter version

$(function(){
   // jQuery methods go here...
}); 


jQuery Selectors allow you to select and manipulate HTML element(s).

HTML elements are "find" (or select) based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.

All selectors in jQuery start with the dollar sign and parentheses: $().

The element Selector selects elements based on the element name.

You can select all elements on a page like this:
$("p")

e.g: This will hide paragraphs when button is click

< html >
< head>
< script language="javascript" src="javascript/jquery-1.12.4.min.js">< /script>
< script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").hide();
    });
});
< /script>
< /head>
< body>
< h2>Hide The Para..< /h2>
< p>First paragraph.< /p>
< p>Second paragraph.< /p>
< button>Click me to hide paragraphs< /button>
< /body>
< /html >


The #id Selector
uses the id attribute of an HTML tag to find the specific element.
An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
To find an element with a specific id, write a hash character, followed by the id of the HTML element:
$("#test")

e.g. This will hide 'Second Para' with 'id=test' when button is click

< html>
< head>
< script language="javascript" src="javascript/jquery-1.12.4.min.js">< /script>
< script>
$(document).ready(function(){
    $("button").click(function(){
        $("#test").hide();
    });
});
< /script>
< /head>
< body>
< h2>Hide The Para..< /h2>
< p>First paragraph.< /p>
< p id="test">Second paragraph.< /p>
< button>Click me to hide paragraphs< /button>
< /body>
< /html>


The .class Selector finds elements with a specific class.
To find elements with a specific class, write a period character, followed by the name of the class:
$(".testclass")

e.g:This will hide the para with 'class=testclass' when button is click
< html>
< head>
< script language="javascript" src="javascript/jquery-1.12.4.min.js">< /script>
< script>
$(document).ready(function(){
    $("button").click(function(){
        $(".testclass").hide();
    });
});
< /script>
< /head>
< body>
< h2>Hide The Para..< /h2>
< p>First paragraph.< /p>
< p class="testclass">Second paragraph.< /p>
< button>Click me to hide paragraphs< /button>
< / body>
< /html>


A few examples of jQuery Selectors
  • $("*")     Selects all elements    
  • $(this)     Selects the current HTML element    
  • $("p.intro")     Selects all < p> elements with class="intro"    
  • $("p:first")     Selects the first < p> element    
  • $("ul li:first")     Selects the first < li> element of the first < ul>    
  • $("ul li:first-child")     Selects the first
  • element of every < ul>    
  • $("[href]")     Selects all elements with an href attribute    
  • $("a[target='_blank']")     Selects all < a> elements with a target attribute value equal to "_blank"    
  • $("a[target!='_blank']")     Selects all < a> elements with a target attribute value NOT equal to "_blank"    
  • $(":button")     Selects all < button> elements and < input> elements of type="button"    
  • $("tr:even")     Selects all even < tr> elements    
  • $("tr:odd")     Selects all odd < tr> elements 
JQuery Interview Questions
 
Whether jQuery HTML work for both HTML and XML documents?
jQuery HTML only works for HTML documents not for XML Documents.

Where jQuery code is getting executed?
jQuery code is getting executed on a client browser.

Which command will give a version of jQuery?
The command $.ui.version returns jQuery UI version.

What is the difference between size and length of jQuery?
Size and length both returns the number of element in an object. But length is faster than the size because length is a property and size is a method.

Can we add more than one ‘document.ready’ function in a page?
Yes, we can add more than one document.ready function in a page. But, body.onload can be added once in a page.

What is the difference between onload() and document.ready()?
In a page, we can have only one onload function but we can have more than one document.ready function. Document.ready function is called when DOM is loaded but onload function is called when DOM and images are loaded on the page.

What is the use of jQuery load method?
jQuery load method is a powerful AJAX method which is used to load the data from a server and assign the data into the element without loading the page.

Which sign is used as a shortcut for jQuery?

Dollar ($) sign is used as a shortcut for jQuery.

Whether our own specific characters are used in place of $ in jQuery?
Yes, We can use our own variable in place of $ by using the method called no Conflict () method.
var sample = $.noConflict()

Is jQuery is a client or server scripting?
jQuery is a client scripting.

Is jQuery is a replacement of JavaScript?

No.

Why jQuery is better than JavaScript?
jQuery is a library used for developing Ajax application and it helps to write the code clean and concise. It also handles events, animation and Ajax support applications.

What are the advantages of jQuery?
  • Just a JavaScript enhancement
  • Coding is simple, clear, reusable
  • Removal of writing more complex conditions and loops
What is the use of jQuery each function?
It is used to loop through each and every element of the target jQuery object. It is also useful for multi element DOM, looping arrays and object properties.

Which is the fastest selector in jQuery?
ID and Element are the fastest selectors in jQuery.

What is the slowest selector in jQuery?
Class selectors are the slowest selectors in jQuery.

-K Himaanshu Shuklaa..
 

April 07, 2016

Java Reflection API Interview Questions and Answers..

What is Reflection?
Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection. That means with reflection, we can examine or modify the runtime behavior of applications running in the Java virtual machine.

Reflection API usage can break the design pattern such as Singleton pattern by invoking the private constructor i.e violating the rules of access modifiers.

Difference between Introspection and Reflection?
Introspection is the ability of a program to examine the type or properties of an object at runtime. Where as, Reflection is the ability of a program to examine and modify the structure and behavior of an object at runtime.

Introspection is a subset of reflection. Some of the languages support introspection, but do not support reflection, e.g., C++.

Introspection Example:
The instanceof operator determines whether an object belongs to a particular class.
if(obj instanceof Account){
   Account acc = (Account)obj;
   acc.getBalance();
}


Reflection Example:
The Class.forName() method returns the Class object associated with the class/interface with the given name(a string and full qualified name). The forName method causes the class with the name to be initialized.

Class c = Class.forName("classpath.classname");
Object acc = c.newInstance();
Method m = c.getDeclaredMethod("getBalance", new Class[0]);
m.invoke(acc);


Why do we need Reflection?
  • Examine an object's class at runtime
  • Construct an object for a class at runtime
  • Examine a class's field and method at runtime
  • Invoke any method of an object at runtime
  • Change accessibility flag of Constructor, Method and Field  etc.
Commonly used methods of Class class:
1) public String getName(): returns the class name
2) public static Class forName(String className)throws ClassNotFoundException: loads the class and returns the reference of Class class.
3) public Object newInstance()throws InstantiationException,IllegalAccessException: creates new instance.
4) public boolean isInterface(): checks if it is interface.
5) public boolean isArray(): checks if it is array.
6) public boolean isPrimitive(): checks if it is primitive.
7) public Class getSuperclass(): returns the superclass class reference.
8) public Field[] getDeclaredFields()throws SecurityException: returns the total number of fields of this class.
9) public Method[] getDeclaredMethods()throws SecurityException: returns the total number of methods of this class.
10) public Constructor[] getDeclaredConstructors()throws SecurityException: returns the total number of constructors of this class.
11) public Method getDeclaredMethod(String name,Class[] parameterTypes)throws NoSuchMethodException,SecurityException: returns the method class instance.

How to use reflection?
Lets define a Printer class.
package mytest;
 class Printer {
    public void print() {
        System.out.println("printing..");
    }
}



Get class name from object
package mytest;
import java.lang.reflect.Method;
public class ReflectionHelloWorld {
    public static void main(String[] args){
        Printer p = new Printer();
        System.out.println("PackageName.ClassName is " + p.getClass().getName());           
    }
}


Invoke method on unknown object: By using reflection, the code can use the object and find out if the object has a method called "print" and then call it.
package mytest;
import java.lang.reflect.Method;
public class ReflectionHelloWorld {
    public static void main(String[] args){
        Printer p = new Printer();

        Method method;
        try {
            method = p.getClass().getMethod("print", new Class[0]);
            method.invoke(p); //this will call print() method
        } catch (Exception e) {
            e.printStackTrace();
        }          
    }
}


Create object from Class instanceThere are 3 ways to get the instance of Class class. They are as follows:
1. forName() method of Class class
2. getClass() method of Object class
3. the .class syntax

package mytest;
public class ReflectionHelloWorld {
    public static void main(String[] args){      
        Class c = null; //create instance of "Class"
        try{
            c=Class.forName("mytest.Printer");
        }catch(Exception e){
            e.printStackTrace();
        }
        Printer p = null;
        try {
            p = (Printer) c.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        p.print();
    }
}


Get constructor and create instance:
Lets define a constructor in Printer class.
package mytest;
 class Printer {
    String name;
    public Printer(){}

    public Printer(String name){
        this.name=name;
    }
    public void print() {
        System.out.println("printing.."+ name);
    }
}

package mytest;
import java.lang.reflect.Constructor;
public class ReflectionHelloWorld {
    public static void main(String[] args){
        Class c = null;
        try{
            c=Class.forName("mytest.Printer");
        }catch(Exception e){
            e.printStackTrace();
        }

        Printer p1 = null;
        Printer p2 = null;

        //it will return all constructors
        Constructor cons[] = c.getConstructors();
        try {
            p1 = (Printer) cons[0].newInstance();
            p2 = (Printer) cons[1].newInstance("testprinter");
        } catch (Exception e) {
            e.printStackTrace();
        }
        p1.print();
        p2.print();
    }
}
Output will be
printing..null
printing..testprinter

Can we access private field and method using Reflection?
Yes we can. Private fields and methods are only accessible in the class they are declared but with reflection you can call private method and access private fields outside the class (which is not possible by any other means in Java).

How to access private fields in Java using Reflection?
In order to access private field using reflection, you need to know the name of field than by calling getDeclaredFields(String name) you will get a java.lang.reflect.Field instance representing that field.

Remember: Use getDeclaredFields() method and not getFields() because the later returns all non private fields both from sub class and super class. While getDeclaredFields() returns both private and non private fields declared in the class.

Once you get the field reference you need to make it accessible by calling Field.setAccessible(true) because you are going to access private field. Now you can get value or private field by calling Field.get(String field_name). If you don't call setAccessible(true) and try to access the private field using reflection you will get below Exception:

java.lang.IllegalAccessException: Class test.ReflectionTest can not access a member of class test.Person with modifiers "private"

How to call private methods in Java using Reflection?
As we have mentioned above (in 'Invoke method on unknown object' section) that we can call a method by its String name and then using the invoke() method. In similar way we can invoke the private methods.

Use getDeclaredMethods(String name, Class.. parameter) to get declared private method. Pass all the argument type needed by method or nothing if method doesn't accept any argument. This will give you instance of java.lang.reflect.Method which can than be used to call private method using reflection, as shown in below example:

Make changes in Printer class:
package mytest;
class Printer {
    private String name;
    public String printerid;
    public Printer(){}
      public Printer(String name, String printerid){
        this.name=name;
        this.printerid=printerid;
    }
    private void print() {
        System.out.println("printing.."+ name);
    }
}

package mytest;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ReflectionTest {

    public static void main(String args[]) throws ClassNotFoundException {    
        Class printer = (Class) Class.forName("mytest.Printer");
    
        System.out.println("Private Fields: " + Arrays.toString(printer.getFields()));
        System.out.println("All Fields : " + Arrays.toString(printer.getDeclaredFields()));     
        System.out.println("Declared methods : " + Arrays.toString(printer.getDeclaredMethods()));
    
        try {        
            //accessing value of private field
            Printer privatePrint = new Printer("PrinterOne" , "1");
            Field privateField = printer.getDeclaredField("name");
            privateField.setAccessible(true);
            String value = (String) privateField.get(privatePrint);
            System.out.println("Private field: " + privateField + ", value: " + value);        
        
            //accessing private method using reflection
            Method privateMethod = printer.getDeclaredMethod("print");
            privateMethod.setAccessible(true);
            privateMethod.invoke(privatePrint);
        }
        catch (InvocationTargetException ex) {}
        catch (NoSuchMethodException ex) {}
        catch (IllegalArgumentException ex) {}
        catch (IllegalAccessException ex) {}
        catch (NoSuchFieldException ex) {}
        catch (SecurityException ex) {}
    }
}


What are some practical uses of Java reflection?
One of the more common uses of Java reflection is with JUnit, which is a popular unit testing framework for Java. One commonly used feature of JUnit uses annotations to mark certain methods as test methods that which are meant to help you test your Java code. Then, when you actually decide to run your unit tests, JUnit will look for the methods which you marked with the “@Test” annotation, and will execute those methods.

-K Himaanshu Shuklaa...

April 06, 2016

Java Interview Questions

What is Association, Aggregation and Composition?
Association is a relationship between two separate classes which can be of any type say one to one, one to may etc. It joins two entirely separate entities.

Aggregation is a special form of association which is a unidirectional one way relationship between classes (or entities), for e.g. Wallet and Money classes. Wallet has Money but money doesn’t need to have Wallet necessarily so its a one directional relationship. In this relationship both the entries can survive if other one ends. In our example if Wallet class is not present, it does not mean that the Money class cannot exist.

Composition is a restricted form of Aggregation in which two entities (or you can say classes) are highly dependent on each other. For e.g. Human and Heart. A human needs heart to live and a heart needs a Human body to survive. In other words when the classes (entities) are dependent on each other and their life span are same (if one dies then another one too) then its a composition. Heart class has no sense if Human class is not present.

April 02, 2016

All About Agile!!

What is Agile?
In traditional software development methodologies like Waterfall model, a project can take several months or years to complete and the customer may not get to see the end product until the completion of the project.

A non-Agile projects allocate extensive periods of time for Requirements gathering, design, development, testing and UAT, before finally deploying the project.

In contrast to this, Agile projects have Sprints or iterations which are shorter in duration (Sprints/iterations can vary from 2 weeks to 2 months) during which pre-determined features are developed and delivered. 

We can say that, Agile is a time boxed, iterative approach to software delivery that builds software incrementally from the start of the project (incremental delivery), instead of trying to deliver it all at once near the end.

What is User Story?
User stories are short, simple descriptions of a feature told from the perspective of the person who desires the new capability, usually a user or customer of the system.

April 01, 2016

Java Collections Interview Questions and Answers

JDK 1.2 introduces a new framework for collections of objects, called the Java Collections Framework.

What are Collections?
A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.

Why we need Collections when we have Array?
  • Arrays are immutable, once defined you cannot increase the size of an Array.
  • Array are not really thread-safe.
What is the difference between Collection and Collections?
Both are part of java collection framework, but both serve different purpose. Collection is a top level interface of java collection framework where as Collections is an utility class.

Collection interface is a member of java.util package and List, Set and Queue are main sub interfaces of this interface. JDK doesn’t provide any direct implementations of this interface. But, JDK provides direct implementations of it’s sub interfaces. ArrayList, Vector, HashSet, LinkedHashSet, PriorityQueue are some indirect implementations of Collection interface. Map interface, which is also a part of java collection framework, doesn’t inherit from Collection interface.

Collections is an utility class in java.util package. It consists of only static methods which are used to operate on objects of type Collection. e.g
  • Collections.max() : - This method returns maximum element in the specified collection.
  • Collections.min() : - This method returns minimum element in the given collection.
  • Collections.sort() : - This method sorts the specified collection.
  • Collections.shuffle() : - This method randomly shuffles the elements in the specified collection.
  • Collections.synchronizedCollection() : - This method returns synchronized collection backed by the specified collection.
  • Collections.binarySearch() : - This method searches the specified collection for the specified object using binary search algorithm.
  • Collections.disjoint() : - This method returns true if two specified collections have no elements in common.
  • Collections.copy() : - This method copies all elements from one collection to another collection.
  • Collections.reverse() : - This method reverses the order of elements in the specified collection.

Difference between CountDownLatch & CyclicBarrier in Java

The main difference between CountDownLatch & CyclicBarrier is that you can not re-use CountDownLatch once count reaches to zero, but you can reuse same CyclicBarrier even after barrier is broken. Let's first understand what exactly CountDownLatch & CyclicBarrier does..

CountDownLatch is a kind of synchronizer which allows one Thread to wait for one or more Threads before starts processing. This is very crucial requirement and often needed in server side core Java application and having this functionality built-in as CountDownLatch greatly simplifies the development.

CountDownLatch is introduced on Java 5 along with other concurrent utilities like CyclicBarrier, Semaphore, ConcurrentHashMap and BlockingQueue in java.util.concurrent package.

We can also implement same functionality using wait and notify mechanism in Java, but it requires lot of code and getting it write in first attempt is tricky, With CountDownLatch it can  be done in just few lines. It also allows flexibility on number of thread for which main thread should wait and it can wait for one thread or n number of thread, there is not much change on code.

Points to remember:
* Use CountDownLatch when one of Thread like main thread, require to wait for one or more thread to complete, before its start doing processing.
* You can not reuse CountDownLatch once count is reaches to zero, this is the main difference between CountDownLatch and CyclicBarrier,
* Main Thread wait on Latch by calling CountDownLatch.await() method while other thread calls CountDownLatch.countDown() to inform that they have completed.

Example:
1). Create a thread class Service, which implements Runnable:

package com.test.thread;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Service implements Runnable{
    private final String serviceName;
    private final int timeToStart;
    private final CountDownLatch latch;
 
    public Service(String serviceName, int timeToStart, CountDownLatch latch){
        this.serviceName = serviceName;
        this.timeToStart = timeToStart;
        this.latch = latch;
    }
 
    @Override
    public void run() {
        try {
            Thread.sleep(timeToStart);
        } catch (InterruptedException ex) {
            Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println( serviceName + " is now UP");
        latch.countDown(); //reduce count of CountDownLatch by 1
    } 
}

2).  Create another class with Main method:

package com.test.thread;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
    public static void main(String args[]) {
       //count is 4 since we have 4 Threads (Services)  
       final CountDownLatch latch = new CountDownLatch(4);
       Thread service1 = new Thread(new Service("service1", 1000, latch));
       Thread service2 = new Thread(new Service("service2", 1000, latch));
       Thread service3 = new Thread(new Service("service3", 1000, latch));
       Thread service4 = new Thread(new Service("service4", 1000, latch));
       service1.start();
       service2.start();
       service3.start();
       service4.start();
       /*
       If we have a requirement that an Application should not start processing any thread until all service is up
       & ready to do there job. We can use CountdownLatch, in this example the main thread will start with count 4
       and wait until count reaches zero. Each thread once up and read will do a count down.
       This will ensure that main thread is not started processing until all services is up.
       */        
       try{
            latch.await();  //main thread is waiting on CountDownLatch to finish
            System.out.println("All services are up..Application is starting now!!");
       }catch(InterruptedException ie){
           ie.printStackTrace();
       }     
    } 
}

3).  When you run CountDownLatchDemo, you will get below output:
service2 is now UP
service3 is now UP
service1 is now UP
service4 is now UP
All services are up..Application is starting now!!


CyclicBarrier can perform a completion task once all thread reaches to the 'barrier'. It is a synchronizer introduced in JDK 5 on java.util.Concurrent package along with other concurrent utility like Counting Semaphore, BlockingQueue, ConcurrentHashMap etc. CyclicBarrier is similar to CountDownLatch and allows multiple threads to wait for each other (barrier) before proceeding.

CyclicBarrier also does the same thing but there is different you cannot reuse CountDownLatch once the count reaches zero while you can reuse CyclicBarrier by calling reset() method which resets Barrier to its initial State. What it implies that CountDownLatch is a good for one-time events like application start-up time and CyclicBarrier can be used to in case of the recurrent event.

When to use CyclicBarrier in Java, e.g.
1). To count population of India you can have 4 threads which count population from North, South, East, and West and once complete they can wait for each other, When last thread completed their task, Main thread or any other thread can add result from each zone and print total population.
2). To implement multi player game which cannot begin until all player has joined.

Points to remember:
1). If CyclicBarrier is initialized with 3 parties means 3 thread needs to call await method to break the barrier.
2). The thread will block on await() until all parties reach to the barrier, another thread interrupt or await timed out.
3). If another thread interrupts the thread which is waiting on barrier it will throw BrokernBarrierException as shown below:
java.util.concurrent.BrokenBarrierException
        at java.util.concurrent.CyclicBarrier.dowait(CyclicBarrier.java:172)
        at java.util.concurrent.CyclicBarrier.await(CyclicBarrier.java:327)
4). CyclicBarrier.reset() put Barrier on its initial state, other thread which is waiting or not yet reached barrier will terminate with java.util.concurrent.BrokenBarrierException.

Example:
1). Create a class which extends Thread
package com.test.thread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class Party extends Thread {
    private int duration;
    private CyclicBarrier barrier;

    public Party(int duration, CyclicBarrier barrier, String name) {
        super(name);
        this.duration = duration;
        this.barrier = barrier;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(duration);
            System.out.println(Thread.currentThread().getName() + " is calling await()");
            barrier.await();
            System.out.println(Thread.currentThread().getName() + " has started running again");
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}




2).
package com.test.thread;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierDemo {
    public static void main(String args[]) throws InterruptedException, BrokenBarrierException {
        CyclicBarrier barrier = new CyclicBarrier(4);
        Party first = new Party(1000, barrier, "Party1");
        Party second = new Party(2000, barrier, "Party2");
        Party third = new Party(3000, barrier, "Party3");
        Party fourth = new Party(4000, barrier, "Party4");

        first.start();
        second.start();
        third.start();
        fourth.start();
        System.out.println(Thread.currentThread().getName() + " has finished");
    }
}

3). Run CyclicBarrierDemo, output will be:
main has finished
Party1 is calling await()
Party2 is calling await()
Party3 is calling await()
Party4 is calling await()
Party4 has started running again
Party3 has started running again
Party2 has started running again
Party1 has started running again

-K Himaanshu Shuklaa..
RSSChomp Blog Directory