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.in);
            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 java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

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) {
                                                myCell.setCellType(cell.getCellType());
                                                switch (cell.getCellType()) {
                                                case HSSFCell.CELL_TYPE_BLANK:
                                                      myCell.setCellValue("");
                                                      break;

                                                case HSSFCell.CELL_TYPE_BOOLEAN:
                                                      myCell.setCellValue(cell.getBooleanCellValue());
                                                      break;

                                                case HSSFCell.CELL_TYPE_ERROR:
                                                      myCell.setCellErrorValue(cell.getErrorCellValue());
                                                      break;

                                                case HSSFCell.CELL_TYPE_FORMULA:
                                                      myCell.setCellFormula(cell.getCellFormula());
                                                      break;

                                                case HSSFCell.CELL_TYPE_NUMERIC:
                                                      myCell.setCellValue(cell.getNumericCellValue());
                                                      break;

                                                case HSSFCell.CELL_TYPE_STRING:
                                                      myCell.setCellValue(cell.getStringCellValue());
                                                      break;
                                                default:
                                                      myCell.setCellFormula(cell.getCellFormula());
                                                }
                                          }
                                    }
                              }
                        }
                  }
            }
            bis.close();
            BufferedOutputStream bos = new BufferedOutputStream(
                        new FileOutputStream("workbook.xls", true));
            myWorkBook.write(bos);
            bos.close();
      }
}

Monday, October 22, 2012

What are the differences between Interface and Abstract class?

Abstract Classs
Intrerface
 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.
Problem:
To create complex objects, we use the factory method but it provides same class object for that method.
Solution:
We provide one extra interface to switch the factory.
Implementation:
Button.java:
public interface Button {
      public void click();
}
Xbutton.java:
public class XButton implements Button {
      @Override
      public void click() {
            System.out.println("XButton is clicked.");
      }
}
Ybutton.java:
public class YButton implements Button {
      @Override
      public void click() {
            System.out.println("YButton is clicked.");
      }
}
ButtonFactory.java:
public interface ButtonFactory {
      public Button createButton();
}
XButtonFactory.java:
public class XButtonFactory implements ButtonFactory {
      @Override
      public Button createButton() {     
            return new XButton();
      }
}
YButtonFactory.java:
public class YButtonFactory implements ButtonFactory{
      @Override
      public Button createButton() {
            return new YButton();
      }
}
Test.java:
public class Test {
      public static void main(String[] args) {
        ButtonFactory factory = new XButtonFactory();
        Button button = factory.createButton();
        button.click();
        factory = new YButtonFactory();
        button = factory.createButton();
        button.click();
    }
}

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.

Problem:
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.

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

Let’s see the implementation:

Animal:
public interface Animal {
    public void makeSound();
}

Dog: Actual Animal
public class Dog implements Animal {
    public void makeSound() {
            System.out.println("woof!");
    }
}

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:
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:
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.


Association
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
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.
Eg:
public class Library {
      private Student student;

      public Student getStudent() {
            return student;
      }

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

Composition
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.
Eg:
public class Library {
      private Book book;

      public Book getBook() {
            return book;
      }

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

Dependency
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.area();
      }
}
Util is not useful without Circle and Circle will not provide calculateArea without Util.

Multiplicity
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.
One:
public class One {
      private Two two;

      public Two getTwo() {
            return two;
      }

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

      public One getOne() {
            return one;
      }

      public void setOne(One one) {
            this.one = one;
      }
     
}

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

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

Generalization:
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.
Eg.
public class GenericCar extends Car{

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

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

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

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