Friday, September 13, 2013

How JDBC driver will be register ?


 JDBC Driver Registration: 

We have two main chances to Load or Register JDBC driver.

1) Using Class.forName("..");
2) Using DriverManager.registerDriver(...);

Already we know that, The first step in JDBC program is driver loading.

But when we write driver loading code, How the driver object is available in the next step of getting the connection object.


example : 

JDBC program code:

         Class.forName("com.mysql.jdbc.Driver");//here no return type
         Connection conn = DriverManager.getConnection(url, username, password);



But still we are able to get the connection object using DriverManager class.


Observe carefully, 

The Driver class "com.nysql.jdbc.Driver" contains one static block, and this static block will be executed while loading this class into jvm's memory by ClassLoader.

This static block has the code to register(assign) MySQL's Driver class object to one of the static varible in DriverManager class.

example code :
 
                static {
                 try {
                java.sql.DriverManager.registerDriver(new Driver());
           } catch (SQLException E) {
              throw new RuntimeException("Can't register driver!");
               }
                   } //end block , code from   com.mysql.jdbc.Driver   

The above code will assign it's object to one of the static varible of DrierManager class.

 
//code from    java.sql.DriverManager 
private final static CopyOnWriteArrayList<DriverInfo> registeredDrivers = new CopyOnWriteArrayList<DriverInfo>(); 
 
 
The above static variable is available for our JDBC application. So that, the second step "getting connection object" is able to execute and returns the Connection object. 

We can easily understand, If we compare this technique with System.out.println().

System is a class and out is static variable which points to PrintStream object and println() is overloaded method available in PrintStream class.

The out variable is assigned with the PrintStream obect while this System class loading into memory.

I think you understood my intention from the above code.

Note: The second style of Driver Loading is also same.


Thursday, September 12, 2013

Circular Dependency in Spring

Circular Dependency :

One object is depending on other object which is also depending on it.

It means

suppose you have two classes A, B.

A -- > B -- >A   is  circular dependency

A is dependent on B and vice-versa .

 Spring IOC throws Runtime exception as ObjectCurrentlyInCreationException .

Spring throws more easily this Exception, in case of Constructor Injection.

source: javapapers.com

Difference between DesignPatterns and Frameworks ?


Design Patterns : 

- Design Patterns are strategies that allow programmers to share knowledge about the recurring problems and their solutions.


Framework : 

- Framework is a set of well-defined classes and interfaces that provides services to our application. With a framework, it contains the executing routines and invokes operations on to your extensions through inheritance and other means.


source: Spring and Hibernate SANTOSH KUMAR K

Wednesday, September 11, 2013

How many ways to sort an ArrayList or Collection ?


Ways to Sort ArrayList or Collection :

There are different ways to sort ArrayList

1) Sort using Arrays class  as below.

  Arrays.sort(array, arrayComparator);
  Arrays.sort(arrayList, arrayListComparator);


2) Sort using Collections class as below.
  
  Collections.sort(arrayList, arrayListComparator);

similarly.. to Sort an ArrayList of Book objects..

   Collections.sort(books, new Comparator<Book>(){//anonymous class
        public int compare(Book b1, Book b2) {
            return if b1 >b2 return +1 , if b2>b1 return -1, otherwise 0;    //pseudo code
        }
}//end method

3) Sort using Comparable Interface.
   If we want to sort ArrayList without the need of Comparator then implement Elements of ArrayList object to Comparable interface, And override compareTo() method based on our requirement.

ex: 


public class Employee implements Comparable<Employee> {
    private int id;
    private String name;
    private int age;
    private long salary;
    public int getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
    public long getSalary() {
        return salary;
    }
    public Employee(int id, String name, int age, int salary) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
    }
    @Override
    public int compareTo(Employee emp) {
        return (this.id - emp.id);
    }
    @Override
    public String toString() {
        return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +
                this.salary + "]";
    }
}// end class


usage:


//sorting custom object array
Employee[] empArr = new Employee[4];
empArr[0] = new Employee(10, "Mikey", 25, 10000);
empArr[1] = new Employee(20, "Arun", 29, 20000);
empArr[2] = new Employee(5, "Lisa", 35, 5000);
empArr[3] = new Employee(1, "Pankaj", 32, 50000);
//
Arrays.sort(empArr);
System.out.println("Default Sorting of Employees list:\n"+Arrays.toString(empArr));
//


When to use Comparable and Comparator:

Comparable: 
      Use this Interface when, An Element in any collection object can be compared at any time. 

 It means , If you write your Employee class by implementing Comparable interface, You are suppose to sort any collection object at any time in the future.

So, simple we can say that implements Comparable interface is used before placing any Element in Collection object.


Comparator: 
     Use this Interface when, you want to sort collection at runtime.

It means, Suppose you don't know how to sort Elements in Collection object and want to sort at runtime based on the requirement.

  ex:  Suppose you have an ArrayList object of elements of type Employee and want to sort that ArrayList object based on employee id for the first time, then sort based on employee name, and then sort based on employee salary... like this way you want to sort at run time.
   
  
For this, you have to write a custom class which implements Comparator interface and override compare() method and write the logic based on the requirement like, sort based on id , name , salary..etc.


public class EmployeeIdSortComparator implements Comparator<Employee>{

     public int  compare(Employee e1, Employee e2){
              //write logic to sort based on the requirement.
    }
    // also override equals(Object o) method to compare..

   }// end class

So, simply we can say that implements Comparable is used after placing any Element in Collection object also. It is runtime comparison. 

4)  Write your own logic to sort collection object like how we sort an array of integers ( bubble, heap, insertion,..etc)..

This is at your own risk.

Please let me know if any mistakes are here in the current post. please give your feedback at nagarjuna.lingala@gmail.com


sources: