Sunday, January 6, 2013

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);
}

Singleton design pattern

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 thewriteExternal() 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.

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);
    }
}

Static and Non Static Synchronized Methods



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.

Sunday, December 16, 2012

Synchronous and Asynchronous Exceptions


     The interpreter executes the java program sequentially. An exception E can occur relative to a line (L) of program. That is that exception E will always occur at the execution of that line L. This is called Synchronous exception.

An asynchronous exception in java can occur at any point in the execution of a program.

Checked Vs Unchecked Exception

Checked Exception  in Java is all those Exception which requires being catches and handled during compile time. If Compiler doesn't see try or catch block handling a Checked Exception, it throws Compilation error. All the Exception which are direct sub Class of Exception but not inherit RuntimeException are Checked Exception.
IOException
SQLException
DataAccessException
ClassNotFoundException
InvocationTargetException

Unchecked Exception  in Java is those Exceptions whose handling is not verified during Compile time. Unchecked Exceptions mostly arise due to programming errors like accessing method of a null object, accessing element outside an array bonding or invoking method with illegal arguments. In Java, Unchecked Exception is direct sub Class of RuntimeException. What is major benefit of Unchecked Exception is that it doesn't reduce code readability and keeps the client code clean.
NullPointerException
ArrayIndexOutOfBound
IllegalArgumentException
IllegalStateException

Difference :- Checked Exception is required to be handled by compile time while Unchecked Exception doesn't.
Checked Exception is direct sub-Class of Exception while Unchecked Exception are of RuntimeException.
CheckedException represent scenario with higher failure rate while UnCheckedException are mostly programming mistakes.






Saturday, December 1, 2012

System.out.println


System – is a final class and cannot be instantiated. Therefore all its members (fields and methods) will be static and we understand that it is an utility class. System class are standard input, standard output, and error output streams.

out – is a static member field of System class and is of type PrintStream. Its access specifiers are public final. This gets instantiated during startup and gets mapped with standard output console of the host.

println – Method of PrintStream class. println prints the argument passed to the standard console and a newline. 

Can a top level class be private or protected


No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.

ShareThis