Wednesday 24 July 2013

What is Comparator and Comparable interface in java and what are the differences between them?



The Array.sort() and Collections.sort() can sort array and arraylist on the basis of single values but Lists are meant to store objects and they can have multiple properties so if need to sort list on the basis of some other properties than we need to use Comparable and Comparator interfaces.

Basically, Collections.sort()  have two types in java collection framework .
  1. Collections.sort(List of objects of class which implements Comparable   or list of objects);
  2. Collections.sort(list of objects, object of class implementing Comparator);

Comparable Interface: When we use Collection.sort() with single arguments or first type of Collections.sort then it basically needs the object of the class and the class should implement Comparable interface of Java.lang package.Comparable interface of java has an abstract method compareTo(Class object) which need to be implemented every time the class implements the Comparable interface. This method is containing the logic for sorting the list on the basis of some property. It compares the property with object property and returns the integer type result as:
Positive    – this object is greater than object’s property
Zero          – Both properties are equal
Negative – this object is less than object’s property

Let‘s suppose that we have a class containing the employee data(Emp Name, Emp Age). Now we can sort the list on the basis of name as well as age with the help of Comparator (refer below example).

 import java.util.*;

class empData implements Comparable<empData>
{
    String name="";
    int age=0;
    empData()    {    }
    empData(String name, int age)  {
          this.name= name;
          this.age=age;
      }

     public int compareTo(empData obj)    {
         // return this.age - obj.age;   /*If we uncomment this line and comment the line below it will sort  
                                                                the list on the basis of employee name*/
         return this.name.compareTo(obj.name); //This will sort the list on the basis of employee age
         }
 }
     
public class demoComparable
      {
        public static void main(String s[])      {
          List<empData> list = new ArrayList<empData>();
          list.add(new empData("B",50));
          list.add(new empData("A",30));
           list.add(new empData("e",25));
            list.add(new empData("c",45));
             list.add(new empData("d",52));
          System.out.println("List before sorting");
          for(empData a : list)  {

                System.out.print(a.name+"  ");
                System.out.println(a.age);   }

/*Calling the sort by passing the list of empData Class objects which implements Comparable interface */
Collections.sort(list); 
          System.out.println("List after sorting");
          for(empData a : list)
          {
                System.out.print(a.name+"  ");
                System.out.println(a.age); }}}
      
Comparator Interface: When we use Collection.sort() with two arguments or second type of Collections.sort then it basically needs the object of the class and the class should implement Comparator interface of Java.util  package. Comparable interface of java has an abstract method compare(Class object 1,class object2) which need to be implemented every time the class implements the Comparator interface. This method is containing the logic for sorting the list on the basis of some property. It compares the object2 property with object1 property and returns the integer type result as:
Positive    – Object1 property is greater than object 2 property
Zero          – Both properties are equal
Negative – Object1 property is less than object 2 property

Same above example can be recreated as below example to understand the concept of Cmparator sorting.

import java.util.*;

class empData implements Comparator<empData>
{
    String name="";
    int age=0;
    empData()    {    }
    empData(String name, int age)  {
          this.name= name;
          this.age=age;
      }

     public int compare(empData a, empData b){
         // return a.age - b.age;   /*If we uncomment this line and comment the line below it will sort  
                                                                the list on the basis of employee name*/
         return a.name.compareTo(b.name); //This will sort the list on the basis of employee age
         }
 }
     
public class demoComparator
      {
        public static void main(String s[])      {
          List<empData> list = new ArrayList<empData>();
          list.add(new empData("B",50));
          list.add(new empData("A",30));
           list.add(new empData("e",25));
            list.add(new empData("c",45));
             list.add(new empData("d",52));
          System.out.println("List before sorting");
          for(empData a : list)  {

                System.out.print(a.name+"  ");
                System.out.println(a.age);   }

/*Calling the sort by passing the list of empData Class objects  and object of the class which implement the comparator(it can be same class whose properties need to be sort or any other class implementing the comparator interface)*/
Collections.sort(list,new empData());
          System.out.println("List after sorting");
          for(empData a : list)
          {
                System.out.print(a.name+"  ");
                System.out.println(a.age); }}}


Differences between Comparator and Comparable

S.No.
Comparable
Comparator
1
Comparable comes under JAVA.LANG Package
Comparator comes under JAVA.UTIL Package
2
It has an abstract method compareTo(class type variable)
It has an abstract method compare(class type variable1 ,class type variable2)
3
The class whose properties need to be sort must implement Comparable interface that’s why they provide natural ordering
The class whose properties need to be sort may or may not implement Comparator interface. Some other class can have the sorting logic or can implement Comparator interface.
4
It is called when Collections.sort(list) is called
It is called when Collections.sort(list, comparator) is called

What is a Global Temporary Table in Oracle?



Global Temporary Table:
The oracle gives the advantage of creating the session specific tables known as Global temporary table.
They are same as the other tables in oracle except that they are exclusive for every session means that the data in temporary table is private to the session (i.e. each session can see and modify its own data). The LOCK statement has no effect on a temporary table because each session has its own private data.
A TRUNCATE statement issued on a session-specific temporary table truncates data in its own session.
It does not truncate the data of other sessions that are using the same table.

Syntax for creating Global Temporary Table:
·         Session Level Global Temporary Table:-
    Create global temporary table temp_table (column1  NUMBER,column2  NUMBER)
    on commit preserve rows

·         Transaction Level Global Temporary Table:-
    Create global temporary table temp_table (column1  NUMBER,column2  NUMBER)
     on commit delete rows;


The ON COMMIT DELETE ROWS clause indicates that the data should be deleted at the end of the transaction.
The ON COMMIT PRESERVE ROWS clause indicates that rows should be preserved until the end of the session.


Summary:

·         You can create indexes for temporary tables using the CREATE INDEX statement. Indexes created on temporary tables are also temporary, and the data in the index has the same session or transaction scope as the data in the temporary table.
·         You can create views that access both temporary and permanent tables.
·         You can also create triggers on temporary tables.
·         You can perform DDL statements (ALTER TABLE, DROP TABLE, CREATE INDEX, and so on) on a temporary table only when no session is currently bound to it. A session gets bound to a temporary table when an INSERT is performed on it. The session gets unbound by a TRUNCATE, at session termination, or by doing a COMMIT or ABORT for a transaction-specific temporary table.

Tuesday 23 July 2013

What is the difference between Checked and Unchecked Exception in Java?



Checked Exception: - All the exceptions which required to be catches and handled at the compile time otherwise a compilation error will be given are known as the checked exception. All checked exception is direct sub Class of Exception but not inherit RuntimeException.
Checked Exception are helpful in ensuring that programmer provide recovery strategy or at least handle the scenario gracefully which can fail the program execution.

Type of checked Exception:-
Following are some Examples of Checked Exception:

1.       IOException
2.       SQLException
3.       DataAccessException
4.       ClassNotFoundException
5.       InvocationTargetException

Advantages and Disadvantages of Checked Exception:-

1.       They help to execute the program by handling some known failure situations.
2.       In long programs, we can location and type of error by handling the proper exceptions.
3.       They are useful in writing the log files for a program.
4.       They make the code complex and less readable

Unchecked Exception:-
All the exceptions whose handling cannot be handled at compile time are known as the Unchecked Exceptions. They mostly arise due to programming errors like accessing method of a null object, accessing element outside an array boundary.  Unchecked Exceptions are direct sub Class of RuntimeException.

Types of Unchecked Exception:-
Here are few examples of Unchecked Exception:

1.       NullPointerException
2.       ArrayIndexOutOfBound
3.       IllegalArgumentException
4.       IllegalStateException


Some Important points:
1. Both Checked and Unchecked Exception are handled using keyword try, catch and finally.
2. In terms of Functionality Checked and Unchecked Exception are same.
3. Checked Exception handling verified during compile time.
4. Unchecked Exception are mostly programming errors
5. JDK7 provides improved Exception handling code with catching multiple Exception in one catch block and reduce amount of boiler plate code required for exception handling in Java.