As the name suggests it is used for observing some objects.Observer watch for any change in state or property of subject.Suppose you are interested in particular object and want to get notified when its state changes then you observe that object and when any state or property change happens to that object,it get notified to you.

As described by GoF:
"Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically".

You can think of observer design pattern in two ways
  • Subject-Observer relationship:Object which is being observed is refereed as Subject and classes which observe subject are called Observer 
  • Publisher-Subscriber relationship:A publisher is one who publish data and notifies it to the list of subscribers who have subscribed for the same to that publisher. A simple example is Newspaper. Whenever a new edition is published by the publisher,it will be circulated among subscribers whom have subscribed to publisher.
The observers will not monitor every time whether there is any change in state of subject or not, since they will be notified for every state change of subject, until they stop observing subject. So it follows hollywood principle-"Don't call us,we will call you".

Some real life examples:

You might have surfed "Flipkart.com-Online megastore".So when you search for any product and it is unavailable then there is option called "Notify me when product is available".If you subscribe to that option then when state of product changes i.e. it is available,you will get notification mail "Product is available now you can buy it".In this case,Product is subject and You are an observer.

Lets say,your permanent address is changed then you need to notify passport authority and pan card authority.So here passport authority and pan card authority are observers and You are a subject.

On facebook also,If you subscribe someone then whenever new updates happen then you will be notified.

When to use it:

  • When one object changes its state,then all other dependents object must automatically change their state to maintain consistency
  • When subject doesn't know about number of observers it has.
  • When an object should be able to notify other objects without knowing who objects are.

 UML diagram for observer design pattern:

Components:

Subject

  • Knows its observers
  • Has any number of observer
  • Provides an interface to attach and detaching observer object at run time
Observer
  • Provides an update interface to receive signal from subject
ConcreteSubject
  • Stores state of interest to ConcreteObserver objects.
  • Send notification to it's observer
ConcreteObserver
  • Maintains reference to a ConcreteSubject object
  • Maintains observer state consistent with subjects.
  • Implements update operation

Java in-built API for observer pattern:

The java API provides one class and one inteface for implementing observer pattern.
1. java.util.Observable-class
2. java.util.Observer-interface

java.util.Observable:

For being observed,class must extend this class. The subclass becomes observable and override methods of  java.util.Observable and other objects can "observe" changes in state of this object.
Methods:
addObserver(Observer o) :add Observer to the list of observers for this subject.
deleteObserver(Observer o) :delete Observers from the list of observers .
notifyObservers() : notify all the observers if object has changed.
hasChanged() :return true if object has changed.
setChanged() :This method marks object has changed
clearChanged() :this method will indicate that subject has no changes or all the observers has been notified.

java.util.Observer:

The class that performs the "observing" must implement the java.util.Observer interface. There is a single method:
public void update(Observable obj, Object arg) :This method is called whenever the observed object is changed. An application calls an Observable object's notifyObservers method for notifying to all the observers of change.

Example:

You might have surfed "Flipkart.com-Online megastore".So when you search for any product and it is unavailable then there is option called "Notify me when product is available".If you subscribe to that option then when state of product changes i.e. it is available,you will get notification mail "Product is available now you can buy it".

Java code:

Below interface is our subject interface.It consists of method for adding or removing observers and also in condition of state change,notify all observer.

1.Subject.java:

package org.arpit.javapostsforlearning;

public interface Subject {
     public void registerObserver(Observer observer);
     public void removeObserver(Observer observer);
     public void notifyObservers();
}

Below class is our ConcreteSubject class.It implements subject interface thus provide implementation of all above three methods. 

2.Product.java:

package org.arpit.javapostsforlearning;

import java.util.ArrayList;

public class Product implements Subject{

	private ArrayList<Observer> observers = new ArrayList<Observer>();
    private String productName;
    private String productType;
    String availability;
    
    
	public Product(String productName, String productType,String availability) {
		super();
		this.productName = productName;
		this.productType = productType;
		this.availability=availability;
	}
	
	public ArrayList<Observer> getObservers() {
		return observers;
	}
	public void setObservers(ArrayList<Observer> observers) {
		this.observers = observers;
	}
	public String getProductName() {
		return productName;
	}
	public void setProductName(String productName) {
		this.productName = productName;
	}
	public String getProductType() {
		return productType;
	}
	public void setProductType(String productType) {
		this.productType = productType;
	}
	
	public String getAvailability() {
		return availability;
	}

	public void setAvailability(String availability) {
		this.availability = availability;
		notifyObservers();
	}

	public void notifyObservers() {
		System.out.println("Notifying to all the subscribers when product became available");
		 for (Observer ob : observers) {
             ob.update(this.availability );
      }

	}

	public void registerObserver(Observer observer) {
		 observers.add(observer);
		
	}

	public void removeObserver(Observer observer) {
		 observers.remove(observer);
		
	}

}

 Below interface is our observer interface.It consists of single method called "update"

3.Observer.java:

package org.arpit.javapostsforlearning;
public interface Observer {
	  public void update(String availability);
}

Below class is our ConcreteObserver class.It implements observer interface and provide implementation for update and other ConcreteObserver specific methods.

4.Person.java:

package org.arpit.javapostsforlearning;
public class Person implements Observer{

	String personName;

	public Person(String personName) {
		this.personName = personName;
	}

	public String getPersonName() {
		return personName;
	}

	public void setPersonName(String personName) {
		this.personName = personName;
	}

	public void update(String availabiliy) {
		
		System.out.println("Hello "+personName+", Product is now "+availabiliy+" on flipkart");
	}
}

5.ObserverPatternMain.java:

package org.arpit.javapostsforlearning;
public class ObserverPatternMain {

    /**
     * @Author arpit mandliya
     */
    public static void main(String[] args) {
        Person arpitPerson=new Person("Arpit");
        Person johnPerson=new Person("John");
        
        Product samsungMobile=new Product("Samsung", "Mobile", "Not available");
        
        //When you opt for option "Notify me when product is available".Below registerObserver method
        //get executed        
        samsungMobile.registerObserver(arpitPerson);
        samsungMobile.registerObserver(johnPerson);
        
        //Now product is available
        samsungMobile.setAvailability("Available");
        
    }
}

Run it:

Notifying to all the subscribers when product became available
Hello Arpit, Product is now Available on flipkart
Hello John, Product is now Available on flipkart
Now in above program,when availability of samsung mobile changes,it get notified subscribers who has subscribed for it.

Using java inbuilt APIs:

1.Product.java:

package org.arpit.javapostsforlearning;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

public class Product extends Observable{
 
   private ArrayList<Observer> observers = new ArrayList<Observer>();
    private String productName;
    private String productType;
    String availability;
    
    
	public Product(String productName, String productType,String availability) {
		super();
		this.productName = productName;
		this.productType = productType;
		this.availability=availability;
	}
	
	public ArrayList<Observer> getObservers() {
		return observers;
	}
	public void setObservers(ArrayList<Observer> observers) {
		this.observers = observers;
	}
	public String getProductName() {
		return productName;
	}
	public void setProductName(String productName) {
		this.productName = productName;
	}
	public String getProductType() {
		return productType;
	}
	public void setProductType(String productType) {
		this.productType = productType;
	}
	
	public String getAvailability() {
		return availability;
	}

	public void setAvailability(String availability) {
		if(!(this.availability.equalsIgnoreCase(availability)))
		{
			this.availability = availability;
			setChanged();
			notifyObservers(this,availability);
		}
	}

	public void notifyObservers(Observable observable,String availability) {
		System.out.println("Notifying to all the subscribers when product became available");
		 for (Observer ob : observers) {
             ob.update(observable,this.availability);
      }

	}

	public void registerObserver(Observer observer) {
		 observers.add(observer);
		
	}

	public void removeObserver(Observer observer) {
		 observers.remove(observer);
		
	}
}

 
2.Person.java

package org.arpit.javapostsforlearning;
import java.util.Observable;
import java.util.Observer;

public class Person implements Observer{

	String personName;
	
	
	public Person(String personName) {
		this.personName = personName;
	}


	public String getPersonName() {
		return personName;
	}


	public void setPersonName(String personName) {
		this.personName = personName;
	}

	public void update(Observable arg0, Object arg1) {
		System.out.println("Hello "+personName+", Product is now "+arg1+" on flipkart");
		
	}

}

3.ObserverPatternMain.java:

package org.arpit.javapostsforlearning;
public class ObserverPatternMain {

    /**
     * @Author arpit mandliya
     */
    public static void main(String[] args) {
        Person arpitPerson=new Person("Arpit");
        Person johnPerson=new Person("John");
        
        Product samsungMobile=new Product("Samsung", "Mobile", "Not available");
        
        //When you opt for option "Notify me when product is available".Below registerObserver method
        //get executed    
        samsungMobile.registerObserver(arpitPerson);
        samsungMobile.registerObserver(johnPerson);
        
        //Now product is available
        samsungMobile.setAvailability("Available");
         
    }
}

Run it:

Notifying to all the subscribers when product became available 
Hello Arpit, Product is now Available on flipkart
Hello John, Product is now Available on flipkart

Some important points about observer pattern:

  • Loose coupling between Subject and Observer:Only thing subject know about its observers is that observer implements Observer interface.You can register or delete any observer without affecting subject.
  • Support for broadcast communication:Notification about subject state change does not need to specify its receiver.This notification is broadcasted to all interested object that subscribed to it.
  • The one of the problem with this pattern is that debugging become very hard,if you have large number of subscribers because flow of control is implicit between subject and observers.
  • Spurious updates:If criteria for state change is not well defined then sometimes it lead to spurious updates.

Source code:


One of the common interview question is "What are differences between Comparator and Comparable". or "How will you sort collection of employee objects by its id or name".For that we can use two interfaces.i.e. Comparator and Comparable.Before we actually see differences,let me give you brief introduction of both.

Comparable interface:

Class whose objects to be sorted must implement this interface.In this,we have to implement compareTo(Object) method.
For example:
public class Country implements Comparable<Country>{
       @Override
    public int compareTo(Country country) {
        return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ;
}} 
If any class implements comparable inteface then collection of that object can be sorted automatically using Collection.sort() or Arrays.sort().Object will be sort on the basis of compareTo method in that class.
Objects which implement Comparable in java can be used as keys in a SortedMap like TreeMap or SortedSet like TreeSet without implementing any other interface.

Comparator interface:

Class whose objects to be sorted do not need to implement this interface.Some third class can implement this interface to sort.e.g.CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id. For example:
public class CountrySortByIdComparator implements Comparator<Country>{

    @Override
    public int compare(Country country1, Country country2) {
        
        return (country1.getCountryId() < country2.getCountryId() ) ? -1: (country1.getCountryId() > country2.getCountryId() ) ? 1:0 ;
    }

}
Using Comparator interface,we can write different sorting based on different attributes of objects to be sorted.You can use anonymous comparator to compare at particular line of code. For example:
         Country indiaCountry=new Country(1, "India");
         Country chinaCountry=new Country(4, "China");
         Country nepalCountry=new Country(3, "Nepal");
         Country bhutanCountry=new Country(2, "Bhutan");
        
         List<Country> listOfCountries = new ArrayList<Country>();
         listOfCountries.add(indiaCountry);
         listOfCountries.add(chinaCountry);
         listOfCountries.add(nepalCountry);
         listOfCountries.add(bhutanCountry); 

 //Sort by countryName

            Collections.sort(listOfCountries,new Comparator<Country>() {

                @Override
                public int compare(Country o1, Country o2) {

                    return o1.getCountryName().compareTo(o2.getCountryName());
                }
            });

Comparator vs Comparable

Parameter
Comparable
Comparator
Sorting logic
Sorting logic must be in same class whose objects are being sorted. Hence this is called natural ordering of objects
Sorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted. E.g. Sorting using id,name etc.
Implementation
Class whose objects to be sorted must implement this interface.e.g Country class needs to implement comparable to collection of country object by id
Class whose objects to be sorted do not need to implement this interface.Some other class can implement this interface. E.g.-CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id
Sorting method
int compareTo(Object o1)
This method compares this object with o1 object and returns  a integer.Its value has following meaning
1. positive – this object is greater than o1
2. zero – this object equals to o1
3. negative – this object is less than o1
int compare(Object o1,Object o2)
This method compares o1 and o2 objects. and returns  a integer.Its value has following meaning.
1. positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o1
Calling method
Collections.sort(List)
Here objects will be sorted on the basis of CompareTo method
Collections.sort(List, Comparator)
Here objects will be sorted on the basis of Compare method in Comparator
Package
Java.lang.Comparable
Java.util.Comparator

Java code: 

For Comparable:

We will create class country having attribute id and name.This class will implement Comparable interface and implement CompareTo method to sort collection of country object by id.

1. Country.java
package org.arpit.javapostsforlearning;
//If this.cuntryId < country.countryId:then compare method will return -1
//If this.countryId > country.countryId:then compare method will return 1
//If this.countryId==country.countryId:then compare method will return 0
public class Country implements Comparable<Country>{
    int countryId;
    String countryName;
   
   
    public Country(int countryId, String countryName) {
        super();
        this.countryId = countryId;
        this.countryName = countryName;
    }

    @Override
    public int compareTo(Country country) {
       return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ;
    }


    public int getCountryId() {
        return countryId;
    }


    public void setCountryId(int countryId) {
        this.countryId = countryId;
    }


    public String getCountryName() {
        return countryName;
    }


    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
   
}
2.ComparableMain.java
package org.arpit.javapostsforlearning;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparableMain {

 /**
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {
   Country indiaCountry=new Country(1, "India");
   Country chinaCountry=new Country(4, "China");
   Country nepalCountry=new Country(3, "Nepal");
   Country bhutanCountry=new Country(2, "Bhutan");
   
         List<Country> listOfCountries = new ArrayList<Country>();
         listOfCountries.add(indiaCountry);
         listOfCountries.add(chinaCountry);
         listOfCountries.add(nepalCountry);
         listOfCountries.add(bhutanCountry);
  
         System.out.println("Before Sort  : ");
         for (int i = 0; i < listOfCountries.size(); i++) {
    Country country=(Country) listOfCountries.get(i);
    System.out.println("Country Id: "+country.getCountryId()+"||"+"Country name: "+country.getCountryName());
   }
         Collections.sort(listOfCountries);
         
         System.out.println("After Sort  : ");
         for (int i = 0; i < listOfCountries.size(); i++) {
    Country country=(Country) listOfCountries.get(i);
    System.out.println("Country Id: "+country.getCountryId()+"|| "+"Country name: "+country.getCountryName());
   }
 }

}
 
Output:
Before Sort  : 
Country Id: 1||Country name: India
Country Id: 4||Country name: China
Country Id: 3||Country name: Nepal
Country Id: 2||Country name: Bhutan
After Sort  : 
Country Id: 1|| Country name: India
Country Id: 2|| Country name: Bhutan
Country Id: 3|| Country name: Nepal
Country Id: 4|| Country name: China 

For Comparator:

We will create class country having attribute id and name and will create another class CountrySortByIdComparator which will implement Comparator interface and implement compare method to sort collection of country object by id and we will also see how to use anonymous comparator.

1.Country.java

package org.arpit.javapostsforlearning;

public class Country{
    int countryId;
    String countryName;
    
    public Country(int countryId, String countryName) {
        super();
        this.countryId = countryId;
        this.countryName = countryName;
    }

    public int getCountryId() {
        return countryId;
    }


    public void setCountryId(int countryId) {
        this.countryId = countryId;
    }


    public String getCountryName() {
        return countryName;
    }


    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    
} 
2.CountrySortbyIdComparator.java
package org.arpit.javapostsforlearning;

import java.util.Comparator;
//If country1.getCountryId()<country2.getCountryId():then compare method will return -1
//If country1.getCountryId()>country2.getCountryId():then compare method will return 1
//If country1.getCountryId()==country2.getCountryId():then compare method will return 0
 public class CountrySortByIdComparator implements Comparator<Country>{

    @Override
    public int compare(Country country1, Country country2) {
        
        return (country1.getCountryId() < country2.getCountryId() ) ? -1: (country1.getCountryId() > country2.getCountryId() ) ? 1:0 ;
    }

}
3.ComparatorMain.java

package org.arpit.javapostsforlearning;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ComparatorMain {

 /**
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {
   Country indiaCountry=new Country(1, "India");
   Country chinaCountry=new Country(4, "China");
   Country nepalCountry=new Country(3, "Nepal");
   Country bhutanCountry=new Country(2, "Bhutan");
   
         List<Country> listOfCountries = new ArrayList<Country>();
         listOfCountries.add(indiaCountry);
         listOfCountries.add(chinaCountry);
         listOfCountries.add(nepalCountry);
         listOfCountries.add(bhutanCountry);
  
         System.out.println("Before Sort by id : ");
         for (int i = 0; i < listOfCountries.size(); i++) {
    Country country=(Country) listOfCountries.get(i);
    System.out.println("Country Id: "+country.getCountryId()+"||"+"Country name: "+country.getCountryName());
   }
         Collections.sort(listOfCountries,new CountrySortByIdComparator());
         
         System.out.println("After Sort by id: ");
         for (int i = 0; i < listOfCountries.size(); i++) {
    Country country=(Country) listOfCountries.get(i);
    System.out.println("Country Id: "+country.getCountryId()+"|| "+"Country name: "+country.getCountryName());
   }
         
         //Sort by countryName
         Collections.sort(listOfCountries,new Comparator<Country>() {

    @Override
    public int compare(Country o1, Country o2) {
     return o1.getCountryName().compareTo(o2.getCountryName());
    }
   });
   
   System.out.println("After Sort by name: ");
         for (int i = 0; i < listOfCountries.size(); i++) {
    Country country=(Country) listOfCountries.get(i);
    System.out.println("Country Id: "+country.getCountryId()+"|| "+"Country name: "+country.getCountryName());
   }
 }

}
Output:
Before Sort by id : 
Country Id: 1||Country name: India
Country Id: 4||Country name: China
Country Id: 3||Country name: Nepal
Country Id: 2||Country name: Bhutan
After Sort by id: 
Country Id: 1|| Country name: India
Country Id: 2|| Country name: Bhutan
Country Id: 3|| Country name: Nepal
Country Id: 4|| Country name: China
After Sort by name: 
Country Id: 2|| Country name: Bhutan
Country Id: 4|| Country name: China
Country Id: 1|| Country name: India
Country Id: 3|| Country name: Nepal
 
Please go through  top 50 core java interview questions for more interview questions.

What is JAXB?

JAXB stands for Java architecture for XML binding.It is used to convert XML to java object and java object to XML.JAXB defines an API for reading and writing Java objects to and from XML documents.Unlike SAX and DOM,we don't need to be aware of XML parsing techniques.

There are two operations you can perform using JAXB
  1. Marshalling :Converting a java object to XML 
  2. UnMarshalling :Converting a XML to java object

JAXB Tutorial

We will create a java program to marshal and unmarshal.

For Marshalling:

JAXB Marshalling

For Unmarshalling:

JAXB unmarshalling

Java program:

With the help of annotations and API provided by JAXB,converting a java object to XML and vice versa become very easy.

1.Country.java

A Java object which will be used to convert to and from XML
Create Country.java  in src->org.arpit.javapostsforlearning.jaxb
package org.arpit.javapostsforlearning.jaxb;

import java.util.ArrayList;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

//Below annotation defines root element of XML file
@XmlRootElement
//You can define order in which elements will be created in XML file
//Optional
@XmlType(propOrder = { "countryName", "countryPopulation", "listOfStates"})
public class Country {

 private String countryName;
 private double countryPopulation;
    
 private ArrayList<State> listOfStates;
 public Country() {
  
 }
 public String getCountryName() {
  return countryName;
 }
 @XmlElement
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 }
 public double getCountryPopulation() {
  return countryPopulation;
 }
 
 @XmlElement
 public void setCountryPopulation(double countryPopulation) {
  this.countryPopulation = countryPopulation;
 }
 
 
 public ArrayList<State> getListOfStates() {
  return listOfStates;
 }
 
 // XmLElementWrapper generates a wrapper element around XML representation
   @XmlElementWrapper(name = "stateList")
  // XmlElement sets the name of the entities in collection
   @XmlElement(name = "state")
 public void setListOfStates(ArrayList<State> listOfStates) {
  this.listOfStates = listOfStates;
 }
 
}
@XmlRootElement:This annotation defines root element of XML file.
@XmlType(propOrder = {"list of attributes in order"}):This is used to define order of elements in XML file.This is optional.
@XmlElement:This is used to define element in XML file.It sets name of entity. @XmlElementWrapper(name = "name to be given to that wrapper"):It generates a wrapper element around XML representation.E.g.In above example, it will generate <stateList> around each <state> element

2.State.java

package org.arpit.javapostsforlearning.jaxb;

import javax.xml.bind.annotation.XmlRootElement;

//Below statement means that class "Country.java" is the root-element of our example
@XmlRootElement(namespace = "org.arpit.javapostsforlearning.jaxb.Country")
public class State {


 private String stateName;
 long statePopulation;
 
 public State()
 {
  
 }
 public State(String stateName, long statePopulation) {
  super();
  this.stateName = stateName;
  this.statePopulation = statePopulation;
 }

 public String getStateName() {
  return stateName;
 }

 public void setStateName(String stateName) {
  this.stateName = stateName;
 }

 public long getStatePopulation() {
  return statePopulation;
 }

 public void setStatePopulation(long statePopulation) {
  this.statePopulation = statePopulation;
 }
}

3.JAXBJavaToXml.java

package org.arpit.javapostsforlearning.jaxb;

import java.io.File;
import java.util.ArrayList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBJavaToXml {
 public static void main(String[] args) {

  // creating country object
   Country countryIndia=new Country();  
   countryIndia.setCountryName("India");
   countryIndia.setCountryPopulation(5000000);
   
   // Creating listOfStates
   ArrayList<State> stateList=new ArrayList<State>();
   State mpState=new State("Madhya Pradesh",1000000);
   stateList.add(mpState);
   State maharastraState=new State("Maharastra",2000000);
   stateList.add(maharastraState);
    
   countryIndia.setListOfStates(stateList);
   
  try {

   // create JAXB context and initializing Marshaller
   JAXBContext jaxbContext = JAXBContext.newInstance(Country.class);
   Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

   // for getting nice formatted output
   jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

   //specify the location and name of xml file to be created
   File XMLfile = new File("C:\\arpit\\CountryRecord.xml");
   
   // Writing to XML file
   jaxbMarshaller.marshal(countryIndia, XMLfile); 
   // Writing to console
   jaxbMarshaller.marshal(countryIndia, System.out); 
  
  } catch (JAXBException e) {
   // some exception occured
   e.printStackTrace();
  }

 }
}
After running above program,you will get following output

Console output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<country xmlns:ns2="org.arpit.javapostsforlearning.jaxb.Country">
    <countryName>India</countryName>
    <countryPopulation>5000000.0</countryPopulation>
    <stateList>
        <state>
            <stateName>Madhya Pradesh</stateName>
            <statePopulation>1000000</statePopulation>
        </state>
        <state>
            <stateName>Maharastra</stateName>
            <statePopulation>2000000</statePopulation>
        </state>
    </stateList>
</country>

Now we will read above generated XML and retrieve country object from it.

4.JAXBXMLToJava.java

package org.arpit.javapostsforlearning.jaxb;

import java.io.File;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class JAXBXMLToJava {
 public static void main(String[] args) {

  try {
   
   // create JAXB context and initializing Marshaller
   JAXBContext jaxbContext = JAXBContext.newInstance(Country.class);

   Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
   
   // specify the location and name of xml file to be read
   File XMLfile = new File("C:\\arpit\\CountryRecord.xml");
   
   // this will create Java object - country from the XML file
   Country countryIndia = (Country) jaxbUnmarshaller.unmarshal(XMLfile);

   System.out.println("Country Name: "+countryIndia.getCountryName());
   System.out.println("Country Population: "+countryIndia.getCountryPopulation());
   
   ArrayList<State> listOfStates=countryIndia.getListOfStates();
  
   int i=0; 
   for(State state:listOfStates)
   {
    i++;
    System.out.println("State:"+i+" "+state.getStateName());
   }

  } catch (JAXBException e) {
   // some exception occured
   e.printStackTrace();
  }

 }
}
After running above program,you will get following output

Console output:

Country Name: India
Country Population: 5000000.0
State:1 Madhya Pradesh
State:2 Maharastra

JAXB advantages:

  • It is very simple to use than DOM or SAX parser
  • We can marshal XML file to other data targets like inputStream,URL,DOM node.
  • We can unmarshal XML file from other data targets.
  • We don't need to be aware of XML parsing techniques.
  • We don't need to access XML in tree structure always.

JAXB disadvantages:

  • JAXB is high layer API so it has less control on parsing than SAX or DOM.
  • It has some overhead tasks so it is slower than SAX. 

Source code:

Source:Download

This is 6 of 8 parts of tutorial series

Tutorial Content:

    Introduction to hibernate framework Hibernate hello world example in eclipse Hibernate interview questions Hibernate one to one mapping example Hibernate one to many mapping example Hibernate many to many mapping example Hibernate inheritance:Table per class hierarchy Hibernate inheritance:table per subclass Hibernate inheritance:Table per concrete class Difference between openSession and getCurrentSession
ial we will see how to implement inheritance in hibernate.There are 3 ways in which you can implement inheritance in hibernate.In this post,we will see one of them i.e.one table per class hierarchy.

Inheritance in hibernate:

Java is object oriented language and inheritance is one of main functionalities of java.Relation model can implement "is a" and "has a" relationship but hibernate provides us way to implement class hierarchy in a different ways.

One table per class hierarchy:

Lets say we have following class hierarchy.We have shape class as base class and Rectangle and Circle inherit from Shape class.
In one table per class hierarchy,One table will be created for above hierarchy.i.e. SHAPE table will be created having following structure.
As you can see only one table(SHAPE) is created having attributes of subclasses also.
As per our above class diagram,we will create three classes-Shape.java,Rectangle.java and Circle.java

1.Shape.java

This is our root class of entity class hierarchy.
Create Shape.java in src->org.arpit.javapostsforlearning.

package org.arpit.javapostsforlearning;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
import javax.persistence.DiscriminatorType;

@Entity
@Table(name="SHAPE")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn
(
 name="Discriminator",
 discriminatorType=DiscriminatorType.STRING
)
@DiscriminatorValue(value="S")
public class Shape {

 @Id
 @GeneratedValue
 @Column(name="Shape_Id")
 int shapeId;
 @Column(name="Shape_Name")
 String shapeName;
 
        public Shape()
 {
  
 } 
 public Shape(String shapeName)
 {
  this.shapeName=shapeName;
 }
 //getters and setters
 
}

Shape is our root class so some annotations needs to be used with root class for implementing inheritance.

@Inheritance:

For implementing inheritance in hiberante,@Inheritance annotation is used.It defines inheritance strategy to be implement for entity class hierarchy.For one table per class hierarhcy,we have used Single_Table as inheritance strategy.This annotation is defined at root level or sub hierarchy level where different strategy is to be applied.

@DiscriminatorColumn:

This annotation is used to define discriminator column for Single_Table and joined strategy.It is used to distinguish between different class instances.This annotation is defined at root level or sub hierarchy level where different strategy is to be applied.
If @DiscriminatorColumn annotation is not specified,then hibernate will create a column named as "DType" and DiscriminatorType will be string.

@DiscriminatorValue:

This annotation defines value in discriminator column for that class.This can only be applied on entity concrete class.For example,If entry will be of shape instance in SHAPE table then "s" will be value for that row in discriminator column.If this annotation is not specified and Discriminator column is used then provider specific values will be provided and if Discriminator type is String then discriminator value will be entity name.Discriminator value,if not defaulted need to specified on each enitity in hierarchy.

2.Rectangle.java

This is our child class.
Create Rectangle.java in src->org.arpit.javapostsforlearning.

package org.arpit.javapostsforlearning;import javax.persistence.Column;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

@Entity
@DiscriminatorValue(value="R")
public class Rectangle extends Shape{

 @Column(name="Rectangle_Length")
 int length;
 @Column(name="Rectangle_Breadth")
 int breadth;
 // getters and setters
 
 public Rectangle()
 {
  
 }
 
 public Rectangle(String shapeName,int length,int breadth)
 {
  super(shapeName);
  this.length=length;
  this.breadth=breadth;
 }
 
 // getters and setters
}

3.Circle.java

This is our second child class.
Create Circle .java in src->org.arpit.javapostsforlearning.
package org.arpit.javapostsforlearning;import javax.persistence.Column;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

@Entity
@DiscriminatorValue(value="C")
public class Circle extends Shape{

 @Column(name="Circle_Radius")
 int radius;
 
 public Circle()
 {
  
 }
 public Circle(String shapeName,int radius)
 {
  super(shapeName);
  this.radius=radius;
  
 }
 // getters and setters
}

4.Hiberante.cfg.xml:

Create a file named "hibernate.cfg.xml" in src folder.
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <property name="connection.url">jdbc:sqlserver://localhost:1433;database=UserInfo</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.SQLServer2005Dialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>

  <mapping class="org.arpit.javapostsforlearning.Shape"></mapping>
  <mapping class="org.arpit.javapostsforlearning.Rectangle"></mapping>
  <mapping class="org.arpit.javapostsforlearning.Circle"></mapping>

    </session-factory>

</hibernate-configuration>

5.Main Class:

package org.arpit.javapostsforlearning;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateMain {

 public static void main(String[] args) {
  
  Shape shape=new Shape("Sqaure");
  Rectangle rectangle=new Rectangle("Rectangle", 10, 20);  
  Circle circle=new Circle("Circle", 4);
    
  Configuration configuration=new Configuration();
  configuration.configure();
  ServiceRegistry sr= new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
  SessionFactory sf=configuration.buildSessionFactory(sr);
  Session ss=sf.openSession();
  
  ss.beginTransaction();
  ss.save(shape);
  ss.save(rectangle);
  ss.save(circle);
  ss.getTransaction().commit();
  ss.close();
  
 }
}

Project structure:


6.Run it:

When you run it,you will get following output.
Hibernate: create table SHAPE (Discriminator varchar(31) not null, Shape_Id int identity not null, Shape_Name varchar(255), Rectangle_Breadth int, Rectangle_Length int, Circle_Radius int, primary key (Shape_Id))
Feb 04, 2013 11:01:36 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into SHAPE (Shape_Name, Discriminator) values (?, 'S')
Hibernate: insert into SHAPE (Shape_Name, Rectangle_Breadth, Rectangle_Length, Discriminator) values (?, ?, ?, 'R')
Hibernate: insert into SHAPE (Shape_Name, Circle_Radius, Discriminator) values (?, ?, 'C')


7.SQL output:

SHAPE table in database.


One of the common interview question is "What is difference between ArrayList and Vector".Before we actually see differences,let me give you brief introduction of both.

ArrayList

  • ArrayList is implementation of list interface.
  • ArrayList is not synchonized(so not thread safe)
  • ArrayList is implemented using array as internal data structure.It can be dynamically resized .
  • ArrayList increases half of its size when its size is increased.

Vector

  • Vector is implementation of list interface.
  • Vector is synchonized(so thread safe)
  • Vector is implemented using array as internal data structure.It can be dynamically resized.
  • Vector doubles size of array when its size is increased.

ArrayList vs Vector:

Parameter
Vector
ArrayList
Synchonized
Yes
No
ThreadSafe
Yes
No
Performance
It is slower than arraylist
It is faster than Vector
Changes in internal  size of array when  resized
Vector doubles size of its internal  array when its size is increased
ArrayList increases half of its size when its size is increased.

Which is better? ArrayList or Vector?

It actually depends on our need.Vector is slower than ArrayList as its methods are synchronized so if we don't work in multi threaded environment then ArrayList is better choice.

Best Practice:

When we initialize ArrayList or Vector,always initialize with largest capacity java program will need as incrementing size is costlier operation.

Can we synchronize ArrayList?

Yes,ArrayList can also be synchonized with help of method Collections.synchronizedList(arraylist)
List synchronizedArrayList=Collections.synchronizedList(arraylist);

One of the common interview question is "What is difference between HashMap and HashSet"..Before we actually see differences,let me give you brief introduction of both.

Java HashMap:

    HashMap in java How HashMap works in java hash and indexfor method in HashMap hashcode and equals method in java How to sort HashMap by keys and values Difference between HashMap and HashSet Difference between HashMap and Hashtable How to iterate over HashMap

HashMap

HashMap implements Map interface which maps key to value.It is not synchronized and is not thread safe.Duplicate keys are not allowed and null keys as well as values are allowed. For more details, you can also read How HashMap works in java.
HashMap<Interger,String> employeeHashmap=new HashMap<Integer,String>();
employeeHashmap.put(1,"Arpit");
employeeHashmap.put(2,"John");  

HashSet

HashSet implements Set interface which does not allow duplicate value.It is not synchronized and is not thread safe.For more details, you can also read How HashSet works in java.
HashSet<String> employeeSet=new HashSet<String>();
employeeSet.add("Arpit");
employeeSet.add("Arpit");
employeeSet.add("john"); 
Above employeeSet will have 2 elements in it as Set does not allow duplicate values.
add method is used to add element to HashSet.If It return true then element is added successfully but if it return false then you are trying to insert duplicate value.
public boolean add(Object o)
One main thing about HashSet is objects which we are going to add in HashSet must implement Hashcode() and equals() method so that we can check for duplicate values.If we are adding custom objects to HashSet then we must override() Hashcode() and equals() method according to our need.If we do not override then object will take default implementation which may not desirable.

HashMap vs HashSet:

Parameter
HashMap
HashSet
Interface
This is core difference among them.HashMap implements Map interface
HashSet implement Set interface
Method for storing data
It stores data in a form of key->value pair.So it uses put(key,value) method for storing data
It uses add(value) method for storing data
Duplicates
HashMap allows duplicate value but not duplicate keys
HashSet does not allow duplicate values.
Performance
It is faster than hashset as values are stored with unique keys
It is slower than HashMap
HashCode Calculation
In hash map hashcode value is calculated using key object

In this,hashcode is calculated on the basis of value object.Hashcode can be same for two value object so we have to implement equals() method.If equals() method return false then two objects are different.

Please go through  core java interview questions for more interview questions.

One of the common interview question is "What are differences between Hashtable and HashMap".When I started using them,I used any of them irrespective of their differences.Afterwards i found noticeable differences between them which can affect your performance of application. .Before we actually see differences,let me give you brief introduction of both.

Java HashMap:

    HashMap in java How HashMap works in java hash and indexfor method in HashMap hashcode and equals method in java How to sort HashMap by keys and values Difference between HashMap and HashSet Difference between HashMap and Hashtable How to iterate over HashMap

HashMap

HashMap implements Map interface which maps key to value.It is not synchronized and is not thread safe.Duplicate keys are not allowed and null keys as well as value are allowed.
HashMap<Interger,String> employeeHashmap=new HashMap<Integer,String>();
employeeHashmap.put(1,"Arpit");
employeeHashmap.put(2,null);  // will work fine

Hashtable

Hashtable implements Map interface which maps key to value.It is synchronized and thread safe.Duplicate keys are not allowed and null key is not allowed.
Hashtable<Interger,String> employeeHashmap=new Hashtable<Integer,String>();
employeeHashmap.put(1,"Arpit");
employeeHashmap.put(2,null);  //not allowed and will throw NullPointer exception at run time

Hashtable vs HashMap:

Parameter
Hashtable
HashMap
ThreadSafe
Yes
No
Synchronized
Yes
No
Performance
Due to theadSafe and Synchronized,it is often slower than HashMap
In single threaded environment, it is much faster than Hashtable.So if you do not work in multi thread environment ,then hashMap is recommended
Null key
Do not allow
Allows null key as well as values
Fail fast
enumeration in hashtable is not fail fast
Iterator in hashMap is fail fast
Extends
It extends Dictionary class which is quite old
It extends AbstractMap class
Alternative
No alternative
You can use ConcurrentHashMap for multi thread environment

Some important points need to be discussed.
  • Synchonized meaning only one thread can modify one table  at one point of time.When any thread perform update operation on hashtable then it acquires lock on it and other threads have to wait for lock to be released.
  • Fail-fast iterator means if one thread is iterating over hashmap and other thread trying to modify hashmap structurally it will throw ConcurrentModification Exception and fail immediately.Structurally modification means inserting or deleting elements that can change structure of map.

Can we synchronize HashMap?

Yes,We can synchonized a HashMap also with the help of Collections.synchonizedMap(hashmap) so HashMap can be synchronized by
Map map=Collections.synchonizedMap(hashmap)

Please go through  core java interview questions for more interview questions.

This is 5 of 8 parts of tutorial series

Tutorial Content:

    Introduction to hibernate framework Hibernate hello world example in eclipse Difference between openSession and getCurrentSession Hibernate one to one mapping example Hibernate one to many mapping example Hibernate many to many mapping example Hibernate inheritance:Table per class hierarchy Hibernate inheritance:table per subclass Hibernate inheritance:Table per concrete class Difference between openSession and getCurrentSession Difference between get and load Spring MVC Hibernate MySQL CRUD example Spring Rest hibernate example
In this example we will see how to implement many to many relationship using annotations.
Lets take example of Country and Language.One Country can have n number of languages and one language can be spoken by n number of countries.Following is relationship diagram among them.






Now to create above tables in database, you need to create two java files i.e. Country.java and Language.java.

1.Country.java

Country class will be used to create COUNTRY table in database.
Create Country.java in src->org.arpit.javapostsforlearning.

package org.arpit.javapostsforlearning;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name="COUNTRY")
public class Country {
 
 @Id
 @GeneratedValue
 @Column(name="Country_Id")
 int countryId;
 
 @Column(name="Country_Name")
    String countryName ;
 
 @ManyToMany(cascade=CascadeType.ALL)
 @JoinTable(name="COUNTRY_LANGUAGE",joinColumns={@JoinColumn(name="Country_Id")},inverseJoinColumns={@JoinColumn(name="Language_Id")})
 Collection<Language> languages=new ArrayList<Language>();
    
 public Country()
 {
  
 }
    public Country(String countryName) {
  this.countryName=countryName;
 }

 public String getCountryName() {
        return countryName;
    }
          
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

 public Collection<Language> getLanguages() {
  return languages;
 }

 public void setLanguages(ArrayList<Language> languages) {
  this.languages = languages;
 }
}

The @MamyToMany annotation is used to create the many-to-many relationship between the Country and Language entities. The @JoinTable annotation is used to create the COUNTRY_LANGUAGE link table and @JoinColumn annotation is used to refer the linking columns in both the tables.

2.Langauge.java

Language class will be used to create LANGUAGE table in database.
Create Langauge.java in src->org.arpit.javapostsforlearning.

package org.arpit.javapostsforlearning;import javax.persistence.Column;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name="LANGUAGE")
public class Language {

 @Id
 @GeneratedValue
 @Column(name="Language_Id")
 int languageId;
 
 @Column(name="Language_Name")
 String languageName;
 
 @ManyToMany(mappedBy="languages")
 Collection<Country> languageSpeakingCountries=new ArrayList<Country>();

 public Language()
 {
  
 }
 public Language(String languageName) {
  this.languageName=languageName;
 }

 public String getLanguageName() {
  return languageName;
 }

 public void setLanguageName(String languageName) {
  this.languageName = languageName;
 }

 public Collection<Country> getLanguageSpeakingCountries() {
  return languageSpeakingCountries;
 }

 public void setLanguageSpeakingCountries(ArrayList<Country> languageSpeakingCountries) {
  this.languageSpeakingCountries = languageSpeakingCountries;
 }
}

3.Hiberante.cfg.xml:

Create a file named "hibernate.cfg.xml" in src folder.
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <property name="connection.url">jdbc:sqlserver://localhost:1433;database=UserInfo</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.SQLServer2005Dialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>

  <mapping class="org.arpit.javapostsforlearning.Country"></mapping>
  <mapping class="org.arpit.javapostsforlearning.Language"></mapping>

    </session-factory>

</hibernate-configuration>

4.Main Class:

package org.arpit.javapostsforlearning;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateMain {

 public static void main(String[] args) {
  
  Country country=new Country("India");
    
  Language hindiLan=new Language("Hindi");
  hindiLan.getLanguageSpeakingCountries().add(country);
  
  Language engLan=new Language("English");
  engLan.getLanguageSpeakingCountries().add(country);
  
  country.getLanguages().add(hindiLan);
  country.getLanguages().add(engLan);
    
  Configuration configuration=new Configuration();
  configuration.configure();
  ServiceRegistry sr= new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
  SessionFactory sf=configuration.buildSessionFactory(sr);
  Session ss=sf.openSession();
  
  ss.beginTransaction();
  ss.save(country);
  ss.getTransaction().commit();
  ss.close();
  
 }
}

Project Struture:

 

5.Run it:

When you run it,you will get following output.

Hibernate: create table COUNTRY (Country_Id int identity not null, Country_Name varchar(255), primary key (Country_Id))
Hibernate: create table COUNTRY_LANGUAGE (Country_Name int not null, Language_Name int not null)
Hibernate: create table LANGUAGE (Language_Id int identity not null, Language_Name varchar(255), primary key (Language_Id))
Hibernate: alter table COUNTRY_LANGUAGE add constraint FK67645601403CB4F4 foreign key (Language_Name) references LANGUAGE
Hibernate: alter table COUNTRY_LANGUAGE add constraint FK6764560165CEDD60 foreign key (Country_Name) references COUNTRY
Feb 03, 2013 12:07:59 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into COUNTRY (Country_Name) values (?)
Hibernate: insert into LANGUAGE (Language_Name) values (?)
Hibernate: insert into LANGUAGE (Language_Name) values (?)
Hibernate: insert into COUNTRY_LANGUAGE (Country_Name, Language_Name) values (?, ?)
Hibernate: insert into COUNTRY_LANGUAGE (Country_Name, Language_Name) values (?, ?)

5.SQL output:

COUNTRY table in database



LANGUAGE table in database




COUNTRY_LANGUAGE table is created to link above two tables.





Source code:

 

Java tutorial for beginners Copyright © 2012