Saturday, October 8, 2011

Design Patterns

Decorator Pattern

To extend or modify the behaviour of ‘an instance’ at runtime decorator design pattern is used. Inheritance is used to extend the abilities of ‘a class’. Unlike inheritance, you can choose any single object of a class and modify its behaviour leaving the other instances unmodified.
In implementing the decorator pattern you construct a wrapper around an object by extending its behavior. The wrapper will do its job before or after and delegate the call to the wrapped instance.

Design of decorator pattern

You start with an interface which creates a blue print for the class which will have decorators. Then implement that interface with basic functionalities. Till now we have got an interface and an implementation concrete class. Create an abstract class that contains (aggregation relationship) an attribute type of the interface. The constructor of this class assigns the interface type instance to that attribute. This class is the decorator base class. Now you can extend this class and create as many concrete decorator classes. The concrete decorator class will add its own methods. After / before executing its own method the concrete decorator will call the base instance’s method. Key to this decorator design pattern is the binding of method and the base instance happens at runtime based on the object passed as parameter to the constructor. Thus dynamically customizing the behavior of that specific instance alone.

Decorator Design Pattern – UML Diagram


Implementation of decorator pattern

Following given example is an implementation of decorator design pattern. Icecream is a classic example for decorator design pattern. You create a basic icecream and then add toppings to it as you prefer. The added toppings change the taste of the basic icecream. You can add as many topping as you want. This sample scenario is implemented below.
package com.javapapers.sample.designpattern;
 
public interface Icecream {
  public String makeIcecream();
}
The above is an interface depicting an icecream. I have kept things as simple as possible so that the focus will be on understanding the design pattern. Following class is a concrete implementation of this interface. This is the base class on which the decorators will be added.
package com.javapapers.sample.designpattern;
 
public class SimpleIcecream implements Icecream {
 
  @Override
  public String makeIcecream() {
    return "Base Icecream";
  }
 
}
Following class is the decorator class. It is the core of the decorator design pattern. It contains an attribute for the type of interface. Instance is assigned dynamically at the creation of decorator using its constructor. Once assigned that instance method will be invoked.
package com.javapapers.sample.designpattern;
 
abstract class IcecreamDecorator implements Icecream {
 
  protected Icecream specialIcecream;
 
  public IcecreamDecorator(Icecream specialIcecream) {
    this.specialIcecream = specialIcecream;
  }
 
  public String makeIcecream() {
    return specialIcecream.makeIcecream();
  }
}
Following two classes are similar. These are two decorators, concrete class implementing the abstract decorator. When the decorator is created the base instance is passed using the constructor and is assigned to the super class. In the makeIcecream method we call the base method followed by its own method addNuts(). This addNuts() extends the behavior by adding its own steps.
package com.javapapers.sample.designpattern;
 
public class NuttyDecorator extends IcecreamDecorator {
 
  public NuttyDecorator(Icecream specialIcecream) {
    super(specialIcecream);
  }
 
  public String makeIcecream() {
    return specialIcecream.makeIcecream() + addNuts();
  }
 
  private String addNuts() {
    return " + cruncy nuts";
  }
}
package com.javapapers.sample.designpattern;
 
public class HoneyDecorator extends IcecreamDecorator {
 
  public HoneyDecorator(Icecream specialIcecream) {
    super(specialIcecream);
  }
 
  public String makeIcecream() {
    return specialIcecream.makeIcecream() + addHoney();
  }
 
  private String addHoney() {
    return " + sweet honey";
  }
}

Execution of the decorator pattern

I have created a simple icecream and decorated that with nuts and on top of it with honey. We can use as many decorators in any order we want. This excellent flexibility and changing the behaviour of an instance of our choice at runtime is the main advantage of the decorator design pattern.
package com.javapapers.sample.designpattern;
 
public class TestDecorator {
 
  public static void main(String args[]) {
    Icecream icecream = new HoneyDecorator(new NuttyDecorator(new SimpleIcecream()));
    System.out.println(icecream.makeIcecream());
  }
 
}

Output

Base Icecream + cruncy nuts + sweet honey

Decorator Design Pattern in java API

java.io.BufferedReader;
java.io.FileReader;
java.io.Reader;
The above readers of java API are designed using decorator design pattern.

Adapter Pattern

An adapter helps two incompatible interfaces to work together. This is the real world definition for an adapter. Adapter design pattern is used when you want two different classes with incompatible interfaces to work together. The name says it all. Interfaces may be incompatible but the inner functionality should suit the need.
In real world the easy and simple example that comes to mind for an adapter is the travel power adapter. American socket and plug are different from British. Their interface are not compatible with one another. British plugs are cylindrical and American plugs are recangularish. You can use an adapter in between to fit an American (rectangular) plug in British (cylindrical) socket assuming voltage requirements are met with.

How to implement adapter design pattern?

Adapter design pattern can be implemented in two ways. One using the inheritance method and second using the composition method. Just the implementation methodology is different but the purpose and solution is same.

Adapter implementation using inheritance

When a class with incompatible method needs to be used with another class you can use inheritance to create an adapter class. The adapter class which is inherited will have new compatible methods. Using those new methods from the adapter the core function of the base class will be accessed. This is called “is-a” relationship. The same real world example is implemented using java as below. Dont worry too much about logic, following example source code attempts to explain adapter design pattern and the goal is simplicity.
public class CylindricalSocket {
  public String supply(String cylinStem1, String cylinStem1) {
    System.out.println("Power power power...");
  }
}
 
public class RectangularAdapter extends CylindricalSocket {
  public String adapt(String rectaStem1, Sting rectaStem2) {
    //some conversion logic
    String cylinStem1 = rectaStem1;
    String cylinStem2 = rectaStem2;
    return supply(cylinStem1, cylinStem2);
  }
}
 
public class RectangularPlug {
  private String rectaStem1;
  private String rectaStem2;
  public getPower() {
    RectangulrAdapter adapter = new RectangulrAdapter();
    String power = adapter.adapt(rectaStem1, rectaStem2);
    System.out.println(power);
  }
}

Adapter implementation using composition

The above implementation can also be done using composition. Instead of inheriting the base class create adapter by having the base class as attribute inside the adapter. You can access all the methods by having it as an attribute. This is nothing but “has-a” relationship. Following example illustrates this approach. Difference is only in the adapter class and other two classes are same. In most scenarios, prefer composition over inheritance. Using composition you can change the behaviour of class easily if needed. It enables the usage of tools like dependency injection.
public class CylindricalSocket {
  public String supply(String cylinStem1, String cylinStem1) {
    System.out.println("Power power power...");
  }
}
 
public class RectangularAdapter {
  private CylindricalSocket socket;
 
  public String adapt(String rectaStem1, Sting rectaStem2) {
    //some conversion logic
    socket = new CylindricalSocket();
    String cylinStem1 = rectaStem1;
    String cylinStem2 = rectaStem2;
    return socket.supply(cylinStem1, cylinStem2);
  }
}
 
public class RectangularPlug {
  private String rectaStem1;
  private String rectaStem2;
  public getPower() {
    RectangulrAdapter adapter = new RectangulrAdapter();
    String power = adapter.adapt(rectaStem1, rectaStem2);
    System.out.println(power);
  }
}

Adapter design pattern in java API

java.io.InputStreamReader(InputStream)
java.io.OutputStreamWriter(OutputStream)

Singleton Pattern

Singleton design pattern is the first design pattern I learned (many years back). In early days when someone asks me, “do you know any design pattern?” I quickly and promptly answer “I know singleton design pattern” and the question follows, “do you know anything other than singleton” and I stand stumped!
A java beginner will know about singleton design pattern. At least he will think that he knows singleton pattern. The definition is even easier than Newton’s third law. Then what is special about the singleton pattern. Is it so simple and straightforward, does it even deserve an article? Do you believe that you know 100% about singleton design pattern? If you believe so and you are a beginner read through the end, there are surprises for you.
There are only two points in the definition of a singleton design pattern,
  1. there should be only one instance allowed for a class and
  2. we should allow global point of access to that single instance.
GOF says, “Ensure a class has only one instance, and provide a global point of access to it. [GoF, p127]“.
The key is not the problem and definition. In singleton pattern, trickier part is implementation and management of that single instance. Two points looks very simple, is it so difficult to implement it. Yes it is very difficult to ensure “single instance” rule, given the flexibility of the APIs and many flexible ways available to access an instance. Implementation is very specific to the language you are using. So the security of the single instance is specific to the language used.

Strategy for Singleton instance creation

We suppress the constructor and don’t allow even a single instance for the class. But we declare an attribute for that same class inside and create instance for that and return it. Factory design pattern can be used to create the singleton instance.
package com.javapapers.sample.designpattern;
public class Singleton {
  private static Singleton singleInstance;
    private Singleton() {}
  public static Singleton getSingleInstance() {
    if (singleInstance == null) {
      synchronized (Singleton.class) {
        if (singleInstance == null) {
          singleInstance = new Singleton();
        }
      }
    }
    return singleInstance;
  }
You need to be careful with multiple threads. If you don’t synchronize the method which is going to return the instance then, there is a possibility of allowing multiple instances in a multi-threaded scenario. Do the synchronization at block level considering the performance issues. In the above example for singleton pattern, you can see that it is threadsafe.

Early and lazy instantiation in singleton pattern

The above example code is a sample for lazy instantiation for singleton design pattern. The single instance will be created at the time of first call of the getSingleInstance() method. We can also implement the same singleton design pattern in a simpler way but that would instantiate the single instance early at the time of loading the class. Following example code describes how you can instantiate early. It also takes care of the multithreading scenario.
package com.javapapers.sample.designpattern;
public class Singleton {
  private static Singleton singleInstance = new Singleton();
  private Singleton() {}
  public static Singleton getSingleInstance() {
    return singleInstance;
  }
}

Singleton and Serialization

Using serialization, single instance contract of the singleton pattern can be violated. You can serialize and de-serialize and get a new instance of the same singleton class. Using java api, you can implement the below method and override the instance read from the stream. So that you can always ensure that you have single instance.
ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;
This article is an attempt to explain the basics on singleton design pattern. If you want more insight on singleton refer this technical article “When is a Singleton not a Singleton?” and its references.

Usage of Singleton Patter in Java API

java.lang.Runtime#getRuntime() java.awt.Desktop#getDesktop()

Prototype Pattern

When creating an object is time consuming and a costly affair and you already have a most similar object instance in hand, then you go for prototype pattern. Instead of going through a time consuming process to create a complex object, just copy the existing similar object and modify it according to your needs.
Its a simple and straight forward design pattern. Nothing much hidden beneath it. If you don’t have much experience with enterprise grade huge application, you may not have experience in creating a complex / time consuming instance. All you might have done is use the new operator or inject and instantiate.
If you are a beginner you might be wondering, why all the fuss about prototye design pattern and do we really need this design pattern? Just ignore, all the big guys requires it. For you, just understand the pattern and sleep over it. You may require it one day in future.
Prototype pattern may look similar to builder design pattern. There is a huge difference to it. If you remember, “the same construction process can create different representations” is the key in builder pattern. But not in the case of prototype pattern.
So, how to implement the prototype design pattern? You just have to copy the existing instance in hand. When you say copy in java, immediately cloning comes into picture. Thats why when you read about prototype pattern, all the literature invariably refers java cloning.
Simple way is, clone the existing instance in hand and then make the required update to the cloned instance so that you will get the object you need. Other way is, tweak the cloning method itself to suit your new object creation need. Therefore whenever you clone that object you will directly get the new object of desire without modifying the created object explicitly.
The prototype design pattern mandates that the instance which you are going to copy should provide the copying feature. It should not be done by an external utility or provider.
But the above, other way comes with a caution. If somebody who is not aware of your tweaking the clone business logic uses it, he will be in issue. Since what he has in hand is not the exact clone. You can go for a custom method which calls the clone internally and then modifies it according to the need. Which will be a better approach.
Always remember while using clone to copy, whether you need a shallow copy or deep copy. Decide based on your business needs. If you need a deep copy, you can use serialization as a hack to get the deep copy done. Using clone to copy is entirey a design decision while implementing the prototype design pattern. Clone is not a mandatory choice for prototype pattern.
In prototype pattern, you should always make sure that you are well knowledgeable about the data of the object that is to be cloned. Also make sure that instance allows you to make changes to the data. If not, after cloning you will not be able to make required changes to get the new required object.
Following sample java source code demonstrates the prototype pattern. I have a basic bike in hand with four gears. When I want to make a different object, an advance bike with six gears I copy the existing instance. Then make necessary modifications to the copied instance. Thus the prototype pattern is implemented. Example source code is just to demonstrate the design pattern, please don’t read too much out of it. I wanted to make things as simple as possible.

Sample Java Source Code for Prototype Design Pattern

package com.javapapers.sample.designpattern.prototype;
 
class Bike implements Cloneable {
  private int gears;
  private String bikeType;
  private String model;
  public Bike() {
    bikeType = "Standard";
    model = "Leopard";
    gears = 4;
  }
 
  public Bike clone() {
    return new Bike();
  }
 
  public void makeAdvanced() {
    bikeType = "Advanced";
    model = "Jaguar";
    gears = 6;
  }
  public String getModel(){
    return model;
  }
}
 
public class Workshop {
  public Bike makeJaguar(Bike basicBike) {
    basicBike.makeAdvanced();
    return basicBike;
  }
  public static void main(String args[]){
    Bike bike = new Bike();
    Bike basicBike = bike.clone();
    Workshop workShop = new Workshop();
    Bike advancedBike = workShop.makeJaguar(basicBike);
    System.out.println("Prototype Design Pattern: "+advancedBike.getModel());
  }
}

Builder Pattern

Builder pattern is used to construct a complex object step by step and the final step will return the object. The process of constructing an object should be generic so that it can be used to create different representations of the same object.
Complex Object Construction
Complex Object Construction
For example, you can consider construction of a home. Home is the final end product (object) that is to be returned as the output of the construction process. It will have many steps, like basement construction, wall construction and so on roof construction. Finally the whole home object is returned. Here using the same process you can build houses with different properties.
GOF says,
“Separate the construction of a complex object from its representation so that the same construction process can create different representations” [GoF 94]

What is the difference between abstract factory and builder pattern?

Abstract factory may also be used to construct a complex object, then what is the difference with builder pattern? In builder pattern emphasis is on ‘step by step’. Builder pattern will have many number of small steps. Those every steps will have small units of logic enclosed in it. There will also be a sequence involved. It will start from step 1 and will go on upto step n and the final step is returning the object. In these steps, every step will add some value in construction of the object. That is you can imagine that the object grows stage by stage. Builder will return the object in last step. But in abstract factory how complex the built object might be, it will not have step by step object construction.

Sample builder design pattern implementation in Java API

DocumentBuilderFactory , StringBuffer, StringBuilder are some examples of builder pattern usage in java API.

Sample Java Source Code for Builder Pattern

Following is the interface, that will be returned as the product from the builder.
package com.javapapers.sample.designpattern.builder;
 
public interface HousePlan {
 
  public void setBasement(String basement);
 
  public void setStructure(String structure);
 
  public void setRoof(String roof);
 
  public void setInterior(String interior);
}
Following is the interface for which the factory implementation should be done. Inturn all abstract factory will return this type.
package com.javapapers.sample.designpattern.abstractfactory;
 
public interface AnimalFactory {
  public Animal createAnimal();
}
Concrete class for the above interface. The builder constructs an implementation for the following class.
package com.javapapers.sample.designpattern.builder;
 
public class House implements HousePlan {
 
  private String basement;
  private String structure;
  private String roof;
  private String interior;
 
  public void setBasement(String basement) {
    this.basement = basement;
  }
 
  public void setStructure(String structure) {
    this.structure = structure;
  }
 
  public void setRoof(String roof) {
    this.roof = roof;
  }
 
  public void setInterior(String interior) {
    this.interior = interior;
 
  }
 
}
Builder interface. We will have multiple different implementation of this interface in order to facilitate, the same construction process to create different representations.
package com.javapapers.sample.designpattern.builder;
 
public interface HouseBuilder {
 
  public void buildBasement();
 
  public void buildStructure();
 
  public void bulidRoof();
 
  public void buildInterior();
 
  public House getHouse();
}
First implementation of a builder.
package com.javapapers.sample.designpattern.builder;
 
public class IglooHouseBuilder implements HouseBuilder {
 
  private House house;
 
  public IglooHouseBuilder() {
    this.house = new House();
  }
 
  public void buildBasement() {
    house.setBasement("Ice Bars");
  }
 
  public void buildStructure() {
    house.setStructure("Ice Blocks");
  }
 
  public void buildInterior() {
    house.setInterior("Ice Carvings");
  }
 
  public void bulidRoof() {
    house.setRoof("Ice Dome");
  }
 
  public House getHouse() {
    return this.house;
  }
}
Second implementation of a builder. Tipi is a type of eskimo house.
package com.javapapers.sample.designpattern.builder;
 
public class TipiHouseBuilder implements HouseBuilder {
  private House house;
 
  public TipiHouseBuilder() {
    this.house = new House();
  }
 
  public void buildBasement() {
    house.setBasement("Wooden Poles");
  }
 
  public void buildStructure() {
    house.setStructure("Wood and Ice");
  }
 
  public void buildInterior() {
    house.setInterior("Fire Wood");
  }
 
  public void bulidRoof() {
    house.setRoof("Wood, caribou and seal skins");
  }
 
  public House getHouse() {
    return this.house;
  }
 
}
Following class constructs the house and most importantly, this maintains the building sequence of object.
package com.javapapers.sample.designpattern.builder;
 
public class CivilEngineer {
 
  private HouseBuilder houseBuilder;
 
  public CivilEngineer(HouseBuilder houseBuilder){
    this.houseBuilder = houseBuilder;
  }
 
  public House getHouse() {
    return this.houseBuilder.getHouse();
  }
 
  public void constructHouse() {
    this.houseBuilder.buildBasement();
    this.houseBuilder.buildStructure();
    this.houseBuilder.bulidRoof();
    this.houseBuilder.buildInterior();
  }
}
Testing the sample builder design pattern.
package com.javapapers.sample.designpattern.builder;
 
public class BuilderSample {
  public static void main(String[] args) {
    HouseBuilder iglooBuilder = new IglooHouseBuilder();
    CivilEngineer engineer = new CivilEngineer(iglooBuilder);
 
    engineer.constructHouse();
 
    House house = engineer.getHouse();
 
    System.out.println("Builder constructed: "+house);
  }
}

Output of the above sample program for builder pattern

Builder constructed: com.javapapers.sample.designpattern.builder.House@7d772e

Abstract Factory Pattern

Factory of factories. To keep things simple you can understand it like, you have a set of ‘related’ factory method design pattern. Then you will put all those set of simple factories inside a factory pattern. So in turn you need not be aware of the final concrete class that will be instantiated. You can program for the interface using the top factory.
There is also a view that abstract factory is ‘also’ implemented using prototype instead of factory methords pattern. Beginners for now please don’t yourself with that. Just go with factory methods pattern.
As there is a word ‘abstract’ in the pattern name don’t mistake and confuse it with java ‘abstract’ keyword. It is not related to that. This abstract is from object oriented programming paradim.

Sample abstract factory design pattern implementation in Java API

XML API implements abstract factory. There is a class name SchemaFactory. This acts as a factory and supports implemenation of multiple schemas using abstract factory design pattern.

Sample Java Source Code for Factory Method Design Pattern

Following is the interface, that will be returned as the final end product from the factories.
package com.javapapers.sample.designpattern.abstractfactory;
 
public interface Animal {
  public void breathe();
}
Following is the interface for which the factory implementation should be done. Inturn all abstract factory will return this type.
package com.javapapers.sample.designpattern.abstractfactory;
 
public interface AnimalFactory {
  public Animal createAnimal();
}
One of the factory from a predefined set which will instantiate the above interface.
package com.javapapers.sample.designpattern.abstractfactory;
 
public class SeaFactory implements AnimalFactory {
 
  public Animal createAnimal() {
    return new Shark();
  }
 
}
Second factory from a predefined set which will instantiate the Animal interface.
package com.javapapers.sample.designpattern.abstractfactory;
 
public class LandFactory implements AnimalFactory {
  public Animal createAnimal() {
    return new Elephant();
  }
}
Implementation of an Animal. This class is grouped with the first abstract factory.
package com.javapapers.sample.designpattern.abstractfactory;
 
public class Shark implements Animal {
  public void breathe() {
    System.out.println("I breathe in water! He he!");
  }
}
Implementation of an Animal. This class is grouped with the second abstract factory.
package com.javapapers.sample.designpattern.abstractfactory;
 
public class Elephant implements Animal {
  public void breathe() {
    System.out.println("I breathe with my lungs. Its easy!");
  }
}
Following class consumes the abstract factory.
package com.javapapers.sample.designpattern.abstractfactory;
 
public class Wonderland {
  public Wonderland(AnimalFactory factory) {
    Animal animal = factory.createAnimal();
    animal.breathe();
  }
}
Testing the abstract factory design pattern.
package com.javapapers.sample.designpattern.abstractfactory;
 
public class SampleAbstractFactory {
 
  public static void main(String args[]){
    new Wonderland(createAnimalFactory("water"));
  }
 
  public static AnimalFactory createAnimalFactory(String type){
    if("water".equals(type))
      return new SeaFactory();
    else
      return new LandFactory();
  }
}

Output of the above sample program for abstract factory pattern

I breathe in water! He he!

Factory Method Pattern

05/11/2009
A factory method pattern is a creational pattern. It is used to instantiate an object from one among a set of classes based on a logic.
Assume that you have a set of classes which extends a common super class or interface. Now you will create a concrete class with a method which accepts one or more arguments. This method is our factory method. What it does is, based on the arguments passed factory method does logical operations and decides on which sub class to instantiate. This factory method will have the super class as its return type. So that, you can program for the interface and not for the implementation. This is all about factory method design pattern.

Sample factory method design pattern implementation in Java API

For a reference of how the factory method design pattern is implemented in Java, you can have a look at SAXParserFactory. It is a factory class which can be used to intantiate SAX based parsers to pares XML. The method newInstance is the factory method which instantiates the sax parsers based on some predefined logic.

Block diagram for The Design Pattern

factorydesignpattern

Sample Java Source Code for Factory Method Design Pattern

Based on comments received from users, I try to keep my sample java source code as simple as possible for a novice to understand.
Base class:
package com.javapapers.sample.designpattern.factorymethod;
 
//super class that serves as type to be instantiated for factory method pattern
public interface Pet {
 
 public String speak();
 
}
First subclass:
package com.javapapers.sample.designpattern.factorymethod;
 
//sub class 1 that might get instantiated by a factory method pattern
public class Dog implements Pet {
 
 public String speak() {
 return "Bark bark...";
 }
}
Second subclass:
package com.javapapers.sample.designpattern.factorymethod;
 
//sub class 2 that might get instantiated by a factory method pattern
public class Duck implements Pet {
 public String speak() {
 return "Quack quack...";
 }
}
Factory class:
package com.javapapers.sample.designpattern.factorymethod;
 
//Factory method pattern implementation that instantiates objects based on logic
public class PetFactory {
 
 public Pet getPet(String petType) {
 Pet pet = null;
 
 // based on logic factory instantiates an object
 if ("bark".equals(petType))
 pet = new Dog();
 else if ("quack".equals(petType))
 pet = new Duck();
 return pet;
 }
}
Using the factory method to instantiate
package com.javapapers.sample.designpattern.factorymethod;
 
//using the factory method pattern
public class SampleFactoryMethod {
 
 public static void main(String args[]){
 
 //creating the factory
 PetFactory petFactory = new PetFactory();
 
 //factory instantiates an object
 Pet pet = petFactory.getPet("bark");
 
 //you don't know which object factory created
 System.out.println(pet.speak());
 }
 
}

Output of the above sample program for Factory Method Pattern

Bark bark

Download Java Source Code For Factory Method Pattern

Introduction To Design Patterns

Pattern is a defined, used and tested solution for a know problem. Design patterns is all about re-use. Software design patterns evolved as a subject of study only when object oriented programming started becoming popular. OOPS and design patterns became inseparable.
In OOPS, we should have well defined boundaries for objects. That is every object should have its roles and responsibilities well defined. Then at next level, we should have a clear interaction plan between objects. If you design a OO software with the above principle, then by default you will be following some of the already defined design patterns.
A formal definition for design patterns, “A design pattern addresses a recurring design problem that arises in specific design situations and presents a solution to it” (Buschmann, et. al. 1996)
Java widely uses design patterns in its APIs. It started as early as Java 1.2 in java foundation classes. By then you can see the widespread use of commonly know design patterns in collections framework and IO packages. When I say commonly known design patterns, I mention about the set of 23 design patterns by Gang of Four (GOF). Gamma, Helm, Johnson and Vlissides known as Gang of Four (GOF) published a book “Design Patterns — Elements of Reusable Software” (1995) based on their series of technical meetings. It is one of the best seller in computer science books till date.
In China gang of four means different set of people. Jiang Qing (Mao Zedong’s fourth wife), Zhang Chunqiao, Yao Wenyuan, and Wang Hongwen were very popular leaders of cultural revolution. They almost seized power after Mao Zedong’s death. But they were finally arrested and imprisoned for life.
Our GOF divided the 23 design patterns into three types creational design patterns, structural design patterns and behavioral design patterns.
Creational design patterns can be used to instantiate objects. Instead of instantiating objects directly, depending on scenario either X or Y object can be instantiated. This will give flexibility for instantiation in high complex business logic situations.
Structural design patterns can be used to organize your program into groups. This segregation will provide you clarity and will enable you for easier maintainability.
Behavioral design patterns can be used to define the communication and control flow between objects.
Following this post, I have planned to write a series of article on these design patterns with java source code examples and UML diagrams. Looking forward to your comments.

 


Java Exception

What are the causes of exceptions in java?

A java exception can be thrown only in the following three scenarios:
(1) An abnormal execution condition was synchronously detected by the Java virtual machine.
- When evaluation of an expression violates the normal semantics (Example: an integer divide by zero)
- An error occurs in loading or linking part of the program
- When limitation on a resource is exceeded (Example: using too much memory)
(2) A throw statement was executed.
(3) An asynchronous exception occurred.
- The stop method (deprecated) of class Thread was invoked
- An internal error has occurred in the java virtual machine

Checked vs Unchecked Exceptions

Type of exceptions in java are checked exceptions and unchecked exceptions. This classification is based on compile-time checking of exceptions. There is also a classification based on runtime in java. It is not widely known! That is synchronous and asynchronous exceptions. First let us see the java checked exceptions and unchecked exceptions.

When does the finally clause in java exception block never executes?

The finally clause in the try-catch exeception block always executes, irrespective of the occurence of exeception. This is applicable for the normal java program flow. If the execution flow is stopped irreversibly before the finally clause, then the finally block will not be executed.
How can the user achieve that in Java?
Include “System.exit(1);” before the finally block and stop the execution flow of the java program.

Checked Exceptions Vs Unchecked Exceptions in Java

At compile time, the java compiler checks that a program contains handlers for checked exceptions. Java compiler analyzes by which checked exceptions can result from execution of a method or constructor.For each checked exception which is a possible result, the throws clause for the method or constructor must mention the class or its superclasses of that exception.
The class RuntimeException and its subclasses, and the class Error and its subclasses are unchecked exceptions classes. Because the compiler doesn’t forces them to be declared in the throws clause. All the other exception classes that are part of Throwable hierarchy are checked exceptions.
Now let us see a see small discussion on why exceptions are classified as checked exceptions and unchecked exceptions.
Those unchecked exception classes which are the error classes (Error and its subclasses) are exempted from compile-time checking in java because they can occur at many points in the program and recovery from them is difficult or impossible.

Example: OutOfMemoryError

Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.
The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking because, in the judgment of the designers of the Java, having to declare such exceptions would not aid significantly in establishing the correctness of programs.

Example: NullPointerException

Thrown when an application attempts to use null in a case where an object is required.
So the java compiler doesn’t forces them to be declared in the above two cases.

Synchronous and Asynchronous Exceptions in Java

The interpreter executes the java program sequentially. An exception E can occur relative to a line (L) of program. That is that exception E will always occur at the execution of that line L. This is called Synchronous exception.
An asynchronous exception in java can occur at any point in the execution of a program.
They occur only as a result of:
  1. An invocation of the stop methods of class Thread or ThreadGroup
  2. An internal error in the Java virtual machine

Java Collection

Read Only Collections

I do build crazy buildings using my collection of Lego blocks. My 11 months old kid Ben curiously stares at me build it. He always wishes to get hold of it. After I complete the building when I give that to his hand, you know what the first thing he does.
Lego Blocks
Modify the building blocks. Though I wish them to be intact forever Lego buildings are built to be modified.
But this is not the case in programming. You create a java collection and store objects in it. Then there are scenarios where you want them not be modified. Obsessed with file system terminology Java guys have named it as read only collections.
By default some of the languages like dot net provide read only collections. But in Java there are no such things. This is not a special type of collection it is an additional facility provided to change the usual collections as read only.

Methods by Collections class

The Collections class provides six factory methods, one for each of Collection, List, Map, Set, SortedMap, and SortedSet.
  • Collection unmodifiableCollection(Collection collection)
  • List unmodifiableList(List list)
  • Map unmodifiableMap(Map map)
  • Set unmodifiableSet(Set set)
  • SortedMap unmodifiableSortedMap(SortedMap map)
  • SortedSet unmodifiableSortedSet(SortedSet set)
You should set the collection with required values then pass it as value to the Collections’ respective method. Most important thing here is, just passing and setting it as unModifiableX is not enough. These methods will return you collection as read only. You need to overwrite your old collection with this new read only collection. If you don’t do that, using the reference of the old collection the values can be modified. Cool right!
The returned set will be serializable if the specified set is serializable. If you attempt to modify a read-only collection it will throw an UnsupportedOperationException.

Example source code for java read only collections

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
// example program to demonstrate the read-only collection in java
public class ReadOnlyCollections {
 
public static void main(String args[]) {
 
// creating a list
List godList = Arrays
.asList(new String[] { "Donald", "Dennis", "Ken" });
 
// making a read-only list
List list = new ArrayList(godList);
list = Collections.unmodifiableList(list);
 
// checking the reference in a read-only set
Set set = new HashSet(godList);
Collections.unmodifiableSet(set);
 
// the following statement allows to modify the above set as the
// reference is pointing to the original collection therefore it is not
// read-only
set.add("Alan");
 
// making a read-only map and try to modify it
Map godMap = new HashMap();
godMap.put("TAOCP", "Donald");
godMap.put("C", "Dennis");
 
godMap = Collections.unmodifiableMap(godMap);
 
try {
// modifying the read-only map to check what happens
godMap.put("Unix", "Ken");
} catch (UnsupportedOperationException e) {
System.out.println("You cannot modify a read only collection!");
}
}
}

Difference between Vector and ArrayList in java?

java.util.Vector came along with the first version of java development kit (JDK). java.util.ArrayList was introduced in java version1.2, as part of java collections framework. As per java API, in Java 2 platform v1.2,vector has been retrofitted to implement List and vector also became a part of java collection framework.
All the methods of Vector is synchronized. But, the methods of ArrayList is not synchronized. All the new implementations of java collection framework is not synchronized.
Vector and ArrayList both uses Array internally as data structure. They are dynamically resizable. Difference is in the way they are internally resized. By default, Vector doubles the size of its array when its size is increased. But, ArrayList increases by half of its size when its size is increased.
Therefore as per Java API the only main difference is, Vector’s methods are synchronized and ArrayList’s methods are not synchronized.
Vector or ArrayList? Which is better to use in java?
In general, executing a ‘synchronized’ method results in costlier performance than a unsynchronized method. Keeping the difference in mind, using Vector will incur a performance hit than the ArrayList. But, when there is a certain need for thread-safe operation Vector needs to be used.
Is there an alternate available in java for Vector?
ArrayList can be synchronized using the java collections framework utility class and then ArrayList itself can be used in place of Vector.
When there is no need for synchronized operation and you still look for better performance ‘Array’ can be used instead of ArrayList. But the development is tedious, since it doesn’t provide user friendly methods.
When you use Vector or ArrayList, always initialize to the largest capacity that the java program will need. Since incrementing the size is a costlier operation.

Session Tracking Methods

Following answer is applicable irrespective of the language and platform used. Before we enter into session tracking, following things should be understood.

What is a session?

A session is a conversation between the server and a client. A conversation consists series of continuous request and response.

Why should a session be maintained?

When there is a series of continuous request and response from a same client to a server, the server cannot identify from which client it is getting requests. Because HTTP is a stateless protocol.
When there is a need to maintain the conversational state, session tracking is needed. For example, in a shopping cart application a client keeps on adding items into his cart using multiple requests. When every request is made, the server should identify in which client’s cart the item is to be added. So in this scenario, there is a certain need for session tracking.
Solution is, when a client makes a request it should introduce itself by providing unique identifier every time. There are five different methods to achieve this.

Session tracking methods:

  1. User authorization
  2. Hidden fields
  3. URL rewriting
  4. Cookies
  5. Session tracking API
The first four methods are traditionally used for session tracking in all the server-side technologies. The session tracking API method is provided by the underlying technology (java servlet or PHP or likewise). Session tracking API is built on top of the first four methods.

1. User Authorization

Users can be authorized to use the web application in different ways. Basic concept is that the user will provide username and password to login to the application. Based on that the user can be identified and the session can be maintained.

2. Hidden Fields

<INPUT TYPE=”hidden” NAME=”technology” VALUE=”servlet”>
Hidden fields like the above can be inserted in the webpages and information can be sent to the server for session tracking. These fields are not visible directly to the user, but can be viewed using view source option from the browsers. This type doesn’t need any special configuration from the browser of server and by default available to use for session tracking. This cannot be used for session tracking when the conversation included static resources lik html pages.

3. URL Rewriting

Original URL: http://server:port/servlet/ServletName
Rewritten URL: http://server:port/servlet/ServletName?sessionid=7456
When a request is made, additional parameter is appended with the url. In general added additional parameter will be sessionid or sometimes the userid. It will suffice to track the session. This type of session tracking doesn’t need any special support from the browser. Disadvantage is, implementing this type of session tracking is tedious. We need to keep track of the parameter as a chain link until the conversation completes and also should make sure that, the parameter doesn’t clash with other application parameters.

4. Cookies

Cookies are the mostly used technology for session tracking. Cookie is a key value pair of information, sent by the server to the browser. This should be saved by the browser in its space in the client computer. Whenever the browser sends a request to that server it sends the cookie along with it. Then the server can identify the client using the cookie.
In java, following is the source code snippet to create a cookie:
Cookie cookie = new Cookie(“userID”, “7456″);
res.addCookie(cookie);
Session tracking is easy to implement and maintain using the cookies. Disadvantage is that, the users can opt to disable cookies using their browser preferences. In such case, the browser will not save the cookie at client computer and session tracking fails.

5. Session tracking API

Session tracking API is built on top of the first four methods. This is inorder to help the developer to minimize the overhead of session tracking. This type of session tracking is provided by the underlying technology. Lets take the java servlet example. Then, the servlet container manages the session tracking task and the user need not do it explicitly using the java servlets. This is the best of all methods, because all the management and errors related to session tracking will be taken care of by the container itself.
Every client of the server will be mapped with a javax.servlet.http.HttpSession object. Java servlets can use the session object to store and retrieve java objects across the session. Session tracking is at the best when it is implemented using session tracking api.

Session Tracking Methods

Following answer is applicable irrespective of the language and platform used. Before we enter into session tracking, following things should be understood.

What is a session?

A session is a conversation between the server and a client. A conversation consists series of continuous request and response.

Why should a session be maintained?

When there is a series of continuous request and response from a same client to a server, the server cannot identify from which client it is getting requests. Because HTTP is a stateless protocol.
When there is a need to maintain the conversational state, session tracking is needed. For example, in a shopping cart application a client keeps on adding items into his cart using multiple requests. When every request is made, the server should identify in which client’s cart the item is to be added. So in this scenario, there is a certain need for session tracking.
Solution is, when a client makes a request it should introduce itself by providing unique identifier every time. There are five different methods to achieve this.

Session tracking methods:

  1. User authorization
  2. Hidden fields
  3. URL rewriting
  4. Cookies
  5. Session tracking API
The first four methods are traditionally used for session tracking in all the server-side technologies. The session tracking API method is provided by the underlying technology (java servlet or PHP or likewise). Session tracking API is built on top of the first four methods.

1. User Authorization

Users can be authorized to use the web application in different ways. Basic concept is that the user will provide username and password to login to the application. Based on that the user can be identified and the session can be maintained.

2. Hidden Fields

<INPUT TYPE=”hidden” NAME=”technology” VALUE=”servlet”>
Hidden fields like the above can be inserted in the webpages and information can be sent to the server for session tracking. These fields are not visible directly to the user, but can be viewed using view source option from the browsers. This type doesn’t need any special configuration from the browser of server and by default available to use for session tracking. This cannot be used for session tracking when the conversation included static resources lik html pages.

3. URL Rewriting

Original URL: http://server:port/servlet/ServletName
Rewritten URL: http://server:port/servlet/ServletName?sessionid=7456
When a request is made, additional parameter is appended with the url. In general added additional parameter will be sessionid or sometimes the userid. It will suffice to track the session. This type of session tracking doesn’t need any special support from the browser. Disadvantage is, implementing this type of session tracking is tedious. We need to keep track of the parameter as a chain link until the conversation completes and also should make sure that, the parameter doesn’t clash with other application parameters.

4. Cookies

Cookies are the mostly used technology for session tracking. Cookie is a key value pair of information, sent by the server to the browser. This should be saved by the browser in its space in the client computer. Whenever the browser sends a request to that server it sends the cookie along with it. Then the server can identify the client using the cookie.
In java, following is the source code snippet to create a cookie:
Cookie cookie = new Cookie(“userID”, “7456″);
res.addCookie(cookie);
Session tracking is easy to implement and maintain using the cookies. Disadvantage is that, the users can opt to disable cookies using their browser preferences. In such case, the browser will not save the cookie at client computer and session tracking fails.

5. Session tracking API

Session tracking API is built on top of the first four methods. This is inorder to help the developer to minimize the overhead of session tracking. This type of session tracking is provided by the underlying technology. Lets take the java servlet example. Then, the servlet container manages the session tracking task and the user need not do it explicitly using the java servlets. This is the best of all methods, because all the management and errors related to session tracking will be taken care of by the container itself.
Every client of the server will be mapped with a javax.servlet.http.HttpSession object. Java servlets can use the session object to store and retrieve java objects across the session. Session tracking is at the best when it is implemented using session tracking api.

What happens if you call destroy() from init() in java servlet?

destroy() gets executed and the initialization process continues. It is a trick question in servlets interview.
In java servlet, destroy() is not supposed to be called by the programmer. But, if it is invoked, it gets executed. The implicit question is, will the servlet get destroyed? No, it will not. destroy() method is not supposed to and will not destroy a java servlet. Don’t get confused by the name. It should have been better, if it was named onDestroy().
The meaning of destroy() in java servlet is, the content gets executed just before when the container decides to destroy the servlet. But if you invoke the destroy() method yourself, the content just gets executed and then the respective process continues. With respective to this question, the destroy() gets executed and then the servlet initialization gets completed.
Have a look at this java servlet interview question: Servlet Life Cycle – Explain, it might help you to understand better.

How to avoid IllegalStateException in java servlet?

The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.
It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.
Example servlet source code snippet:

public void doGet(HttpServletRequest request,  HttpServletResponse response) throws ServletException, IOException {
if("success".equals(processLogin())) {
response.sendRedirect("menu.jsp");
return; // <-- this return statement ensures that no content is adedd to the response further
}

Note: This same scenario of IllegalStateException is applicable in JSP also.
/*
other servlet code that may add to the response….
*/
}

What is servlet mapping?

Servlet mapping specifies the web container of which java servlet should be invoked for a url given by client. It maps url patterns to servlets. When there is a request from a client, servlet container decides to which application it should forward to. Then context path of url is matched for mapping servlets.

How is servlet mapping defined?

Servlets should be registered with servlet container. For that, you should add entries in web deployment descriptor web.xml. It is located in WEB-INF directory of the web application.
Entries to be done in web.xml for servlet-mapping:
<servlet-mapping>
<servlet-name>milk</servlet-name>
<url-pattern>/drink/*</url-pattern>
</servlet-mapping>
servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called. Be aware that, the container will use case-sensitive for string comparisons for servlet matching.

Syntax for servlet mapping as per servlet specification SRV.11.2:

A string beginning with a ‘/’ character and ending with a ‘/*’ suffix is used for path mapping.
A string beginning with a ‘*.’ prefix is used as an extension mapping.
A string containing only the ‘/’ character indicates the “default” servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
All other strings are used for exact matches only.

Rule for URL path mapping:

It is used in the following order. First successful match is used with no further attempts.
1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet.
2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the ’/’ character as a path separator. The longest match determines the servlet selected.
3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last ’.’ character.
4. If neither of the previous three rules result in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a “default” servlet is defined for the application, it will be used.

What is implicit mapping?

A servlet container can have a internal JSP container. In such case, *.jsp extension is mapped to the internal container. This mapping is called implicit mapping. This implicit mapping allows ondemand execution of JSP pages. Servlt mapping defined in web application has high precedence over the implicit mapping.

Example code for java servlet mapping:

<servlet>
<servlet-name>milk</servlet-name>
<servlet-class>com.javapapers.Milk</servlet-class>
</servlet>
<servlet>
<servlet-name>points</servlet-name>
<servlet-class>com.javapapers.Points</servlet-class>
</servlet>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>com.javapapers.ControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>milk</servlet-name>
<url-pattern>/drink/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>points</servlet-name>
<url-pattern>/pointlist</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

What is Servlet Invoker?

As defined by Apache Tomcat specification, the purpose of Invoker Servlet is to allow a web application to dynamically register new servlet definitions that correspond with a <servlet> element in the /WEB-INF/web.xml deployment descriptor.By enabling servlet invoker the servlet mapping need not be specified for servlets. Servlet ‘invoker’ is used to dispatch servlets by class name.
Enabling the servlet invoker can create a security hole in web application. Because, Any servlet in classpath even also inside a .jar could be invoked directly. The application will also become not portable. Still if you want to enable the servlet invoker consult the web server documentation, because every server has a different method to do it.
In Tomcat 3.x, by default the servlet invoker is enabled. Just place the servlets inside /servlet/ directory and access it by using a fully qualified name like http://[domain]:[port]/[context]/servlet/[servlet.
This mapping is available in web application descriptor (web.xml), located under $TOMCAT_HOME/conf.
/servlet/ is removed from Servlet 2.3 specifications.
In Tomcat 4.x, by defaul the servlet invoker id disabled. The <servlet-mapping> tag is commented inside the default web application descriptor (web.xml), located under $CATALINA_HOME/conf. To enable the invoker servlet uncomment the following two blocks.
<!– The mapping for the invoker servlet –>
<!–
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
–>


<!–
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>
org.apache.catalina.servlets.InvokerServlet
</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
–>

Difference between HttpServlet and GenericServlet

javax.servlet.GenericServlet
Signature: public abstract class GenericServlet extends java.lang.Object implements Servlet, ServletConfig, java.io.Serializable
  • GenericServlet defines a generic, protocol-independent servlet.
  • GenericServlet gives a blueprint and makes writing servlet easier.
  • GenericServlet provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface.
  • GenericServlet implements the log method, declared in the ServletContext interface.
  • To write a generic servlet, it is sufficient to override the abstract service method.
javax.servlet.http.HttpServlet
Signature: public abstract class HttpServlet extends GenericServlet implements java.io.Serializable
  • HttpServlet defines a HTTP protocol specific servlet.
  • HttpServlet gives a blueprint for Http servlet and makes writing them easier.
  • HttpServlet extends the GenericServlet and hence inherits the properties GenericServlet.

What is preinitialization of a java servlet?

In the java servlet life cycle, the first phase is called ‘Creation and intialization’.
The java servlet container first creates the servlet instance and then executes the init() method. This initialization can be done in three ways. The default way is that, the java servlet is initialized when the servlet is called for the first time. This type of servlet initialization is called lazy loading.

The other way is through the <load-on-startup>non-zero-integer</load-on-startup> tag using the deployment descriptor web.xml. This makes the java servlet to be loaded and initialized when the server starts. This process of loading a java servlet before receiving any request is called preloading or preinitialization of a servlet.
Servlet are loaded in the order of number(non-zero-integer) specified. That is, lower(example: 1) the load-on-startup value is loaded first and then servlet with higher values are loaded.
Example usage:
<servlet>
       <servlet-name>Servlet-URL</servlet-name>
       <servlet-class>com.javapapers.Servlet-Class</servlet-class>
       <load-on-startup>2</load-on-startup>
</servlet>

Difference between ServletConfig and ServletContext

  • Signature: public interface ServletConfig
    ServletConfig is implemented by the servlet container to initialize a single servlet using init(). That is, you can pass initialization parameters to the servlet using the web.xml deployment descriptor. For understanding, this is similar to a constructor in a java class.
Example code:
<servlet>
<servlet-name>ServletConfigTest</servlet-name>
<servlet-class>com.javapapers.ServletConfigTest</servlet-class>
<init-param>
<param-name>topic</param-name>
<param-value>Difference between ServletConfig and ServletContext</param-value>
</init-param>
</servlet>

  • Signature: public interface ServletContext
    ServletContext is implemented by the servlet container for all servlet to communicate with its servlet container, for example, to get the MIME type of a file, to get dispatch requests, or to write to a log file. That is to get detail about its execution environment. It is applicable only within a single Java Virtual Machine. If a web applicationa is distributed between multiple JVM this will not work. For understanding, this is like a application global variable mechanism for a single web application deployed in only one JVM.
The ServletContext object is contained within the ServletConfig object. That is, the ServletContext can be accessed using the ServletConfig object within a servlet. You can specify param-value pairs for ServletContext object in <context-param> tags in web.xml file.
Example code:
<context-param>
<param-name>globalVariable</param-name>
<param-value>javapapers.com</param-value>
</context-param>

Difference between ServletRequest.getRequestDispatcher and ServletContext.getRequestDispatcher

  • request.getRequestDispatcher(“url”) means the dispatch is relative to the current HTTP request.
    Example code: RequestDispatcher reqDispObj = request.getRequestDispatcher("/home.jsp");
  • getServletContext().getRequestDispatcher(“url”) means the dispatch is relative to the root of the ServletContext.
    Example code:RequestDispatcher reqDispObj = getServletContext().getRequestDispatcher("/ContextRoot/home.jsp");  

    ServletRequest vs ServletResponse

  • ServletRequest and ServletResponse are two interfaces that serve as the backbone of servlet technology implementation. They belong to the javax.servlet package.
  • Signature: public interface ServletRequest
    Blueprint of an object to provide client request information to a servlet. The servlet container creates a ServletRequest object and sends it as an argument to the servlet’s service method.
  • Signature: public interface ServletResponse
    Blueprint of an object to assist a servlet in sending a response to the client. The servlet container creates a ServletResponse object and passes it as an argument to the servlet’s service method. Data that needs to be sent to the client will be put inside the ServletResponse object. To send binary data back to the client in a MIME body response, use the ServletOutputStream from the ServletResponse object by calling the getOutputStream() method. To send character data to the client, the PrintWriter object returned by getWriter() should be used.

Why not declare a constructor in servlet?

Technically you can define constructors in servlet. But, the declared constructor cannot access the ServletConfig object or throw a ServletException.
Then why is it not customary to declare a constructor in a servlet? Because the init() method is used to perform servlet initialization. In JDK 1.0 (servlet were written in this version), constructors for dynamically loaded Java classes such as servlets cannot accept arguments. Therefore init() was used to initialize by passing the implemented object of ServletConfig interface and other needed parameters.
Also, Java constructors cannot be declared in interfaces. So, javax.servlet.Servlet interface cannot have a constructor that accepts a ServletConfig parameter. To overcome this, init() method is used for initialization instead of declaring a constructor.

Servlet Life Cycle

The interface javax.servlet.Servlet defines the following three methods known as servlet life cycle methods.
 public void init(ServletConfig config) throws ServletException
 public void service(ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException
 public void destroy()
  1. Creation and initialization

    The container first creates the servlet instance and then executes the init() method.
     init() can be called only once in its life cycle by the following ways:
    a) Through the ‘load-on-startup’ tag using the web.xml. This makes the servlet to be loaded and initialized when the server starts.
    b) For the first time only in its life cycle, just before the service() is invoked.
    c) Server administrator can request for the initialization of a servlet directly.
  2. Execution of service

    Whenever a client requests for the servlet, everytime the service() method is invoked during its life cycle. From service() then it is branched to the doGet() or doXx..() methods for a HttpServlet. The service() method should contain the code that serves the Servlet purpose.
  3. Destroy the servlet

    destroy() method is invoked first, then Servlet is removed from the container and then eventually garbage collected. destroy() method generally contains code to free any resources like jdbc connection that will not be garbage collected.

    What is a filter?

    A filter is used to dynamically intercept request and response objects and change or use the data present in them. Filters should be configured in the web deployment descriptor. Filters can perform essential functions like authentication blocking, logging, content display style conversion, etc.

Abstract and Interface

What is a java marker interface?

Java marker interface has no members in it. Marker interface ‘was’ used as a tag to inform a message to the java compiler.
Java Marker Interface Examples:
java.lang.Cloneable
java.io.Serializable
java.util.EventListener
Lets take the java.io.Serializable marker interface. It doesnot has any members defined it it. When a java class is to be serialized, you should intimate the java compiler in some way that there is a possibility of serializing this java class. In this scenario, marker interfaces are used. The java class which may be serialized has to implement the java.io.Serializable marker interface. In such way, we are intimating the java compiler.
From java 1.5, the need for marker interface is eliminated by the introduction of the java annotation feature. So, it is wise to use java annotations than the marker interface. It has more feature and advantages than the java marker interface.

Difference Between Interface and Abstract Class

  1. Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior.
  2. Variables declared in a Java interface is by default final. An  abstract class may contain non-final variables.
  3. Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..
  4. Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.
  5. An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
  6. A Java class can implement multiple interfaces but it can extend only one abstract class.
  7. Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
  8. In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.

When can an object reference be cast to a Java interface reference?

When a Java object implements the referenced interface it can be cast to the Java interface reference.

Java interface

A java class containing all the methods as abstract is called an interface. A method that has no implementation and which is expected to be implemented by a subclass is called an abstract method. Java interface can contain constants. When an interface needs to be instantiated it should be implemented by a class and all its abstract methods should be defined. If all the methods are not implemented in the class then it becomes a java abstract class and so cannot be instantiated. Variables declared in a java interface by default is final.

How can you invoke a defined method of an abstract class?

An abstract class cannot be instantiated directly. An abstract class has to be sub-classed first and then instantiated. Only then the method defined in the abstract class can be invoked.

What is an abstract class?

A class containing atleast one abstract method is called an abstract class. A method that has no implementation and which is expected to be implemented by a subclass is called an abstract method. An Abstract class cannot be instantiated. It is expected to be extended by a subclass. An abstract class may contain static variables declared. Any class with an abstract method must be declared explicitly as abstract. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.

What is an abstract method?

A method that has no implementation and which is expected to be implemented by a subclass is called an abstract method.