20 September, 2011

Design Pattern notes

Why do we need design pattern?
Each pattern describe a problem which occurs again  and again and then describe a solution following which we can avoid that problem

Types of design pattern:
1) Creational
2) Structural
3)Behavioral

Creational Design Pattern:
It provides us a system in which the object creation are independent.
a)Factory Pattern:
Provides an interface for creating object but let sub-class decide which class to instantiate. It is used when we require to instantiate a sub-class according to the data provided.
public interface Person {
    public void showPersonDetails(String name);
}
public class Male implements Person{
    @Override
    public void showPersonDetails(String name) {
        System.out.println("hello i am male and my name is="+name);
       
    }
}
public class Female implements Person{
    @Override
    public void showPersonDetails(String name) {
        System.out.println("hi i m female and my name is="+name);
    }
}
public class PersonFactory {
    private PersonFactory(){
       
    }
    public Person getPersonInstance(String gender){
        if(gender.equalsIgnoreCase("male")){
            return new Male();
        }else{
            return new Female();
        }
    }
    public static PersonFactory newInstance(){
        return new PersonFactory();
    }
}
public class FactoryPatternImpl {
    public static void main(String[] args){
        PersonFactory pf = PersonFactory.newInstance();
        Male m =(Male) pf.getPersonInstance("male");
        m.showPersonDetails("mks");
   
    }
}

b)Singleton:
It ensures that a class has only one instance. It is generally used in case of Logging.
public class Log implements Cloneable {
    private static Log log = null;
    private Log(String str) {
        System.out.println("got log instance");
    }
    public synchronized static Log getLogInstance(String str) {
        if (log == null) {
            return new Log(str);
        }
        return log;
    }
    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }
}
public class SingletonImpl {
    public static void main(String[] args) {
        Log l1 = Log.getLogInstance("hello");
    }
}


c)Prototype:
The prototype means making a clone. This implies cloning of an object to avoid creation. If the cost of creating a new object is large and creation is resource intensive, we clone the object.
We use the interface Cloneable and call its method clone() to clone the object.



class Car {
    private String name;
    public Car(String s) {
        name = s;
    }
    public String getName() {
        return name;
    }
    public void setName(String s) {
        name = s;
    }
}
 

class Person implements Cloneable {

    private Car car;

    public Car getCar() {
        return car;
    }

    public Person(String carName) {
        car = new Car(carName);
    }

    public Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            return null;
        }
    }
}



public class PrototypeImpl {
    public static void main(String[] args){
        Person p = new Person("civic");
        Person q = (Person) p.clone();
        System.out.println(q.getCar().getName());
    }
}

d)objectpool:
While the Prototype pattern helps in improving the performance by cloning the objects, the Object Pool pattern offer a mechanism to reuse objects that are expensive to create.


object pool pattern is used in db connection creation.




Structural Design Pattern:
It describes how object and class are composed together to form a larger object.
a)Facade Pattern:
  It hides the complexities of the system and provides an interface to the client from where the client can access the system.
In Java, the interface JDBC can be called a facade. We as
users or clients create connection using the “java.sql.Connection” interface, the implementation of which we are not concerned about. 

In general web application this layer separates the front end layer and service layer.


A general flow of web application:
Front End-->Facade layer-->Service layer-->DAO layer-->DB 




 

25 February, 2011

javafaq


Question. Why do we use transient variable? 
Ans:Transient member variable does not serialized with the object. When the class gets de-serialized, this variable gets initialized with a default value of its data type (i.e. zero for integers).

Question. How many types of casting are there in java.
Ans: a)Explicit casting(When u assign superclass object to subclass object)
           Object o = "hello";
           String x;
           x= (String) o;       
       b)implicit casting(when u assign subclass object to superclass)
            String x1 = "hi";
           Object o1;
           o1 = x1;

Question: What's the difference between constructors and other methods?
Answer: Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

Question: What's the difference between constructors and methods?
Answer:
    Constructors:
        must have the same name as the class name.
        does not return any value.
        called once while making instance of the class
    methods:
        method name differ from class name
        it may return/not return any value.
        can be called many times.

Question: Explain the usage of Java packages.
Answer:
way of organizing the files
helps resolving naming conflicts when classes with the same names.
protect data from being used by the non-authorized classes.

Question: what is difference between "==" and the method "equals()"?
Answer:  '==' : Check the actual object instances are same or not.
         .equals:  check if the contents are equal or not.

Question: what is difference between && and &
Answer:
     &&:if first condition fails then 2nd condition is not checked.
     &:if first condition fails even it checks 2nd condition.

Question: How can a subclass call a method or a constructor defined in a superclass?
Answer: for method :super.myMethod();
        for constructor:super();

Question: How is shallow copy implemented in Java?
Answer: Object cloning.

Question: How would you make a copy of an entire Java object with its state?
Answer: Implement Cloneable interface and override clone() method.

Question: If you're overriding the method equals() of an object, which other method you also need to override?
Answer: hashCode()

Question:What are access modifiers in java?
Answer:
        private: accessible only inside the class
        default: accessible in same package only
        protected: accessible in same package and all subclasses of this class
        public: accessible everywhere

Question: What is polymorphism in java?
Answer: Polymorphism means one name many form. Java implement it in 2 ways.
1) Method overloading(Compile time polymorphism):
   In same class, if name of the method remains common but the number and type of parameters are different, then it is called method overloading in Java.
   public class alpha{
     public int add(int a,int b) {
       return a+b;
     }
     public int add(int a,int b,int c){
       return a+b+c;
     }
     public static void main(String[] args){
       alpha a = new alpha();
       System.out.println(a.add(1,2));
       System.out.println(a.add(1,2,3));
     }
   }
2) Method overriding:
  A method is said to be overridden when one is in parent class and
  another is in child class with the same name, same return type, same
  parameter. It is implemented in two ways:  
    a)through inheritence:
      public class Base{
        public void show(){
          System.out.println("base")
        }
      }
      public class Derive extends Base{
        public void show{
          System.out.println("derive");
        }
        public static void main(String[] args){
          Base b = new Derive();
          b.show();
        }
      }
      b)through java interface :
what is enhanced for loop in java?
for loop before java5(old form):
for (int i=0; i < array.length; i++) {
    System.out.println("Element: " + array[i]);
}
for loop in newer form
for (String element : array) {
    System.out.println("Element: " + element);
}
 1)with old form there is initialization,termination and increment.
 with enhanced for loop we dont require to go for these steps
2) new form increases the clarity and readability.

Why do we go for enhanced for loop even we have iterator?
 when we use iterator there is chances of getting it wrong.
 during nested for loop, with iterator we have to first take the outer variable and
 then we can use it in inner variable.
 for (Iterator i = empList.iterator(); i.hasNext(); ) {
     Emp emp = (Emp) i.next();
     for (Iterator j = deptList.iterator(); j.hasNext(); )
         db_opr.add(emp,j.next);
 }
 but with enhanced for loop we can go straight forward as:
 for (Emp emp : empList)
     for (Dept dept : deptList)
        db_opr.add(emp,dept);

 enhanced for loop has limitations:  
1)The program needs access to the iterator in order to remove the current element.
  2)it is not usable for loops where you need to replace elements in a list or array
  as you traverse it.
  3)it is not usable for loops that must iterate over multiple collections in parallel.