Sunday, September 25, 2011

How to extract a list of filtered files in Java?

Sometimes, we need to get a list of files exist within a directory as per our criteria like filename, file extension, last modified date or other attributes. It reduces the overhead to filter them after getting the list using our code. To achieve this, Java provides an interface - FileFilter which has a single method prototype as boolean accept(File file). To apply our filtering criteria, we have to override this method and if our logic returns true for a file then only the file will be included in the list otherwise not. Here is the sample code -
import java.io.*;
import java.util.*;

public class FilteredFileList {
    public static File[] getFilteredFileList(File folder, final String filenameFilter, Date lastModifiedDateFilter) {
        File[] listOfFiles = folder.listFiles(new FileFilter(){
                                public boolean accept(File file) {
                                    //file is the object against which we are applying our logic.
                                    //You can put your logic using filenameFilter and check whether
                                    //the file's name comes under your criteria or not.
                                    //To check against the lastmodified date you can use lastModifiedDateFilter.
                                    return true;
                                }});
        return listOfFiles;
    }
}

Thursday, September 15, 2011

How to use Comparator and Comparable to sort the objects?


Today, we will see how can we sort the elements of an Array or Collections. There are two utilities to sort the collection of objects -

  • Comparable - This interface contains only one method prototype i.e. compareTo (Object obj). This method returns a negative integer, zero, or a positive integer as this object (through which the method has been called) is less than, equal to, or greater than the specified object. To make our objects comparable we should implement our class to this interface.


Here is the sample code -

public class Employee implements Comparable {
    int id;
    String name;
    Date dob;

    Employee(int id, String name, Date date) {
        this.id = id;
        this.name  = name;
        this.dob  = dob;
    }
    
    //If you want to sort the Employee Collection based on empId;
    public int compareTo(Object object) {
        Employee emp = (Employee) object;
        // If you want the reversed order just reverse the subtraction as emp.id - this.id
        return this.id - emp.id;
    }

    //If you want to sort the Employee Collection based on name;
    public int compareTo(Object object) {
        Employee emp = (Employee) object;
        // If you want the reversed order call the below compare method using emp.name and pass this.name
        return this.name.compareTo(emp.name);
    }

    //If you want to sort the Employee Collection based on DOB;
    public int compareTo(Object object) {
        Employee emp = (Employee) object;
        // If you want the reversed order just reverse the subtraction
        return this.dob.equals(emp.dob);
    }
}

public class EmployeeSorter {
    public static void main(String[] args) throws Exception {
        DateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
        Employee emp1 = new Employee(1, "Ram", formatter.parse("26-01-1988");
        Employee emp1 = new Employee(3, "Shyam", formatter.parse("14-10-1984");
        Employee emp1 = new Employee(2, "Ghanshyam", formatter.parse("25-01-1983");
        List listOfEmployee = new ArrayList();
        listOfEmployee.add(emp1);
        listOfEmployee.add(emp2);
        listOfEmployee.add(emp3);
        Collections.sort(listOfEmployee);
    }
}        


  • Comparator - This interface contains two methods prototype. One is compare(Object obj1, Object obj2) and equals(Object obj). To sort the elements, we just have to override the compare method. This method also returns a negative integer, zero, or a positive integer as this object (through which the method has been called) is less than, equal to, or greater than the specified object. To make the objects comparable we have to create a class implementing this interface and override the compare method.


Here is the code -

public class Employee {
    int id;
    String name;
    Date dob;

    Employee(int id, String name, Date date) {
        this.id = id;
        this.name  = name;
        this.dob  = dob;
    }
    
    //If you want to sort the Employee Collection based on empId;
    public int compareTo(Object object) {
        Employee emp = (Employee) object;
        // If you want the reversed order just reverse the subtraction as emp.id - this.id
        return this.id - emp.id;
    }

    //If you want to sort the Employee Collection based on name;
    public int compareTo(Object object) {
        Employee emp = (Employee) object;
        // If you want the reversed order call the below compare method using emp.name and pass this.name
        return this.name.compareTo(emp.name);
    }

    //If you want to sort the Employee Collection based on DOB;
    public int compareTo(Object object) {
        Employee emp = (Employee) object;
        // If you want the reversed order just reverse the subtraction
        return this.dob.eqauls(emp.dob);
    }
}

public class EmployeeComparator implements Comparator {
    //If you want to sort the Employee Collection based on empId;
    public int compareTo(Object obj1, Object obj2) {
        Employee emp1 = (Employee) obj1;
        Employee emp2 = (Employee) obj2;
        // If you want the reversed order just reverse the subtraction as emp.id - this.id
        return emp1.id - emp2.id;
    }

    //If you want to sort the Employee Collection based on name;
    public int compareTo(Object obj1, Object obj2) {
        Employee emp1 = (Employee) obj1;
        Employee emp2 = (Employee) obj2;
        // If you want the reversed order call the below compare method using emp.name and pass this.name
        return emp1.name.compareTo(emp2.name);
    }

    //If you want to sort the Employee Collection based on DOB;
    public int compareTo(Object obj1, Object obj2) {
        Employee emp1 = (Employee) obj1;
        Employee emp2 = (Employee) obj2;
        // If you want the reversed order just reverse the subtraction
        return emp1.dob.equals(emp2.dob);
    }
}

public class EmployeeSorter {
    public static void main(String[] args) throws Exception {
        DateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
        Employee emp1 = new Employee(1, "Ram", formatter.parse("26-01-1988");
        Employee emp1 = new Employee(3, "Shyam", formatter.parse("14-10-1984");
        Employee emp1 = new Employee(2, "Ghanshyam", formatter.parse("25-01-1983");
        List listOfEmployee = new ArrayList();
        listOfEmployee.add(emp1);
        listOfEmployee.add(emp2);
        listOfEmployee.add(emp3);
        Collections.sort(listOfEmployee, new EmployeeComparator());
    }
}

Note: The difference between two approach is in case of Comparable, we have to create our class whose objects need to be sorted and implement Comparable interface with overriding compare method which takes only one argument. While in case of Comparator, we have to create our own Comparator and implement Comparator interface with overriding compareTo mehod which takes two arguments.

Sunday, September 11, 2011

How to create a JDBC Connection in Java?

JDBC (Java DataBase Connectivity) is an API for the Java programming language through which the databse can be accessed using methods for querying and updating data.
Here is the sample code -

import java.sql.*;

public class ConnectionInfo {

    public Connection getConnection() {
        Connection conn = null;
        // the below properties should be read from a properties file based on the Database used
        String url = "jdbc:mysql://localhost:3306/"; // url = jdbc:[subprotocol]://[hostname]:[portnumber]/
        String dbName = "jdbctutorial"; // database name
        String driver = "com.mysql.jdbc.Driver"; //Driver class name
        String username = "root"; // username
        String password = "root"; // password
        try {
          Class.forName(driver); // Dynamic loading based on database used.
          conn = DriverManager.getConnection(url + dbName, username, password);
          System.out.println("Connection Established");
        } catch (SQLException e) {
          e.printStackTrace();
        } finally {
            return conn;
        }
    }

    public void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Friday, September 9, 2011

Java Multithreading

Process can be further divided into small tasks which refer as a Thread. If two or more tasks of a process executes concurrently, then this scenario refers as a Multithreading environment. Every thread has it's own independent path of execution. In java, there are two ways to implement multithreading -

Through implementation of Runnable interface - To create a thread, we can implement Runnable interface. This interface has a single run() method declaration, so we have to override that method. Actually, in this approach, we write a wrapper over Thread class. The objects of the class which implements Runnable interface, work as a thread of the program and run on their own execution paths.

Here is the sample code -

//This class objects will work as Threads
public class RunnableExample implements Runnable {
    private Thread thread;
    public RunnableExample(String name) {
        //here we pass the reference whose run method should be called.
        thread = new Thread(this, name);
        //creating thread
        thread.start();
    }
    
    public void run() {
        //your logic will go here
        System.out.println(thread.getName());
    }
}

public class RunnableMain {
    public static void main(String[] args) {
        //Creating three objects
        Runnable run1 = new RunnableExample("Thread-1");
        Runnable run2 = new RunnableExample("Thread-2");
        Runnable run3 = new RunnableExample("Thread-3");
    }
}


2. Using Thread class extension - This is another approach of thread creation. But, it restricts the class to extend other classes (if required). In this approach, we extend our class to Thread class so that it's objects work as threads and run on their own separate execution paths.

Here is the sample code -
//This class objects will work as Threads
public class ThreadExample extends Thread {

    public ThreadExample(String name) {
        super(name);
    }
    
    public void run() {
        //your logic will go here
        System.out.println(thread.getName());
    }
}

public class ThreadMain {
    public static void main(String[] args) {
        //Creating three objects
        Thread t1 = new ThreadExample("Thread-1");
        Thread t2 = new ThreadExample("Thread-2");
        Thread t3 = new ThreadExample("Thread-3");
        creating threads
        t1.start();
        t2.start();
        t3.start();
    }
}

Sunday, September 4, 2011

How to work with Recursion?

Recursion is one of the interesting topic. The problems, which can be implemented using loops, can be implemented with Recursion as well. But, most of us go with the looping solution. Today, I am going to set some light on how the same logic can be implemented using recursion. If we could derive a mathematical function for these type of problems, the implementation will be more easier. Lets understand it through some examples.

Example 1 : Factorial
The factorial of a non-negative number is the multiplication of all the positive integers which are less than or equal to the number.

Suppose fact(n) is a function of n, where x is non-negative integer value. Hence

fact(0) = fact(1) = 1
fact(2) = 2 * fact(1) = 2
fact(3) = 3 * fact(2) = 6
...
...
...
fact(n) = n * fact(n-1)

So, the logic would be - If the value of n is 0 or 1 return 1, else return multiplication of n and value of function for (n-1).

int fact(int num) {
    if(num == 0 || num == 1)
        return 1;
    else
        return num * fact (num - 1);
}

Example 2 : Fibonacci Series 
The Fibonacci series is a sequence of integers whose first and second terms are 0 and 1 respectively and  each subsequent term is the sum of the previous two terms. Like - 0, 1, 1, 2, 3, 5, 8, 13, 21, .....

Suppose fibo(n) is a function of n which returns the term n of the fibonacci series and where n > 0 -

fibo(1) = 0
fibo(2) = 1
fibo(3) = fibo(1) + fibo(2) = 1
fibo(4) = fibo(2) + fibo(3) = 2
fibo(5) = fibo(3) + fibo(4) = 3
...
...
...
fibo(n) = fibo(n-2) + fibo(n-1)


So, the logic would be - If the value of n is 1 or 2 return (n-1), else return the addition of value of function for (n-2) and function for (n-1) .

int fibo(int num) {
    if(num == 1 || num == 2)
        return (num - 1);
    else
        return fibo(num - 2) + fibo(num - 1);
}
I hope, this post will really helpful.

Saturday, September 3, 2011

How to make a class Singleton?

The Singleton class means whose only one instance can be created. To make the class Singleton, we should restrict the ways through which the objects can be created. The object can be created in the following ways -
  1. Using new operator
  2. Using newInstance() method  (by Dynamic loading of class).
  3. Through Serialization/Deserialization
  4. Through Cloning
To restrict the ways of object  creation, we should take care of the following points -
  1. The Constructer must be private so that static (using new operator) and dynamic (using newInstance() method) creation of object does not get supported.
  2. Static field as object of the Singleton class should be declared within that class. In getInstance() method, it should be checked whether the static object has been instantiated or not. If not, then instantiate and return it.
  3. The method getInstance() must be Static and Synchronized. Static, so it can be accessed through the class name. Synchronized, because it should be thread-safe.
  4. The class must implement the Externalizable interface and override the writeExternal() and readExternal() methods such that serialization/deserialization should not be supported.
  5. The class must override clone() method so that another object could not get created.
Here is an example -

import java.io.*;

//Implement Externalizable interface to avoid object creation through Deserialization.
public class SingletonExample implements Externalizable {
    //make a static object
    private static SingletonExample g_instance;

    //make the construct as provate to hide it from outer world.
    private SingletonExample() {
        //do nothing
    }

    //make this static method as synchronized for thread-safe model.
    public synchronized static SingletonExample getInstance() {
        if (g_instance == null)             
            g_instance = new SingletonExample();
        return g_instance;
    }
    
    //override method and throw exception to avoid serialization     
    public void writeExternal(ObjectOutput out) throws SerializationNotAllowedException {
        throw new SerializationNotAllowedException("Serialization is not supported.");
    }     

    //override method and throw exception to avoid deserialization
    public void readExternal(ObjectInput in) throws SerializationNotAllowedException {
        throw new SerializationNotAllowedException("Deserialization is not supported.");
    }         

    //override method to avoid object cloning
    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Cloning not allowed");
    } 
}

//As the methods writeExternal and readExternal throws IOException, hence we have to extend to create our own Exception.
class SerializationNotAllowedException extends IOException {
    public SerializationNotAllowedException(String message) {
        super(message);
    }
}

Thursday, September 1, 2011

Static and Non Static Synchronized Methods

Hi Friends,

This is my first post. I hope you will like this one.

Have you ever thought about the behavior of a static synchronized method call and a non-static synchronized method call in Java? Before that, first of all we should have a look on how the static and non static calls work -


Static Method Call - When we make a call to a static method (either directly from class or any object of that class), the Class object of that Class involves in that call. Every Class has only one Class object.

Non-static Call When we call a non-static method (always from an object of that class), it works for that object only (which is of that class only). A class can have as many objects (if not restricted though some design patterns or lack of memory).

Now, lets come to Static and Non-static Synchronized method calls -

Static Synchronized Method Call - Whenever a thread accesses any synchronized static method, it acquires the lock on Class object of that class and hence no other static method can be accessed of that class.

Non-static Synchronized Method Call - As the non-static methods can be accessed through only objects of that class. So whenever, a thread enters any non-static synchronized method, it acquires the lock on the object through which the call has been made. Hence the other threads can still access the same or other non-static methods using other unlocked objects (free resources) of that class.

Thanks