[go: up one dir, main page]

0% found this document useful (0 votes)
94 views37 pages

006 Misc 37

The document discusses various design patterns in Java including Singleton, Factory, Observer, Decorator, and Abstract Factory patterns. It provides code examples to illustrate each pattern. For Factory pattern, it shows an example of creating different mobile objects like Samsung, Sony, Blackberry using a MobileFactory class. For Abstract Factory pattern, it demonstrates creating mobile and color objects using separate factories extending an abstract factory class.

Uploaded by

JP
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views37 pages

006 Misc 37

The document discusses various design patterns in Java including Singleton, Factory, Observer, Decorator, and Abstract Factory patterns. It provides code examples to illustrate each pattern. For Factory pattern, it shows an example of creating different mobile objects like Samsung, Sony, Blackberry using a MobileFactory class. For Abstract Factory pattern, it demonstrates creating mobile and color objects using separate factories extending an abstract factory class.

Uploaded by

JP
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

MISC

Ques 1. What is design patterns?


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

Ques 2. Can you name few design patterns used in standard JDK library?
Ans. Decorator design pattern which is used in various Java IO classes, Singleton pattern which is used in Runtime , Calendar and
various other classes, Factory pattern which is used along with various Immutable classes likes Boolean e.g. Boolean.valueOf and
Observer pattern which is used in Swing and many event listener frameworks.

Ques 3. What is Singleton design pattern in Java ? write code for thread-safe singleton in Java.
Ans. Singleton pattern focus on sharing of expensive object in whole system. Only one instance of a particular class is maintained in
whole application which is shared by all modules. Java.lang.Runtime is a classical example of Singleton design pattern. From Java 5
onwards you can use enum to thread-safe singleton.

Ques 4. What is main benefit of using factory pattern? Where do you use it?
Ans. Factory pattern’s main benefit is increased level of encapsulation while creating objects. If you use Factory to create object you
can later replace original implementation of Products or classes with more advanced and high performance implementation without
any change on client layer.

Ques 5. What is observer design pattern in Java?


Ans. Observer design pattern is based on communicating changes in state of object to observers so that they can take there action.
Simple example is a weather system where change in weather must be reflected in Views to show to public. Here weather object is
Subject while different views are Observers.

Ques 6. Give example of decorator design pattern in Java ? Does it operate on object level or class level?
Ans. Decorator pattern enhances capability of individual object. Java IO uses decorator pattern extensively and classical example is
Buffered classes like BufferedReader and BufferedWriter which enhances Reader and Writer objects to perform Buffer level reading
and writing for improved performance.

Ques 7. What is decorator design pattern in Java?


Ans.
 Decorator design pattern is used to enhance the functionality of a particular object at run-time or dynamically.
 At the same time other instance of same class will not be affected by this so individual object gets the new behavior.
 Basically we wrap the original object through decorator object.
 Decorator design pattern is based on abstract classes and we derive concrete implementation from that classes,
 It’s a structural design pattern and most widely used.

Ques 8. What is Factory Design Pattern with example?


Ans.

Factory pattern is one of most used design pattern in Java. This type of design pattern comes under creational pattern as this pattern
provides one of the best ways to create an object.
In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a
common interface.
We're going to create a Mobile interface and concrete classes implementing the Mobile interface. A factory class MobileFactory is
defined as a next step.
FactoryPatternDemo, our demo class will use MobileFactory to get a Mobile object. It will pass information (SAMSUNG / SONY /
BLACKBERRY) to MobileFactory to get the type of object it needs.
Step 1: Create an interface.
Mobile.java
public interface Mobile {
   void draw();
}
Step 2
Create concrete classes implementing the same interface.
Sony.java
public class Sony implements Mobile {
   @Override
   public void draw() {
      System.out.println("Inside Sony::draw() method.");
   }
}
Blackberry.java
public class Blackberry implements Mobile {
   @Override
   public void draw() {
      System.out.println("Inside Blackberry::draw() method.");
   }
}
Samsung.java
public class Samsung implements Mobile {
   @Override
   public void draw() {
      System.out.println("Inside Samsung::draw() method.");
   }
}
Step 3
Create a Factory to generate object of concrete class based on given information.
MobileFactory.java
public class MobileFactory {
   //use getMobile method to get object of type Mobile 
   public Mobile getMobile(String MobileType){
      if(MobileType == null){
         return null;
   }
      if(MobileType.equalsIgnoreCase("SAMSUNG")){
         return new Samsung();
      } else if(MobileType.equalsIgnoreCase("SONY")){
         return new Sony();
      } else if(MobileType.equalsIgnoreCase("BLACKBERRY")){
         return new Blackberry();
   }
      return null;
   }
}
Step 4
Use the Factory to get object of concrete class by passing an information such as type.
FactoryPatternDemo.java
public class FactoryPatternDemo {
   public static void main(String[] args) {
      MobileFactory MobileFactory = new MobileFactory();
      //get an object of Samsung and call its draw method.
      Mobile Mobile1 = MobileFactory.getMobile("SAMSUNG");
      //call draw method of Samsung
      Mobile1.draw();
      //get an object of Sony and call its draw method.
      Mobile Mobile2 = MobileFactory.getMobile("SONY");
      //call draw method of Sony
      Mobile2.draw();
      //get an object of Blackberry and call its draw method.
      Mobile Mobile3 = MobileFactory.getMobile("BLACKBERRY");
      //call draw method of Blackberry
      Mobile3.draw();
   }
}
Step 5
Verify the output.
Inside Samsung::draw() method.
Inside Sony::draw() method.
Inside Blackberry::draw() method.

Ques 9. What is Abstract Factory Design Patter in Java with example?


Ans.
Abstract Factory patterns works around a super-factory which creates other factories. This factory is also called as Factory of
factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an
object.
In Abstract Factory pattern an interface is responsible for creating a factory of related objects, without explicitly specifying their
classes. Each generated factory can give the objects as per the Factory pattern.
We're going to create a Shape and Color interfaces and concrete classes implementing these interfaces. We create an abstract
factory class AbstractFactory as next step. Factory classes MobileFactory and ColorFactory are defined where each factory extends
AbstractFactory. A factory creator/generator class FactoryProducer is created.
AbstractFactoryPatternDemo, our demo class uses FactoryProducer to get a AbstractFactory object. It will pass information
(SAMSUNG / SONY / BLACKBERRY for Mobile) to AbstractFactory to get the type of object it needs. It also passes information (RED /
GREEN / BLUE for Color) to AbstractFactory to get the type of object it needs.
Step 1
Create an interface for Mobiles.
Mobile.java
public interface Mobile {
   void make();
}
Step 2
Create concrete classes implementing the same interface.
Sony.java
public class Sony implements Mobile {
   @Override
   public void make() {
      System.out.println("Inside Sony::make() method.");
   }
}

Blackberry.java
public class Blackberry implements Mobile {
   @Override
   public void make() {
      System.out.println("Inside Blackberry::make() method.");
   }
}
Samsung.java
public class Samsung implements Mobile {
   @Override
   public void make() {
      System.out.println("Inside Samsung::make() method.");
   }
}
Step 3
Create an interface for Colors.
Color.java
public interface Color {
   void fill();
}
Step4
Create concrete classes implementing the same interface.
Red.java
public class Red implements Color {
   @Override
   public void fill() {
      System.out.println("Inside Red::fill() method.");
   }
}
Green.java
public class Green implements Color {
   @Override
   public void fill() {
      System.out.println("Inside Green::fill() method.");
   }
}
Blue.java
public class Blue implements Color {
   @Override
   public void fill() {
      System.out.println("Inside Blue::fill() method.");
   }
}
Step 5
Create an Abstract class to get factories for Color and Mobile Objects.
AbstractFactory.java
public abstract class AbstractFactory {
   abstract Color getColor(String color);
   abstract Mobile getMobile(String shape) ;
}
Step 6
Create Factory classes extending AbstractFactory to generate object of concrete class based on given information.
MobileFactory.java
public class MobileFactory extends AbstractFactory {
   @Override
   public Mobile getMobile(String shapeType){
      if(shapeType == null){
         return null;
   }
      if(shapeType.equalsIgnoreCase("SAMSUNG")){
         return new Samsung();
      } else if(shapeType.equalsIgnoreCase("SONY")){
         return new Sony();
      } else if(shapeType.equalsIgnoreCase("BLACKBERRY")){
         return new Blackberry();
   }
      return null;
   }
   @Override
   Color getColor(String color) {
      return null;
   }
}
ColorFactory.java
public class ColorFactory extends AbstractFactory {
   @Override
   public Mobile getMobile(String shapeType){
      return null;
   }
  
   @Override
   Color getColor(String color) {
      if(color == null){
         return null;
   }
      if(color.equalsIgnoreCase("RED")){
         return new Red();
      } else if(color.equalsIgnoreCase("GREEN")){
         return new Green();
      } else if(color.equalsIgnoreCase("BLUE")){
         return new Blue();
   }
      return null;
   }
}
Step 7
Create a Factory generator/producer class to get factories by passing an information such as Mobile or Color
FactoryProducer.java
public class FactoryProducer {
   public static AbstractFactory getFactory(String choice){
      if(choice.equalsIgnoreCase("SHAPE")){
         return new MobileFactory();
      } else if(choice.equalsIgnoreCase("COLOR")){
         return new ColorFactory();
   }
      return null;
   }
}
Step 8
Use the FactoryProducer to get AbstractFactory in order to get factories of concrete classes by passing an information such as type.
AbstractFactoryPatternDemo.java
public class AbstractFactoryPatternDemo {
   public static void main(String[] args) {
      //get shape factory
      AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE");
      //get an object of Mobile Samsung
      Mobile shape1 = shapeFactory.getMobile("SAMSUNG");
      //call make method of Mobile Samsung
      shape1.make();
      //get an object of Mobile Sony
      Mobile shape2 = shapeFactory.getMobile("SONY");
      //call make method of Mobile Sony
      shape2.make();
      //get an object of Mobile Blackberry 
      Mobile shape3 = shapeFactory.getMobile("BLACKBERRY");
      //call make method of Mobile Blackberry
      shape3.make();
      //get color factory
      AbstractFactory colorFactory = FactoryProducer.getFactory("COLOR");
      //get an object of Color Red
      Color color1 = colorFactory.getColor("RED");

      //call fill method of Red


      color1.fill();
      //get an object of Color Green
      Color color2 = colorFactory.getColor("Green");
      //call fill method of Green
      color2.fill();
      //get an object of Color Blue
      Color color3 = colorFactory.getColor("BLUE");
      //call fill method of Color Blue
      color3.fill();
   }
}
Step 9
Verify the output:
Inside Samsung::make() method.
Inside Sony::make() method.
Inside Blackberry::make() method.
Inside Red::fill() method.
Inside Green::fill() method.
Inside Blue::fill() method.

Ques 10. What is Singleton Design Pattern with example in java design patterns?
Ans.
Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this
pattern provides one of the best way to create an object.
This pattern involves a single class which is responsible to creates own object while making sure that only single object get created.
This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.
We're going to create a SingleObject class. SingleObject class have its constructor as private and have a static instance of itself.
SingleObject class provides a static method to get its static instance to outside world. SingletonPatternDemo, our demo class will use
SingleObject class to get a SingleObject object.
Step 1
Create a Singleton Class.
SingleObject.java
public class SingleObject {

   //create an object of SingleObject


   private static SingleObject instance = new SingleObject();
   //make the constructor private so that this class cannot be
   //instantiated
   private SingleObject(){}
   //Get the only object available
   public static SingleObject getInstance(){
      return instance;
   }
   public void showMessage(){
      System.out.println("Hello World!");
   }
}
Step 2
Get the only object from the singleton class.
SingletonPatternDemo.java
public class SingletonPatternDemo {
   public static void main(String[] args) {
      //illegal construct
      //Compile Time Error: The constructor SingleObject() is not visible
      //SingleObject object = new SingleObject();
      //Get the only object available
      SingleObject object = SingleObject.getInstance();
      //show the message
      object.showMessage();
   }
}
Step 3
Verify the output:
Hello World!

Ques 11. What is Prototype Design Pattern in java design patterns?


Ans.
Prototype pattern refers to creating duplicate object while keeping performance in mind. This type of design pattern comes under
creational pattern as this pattern provides one of the best way to create an object.

This pattern involves implementing a prototype interface which tells to create a clone of the current object. This pattern is used when
creation of object directly is costly. For example, a object is to be created after a costly database operation. We can cache the object,
returns its clone on next request and update the database as as and when needed thus reducing database calls.
We're going to create an abstract class Mobile and concrete classes extending the Mobile class. A class MobileCache is defined as a
next step which stores shape objects in a Hashtable and returns their clone when requested.
PrototypPatternDemo, our demo class will use MobileCache class to get a Mobile object.
Step 1
Create an abstract class implementing Clonable interface.
Mobile.java
public abstract class Mobile implements Cloneable {
   private String id;
   protected String type;
   abstract void make(); 
   public String getType(){
      return type;
   }
   public String getId() {
      return id;
   }
   public void setId(String id) {
      this.id = id;
   }
   public Object clone() {
      Object clone = null;
      try {
         clone = super.clone();
      } catch (CloneNotSupportedException e) {
         e.printStackTrace();
   }
      return clone;
   }
}

Step 2
Create concrete classes extending the above class.
Sony.java
public class Sony extends Mobile {
   public Sony(){
     type = "Sony";
   }
   @Override
   public void make() {
      System.out.println("Inside Sony::make() method.");
   }
}
Blackberry.java
public class Blackberry extends Mobile {
   public Blackberry(){
     type = "Blackberry";
   }
   @Override
   public void make() {
      System.out.println("Inside Blackberry::make() method.");
   }
}
Samsung.java
public class Samsung extends Mobile {
   public Samsung(){
     type = "Samsung";
   }
   @Override
   public void make() {
      System.out.println("Inside Samsung::make() method.");
   }
}

Step 3
Create a class to get concreate classes from database and store them in a Hashtable.
MobileCache.java
import java.util.Hashtable;
public class MobileCache {
   private static Hashtable<String, Mobile> shapeMap  = new Hashtable<String, Mobile>();
   public static Mobile getMobile(String shapeId) {
      Mobile cachedMobile = shapeMap.get(shapeId);
      return (Mobile) cachedMobile.clone();
   }
   // for each shape run database query and create shape
   // shapeMap.put(shapeKey, shape);
   // for example, we are adding three shapes
   public static void loadCache() {
      Samsung circle = new Samsung();
      circle.setId("1");
      shapeMap.put(circle.getId(),circle);
      Blackberry square = new Blackberry();
      square.setId("2");
      shapeMap.put(square.getId(),square);
      Sony rectangle = new Sony();
      rectangle.setId("3");
      shapeMap.put(rectangle.getId(),rectangle);
   }
}

Step 4
PrototypePatternDemo uses MobileCache class to get clones of shapes stored in a Hashtable.
PrototypePatternDemo.java
public class PrototypePatternDemo {
   public static void main(String[] args) {
      MobileCache.loadCache();

      Mobile clonedMobile = (Mobile) MobileCache.getMobile("1");


      System.out.println("Mobile : " + clonedMobile.getType());

      Mobile clonedMobile2 = (Mobile) MobileCache.getMobile("2");


      System.out.println("Mobile : " + clonedMobile2.getType());

      Mobile clonedMobile3 = (Mobile) MobileCache.getMobile("3");


      System.out.println("Mobile : " + clonedMobile3.getType());
   }
}

Step 5
Verify the output.
Mobile : Samsung
Mobile : Blackberry
Mobile : Sony

Ques 12. What is Decorator Design Pattern in java design patterns?


Ans.
Decorator pattern allows to add new functionality an existing object without altering its structure. This type of design pattern comes
under structural pattern as this pattern acts as a wrapper to existing class.
This pattern creates a decorator class which wraps the original class and provides additional functionality keeping class methods
signature intact.
We are demonstrating use of Decorator pattern via following example in which we'll decorate a shape with some color without alter
shape class.
We're going to create a Mobile interface and concrete classes implementing the Mobile interface. We then create a abstract
decorator class MobileDecorator implementing the Mobile interface and having Mobile object as its instance variable.
RedMobileDecorator is concrete class implementing MobileDecorator.
DecoratorPatternDemo, our demo class will use RedMobileDecorator to decorate Mobile objects.
Step 1
Create an interface.
Mobile.java
public interface Mobile {
   void make();
}

Step 2
Create concrete classes implementing the same interface.
Sony.java
public class Sony implements Mobile {
   @Override
   public void make() {
      System.out.println("Mobile: Sony");
   }
}
Blackberry.java
public class Blackberry implements Mobile {
   @Override
   public void make() {
      System.out.println("Mobile: Blackberry");
   }
}
Step 3
Create abstract decorator class implementing the Mobile interface.
MobileDecorator.java
public abstract class MobileDecorator implements Mobile {
   protected Mobile decoratedMobile;
   public MobileDecorator(Mobile decoratedMobile){
      this.decoratedMobile = decoratedMobile;
   }
   public void make(){
      decoratedMobile.make();
   }
}
Step 4
Create concrete decorator class extending the MobileDecorator class.
RedMobileDecorator.java
public class RedMobileDecorator extends MobileDecorator {
   public RedMobileDecorator(Mobile decoratedMobile) {
      super(decoratedMobile);
   }
   @Override
   public void make() {
      decoratedMobile.make();        
      setRedBorder(decoratedMobile);
   }
   private void setRedBorder(Mobile decoratedMobile){
      System.out.println("Border Color: Red");
   }
}
Step 5
Use the RedMobileDecorator to decorate Mobile objects.
DecoratorPatternDemo.java
public class DecoratorPatternDemo {
   public static void main(String[] args) {
      Mobile circle = new Blackberry();
      Mobile redBlackberry = new RedMobileDecorator(new Blackberry());
      Mobile redSony = new RedMobileDecorator(new Sony());
      System.out.println("Blackberry with normal border");
      circle.make();
      System.out.println("\nBlackberry of red border");
      redBlackberry.make();
      System.out.println("\nSony of red border");
      redSony.make();
   }
}

Step 6
Verify the output.
Blackberry with normal border
Mobile: Blackberry
Blackberry of red border
Mobile: Blackberry
Border Color: Red
Sony of red border
Mobile: Sony
Border Color: Red

Ques 13. What is Observer Design Pattern in java design patterns?


Ans.
Observer pattern is used when there is one to many relationship between objects such as if one object is modified, its depenedent
objects are to be notified automatically. Observer pattern falls under behavioral pattern category.
Observer pattern uses three actor classes. Subject, Observer and Client. Subject, an object having methods to attach and de-attach
observers to a client object. We've created classes Subject, Observer abstract class and concrete classes extending the abstract class
the Observer.
ObserverPatternDemo, our demo class will use Subject and concrete class objects to show observer pattern in action.
Step 1
Create Subject class.
Subject.java
import java.util.ArrayList;
import java.util.List;
public class Subject {
   private List<Observer> observers 
      = new ArrayList<Observer>();
   private int state;
   public int getState() {
      return state;
   }
   public void setState(int state) {
      this.state = state;
      notifyAllObservers();
   }
   public void attach(Observer observer){
      observers.add(observer);
   }
   public void notifyAllObservers(){
      for (Observer observer : observers) {
         observer.update();
   }
   } 
}
Step 2
Create Observer class.
Observer.java
public abstract class Observer {
   protected Subject subject;
   public abstract void update();
}
Step 3
Create concrete observer classes
BinaryObserver.java
public class BinaryObserver extends Observer{
   public BinaryObserver(Subject subject){
      this.subject = subject;
      this.subject.attach(this);
   }
   @Override
   public void update() {
      System.out.println( "Binary String: " 
      + Integer.toBinaryString( subject.getState() ) ); 
   }
}
OctalObserver.java
public class OctalObserver extends Observer{
   public OctalObserver(Subject subject){
      this.subject = subject;
      this.subject.attach(this);
   }
   @Override
   public void update() {
     System.out.println( "Octal String: " 
     + Integer.toOctalString( subject.getState() ) ); 
   }
}

HexaObserver.java
public class HexaObserver extends Observer{
   public HexaObserver(Subject subject){
      this.subject = subject;
      this.subject.attach(this);
   }
   @Override
   public void update() {
      System.out.println( "Hex String: " 
      + Integer.toHexString( subject.getState() ).toUpperCase() ); 
   }
}
Step 4
Use Subject and concrete observer objects.
ObserverPatternDemo.java
public class ObserverPatternDemo {
   public static void main(String[] args) {
      Subject subject = new Subject();
      new HexaObserver(subject);
      new OctalObserver(subject);
      new BinaryObserver(subject);
      System.out.println("First state change: 15");
      subject.setState(15);
      System.out.println("Second state change: 10");
      subject.setState(10);
   }
}
Step 5
Verify the output:
First state change: 15
Hex String: F
Octal String: 17
Binary String: 1111
Second state change: 10
Hex String: A
Octal String: 12
Binary String: 1010

Ques 14. What is MVC design pattern in java design patterns?


Ans.
MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application's concerns.
Model - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes.
View - View represents the visualization of the data that model contains.
Controller - Controller acts on both Model and view. It controls the data flow into model object and updates the view whenever data
changes. It keeps View and Model separate.
We're going to create a Employee object acting as a model.EmployeeView will be a view class which can print employee details on
console and EmployeeController is the controller class responsible to store data in Employee object and update view EmployeeView
accordingly.
MVCPatternDemo, our demo class will use EmployeeController to demonstrate use of MVC pattern.
Step 1
Create Model.
Employee.java
public class Employee {
   private String salary;
   private String name;
   public String getSalary() {
      return salary;
   }
   public void setSalary(String salary) {
      this.salary = salary;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
Step 2
Create View.
EmployeeView.java
public class EmployeeView {
   public void printEmployeeDetails(String employeeName, String employeeSalary){
      System.out.println("Employee: ");
      System.out.println("Name: " + employeeName);
      System.out.println("Salary: " + employeeSalary);
   }
}
Step 3
Create Controller.
EmployeeController.java
public class EmployeeController {
   private Employee model;
   private EmployeeView view;
   public EmployeeController(Employee model, EmployeeView view){
      this.model = model;
      this.view = view;
   }
   public void setEmployeeName(String name){
      model.setName(name);
   }
   public String getEmployeeName(){
      return model.getName();
   }
   public void setEmployeeSalary(String salary){
      model.setSalary(salary);
   }
   public String getEmployeeSalary(){
      return model.getSalary();
   }

   public void updateView(){


      view.printEmployeeDetails(model.getName(), model.getSalary());
   }
}
Step 4
Use the EmployeeController methods to demonstrate MVC design pattern usage.
MVCPatternDemo.java
public class MVCPatternDemo {
   public static void main(String[] args) {
      //fetch employee record based on his roll no from the database
      Employee model  = retriveEmployeeFromDatabase();
      //Create a view : to write employee details on console
      EmployeeView view = new EmployeeView();
      EmployeeController controller = new EmployeeController(model, view);
      controller.updateView();
      //update model data
      controller.setEmployeeName("Craig");
      controller.updateView();
   }
   private static Employee retriveEmployeeFromDatabase(){
      Employee employee = new Employee();
      employee.setName("Maxwell");
      employee.setSalary("30000");
      return employee;
   }
}

Step 5
Verify the output:
Employee: 
Name: Maxwell
Salary: 30000
Employee: 
Name: Kate
Salary: 30000

Ques 15. What is builder pattern and give an example.


Ans.
Builder pattern builds a complex object using simple objects and using a step by step approach. It creates one by one object and
wraps on parent object. E.g. burger making, pizza making, house building etc.
Below we have created a Pizza restaurant where pizza and cold-drink is a typical meal. Pizza can be Italian, American, Mexican etc
which will be packed in a wrapper and Cold-drink can be Pepsi, Coke, Limca etc which will be packed in a bottle.

Creating an Item interface representing food items such as pizzas and cold drinks and concrete classes implementing the Item
interface and a Packing interface representing packaging of food items and concrete classes implementing the Packing interface as
burger would be packed in wrapper and cold drink would be packed as bottle.
We then create a Meal class having ArrayList of Item and a MealBuilder to build different types of Meal object by combining Item.
BuilderPatternDemo, our demo class will use MealBuilder to build a Meal.
Step 1
Create an interface Item representing food item and packing.
Item.java
public interface Item {
   public String name();
   public Packing packing();
   public float price();
}

Packing.java
public interface Packing {
   public String pack();
}

Step 2
Create concreate classes implementing the Packing interface.
Wrapper.java
public class Wrapper implements Packing {

   @Override
   public String pack() {
      return "Wrapper";
   }
}

Bottle.java
public class Bottle implements Packing {
   @Override
   public String pack() {
      return "Bottle";
   }
}
Step 3
Create abstract classes implementing the item interface providing default functionalities.
Pizza.java
public abstract class Pizza implements Item {

   @Override
   public Packing packing() {
      return new Wrapper();
   }
   @Override
   public abstract float price();
}

ColdDrink.java
public abstract class ColdDrink implements Item {
@Override
public Packing packing() {
       return new Bottle();
}
@Override
public abstract float price();
}
Step 4
Create concrete classes extending Pizza and ColdDrink classes
ItalianPizza.java
public class ItalianPizza extends Pizza {
   @Override
   public float price() {
      return 200.0f;
   }
   @Override
   public String name() {
      return "Italian Pizza";
   }
}

AmericanPizza.java
public class AmericanPizza extends Pizza {
   @Override
   public float price() {
      return 300.0f;
   }
   @Override
   public String name() {
      return "American Pizza";
   }
}

Coke.java
public class Coke extends ColdDrink {
   @Override
   public float price() {
      return 30.0f;
   }
   @Override
   public String name() {
      return "Coke";
   }
}
Pepsi.java
public class Pepsi extends ColdDrink {
   @Override
   public float price() {
      return 40.0f;
   }
   @Override
   public String name() {
      return "Pepsi";
   }
}
Step 5
Create a Meal class having Item objects defined above.
Meal.java
import java.util.ArrayList;
import java.util.List;
public class Meal {
   private List<Item> items = new ArrayList<Item>();
   public void addItem(Item item){
      items.add(item);
   }
   public float getCost(){
      float cost = 0.0f;
      for (Item item : items) {
         cost += item.price();
   }
      return cost;
   }
   public void showItems(){
      for (Item item : items) {
         System.out.print("Item : "+item.name());
         System.out.print(", Packing : "+item.packing().pack());
         System.out.println(", Price : "+item.price());
   }
   }
}
Step 6
Create a MealBuilder class, the actual builder class responsible to create Meal objects.
MealBuilder.java
public class MealBuilder {
   public Meal prepareVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new ItalianPizza());
      meal.addItem(new Coke());
      return meal;
   }   
   public Meal prepareNonVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new AmericanPizza());
      meal.addItem(new Pepsi());
      return meal;
   }
}
Step 7
BuiderPatternDemo uses MealBuider to demonstrate builder pattern.
BuilderPatternDemo.java
public class BuilderPatternDemo {
   public static void main(String[] args) {
      MealBuilder mealBuilder = new MealBuilder();
      Meal vegMeal = mealBuilder.prepareVegMeal();
      System.out.println("Veg Meal");
      vegMeal.showItems();
      System.out.println("Total Cost: " +vegMeal.getCost());
      Meal nonVegMeal = mealBuilder.prepareNonVegMeal();
      System.out.println("\n\nNon-Veg Meal");
      nonVegMeal.showItems();
      System.out.println("Total Cost: " +nonVegMeal.getCost());
   }
}
Step 8
Verify the output.
Veg Meal
Item : Italian Pizza, Packing : Wrapper, Price : 200.0
Item : Coke, Packing : Bottle, Price : 30.0
Total Cost: 230.0

Non-Veg Meal
Item : American Pizza, Packing : Wrapper, Price : 300.0
Item : Pepsi, Packing : Bottle, Price : 40.0
Total Cost: 340.0

1. When to use Strategy Design Pattern in Java?


Strategy pattern in quite useful for implementing set of related algorithms e.g. compression algorithms, filtering strategies etc.
Strategy design pattern allows you to create Context classes, which uses Strategy implementation classes for applying business rules.
This pattern follow open closed design principle and quite useful in Java. One example of Strategy pattern from JDK itself is
a Collections.sort() method and Comparator interface, which is a strategy interface and defines strategy for comparing objects.
Because of this pattern, we don't need to modify sort() method (closed for modification) to compare any object, at same time we
can implement Comparator interface to define new comparing strategy (open for extension).

2. What is Observer design pattern in Java? When do you use Observer pattern in Java?
This is one of the most common Java design pattern interview question. Observer pattern is based upon notification, there are two
kinds of object Subject and Observer. Whenever there is change on subject's state observer will receive notification. SeeWhat is
Observer design pattern in Java with real life example for more details.

3. Difference between Strategy and State design Pattern in Java?


This is an interesting Java design pattern interview questions as both Strategy and State pattern has same structure. If you look at
UML class diagram for both pattern they look exactly same, but there intent is totally different. State design pattern is used to define
and mange state of object, while Strategy pattern is used to define a set of interchangeable algorithm and let's client to choose one
of them. So Strategy pattern is a client driven pattern while Object can manage there state itself.

4. What is decorator pattern in Java? Can you give an example of Decorator pattern?
Decorator pattern is another popular java design pattern question which is common because of its heavy usage
in java.iopackage. BufferedReader and BufferedWriter are good example of decorator pattern in Java. See How to use Decorator
pattern in Java fore more details.

5. When to use Composite design Pattern in Java? Have you used previously in your project?
This design pattern question is asked on Java interview not just to check familiarity with Composite pattern but also, whether
candidate has real life experience or not. Composite pattern is also a core Java design pattern, which allows you to treat both whole
and part object to treat in similar way. Client code, which deals with Composite or individual object doesn't differentiate on them, it
is possible because Composite class also implement same interface as there individual part. One of the good example of Composite
pattern from JDK is JPanel class, which is both Component and Container.  Whenpaint() method is called on JPanel, it internally
called paint() method of individual components and let them draw themselves. On second part of this design pattern interview
question, be truthful, if you have used then say yes, otherwise say that you are familiar with concept and used it by your own. By the
way always remember, giving an example from your project creates better impression.

6. What is Singleton pattern in Java? 


Singleton pattern in Java is a pattern which allows only one instance of Singleton class available in whole application.
java.lang.Runtime is good example of Singleton pattern in Java. There are lot's of follow up questions on Singleton pattern see 10
Java singleton interview question answers for those followups 
7. Can you write thread-safe Singleton in Java?
There are multiple ways to write thread-safe singleton in Java e.g by writing singleton using double checked locking, by using static
Singleton instance initialized during class loading. By the way using Java enum to create thread-safe singleton is most simple way.
See Why Enum singleton is better in Java for more details.

8. When to use Template method design Pattern in Java?Template pattern is another popular core Java design pattern interview
question. I have seen it appear many times in real life project itself. Template pattern outlines an algorithm in form of template
method and let subclass implement individual steps. Key point to mention, while answering this question is that template method
should be final, so that subclass can not override and change steps of algorithm, but same time individual step should be abstract, so
that child classes can implement them.

9. What is Factory pattern in Java? What is advantage of using static factory method to create object?
Factory pattern in Java is a creation Java design pattern and favorite on many Java interviews.Factory pattern used to create object
by providing static factory methods. There are many advantage of providing factory methods e.g. caching immutable objects, easy to
introduce new objects etc. See What is Factory pattern in Java and benefits for more details.

10. Difference between Decorator and Proxy pattern in Java?Another tricky Java design pattern question and trick here is that both
Decorator and Proxy implements interface of the object they decorate or encapsulate. As I said, many Java design pattern can have
similar or exactly same structure but they differ in there intent. Decorator pattern is used to implement functionality on already
created object, while Proxy pattern is used for controlling access to object. One more difference between Decorator and Proxy
design pattern is that, Decorator doesn't create object, instead it get object in it's constructor, while Proxy actually creates objects.

11. When to use Setter and Constructor Injection in Dependency Injection pattern?
Use Setter injection to provide optional dependencies of an object, while use Constructor injection to provide mandatory
dependency of an object, without which it can not work. This question is related to Dependency Injection design pattern and mostly
asked in context of Spring framework, which is now become an standard for developing Java application. Since Spring provides IOC
container, it also gives you way to specify dependencies either by using setter methods or constructors. You can also take a look
my previous post on same topic.

12. What is difference between Factory and Abstract factory in Java


see  here to answer this Java design pattern interview question. 

13. When to use Adapter pattern in Java? Have you used it before in your project?
Use Adapter pattern when you need to make two class work with incompatible interfaces. Adapter pattern can also be used to
encapsulate third party code, so that your application only depends upon Adapter, which can adapt itself when third party code
changes or you moved to a different third party library. By the way this Java design pattern question can also be asked by providing
actual scenario.

14. Can you write code to implement producer consumer design pattern in Java?
Producer consumer design pattern is a concurrency design pattern in Java which can be implemented using multiple way. if you are
working in Java 5 then its better to use Concurrency util to implement producer consumer pattern instead of plain oldwait and notify
in Java.  Here is a good example of implementing producer consumer problem using BlockingQueue in Java.

15. What is Open closed design principle in Java?


Open closed design principle is one of the SOLID principle defined by Robert C. Martin, popularly known as Uncle Bob. This principle
advices that a code should be open for extension but close for modification. At first this may look conflicting but once you explore
power of polymorphism, you will start finding patterns which can provide stability and flexibility of this principle. One of the key
example of this is State and Strategy design pattern, where Context class is closed for modification and new functionality is provided
by writing new code by implementing new state of strategy. See this article to know more about Open closed principle.

16. What is Builder design pattern in Java? When do you use Builder pattern ?
Builder pattern in Java is another creational design pattern in Java and often asked in Java interviews because of its specific use
when you need to build an object which requires multiple properties some optional and some mandatory. See When to use Builder
pattern in Java for more details  

17. Can you give an example of  SOLID design principles in Java?
There are lots of SOLID design pattern which forms acronym SOLID, read this list of SOLID design principles for Java programmer  to
answer this Java interview question.
18. What is difference between Abstraction and Encapsulation in Java?
I have already covered answer of this Java interview question in my previous post as Difference between encapsulation and
abstraction in Java. See there to answer this question. 
1) How to find all the links in a folder in UNIX or Linux ?
This is a tricky UNIX question as there is no specific command to find all symbolic links. Though you have ln command for creating
and updating soft links but nothing which gives you all the links in a directory. You need to use ls command which list everything in
directory and then you need to list all the links, as they starts with "l" as first characters, as shown in above article .

here is the actual UNIX command to find all links in a directory :

linux@nyj872:~ ls -lrt
total 2.0K
-rw-r--r--  1 Linux Domain Users  0 Dec  6  2011 a
drwxr-xr-x+ 1 Linux Domain Users  0 Sep 19 12:30 java/
lrwxrwxrwx  1 Linux Domain Users  4 Sep 19 12:31 version_1.0 -> java/

linux@nyj872:~ ls -lrt | grep '^l'


lrwxrwxrwx  1 Linux Domain Users  4 Sep 19 12:31 version_1.0 -> java/

2) How to find a process and kill that ?


Another classic UNIX interview questions. Answer of this question is simple if you are familiar with ps, grep and kill command. by
using "ps -ef" you can get list of all process and then use grep to find your process and get the PID of that process. Once you got PID
you can use kill command to kill that process as shown in this example of kill command in UNIX.

3) How to run a program in background in UNIX or Linux ?


an easy UNIX or Linux interview question, only when you know. You can use &amp; to run any process in background and than you
can use jobs to find the job id for that process and can use  fg and bg command to bring that process into foreground and
background.

4) How to sort output of a command in reverse order in Linux or UNIX ?


One more Linux command interview question which checks knowledge of frequently used command. you can use sort command in
UNIX to sort output of any command by using PIPE. By using -r option with sort command you can sort output of any command in
reverse order. See these sort command examples for more details.

5) How to create archive file in UNIX or Linux Operating System ?


Another interview question based on knowledge of UNIX or Linux command. you can use tar command to great archives in UNIX or
Linux. you can even combine tar and gzip to create a compressed archive in UNIX.

6) What is meaning of a file has 644 permission ?


To answer this UNIX or Linux interview question, you must know basics of files and directories in UNIX.  644 represents permission
110 for owner, permission 100 for group and 100 for others which means read + write for owner who create that file and read only
permission for group and others. See this tutorial on UNIX file permission for more details.

7) How will you remove empty files or directories from /tmp ?


See how to delete empty directory and files in UNIX to answer this UNIX command interview questions.

8) I have read permission on a directory but I am not able to enter it why ?


One more tricky UNIX questions. In order to get into a directory you need execute permission. if your directory does not have
execute permission than you can not go into that directory by using cd command. read UNIX files and directory permissions for more
information.

9) How do you find all files which are modified 10 minutes before ?
This is another the Linux interview questions from frequently used command e.g. find and grep. you can use -mtime option of find
command to list all the files which are modified 10 or m minutes before. see these find command examples for more details.

10) How to do you find size of directory in UNIX or Linux ?


This is another tricky and bit tough Linux interview question as popular ls command doesn't show complete size of directories in
UNIX. you need to use du command to get full size of directories including all sub directories in UNIX. See How to find directory size
in UNIX for exact command and detailed explanation.
These were some of the frequently asked UNIX and Linux command interview questions and answers which appear in many IT Job
interview which requires knowledge of UNIX operating system, Including programming job interviews e.g. core Java and J2EE
interviews. Questions from UNIX and Linux is also very popular during C and C++ programming interviews.

Design pattern interview questions for Senior and experienced level

These are questions which not only relates to design patterns but also related to software design. These questions requires
some amount of thinking and experience to answer. In most of the cases interviewer is not looking for absolute answers but looking
for your approach, how do you think about a problem, do you able to think through, do you able to bring out things which are not
told to you. This is where experience come in picture, What are things you consider while solving a problem etc. overall these design
questions kicks off your thought process. Some time interviewer ask you to write code as well so be prepare for that. you can excel
in these questions if you know the concept, example and application of your programming and design skill.
1. Give an example where you prefer abstract class over interface ?
This is common but yet tricky design interview question. both interface and abstract class follow "writing code for interface than
implementation" design principle which adds flexibility in code, quite important to tackle with changing requirement. here are some
pointers which help you to answer this question:
1. In Java you can only extend one class but implement multiple interface. So if you extend a class you lost your chance of extending
another class.
2. Interface are used to represent adjective or behavior e.g. Runnable, Clonable, Serializable etc, so if you use an abstract class to
represent behavior your class can not be Runnable and Clonable at same time because you can not extend two class in Java but if
you use interface your class can have multiple behavior at same time.
3. On time critical application prefer abstract class is slightly faster than interface.
4. If there is a genuine common behavior across the inheritance hierarchy which can be coded better at one place than abstract class
is preferred choice. Some time interface and abstract class can work together also where defining function in interface and default
functionality on abstract class.
To learn more about interface in Java check my post 10 things to know about Java interfaces
2. Design a Vending Machine which can accept different coins, deliver different products?
This is an open design question which you can use as exercise, try producing design document, code and Junit test rather just
solving the problem and check how much time it take you to come to solution and produce require artifacts, Ideally this question
should be solve in 3 hours, at least a working version.
3. You have a Smartphone class and will have derived classes like IPhone, AndroidPhone,WindowsMobilePhone
can be even phone names with brand, how would you design this system of Classes.
This is another design pattern exercise where you need to apply your object oriented design skill to come with a design which is
flexible enough to support future products and stable enough to support changes in existing model.
4. When do you overload a method in Java and when do you override it ?
Rather a simple question for experienced designer in Java. if you see different implementation of a class has different way of doing
certain thing than overriding is the way to go while overloading is doing same thing but with different input. method signature varies
in case of overloading but not in case of overriding in java.
5. Design ATM Machine ?
We all use ATM (Automated Teller Machine) , Just think how will you design an ATM ? for designing financial system one must
requirement is that they should work as expected in all situation. so no matter whether its power outage ATM should
maintain correct state (transactions), think about locking, transaction, error condition, boundary condition etc. even if you not able
to come up exact design but if you be able to point out non functional requirement, raise some question , think about boundary
condition will be good progress.

6. You are writing classes to provide Market Data and you know that you can switch to different vendors overtime
like Reuters, wombat and may be even to direct exchange feed , how do you design your Market Data system.
This is very interesting design interview question and actually asked in one of big investment bank and rather common scenario if
you have been writing code in Java. Key point is you will have a MarketData interface which will have methods required by client
e.g. getBid(), getPrice(), getLevel() etc and MarketData should be composed with a MarketDataProvider by using dependency
injection. So when you change your MarketData provider Client won't get affected because they access method
form MarketData interface or class.
7. Why is access to non-static variables not allowed from static methods in Java
You can not access non-static data from static context in Java simply because non-static variables are associated with a particular
instance of object while Static is not associated with any instance. You can also see my post why non static variable are not
accessible in static context for more detailed discussion.
8. Design a Concurrent Rule pipeline in Java?
Concurrent programming or concurrent design is very hot now days to leverage power of ever increasing cores in
advanced processor and Java being a multi-threaded language has benefit over others. Do design a concurrent system key point to
note is thread-safety, immutability, local variables and avoid using static or instance variables. you just to think that one class can be
executed by multiple thread a same time, So best approach is that every thread work on its own data, doesn't interfere on other
data and have minimal synchronization preferred at start of pipeline. This question can lead from initial discussion to full coding of
classes and interface but if you remember key points and issues around concurrency e.g. race condition, deadlock, memory
interference, atomicity, ThreadLocal variables  etc you can get around it.

Design pattern interview questions for Beginners


These software design and design pattern questions are mostly asked at beginners level and just informative purpose that how much
candidate is familiar with design patterns like does he know what is a design pattern or what does a particular design pattern do ?
These questions can easily be answered by memorizing the concept but still has value in terms of information and knowledge.
1. What is design patterns ? Have you used any design pattern in your code ?
Design patterns are tried and tested way to solve particular design issues by various programmers in the world. Design patterns are
extension of code reuse.
2. Can you name few design patterns used in standard JDK library?
Decorator design pattern which is used in various Java IO classes, Singleton pattern which is used in Runtime , Calendar and various
other classes, Factory pattern which is used along with various Immutable classes likes Boolean e.g. Boolean.valueOf and Observer
pattern which is used in Swing and many event listener frameworks.
3. What is Singleton design pattern in Java ? write code for thread-safe singleton in Java
Singleton pattern focus on sharing of expensive object in whole system. Only one instance of a particular class is maintained in
whole application which is shared by all modules. Java.lang.Runtime is a classical example of Singleton design pattern. You can also
see my post 10 questions on Singleton pattern in Java for more questions and discussion. From Java 5 onwards you can use enum to
thread-safe singleton.
4. What is main benefit of using factory pattern ? Where do you use it?
Factory pattern’s main benefit is increased level of encapsulation while creating objects. If you use Factory to create object you can
later replace original implementation of Products or classes with more advanced and high performance implementation without any
change on client layer. See my post on Factory pattern for more detailed explanation and benefits.
5. What is observer design pattern in Java
Observer design pattern is based on communicating changes in state of object to observers so that they can take there action.
Simple example is a weather system where change in weather must be reflected in Views to show to public. Here weather object is
Subject while different views are Observers. Look on this article for complete example of Observer pattern in Java.
6. Give example of decorator design pattern in Java ? Does it operate on object level or class level ?
Decorator pattern enhances capability of individual object. Java IO uses decorator pattern extensively and classical example is
Buffered classes like BufferedReader and BufferedWriter which enhances Reader and Writer objects to perform Buffer level reading
and writing for improved performance. Read more on Decorator design pattern and Java
7. What is MVC design pattern ? Give one example of MVC design pattern ?
8. What is FrontController design pattern in Java ? Give an example of front controller pattern ?
9. What is Chain of Responsibility design pattern ?
10.What is Adapter design pattern ? Give examples of adapter design pattern in Java?
 These are left for your exercise, try finding out answers of these design pattern questions as part of your preparation.

XML interview questions and answers for freshers and experienced below
What is XML?
XML (Extensible markup language) is all about describing data. Below is a XML which describes book store.
< ?xml version="1.0" encoding="ISO-8859-1"? >
< book>
< php>php by pcds infotech< /php>
< java>Jave j2ee by pcds infotec< /java>

An XML tag is not something predefined but it is something you have to define according to your needs. For
instance in the above example of books all tags are defined according to business needs. The XML document is
self explanatory, any one can easily understand looking at the XML data what exactly it means.
 
What is the version information in XML?
"version" tag shows which version of XML is used.
 
What is ROOT element in XML ?
In our XML sample given previously < book> tag is the root element. Root element is the top most elements for a
XML. and it's must be unique
 
If XML does not have closing tag will it work ?
No, every tag in XML which is opened should have a closing tag. For instance in the top if we remove tag that
XML will not be understood by lot of application.
 
Is XML case sensitive ?
Yes, they are case sensitive. .
 
What is the difference between XML and HTML?
XML describes data while HTML describes how the data should be displayed. So HTML is about displaying
information while XML is about describing and storing the information.
 
Is XML meant to replace HTML?
No, they both go together one is for describing data while other is for displaying data.
 
Can you explain why your project needed XML ? or why you have chosen XML.
Remember XML was meant to exchange data between two entities as we can define our user friendly tags with
ease. In real world scenarios XML is meant to exchange data. For instance we have two applications who want to
exchange information. But because they work in two complete opposite technologies it’s difficult to do it
technically. For instance one application is made in JAVA and the other in .NET. But both languages understand
XML so one of the applications will spit XML file which will be consumed and parsed by other applications
we can give a scenario of two applications which are working separately and how you chose XML as the data
transport medium.
 
What is DTD ( Document Type definition )?
It defines how our XML should structure.means type of element like integer or value char etc
 
What is well formed XML?
If a XML document is confirming to XML rules (all tags started are closed, there is a root element , all valid char
have used etc) then it’s a well formed XML.
 
What is a valid XML?
If XML is confirming to DTD rules then it’s a valid XML.
 
What is CDATA section in XML?
All data is normally parsed in XML but if you want to exclude some elements you will need to put those elements
in CDATA.
 
What is element and attributes in XML?
In the below example book is the element and the price the attribute < book price=1002>< /book>
 
What is XSL?
XSL (the eXtensible Stylesheet Language) is used to transform XML document to some other document. So its
transformation document which can convert XML to some other document. For instance you can apply XSL to
XML and convert it to HTML document or probably CSV files.
 
What are the standard ways of parsing XML document? or What is a XML parser?
XML parser sits in between the XML document and the application who want to use the XML document. Parser
exposes set of well defined interfaces which can be used by the application for adding, modifying and deleting
the XML document contents. Now whatever interfaces XML parser exposes should be standard or else that
would lead to different vendors preparing there own custom way of interacting with XML document. 
There are two standard specifications which are very common and should be followed by a XML parser:-
DOM: - Document Object Model.
DOM is a W3C recommended way for treating XML documents. In DOM we load entire XML document into
memory and allows us to manipulate the structure and data of XML document.
SAX: - Simple API for XML.
SAX is event driven way for processing XML documents. In DOM we load the whole XML document in to memory
and then application manipulates the XML document. But this is not always the best way to process large XML
documents which have huge data elements. For instance you only want one element from the whole XML
document or you only want to see if the XML is proper which means loading the whole XML in memory will be
quiet resource intensive. SAX parsers parse the XML document sequentially and emit events like start and end of
the document, elements, text content etc. So applications who are interested in processing these events can
register implementations of callback interfaces. SAX parser then only sends those event messages which the
application has demanded.
 
In What scenarios will you use a DOM parser and SAX parser ?
=> If we do not need all the data from the XML file then SAX approach is much preferred than DOM as DOM can
quiet memory intensive. In short if you need large portion of the XML document its better to have DOM. 
=> With SAX parser you have to write more code than DOM. 
=> If we want to write the XML in to a file DOM is the efficient way to do it. 
=> Some time you only need to validate the XML structure and do not want to retrieve any Data for those
instances SAX is the right approach.
 
Define XPATH? and What is XSLT?
XPATH is an XML query language to select specific parts of an XML document. Using XPATH we can address or
filter elements and text in a XML document. For instance a simple XPATH expression like "book/price" states find
"price" node which are children of “Invoice” node.
XSLT is a rule based language used to transform XML documents in to other file formats. XSLT are nothing but
generic transformation rules which can be applied to transform XML document to HTML, CS, Rich text etc.
 
What is the concept of XPOINTER?
XPOINTER is used to locate data within XML document. XPOINTER can point to a particular portion of a XML
document, for instance
address.xml#xpointer(/descendant::streetnumber[@id=9])
So the above XPOINTER points streetnumber=9 in "address.xml".
 
Ques 1. What is Log4j?
Ans. Log4j (Log for Java) is logging framework provided by apache foundation for java based applications.
In the applicaitons, if you want to log some information, like any event triggered, or any Database updated is happened, we have the
need to log the specific information or error for the useful of the application.
To debug any issues in applications, we have to log the error/exceptions in the logs. For this we will use log4j mechanism .
Log4j logs the information and shows this information in different targets. The different targets are called appenders (console, file etc
). 

Ques 2. How do you define logging for your application?


Ans. To define logging for your application, you have to download the log4j framework (log4j.jar) from the apache site.
Once log4j jars are downloaded, make sure that these jars are in classpath of your application. let say you have web-application
need to be added log4j. In this case, log4j jars are copied to WEB-INFO/lib folder of your webapplication
create new file either logging.properties or log4j.xml which will be copied to WEB-INF/classes folder
logging.properties/log4j.xml contains the all the configuration related to logging mechanism and logger level and package that you
want to define logger level.
Example:
logging.properties:
logger.level=INFO
logger.handlers=CONSOLE,FILE,RejRec
handler.RejRec=org.jboss.logmanager.handlers.PeriodicRotatingFileHandler
handler.RejRec.level=WARN
handler.RejRec.formatter=RejRec
handler.RejRec.properties=append,autoFlush,enabled,suffix,fileName
handler.RejRec.append=true
handler.RejRec.autoFlush=true
handler.RejRec.enabled=true
handler.RejRec.suffix=.yyyy-MM-dd
handler.RejRec.fileName=E\:\\Docs\\WithoutBook\\DID\\jboss-eap-6.2\\standalone\\log\\RejectedRecords.log
log4j.xml:
<log4j:configuration>
<appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
        <appender-ref ref="LOG"/>
</appender>
 <appender name="MEETING-APP-LOG" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File"
value="E:/Softwares/glassfish_dump/glassfish/domains/domain1/logs/meeting_app.log" /> <param name="Append" value="true"/>
<param name="DatePattern" value="'.'yyyy-MM-dd-a"/> <layout class="org.apache.log4j.PatternLayout"> <param
name="ConversionPattern" value="%d{yyyy-MM-dd} %d{HH:mm:ss,SSS} %-5p [%t] %c - %m%n" /> </layout> </appender>
 <logger name="com.withoutbook" additivity="false">
        <level value="warn"/>
        <appender-ref ref="MEETING-APP-LOG"/>
</logger>
    <root>
        <priority value="debug"/>
        <appender-ref ref="ASYNC"/>
        <appender-ref ref="ERROR-LOG"/>
    </root>
</log4j:configuration>

Ques 3. What are the different logging levels?


Ans. There are several logging levels that you can configure in you applicaiton 
Those are FATAL,ERROR,WARN,TRACE,DEBUG,INFO OR ALL in apache logging. Default logging level is INFO.

Ques 4. What are different types of logs?


Ans. Usually in any application there two types of logs
1.Application server logs :- These are the logs configured at the application server level. for example in tomcat,
we have log files called localhost.log. tomcat.log,catalina.log, stdout.log, sterr.log. all these logs are showing with default settings
defined in logging.properites located in your tomcat installation folder/conf folder.
if you want custom settings, we have to change the different parameters in logging.properties in conf folder of tomcat directory.

2.Application logs:- We can define logging at each applicaiton level, For this we have to create log4j.xml or logging.properties in
WEB-INF/classes folder.

Ques 5. What are different appenders that can configure in log4j?


Ans. There are different appenders that we can configure in log4j are: CONSOLE, FILES, DATABASE, JMS, EVENT LOGGING
Mainly used appenders:
CONSOLE in log4j:- If we use this as appenders in your application, log4j logs the information in the console or command prompt
window that is started with startup script.
Files in log4j:- Files Appender is used to log the information into our custom name files. when we are configuring this appender, we
can specify the file name.

Ques 6. What is the importance of logging applications?


Ans. Logging helps in debugging as well. Although debuggers are available but frankly it takes time to debug an application using a
debugger. An application can be debugged more easily with few well-placed logging messages. So we can safely say that logging is a
very good debugging tool. If logging is done sensibly and wisely, it can provide detailed context for application failures.

In distributed applications (e.g. web/remote applications), the logging is very important. The administrator can read logs to learn
about the problems that occurred during some interval.

Java's built-in APIs provide logging options but they are not that flexible. Another option is to use Apache’s open source logging
framework called log4j. 

Drawbacks of logging applications:


There are some drawbacks of use logging in your application. For example: logging will
- pollute the code
- increase the size of the code
- reduce the speed

These are important points because, we ultimately want efficient applications. Log4J has the solution to this. You may turn on or turn
off the logging at runtime by changing the configuration file. This means no change in the Java source code (binary).
To reduce the code now in Spring Framework you can use of AOP where you can configure log mechanisms easily.

Ques 7. Describe about logger levels in log4j.


Ans. Before using log4j framework, one should be aware of different categories of log messages. Following are 5 categories:
DEBUG
The DEBUG Level is used to indicate events that are useful to debug an application. Handling method for DEBUG level is: debug().
INFO
INFO level is used to highlight the progress of the application. Handling method for INFO level is: info().
WARN
The WARN level is used to indicate potentially harmful situations. Handling method for WARN level is: warn().
ERROR
The ERROR level shows errors messages that might not be serious enough and allow the application to continue. Handling method
for ERROR level is: error().
FATAL
The Fatal level is used to indicate severe events that will may cause abortion of the application. Handling method for FATAL level is:
fatal().
If you declare log level as debug in the configuration file, then all the other log messages will also be recorded. 
If you declare log level as info in the configuration file, then info, warn, error and fatal log messages will be recorded.
If you declare log level as warn in the configuration file, then warn, error and fatal log messages will be recorded.
If you declare log level as error in the configuration file, then error and fatal log messages will be recorded.
If you declare log level as fatal in the configuration file, then only fatal log messages will be recorded.

Ques 8. What are the three main components in log4j?


Ans. There are 3 main components that are used to log messages based upon type and level. These components also control the
formatting and report place at runtime. These components are:
- loggers
- appenders
- layouts
Q: What are the steps involved in project deployment?
A: Normally a deployment process consists of following steps:
 Check-in the code from all projects in progress into the SVN or source code repository and tag it.
 Download the complete source code from SVN.
 Build the application.
 Store the build output either WAR or EAR file to a common network location.
 Get the file from network and deploy the file to the production site.
 Updated the documentation with date and updated version number of the application.
Q: What is Maven?
A: Maven is a project management and comprehension tool. Maven provides developers a complete build lifecycle framework.
Development team can automate the project's build infrastructure in almost no time as Maven uses a standard directory layout and
a default build lifecycle.
Q: What does it mean when you say Maven uses Convention over Configuration?
A: Maven uses Convention over Configuration which means developers are not required to create build process themselves.
Developers do not have to mention each and every configuration details.
Q: What are the aspects Maven manages?
A: Maven provides developers ways to manage following:
 Builds
 Documentation
 Reporting
 Dependencies
 SCMs
 Releases
 Distribution
 mailing list
Q: How do you know the version of mvn you are using?
A: Type the following command:
mvn --version
Q: What is POM?
A: POM stands for Project Object Model. It is fundamental Unit of Work in Maven. It is an XML file. It always resides in the base
directory of the project as pom.xml. It contains information about the project and various configuration details used by Maven to
build the project(s).
Q: What information does POM contain?
A:POM contains the some of the following configuration information:
 project dependencies
 plugins
 goals
 build profiles
 project version
 developers
 mailing list
Q: What is Maven artifact?
A: An artifact is a file, usually a JAR that gets deployed to a Maven repository. A Maven build produces one or more artifacts, such as
a compiled JAR and a "sources" JAR.
Each artifact has a group ID (usually a reversed domain name, like com.example.foo), an artifact ID (just a name), and a version
string. The three together uniquely identify the artifact. A project's dependencies are specified as artifacts.
Q: What is Maven Build Lifecycle?
A: A Build Lifecycle is a well defined sequence of phases which define the order in which the goals are to be executed. Here phase
represents a stage in life cycle.
Q: Name the 3 build lifecycle of Maven.
A: The three build lifecycles are:
 clean:cleans up artifacts created by prior builds.
 default (or build):This is used to build the application.
 site: generates site documentation for the project.
Q: What is the command to quickly build your Maven site?
A: Type the command:
mvn site
Q: What would the command mvn clean do ?
A: This command removes the target directory with all the build data before starting the build process.
Q: What are the phases of a Maven Build Lifecycle?
A: Following are the phases:
 validate: validate the project is correct and all necessary information is available.
 compile: compile the source code of the project.
 test: test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or
deployed
 package: take the compiled code and package it in its distributable format, such as a JAR.
 integration-test: process and deploy the package if necessary into an environment where integration tests can be run.
 verify: run any checks to verify the package is valid and meets quality criteria.
 install: install the package into the local repository, for use as a dependency in other projects locally.
 deploy: done in an integration or release environment, copies the final package to the remote repository for sharing with other
developers and projects.
Q: What is a goal in Maven terminology?
A: A goal represents a specific task which contributes to the building and managing of a project. It may be bound to zero or more
build phases. A goal not bound to any build phase could be executed outside of the build lifecycle by direct invocation.
Q: What would this command do mvn clean dependency:copy-dependencies package?
A: This command will clean the project, copy the dependencies and package the project (executing all phases up to package).
Q: What phases does a Clean Lifecycle consist?
A: The clean lifecycle consists of the following phases:
 pre-clean
 clean
 post-clean
Q: What phases does a Site Lifecycle consist?
A: The phases in Site Lifecycle are:
 pre-site
 site
 post-site
 site-deploy
Q: What is Build Profile?
A: A Build profile is a set of configuration values which can be used to set or override default values of Maven build. Using a build
profile, you can customize build for different environments such as Production v/s Development environments.
Q: What are different types of Build Profiles?
A: Build profiles are of three types:
 Per Project: Defined in the project POM file, pom.xml.
 Per User: Defined in Maven settings xml file (%USER_HOME%/.m2/settings.xml).
 Global: Defined in Maven global settings xml file (%M2_HOME%/conf/settings.xml)
Q: How can you activate profiles?
A: A Maven Build Profile can be activated in various ways:
 Explicitly using command console input.
 Through maven settings.
 Based on environment variables (User/System variables).
 OS Settings (for example, Windows family).
 Present/missing files.
Q: What is a Maven Repository?
A: A repository is a place i.e. directory where all the project jars, library jar, plugins or any other project specific artifacts are stored
and can be used by Maven easily.
Q: What types of Maven repository?
A: Maven repository are of three types: local, central, remote
Q: What is local repository?
A: Maven local repository is a folder location on your machine. It gets created when you run any maven command for the first time.
Maven local repository keeps your project's all dependencies (library jars, plugin jars etc).
Q: What is the default location for your local repository?
A: ~/m2./repository.
Q: What is the command to install JAR file in local repository?
A: mvn install
Q: What is Central Repository?
A: It is repository provided by Maven community. It contains a large number of commonly used libraries. When Maven does not find
any dependency in local repository, it starts searching in central repository using following URL: http://repo1.maven.org/maven2/.
Q: What is Remote Repository?
A: Sometimes, Maven does not find a mentioned dependency in central repository as well then it stops the build process and output
error message to console. To prevent such situation, Maven provides concept of Remote Repository which is developer's own
custom repository containing required libraries or other project jars.
Q: What is the sequence in which Maven searches for dependency libraries?
A: Following is the search pattern:
 Step 1 - Search dependency in local repository, if not found, move to step 2 else if found then do the further processing.
 Step 2 - Search dependency in central repository, if not found and remote repository/repositories is/are mentioned then move to
step 4 else if found, then it is downloaded to local repository for future reference.
 Step 3 - If a remote repository has not been mentioned, Maven simply stops the processing and throws error (Unable to find
dependency).
 Step 4 - Search dependency in remote repository or repositories, if found then it is downloaded to local repository for future
reference otherwise Maven as expected stop processing and throws error (Unable to find dependency).
Q: Why are Maven Plugins used?
A: Maven Plugins are used to :
 create jar file.
 create war file.
 compile code files.
 unit testing of code
 create project documentation.
 create project reports.
Q: What are the types of Maven Plugins?
A: Maven provides following two types of Plugins:
 Build plugins: They execute during the build and should be configured in the element of pom.xml
 Reporting plugins: They execute during the site generation and they should be configured in theelement of the pom.xml
Q: When does Maven use External Dependency concept?
A: Maven dependency management using concept of Maven Repositories (Local, Central, Remote). Suppose dependency is not
available in any of remote repositories and central repository; in such scenarios Maven uses concept of External Dependency.
Q: What are the things you need to define for each external dependency?
A: External dependencies (library jar location) can be configured in pom.xml in same way as other dependencies.
 Specify groupId same as name of the library.
 Specify artifactId same as name of the library.
 Specify scope as system.
 Specify system path relative to project location.
Q: What is Archetype?
A: Archetype is a Maven plugin whose task is to create a project structure as per its template.
Q: What is the command to create a new project based on an archtype?
A: Type the following command:
mvn archetype:generate
Q: What is SNAPSHOT in Maven?
A: SNAPSHOT is a special version that indicates a current development copy. Unlike regular versions, Maven checks for a new
SNAPSHOT version in a remote repository for every build.
Q: What is difference between Snapshot and Version?
A: In case of Version, if Maven once downloaded the mentioned version say data-service:1.0, it will never try to download a newer
1.0 available in repository. To download the updated code, data-service version is be upgraded to 1.1.
In case of SNAPSHOT, Maven will automatically fetch the latest SNAPSHOT (data-service:1.0-SNAPSHOT) everytime app-ui team
build their project.
Q: What is transitive dependency in Maven?
A: Transitive dependency means to avoid needing to discover and specify the libraries that your own dependencies require, and
including them automatically.
Q: What does dependency management mean in the context of transitive dependency?
A: It means to directly specify the versions of artifacts to be used when they are encountered in transitive dependencies. For an
example project C can include B as a dependency in its dependencyManagement section and directly control which version of B is to
be used when it is ever referenced.
Q: How Maven handles and determines what version of dependency will be used when multiple version of an artifact are
encountered?
A: Maven determines what version of a dependency is to be used when multiple versions of an artifact are encountered. If two
dependency versions are at the same depth in the dependency tree, the first declared dependency will be used. This is called
dependency mediation.
Q: What is dependency scope? Name all the dependency scope.
A: Dependency scope includes dependencies as per the current stage of the build. Various Dependency Scopes are:
 compile: This scope indicates that dependency is available in classpath of project. It is default scope.
 provided: This scope indicates that dependency is to be provided by JDK or web-Server/Container at runtime.
 runtime: This scope indicates that dependency is not required for compilation, but is required during execution.
 test: This scope indicates that the dependency is only available for the test compilation and execution phases.
 system: This scope indicates that you have to provide the system path.
 import: This scope is only used when dependency is of type pom. This scope indicates that the specified POM should be replaced
with the dependencies in that POM's section.
Q: What is the minimal set of information for matching a dependency references against a dependencyManagement section ?
A: {groupId,artifactId,type,classifier}.
Q: How do you reference a property defined in your pom.xml file?
A: To reference a property defined in your pom.xml, the property name uses the names of the XML elements that define the value,
with "pom" being allowed as an alias for the project (root) element.
So ${pom.name} refers to the name of the project, ${pom.version} refers to the version of the project, ${pom.build.finalName}
refers to the final name of the file created when the built project is packaged, etc.
Q: What are the default values for packaging element? If there is no packaging element defined? What is the default value for
that?
A: Some of the valid packaging values are jar, war, ear and pom. If no packaging value has been specified, it will default to jar.
Q: What is the value for packaging element in pom for a project that is purely meta-data?
A: pom
Q: What is the use of execution element in pom file?
A: The <execution> element contains information's required for the execution of a plugin.
Q: What is a project's fully qualified artifact name?
A: <groupId>:<artifactId>:<version>
Q: If you do not define any information, where does your pom inherits that information from?
A: All POMs inherit from a parent (despite explicitly defined or not). This base POM is known as the Super POM, and contains values
inherited by default.
Q: How profiles are specified in Maven?
A: Profiles are specified using a subset of the elements available in the POM itself.
Q: What are the elements in POM that a profile can modify when specified in the POM?
A: <repositories>, <pluginRepositories>,<dependencies>, <plugins> ,<properties>,
<modules><reporting>,<dependencyManagement>,<distributionManagement>
Q: Why profile is used in Maven?
A: To give portability to projects ( e.g. windows, linux etc).
Q: What are the benefit of storing JARS/external dependencies in local repository instead of remote one?
A: It uses less storage, it makes checking out project quicker, non need for versioning JAR files.
Q: How can you build your project offline?
A: Use the command:
mvn o package.
Q: How do you exclude dependency?
A: Using the exclusion element.
Q: What is a system dependency?
A: Dependency with scope system are always available and are not looked up in repository, they are usually used to tell Maven
about dependencies which are provided by the JDK or the VM. Thus, system dependencies are especially useful for resolving
dependencies on artifacts which are now provided by the JDK.
Q: What is the use of optional dependency?
A: Any transitive dependency can be marked as optional using "optional" element. As example, A depends upon B and B depends
upon C. Now B marked C as optional. Then A will not use C.
Q: What is dependency exclusion ?
A: Any transitive dependency can be exclude using "exclusion" element. As example, A depends upon B and B depends upon C then
A can mark C as excluded.
Q: How can you run the clean plugin automatically during the build?
A: You can put the clean plugin inside the execution tag in pom.xml file.
Q: How to stop the propagation of plugins to child POMs?
A: set <inherited> to false.
Q: What does the "You cannot have two plugin executions with the same (or missing) elements" message mean?
A: It means that you have executed a plugin multiple times with the same <id>. Provide each <execution> with a unique <id> then it
would be ok.
Q: What is a Mojo?
A: A mojo is a Maven plain Old Java Object. Each mojo is an executable goal in Maven, and a plugin is a distribution of one or more
related mojos.
Q: What is difference between Apache Ant and Maven?
A: Ant is simply a toolbox whereas Maven is about the application of patterns in order to achieve an infrastructure which displays
the characteristics of visibility, reusability, maintainability, and comprehensibility. It is wrong to consider Maven as a build tool and
just a replacement for Ant.
Junit
Q: What is testing?
A: Testing is the process of checking the functionality of the application whether it is working as per requirements.
Q: What is unit testing?
A: Unit testing is the testing of single entity (class or method). Unit testing is very essential to every software company to give a
quality product to their customers.
Q: What is Manual testing?
A: Executing the test cases manually without any tool support is known as manual testing.
Q: What is Automated testing?
A: Taking tool support and executing the test cases by using automation tool is known as automation testing.
Q: Out of Manual and Automated testing which one is better and why?
A: Manual Testing is:
1. Time consuming and tedious.
2. Huge investment in human resources.
3. Less reliable.
4. Non-programmable.
Automated testing is
1. Fast
2. Less investment in human resources
3. More reliable
4. Programmable
Q: What is JUnit?
A: JUnit is a unit testing framework for the Java Programming Language. It is written in Java and is an Open Source Software
maintained by the JUnit.org community.
Q: What are important features of JUnit?
A: Import features of JUnit are:
1. It is an open source framework.
2. Provides Annotation to identify the test methods.
3. Provides Assertions for testing expected results.
4. Provides Test runners for running tests.
5. JUnit tests can be run automatically and they check their own results and provide immediate feedback.
6. JUnit tests can be organized into test suites containing test cases and even other test suites.
7. JUnit shows test progress in a bar that is green if test is going fine and it turns red when a test fails.
Q: What is a Unit Test Case?
A: A Unit Test Case is a part of code which ensures that the another part of code (method) works as expected. A formal written unit
test case is characterized by a known input and by an expected output, which is worked out before the test is executed. The known
input should test a precondition and the expected output should test a post condition.
Q: When are Unit Tests written in Development Cycle?
A: Tests are written before the code during development in order to help coders write the best code.
Q: Why not just use System.out.println() for testing?
A: Debugging the code using system.out.println() will lead to manual scanning of the whole output every time the program is run to
ensure the code is doing the expected operations. Moreover, in the long run, it takes lesser time to code JUnit methods and test
them on class files.
Q: How to install JUnit?
A: Follow the steps below:
1. Download the latest version of JUnit, referred to below as junit.zip.
2. Unzip the junit.zip distribution file to a directory referred to as %JUNIT_HOME%.
3. Add JUnit to the classpath:
set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit.jar
4. Test the installation by running the sample tests distributed with JUnit (sample tests are located in the installation directory directly,
not the junit.jar file). Then simply type:
java org.junit.runner.JUnitCore org.junit.tests.AllTests
All the tests should pass with an "OK" message. If the tests don't pass, verify that junit.jar is in the CLASSPATH.
Q: Why does JUnit only report the first failure in a single test?
A: Reporting multiple failures in a single test is generally a sign that the test does too much and it is too big a unit test. JUnit is
designed to work best with a number of small tests. It executes each test within a separate instance of the test class. It reports
failure on each test.
Q: In Java, assert is a keyword. Won't this conflict with JUnit's assert() method?
A: JUnit 3.7 deprecated assert() and replaced it with assertTrue(), which works exactly the same way. JUnit 4 is compatible with the
assert keyword. If you run with the -ea JVM switch, assertions that fail will be reported by JUnit.
Q: How do I test things that must be run in a J2EE container (e.g. servlets, EJBs)?
A: Refactoring J2EE components to delegate functionality to other objects that don't have to be run in a J2EE container will improve
the design and testability of the software. Cactus is an open source JUnit extension that can be used for unit testing server-side java
code.
Q: What are JUnit classes? List some of them.
A: JUnit classes are important classes which are used in writing and testing JUnits. Some of the important classes are:
1. Assert - A set of assert methods.
2. TestCase - It defines the fixture to run multiple tests.
3. TestResult - It collects the results of executing a test case.
4. TestSuite - It is a Composite of Tests.
Q: What are annotations and how are they useful in JUnit?
A: Annotations are like meta-tags that you can add to you code and apply them to methods or in class. The annotation in JUnit gives
us information about test methods , which methods are going to run before & after test methods, which methods run before & after
all the methods, which methods or class will be ignore during execution.
Q: How will you run JUnit from command window?
A: Follow the steps below:
1. Set the CLASSPATH
2. Invoke the runner:
3. java org.junit.runner.JUnitCore
Q: What is JUnitCore class?
A: JUnitCore is an inbuilt class in JUnit package. It is based on Facade design pattern. This class is used to run only specified test
classes.
Q: What is Test suite?
A: Test suite means bundle a few unit test cases and run it together. In JUnit, both @RunWith and @Suite annotation are used to
run the suite test.
Q: What is @Ignore annotation and how is this useful?
A: Sometimes it happens that our code is not ready and test case written to test that method/code will fail if run. The @Ignore
annotation helps in this regards. Following are some of the usefulness of @Ignore annotation:
1. You can easily identify all @Ignore annotations in the source code, while unannotated or commented out tests are not so simple to
find.
2. There are cases when you can't fix a code that is failing, but you still want to method to be around, precisely so that it does not get
forgotten. In such cases @Ignore makes sense.
Q: What are Parameterized tests?
A: Parameterized tests allow developer to run the same test over and over again using different values.
Q: How do you use test fixtures?
A: Fixtures is a fixed state of a set of objects used as a baseline for running tests. The purpose of a test fixture is to ensure that there
is a well known and fixed environment in which tests are run so that results are repeatable. It includes:
1. setUp() method which runs before every test invocation.
2. tearDown() method which runs after every test method.
Q: How to compile a JUnit Test Class?
A: Compiling a JUnit test class is like compiling any other Java classes. The only thing you need watch out is that the JUnit JAR file
must be included in the classpath.
Q: What happens if a JUnit Test Method is Declared as "private"?
A: If a JUnit test method is declared as "private", it compiles successfully. But the execution will fail. This is because JUnit requires
that all test methods must be declared as "public".
Q: How do you test a "protected" method?
A: When a method is declared as "protected", it can only be accessed within the same package where the class is defined. Hence to
test a "protected" method of a target class, define your test class in the same package as the target class.
Q: How do you test a "private" method?
A: When a method is declared as "private", it can only be accessed within the same class. So there is no way to test a "private"
method of a target class from any test class. Hence you need to perform unit testing manually. Or you have to change your method
from "private" to "protected".
Q: What happens if a JUnit test method is declared to return "String"?
A: If a JUnit test method is declared to return "String", the compilation will pass ok. But the execution will fail. This is because JUnit
requires that all test methods must be declared to return "void".
Q: How can you use JUnit to test that the code throws desired exception?
A: JUnit provides a option of tracing the Exception handling of code. You can test if a code throws desired exception or not. The
expected parameter is used along with @Test annotation as follows: @Test(expected)
Q: What are Parameterized tests in JUnit?
A: Parameterized tests allow developer to run the same test over and over again using different values.
Q: How to create Parameterized tests?
A: There are five steps, which you need to follow to create Parameterized tests:
1. Annotate test class with @RunWith(Parameterized.class).
2. Create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set.
3. Create a public constructor that takes in what is equivalent to one "row" of test data.
4. Create an instance variable for each "column" of test data.
5. Create your tests case(s) using the instance variables as the source of the test data.
The test case will be invoked once per each row of data.
Q: Can you use a main() Method for Unit Testing?
A: Yes you can test using main() method. One obvious advantage seems to be that you can whitebox test the class. That is, you can
test the internals of it (private methods for example). You can't do that with unit-tests. But primarily the test framework tests the
interface and the behavior from the user's perspective.
Q: Do you need to write a test class for every class that needs to be tested?
A: No. We need not write an independent test class for every class that needs to be tested. If there is a small group of tests sharing a
common test fixture, you may move those tests to a new test class.
Q: When are tests garbage collected?
A: The test runner holds strong references to all Test instances for the duration of the test execution. This means that for a very long
test run with many Test instances, none of the tests may be garbage collected until the end of the entire test run. Explicitly setting
an object to null in the tearDown() method, for example, allows it to be garbage collected before the end of the entire test run.

Q: What is an IDE?
A: An IDE or Integrated Development Environment is a software program that is designed to help programmers and developers build
software.
Q: What are the basic things an IDE includes?
A: Most IDEs include:
1. A source code editor
2. A compiler and/or an interpreter
3. Build automation tools
4. A debugger
Q: What is eclipse?
A: Eclipse is an open source community whose projects are focused on building an extensible development platform, runtimes and
application frameworks for building, deploying and managing software across the entire software lifecycle.
Eclipse is used in several different areas, e.g. as a development environment for Java or Android applications.
Q: Who governs the Eclipse projects?
A: The Eclipse projects are governed by the Eclipse Foundation. The Eclipse Foundation is a non-profit, member supported
corporation that hosts the Eclipse Open Source projects.
Q: What is Rich Client Platform?
A: The minimal set of plugins needed to build a rich client application is collectively known as the Rich Client Platform. It means your
application need only require two plugins, org.eclipse.ui andorg.eclipse.core.runtime, and their prerequisites.
Q: What are the prerequisite for installing Eclipse?
A: Eclipse requires an installed Java runtime. You may either install a Java Runtime Environment (JRE), or a Java Development Kit
(JDK), depending on what you want to do with Eclipse. If you intend to use Eclipse for Java development, then you should install a
JDK. If you aren't planning to use Eclipse for Java development and want to save some disk space, install a JRE.
Q: What is a workspace?
A: The workspace is the physical location (file path) you are working in. Your projects, source files, images and other artifacts can be
stored and saved in your workspace. The workspace also contains preferences settings, plugin specific meta data, logs etc
Q: What is an Eclipse project?
A: An Eclipse project contains:
1. source
2. configuration and
3. binary files related to a certain task
Eclipse groups the above into buildable and reusable units. An Eclipse project can have natures assigned to it which describe the
purpose of this project. For example the Java nature defines a project as Java project. Projects can have multiple natures combined
to model different technical aspects.
Natures for a project are defined via the .project file in the project directory.
Q: What are visible parts or user interface components of an Eclipse Window?
A: The major visible parts of an eclipse window are:
1. Views
2. Editors (all appear in one editor area)
3. Menu Bar
4. Toolbar
Q: What are views?
A: A view is typically used to work on a set of data, which might be a hierarchical structure. If data is changed via the view, the
change is directly applied to the underlying data structure. A view sometimes allows us to open an editor for a selected set of data.
E.g.:Package Explorer is a view, which allows you to browse the files of Eclipse projects.
Q: What are Editors?
A: Editors are typically used to modify a single data element, e.g. a file or a data object.
Q: What is difference between Views and Editors?
A: Editors are used to edit the project data and Views are used to view the project metadata. For example the package explorer
shows the java files in the project and the java editor is used to edit a java file.
Q: What is a Perspective?
A: An eclipse perspective is the name given to an initial collection and arrangement of views and an editor area. The default
perspective is called java.
Q: What is Refactoring and how is Refactoring in eclipse done?
A: Refactoring is the process of restructuring the code without changing its behavior. For example renaming a Java class or method
is a refactoring activity.
Eclipse supports several refactoring activities, for example renaming or moving. E.g.:To use the Rename refactoring, you can right-
click on your class (in the editor or Package Explorer) and select Refactor ? Rename to rename your class. Eclipse will make sure that
all calls in your Workspace to your class or method are renamed.
Q: Where do you set the memory heap size in Eclipse?
A: Eclipse installation contains a file called eclipse.ini which allows you to configure the memory parameters for the Java virtual
machine which runs the Eclipse IDE. For example the -Xmx parameter can be used to define how large the Java heap size can get. -
Xms defines the initial heap size of the Java virtual machine
Q: Why should we close a project in Eclipse?
A: An eclipse workspace can contain any number of projects. A project can be either in the open state or closed state. Open projects:
 Consume memory
 Take up build time especially when the Clean All Projects (Project > Clean all projects) with the Start a build immediately option is
used.
A closed project is visible in the Package Explorer view but its contents cannot be edited using the Eclipse user interface.
Q: What are extensions and extension points in eclipse?
A: Loose coupling in Eclipse is achieved partially through the mechanism of extensions and extension points. A general example for
this would be: electrical outlets. The outlet, or socket, is the extension point; the plug, or light bulb that connects to it, is the
extension. As with electric outlets, extension points come in a wide variety of shapes and sizes, and only the extensions that are
designed for that particular extension point will fit.
When a plugin wants to allow other plugins to extend or customize portions of its functionality, it will declare an extension point.
The extension point declares typically a combination of XML markup and Java interfaces. The extensions must conform to this.
plugins that want to connect to that extension point must implement that contract in their extension. Extension points are define in
the plugin.xml
Q: What are eclipse plugins?
A: A software component in Eclipse is called a plugin. The Eclipse IDE allows the developer to extend the IDE functionality via plugins.
For example you can create new menu entries and associated actions via plugins.
Q: When does a plugin get started?
A: Each plugin can be viewed as having a declarative section and a code section. The declarative part is contained in the plugin. xml
file. This file is loaded into a registry when the platform starts up and so is always available, regardless of whether a plugin has
started. The code section is activated only when their functionality has been explicitly invoked by the user.
Q: Does Eclipse save any report or log file?
A: Yes, whenever it encounters a problem that does not warrant launching a dialog, Eclipse saves a report in the workspace log file.
You can find the log file at :workspace/.metadata/.log.
Q: What is "Cannot find a VM" start up problem in Eclipse?
A: Eclipse requires a JVM to run and does not include one in the download. You may have a VM, but Eclipse cannot find it. To avoid
possible conflicts, always specify the VM you are using with the -vm command-line argument.
Q: What is "Disk full or out of memory" problem?
A: Eclipse, especially 2.1 and earlier, does not always gracefully report disk-full errors or out-of-memory errors. Make sure that you
have adequate disk space and that you are giving the Java VM enough heap space.
Q: How to install new plugins?
A: Best approach is to use the Eclipse Update Manager. The Update Manager allows you to find new plugins on your machine, your
network, or the Internet, compare new plugins to your configuration, and install only those that are compatible with your current
configuration. The Update Manager is invoked byHelp > Software Updates.
Q: How to remove a plugin?
A: plugins from Eclipse should never be removed. Instead they can be disabled by using the Eclipse Update Manager.
Run Help > About Eclipse >Installation Details, select the software you no longer want and click Uninstall.
Q: Where does System.out and System.err output logged?
A: Eclipse is simply a Java program and when launched from a shell or command line, the output will generally go back to that shell.
In Windows, the output will disappear completely if Eclipse is launched using the javaw.exe VM. As output is lost, it's better to log
error information by using the platform logging facility.
Q: What is autobuilding of Java code in Eclipse?
A: Eclipse provides autobuild facilities. If a resource changes, the platform checks the project description file ( .project in your
projects). When the file contains a reference to the Java builder, the builder gets notified of the change and will then compile the
Java source file and it's dependents.
Q: What is a Quick Fix?
A: As you type characters into an eclipse editor it analyzes the document content for potential error and warnings. The java editor
uses the java syntax to detect errors in the code. When it finds error it highlights errors using red wavy lines under the offending
code and a marker in the left editor margin.
The marker can be selected with the left mouse to activate the Quick Fix pop-up dialog. It provides a list of possible corrections for
the error.
Q: What is hot code replace?
A: Hot code enables you to change code while debugging. It simply means that you may change the code in debug mode and see its
affect.
Q: Why does the Eclipse compiler create a different serialVersionUID from javac?
A: Serializable classes compiled with Eclipse are not compatible with the same classes compiled using javac. When classes compiled
in Eclipse are written to an object stream, you may not be able to read them back in a program that was compiled elsewhere. Many
people blame this on the Eclipse compiler, assuming that it is somehow not conforming properly to spec. In fact, this can be a
problem between any two compilers or even two versions of a compiler provided by the same vendor.
If you need object serialization, the only way to be safe is to explicitly define the serialVersionUID in your code:
class MyClass implements Serializable {
public static final long serialVersionUID = 1;
}
whenever your class changes say it is incompatible with previously serialized versions, simply increment this number.
Q: What is the difference between a perspective and a workbench page?
A: The workbench page is the main body of a workbench window: between the toolbar and the status line, the area that contains
views and editors.The workbench page can have one or more perspectives associated with it that define the layout of the views and
editors in the page.
Project Manager Round FAQs
 Q1. What is the architecture of your project?
 Q2. What is your role and responsibilities in the project?
 Q3. What are the corporate trainings you have attended?
 Q4. What are the technologies you have worked on?
 Q5. What are the tools that were used in your project?
 Q6. What are the IDEs you have worked on?
 Q7. What are the DBs you have worked on?
 Q8. What are the Servers you have worked on?
 Q9. Have you ever been involved in Testing?
 Q10. Have you ever been involved in Design?
 Q11. What is the reporting tool in your project?
 Q12. What are your strengths and weakness in general and technical?
 Q13. What is your team size?
 Q14. What are all the different standards you employed for the project?(TCS)
 Q15. Tell and explain to us about a specific situation during the project where you have to cope with a less
experienced candidate in your team and what are the measures you took to meet your deadlines?(Verizon)
 Q16. Tell us some of your extraordinary skills which place you in the leading position over  the other technical
associates?(Juniper Networks)
 Q17. What was the criticism/difficulties you got during your projects, how  did you handle it and what  are the
measures you took to avoid repetition of the same?(Mecedes Benz, ORACLE, CA, Pega Systems)
 Q18. Your project is beginning to exceed budget and to fall behind schedule due to almost daily user change
orders and increasing conflicts in user  requirements. As a senior developer, how will you address the user
issues?(United Health Group)
 Q19. You’ve encountered a delay on an early phase of your project. What actions can you take to counter the
delay?(Wipro, Accenture)
 Q20. You have been assigned as the Team Lead for a team comprised of new employees just out of college and
“entry-level” consulting staff. What steps can you take to insure that the project is completed against a very
tight time deadline?(TCS, Infosys, CTS, LogicaCMG)
 Q21. How do you handle non-productive team members?(Accenture, CISCO, GE)
 Q22. How do you handle team members who come to you with their personal problems?(TCS, GE, CapGemini)
 Q23. What are the different phases in delivering the project during development and during maintenance?
(CTS, Patni, Galaxe Systems, General Motors)
 Q24. Do you have experience in Production Support and what is the hierarchy in Production Support?(HCL,
RBS, Amdocs(Gurgaon), HSBC)
 Q25. How do you write Unit Test Cases?(Microsoft, Google, Tanla, Adobe, Bharti Telecom)
 Q26. What is STQC testing?(For all Govt. projects)
 Q27. How do you perform impact analysis for your code?(Microsoft, EmcSquare, Honeywell, INTEL, Symphony,
TCS, CTS,Amazon.com, NOKIA)
 Q28. Why Analysis & Testing phases are very important?(Infosys, Mphasis)
 Q29. What is the document that should be consulted to know about your project, the activities you do, to
know about your project, the activities you do, your schedules and milestones?(Dell, Qualcomm, HCL,
MindTree, PSPL, TechMahindra)
 Q30. What is the difference between Architecture and Design?(TCS, Infosys, HCL, Tech Mahindra, Accenture,
HP)
 Q31. What is the reporting hierarchy in your project?(all CMM Level 5 companies)

Q1. What is J2EE?


J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services,
application programming interfaces (APIs), and protocols that provide the functionality for developing multi tiered, and web-based
applications.
Q2. What is the J2EE module?
A J2EE module consists of one or more J2EE components for the same container type and one component deployment descriptor of
that type.
Q3. What are the components of J2EE application?
A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and
files and communicates with other components. The J2EE specification defines the following J2EE components:
• Application clients and applets are client components.
• Java Servlets and Java Server PagesTM (JSPTM) technology components are web components.
• Enterprise JavaBeansTM (EJBTM) components (enterprise beans) are business components.
• Resource adapter components provided by EIS and tool vendors.
Q4. What are the four types of J2EE modules?
1. Application client module
2. Web module
3. Enterprise JavaBeans module
4. Resource adapter module
Q5. What does application client module contain?
The application client module contains:
• class files,
• an application client deployment descriptor.
Application client modules are packaged as JAR files with a .jar extension.

Q6. What does Enterprise JavaBeans module contain?


The Enterprise JavaBeans module contains:
• class files for enterprise beans
• An EJB deployment descriptor.
EJB modules are packaged as JAR files with a .jar extension.
Q7. What does resource adapt module contain?

The resource adapt module contains:


• all Java interfaces,
• classes,
• native libraries,
• other documentation,
• A resource adapter deployment descriptor.
Resource adapter modules are packages as JAR files with a .rar (Resource adapter Archive) extension.
Q8. How many development roles are involved in J2EE application?
There are at least 5 roles involved:
1. Enterprise Bean Developer
◦ Writes and compiles the source code
◦ Specifies the deployment descriptor
◦ Bundles the .class files and deployment descriptor into an EJB JAR file
2. Web Component Developer
◦ Writes and compiles Servlets source code
◦ Writes JSP and HTML files
◦ Specifies the deployment descriptor for the Web component
◦ Bundles the .class, .jsp, .html, and deployment descriptor files in the WAR file
3. J2EE Application Client Developer
◦ Writes and compiles the source code
◦ Specifies the deployment descriptor for the client
◦ Bundles the .class files and deployment descriptor into the JAR file
4. Application Assembler The application assembler is the company or person who receives application component JAR files from
component providers and assembles them into a J2EE application EAR file. The assembler or deployer can edit the deployment
descriptor directly or use tools that correctly add XML tags according to interactive selections. A software developer performs the
following tasks to deliver an EAR file containing the J2EE application:
◦ Assembles EJB JAR and WAR files created in the previous phases into a J2EE application (EAR) file
◦ Specifies the deployment descriptor for the J2EE application
◦ Verifies that the contents of the EAR file are well formed and comply with the J2EE specification
5. Application Deployer and Administrator
◦ Configures and deploys the J2EE application
◦ Resolves external dependencies
◦ Specifies security settings & attributes
◦ Assigns transaction attributes and sets transaction controls
◦ Specifies connections to databases
◦ Deploys or installs the J2EE application EAR file into the J2EE server
◦ Administers the computing and networking infrastructure where J2EE applications run.
◦ Oversees the runtime environment
But a developer role depends on the job assignment. For a small company, one developer may take these 5 roles altogether.
Q9. What is difference between J2EE 1.3 and J2EE 1.4?
J2EE 1.4 is an enhancement version of J2EE 1.3. It is the most complete Web services platform ever. J2EE 1.4 includes:
• Java API for XML-Based RPC (JAX-RPC 1.1)
• SOAP with Attachments API for Java (SAAJ),
• Web Services for J2EE(JSR 921)
• J2EE Management Model(1.0)
• J2EE Deployment API(1.1)
• Java Management Extensions (JMX),
• Java Authorization Contract for Containers(JavaACC)
• Java API for XML Registries (JAXR)
• Servlet 2.4
• JSP 2.0
• EJB 2.1
• JMS 1.1
• J2EE Connector 1.5
The J2EE 1.4 features complete Web services support through the new JAX-RPC 1.1 API, which supports service endpoints based on
Servlets and enterprise beans. JAX-RPC 1.1 provides interoperability with Web services based on the WSDL and SOAP protocols. The
J2EE 1.4 platform also supports the Web Services for J2EE specification (JSR 921), which defines deployment requirements for Web
services and utilizes the JAX-RPC programming model. In addition to numerous Web services APIs, J2EE 1.4 platform also features
support for the WS-I Basic Profile 1.0. This means that in addition to platform independence and complete Web services support,
J2EE 1.4 offers platform Web services interoperability.
The J2EE 1.4 platform also introduces the J2EE Management 1.0 API, which defines the information model for J2EE management,
including the standard Management EJB (MEJB). The J2EE Management 1.0 API uses the Java Management Extensions API (JMX).
The J2EE 1.4 platform also introduces the J2EE Deployment 1.1 API, which provides a standard API for deployment of J2EE
applications. The J2EE 1.4 platform includes security enhancements via the introduction of the Java Authorization Contract for
Containers (JavaACC). The JavaACC API improves security by standardizing how authentication mechanisms are integrated into J2EE
containers. The J2EE platform now makes it easier to develop web front ends with enhancements to Java Servlet and JavaServer
Pages (JSP) technologies. Servlets now support request listeners and enhanced filters. JSP technology has simplified the page and
extension development models with the introduction of a simple expression language, tag files, and a simpler tag extension API,
among other features. This makes it easier than ever for developers to build JSP-enabled pages, especially those who are familiar
with scripting languages.
Other enhancements to the J2EE platform include the J2EE Connector Architecture, which provides incoming resource adapter and
Java Message Service (JMS) plug ability. New features in Enterprise JavaBeans (EJB) technology include Web service endpoints, a
timer service, and enhancements to EJB QL and message-driven beans. The J2EE 1.4 platform also includes enhancements to
deployment descriptors. They are now defined using XML Schema which can also be used by developers to validate their XML
structures.
Note: The above information comes from SUN released notes.

Q10. Is J2EE application only a web-based?


NO. A J2EE application can be web-based or non-web-based. If an application client
executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle
tasks such as J2EE system or application administration. It typically has a graphical user interface created from Swing or AWT APIs, or
a command-line interface. When user request, it can open an HTTP connection to establish communication with a Servlet running in
the web tier.
Q11. Are JavaBeans J2EE components?
NO. JavaBeans components are not considered J2EE components by the J2EE specification. JavaBeans components written for the
J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans
components used in this way are typically simple in design and implementation, but should conform to the naming and design
conventions outlined in the JavaBeans component architecture.
Q12. Is HTML page a web component?
NO. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web
components by the J2EE specification. Even the server-side utility classes are not considered web components, either.
Q13. What is the container?
A container is a runtime support of a system-level entity. Containers provide components with services such as lifecycle
management, security, deployment, and threading.
Q14. What is the web container?
Servlet and JSP containers are collectively referred to as Web containers.
Q15. What is the thin client?
A thin client is a lightweight interface to the application that does not have such operations like query databases, execute complex
business rules, or connect to legacy applications.
Q16. What are types of J2EE clients?
• Applets
• Application clients
• Java Web Start-enabled rich clients, powered by Java Web Start technology.
• Wireless clients, based on Mobile Information Device Profile (MIDP) technology.
Q17. What is deployment descriptor?
A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a
component's deployment settings. A J2EE application and each of its modules has its own deployment descriptor.
Q18.What is the EAR file?
An EAR file is a standard JAR file with an .ear extension, named from Enterprise Archive file. A J2EE application with all of its modules
is delivered in EAR file.
Q19. What are JTA and JTS?
JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Java Transaction Service. JTA provides a standard
interface and allows you to demarcate transactions in a manner that is independent of the transaction manager implementation.
The J2EE SDK implements the transaction manager with JTS. But your code doesn't call the JTS methods directly. Instead, it invokes
the JTA methods, which then call the lower-level JTS routines. Therefore, JTA is a high level transaction interface that your
application uses to control transaction. And JTS is a low level transaction interface and EJBs uses behind the scenes (client code
doesn't directly interact with JTS. It is based on object transaction service (OTS) which is part of CORBA.
Q20. What is JAXP?
JAXP stands for Java API for XML. XML is a language for representing and describing textbased data which can be read and handled
by any program or tool that uses XML APIs.
Q21. What is J2EE Connector?
The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support access to
enterprise information systems that can be plugged into any J2EE product. Each type of database or EIS has a different resource
adapter.
Q22. What is JAAP?
The Java Authentication and Authorization Service (JAAS) provide a way for a J2EE
application to authenticate and authorize a specific user or group of users to run it. It is a standard Pluggable Authentication Module
(PAM) framework that extends the Java 2 platform security architecture to support user-based authorization.
Q23. What is Model 1?
Using JSP technology alone to develop Web page. Such term is used in the earlier JSP specification. Model 1 architecture is suitable
for applications that have very simple page flow, have little need for centralized security control or logging, and change little over
time. Model 1 applications can often be refactored to Model 2 when application requirements change.
Q24. What is Model 2?
Using JSP and Servlet together to develop Web page. Model 2 applications are easier to maintain and extend, because vQ25. What is
Struts?
A Web page development framework. Struts combine Java Servlets, Java Server Pages, custom tags, and message resources into a
unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone
between.
Q26. How is the MVC design pattern used in Struts framework?
In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate
handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model
represents, or encapsulates, an application's business logic or state. Control is usually then forwarded back through the Controller to
the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or
configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to
create and maintain. Controller--Servlet controller which supplied by Struts itself; View --- what you can see on the screen, a JSP
page and presentation components; Model --- System state and a business logic JavaBeans.
Q27. Do you have to use design pattern in J2EE project?

Yes. If I do it, I will use it. Learning design pattern will boost my coding skill.
Q28. Is J2EE a super set of J2SE?
       Yes
views do not refer to each other directly.
Q29. What does web module contain?

The web module contains:


• JSP files,
• class files for Servlets,
• GIF and HTML files, and
• A Web deployment descriptor.
  Web modules are packaged as JAR files with a .war (Web Archive) extension.
Q30. What APIs are available for developing a J2EE application?
• Enterprise JavaBeans Technology(3 beans: Session Beans, Entity Beans and
  Message-Driven Beans)
• JDBC API(application level interface and service provider interface or driver)
• Java Servlets Technology(Servlet)
• Java ServerPage Technology(JSP)
• Java Message Service(JMS)
• Java Naming and Directory Interface(JNDI)
• Java Transaction API(JTA)
• JavaMail API
• JavaBeans Activation Framework(JAF used by JavaMail)
• Java API for XML Processing(JAXP,SAX, DOM, XSLT)
• Java API for XML Registries(JAXR)
• Java API for XML-Based RPC(JAX-RPC)-SOAP standard and HTTP
• SOAP with Attachments API for Java(SAAJ)-- low-level API upon which JAX-RPC
  depends
• J2EE Connector Architecture
• Java Authentication and Authorization Service(JAAS)

You might also like