Wednesday, November 7, 2012

Scanner Demo

package com.lenin.util;

import java.util.Scanner;

public class ScannerDemo {

      public static void main(String[] args) {
            Scanner scanner = new Scanner(;
            System.out.print("Enter a string:");
            String data = scanner.nextLine();
            System.out.println("The string entered is :" + data);
            System.out.print("Enter an integer number:");
            int intNumber = scanner.nextInt();
            System.out.println("The int number entered is :" + intNumber);

Monday, November 5, 2012

Create a copy of excel using POI

package com.lenin.util;


import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelReadAndWrite {

      public static void main(String[] args) throws IOException {
            ExcelReadAndWrite excel = new ExcelReadAndWrite();
            excel.process("D:/LNN/My Workspace/POI/src/tables.xls");
      public void process(String fileName) throws IOException {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName));
            HSSFWorkbook workbook = new HSSFWorkbook(bis);
            HSSFWorkbook myWorkBook = new HSSFWorkbook();
            HSSFSheet sheet = null;
            HSSFRow row = null;
            HSSFCell cell = null;
            HSSFSheet mySheet = null;
            HSSFRow myRow = null;
            HSSFCell myCell = null;
            int sheets = workbook.getNumberOfSheets();
            int fCell = 0;
            int lCell = 0;
            int fRow = 0;
            int lRow = 0;
            for (int iSheet = 0; iSheet < sheets; iSheet++) {
                  sheet = workbook.getSheetAt(iSheet);
                  if (sheet != null) {
                        mySheet = myWorkBook.createSheet(sheet.getSheetName());
                        fRow = sheet.getFirstRowNum();
                        lRow = sheet.getLastRowNum();
                        for (int iRow = fRow; iRow <= lRow; iRow++) {
                              row = sheet.getRow(iRow);
                              myRow = mySheet.createRow(iRow);
                              if (row != null) {
                                    fCell = row.getFirstCellNum();
                                    lCell = row.getLastCellNum();
                                    for (int iCell = fCell; iCell < lCell; iCell++) {
                                          cell = row.getCell(iCell);
                                          myCell = myRow.createCell(iCell);
                                          if (cell != null) {
                                                switch (cell.getCellType()) {
                                                case HSSFCell.CELL_TYPE_BLANK:

                                                case HSSFCell.CELL_TYPE_BOOLEAN:

                                                case HSSFCell.CELL_TYPE_ERROR:

                                                case HSSFCell.CELL_TYPE_FORMULA:

                                                case HSSFCell.CELL_TYPE_NUMERIC:

                                                case HSSFCell.CELL_TYPE_STRING:
            BufferedOutputStream bos = new BufferedOutputStream(
                        new FileOutputStream("workbook.xls", true));

Monday, October 22, 2012

What are the differences between Interface and Abstract class?

Abstract Classs
 A class may extend only one abstract class.
A Class may implement several interfaces.
An abstract class can have non-abstract methods.
All methods of an Interface are abstract.
An abstract class can have instance variables.
An Interface cannot have instance variables.
An abstract class can have any visibility: public, private, protected.
An Interface visibility must be public (or) none.
An abstract class can contain constructors.
An Interface cannot contain constructors.
An abstract class can provide complete, default code and/or just the details that have to be overridden.
An interface cannot provide any code at all, just the signature. (I.e. All Interface methods are public).
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.

Friday, October 19, 2012

Creational Design Pattern : Abstract Factory

Abstract Factory is a creational design pattern and it provides one level of interface higher than the Factory design pattern.
To create complex objects, we use the factory method but it provides same class object for that method.
We provide one extra interface to switch the factory.
public interface Button {
      public void click();
public class XButton implements Button {
      public void click() {
            System.out.println("XButton is clicked.");
public class YButton implements Button {
      public void click() {
            System.out.println("YButton is clicked.");
public interface ButtonFactory {
      public Button createButton();
public class XButtonFactory implements ButtonFactory {
      public Button createButton() {     
            return new XButton();
public class YButtonFactory implements ButtonFactory{
      public Button createButton() {
            return new YButton();
public class Test {
      public static void main(String[] args) {
        ButtonFactory factory = new XButtonFactory();
        Button button = factory.createButton();;
        factory = new YButtonFactory();
        button = factory.createButton();;

Wednesday, October 10, 2012

Design Pattern: NullObject

Null Object Pattern is one of good pattern used to avoid NullPointerException.
Null Object is not ‘null’ i.e. it is not default value used for object references.

We use the null condtion to check the value is null or not null to avoid Null Pointer Exception But it is not a proper solution because we need to add this check whereever we call a method on our object.
I.e. we need to null check for each object before making the calls finally, unnecessary code and unnecessary checks will be added in our program.

Create an object that will do nothing whenever nothing is available for reference.

Let’s see the implementation:

public interface Animal {
    public void makeSound();

Dog: Actual Animal
public class Dog implements Animal {
    public void makeSound() {

NullAnimal: Default Animal
public class NullAnimal implements Animal {
    public void makeSound() {

When we know actual animal then we will create that animal class if not applicable we will create NullAnimal with default and it will not do anything.

Cohesion and Coupling

Cohesion and Coupling deal with the quality of an Obeject Oriented design. Generally, good OO design should be loosely coupled and highly cohesive. Lot of the design principles, design patterns which have been created are based on the idea of “Loose coupling and high cohesion”.
The aim of the design should be to make the application:
  • easier to develop
  • easier to maintain
  • easier to add new features
  • less Fragile.
Coupling is the degree to which one class knows about another class. Let us consider two classes class A and class B. If class A knows class B through its interface only i.e it interacts with class B through its API then class A and class B are said to be loosely coupled.
If on the other hand class A apart from interacting class B by means of its interface also interacts through the non-interface stuff of class B then they are said to be tightly coupled. Suppose the developer changes the class B‘s non-interface part i.e non API stuff then in case of loose coupling class A does not breakdown but tight coupling causes the class A to break.
So its always a good OO design principle to use loose coupling between the classes i.e all interactions between the objects in OO system should use the APIs. An aspect of good class and API design is that classes should be well encapsulated.
Cohesion is used to indicate the degree to which a class has a single, well-focused purpose. Coupling is all about how classes interact with each other, on the other hand cohesion focuses on how single class is designed. Higher the cohesiveness of the class better is the OO design.
Benefits of Higher Cohesion:
  • Highly cohesive classes are much easier to maintain and less frequently changed.
  • Such classes are more usable than others as they are designed with a well-focused purpose.
Single Responsibility principle aims at creating highly cohesive classes.

Thursday, October 4, 2012

UML Relations : Association, Aggregation, Composition, Dependency, Realization, Abstraction and Generalization.

We use some key terms to specify the relationship between objects. Those are Association, Aggregation, Composition, Dependency, Realization, Abstraction and Generalization. I have tried to put the relations in following chart as per their definations to remember easily.

An Association is the basic term to represent the relation between objects and we can say it is parent of any relation between objects.

Aggregation is more specific than Association. It is a variant of the "has a" or association relationship; I.e. when an object holds other object then we called it as Aggregation.
public class Library {
      private Student student;

      public Student getStudent() {
            return student;

      public void setStudent(Student student) {
            this.student = student;

Composition is more specific than aggregation. It is a stronger variant of the "owns a" or association relationship i.e. contains object will not exists without the container class.
public class Library {
      private Book book;

      public Book getBook() {
            return book;

      public void setBook(Book book) {
   = book;
There will be no book without library.

Dependency is more specific than Composition. It is a weaker form of relationship which indicates that one class depends on another because it uses it at some point of time. I.e. One class depends on another.
public class Circle {
      public void calulateArea(Util util){
Util is not useful without Circle and Circle will not provide calculateArea without Util.

Multiplicity is more specific than Composition. This is association relationship indicates that (at least) one of the two related classes makes reference to the other. I.e. one contains other and vice-versa.
public class One {
      private Two two;

      public Two getTwo() {
            return two;

      public void setTwo(Two two) {
            this.two = two;
public class Two {
      private One one;

      public One getOne() {
            return one;

      public void setOne(One one) {
   = one;

Abstraction is an association used to hide the low level implementation. I.e. Considering the Category of the object is an abstraction.
public interface Vehicle {
      public void forward ();
      public void reverse ();
      public void right ();
      public void left ();

A realization relationship between classes and interfaces and between components and interfaces shows that the class realizes the operations offered by the interface.
public abstract class Car implements Vehicle{
      public void forward(){}
      public void reverse(){}
      public void right(){}
      public void left(){}   

Generalization uses a “is-a” relationship from a specialization to the generalization class. Common structure and behavior are used from the specialization to the generalized class.
public class GenericCar extends Car{

      public void forward() {      
            System.out.println("move forwad.");

      public void reverse() {
            System.out.println("move reverse.");

      public void right() {
            System.out.println("move right.");

      public void left() {
            System.out.println("move left.");