Wednesday 16 March 2016

ExceptionInInitializerError in Java

java.lang.Object à  java.lang.Throwable à java.lang.Error à java.lang.LinkageError à java.lang.ExceptionInInitializerError

public class ExceptionInInitializerError extends LinkageError

Signals that an unexpected exception has occurred in a static initializer.

An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable.

Scenarios of ExceptionInInitializerError

Due to Exception in Static Initializer
If we get any runtime exception while executing static initializer (static block or static variable declaration executes while load the class) and JVM class loader will not able to initialize the class and throws ExceptionInInitializerError.

class DivideClass {

     /**Here ArithmeticException will lead
      * to ExceptionInInitializerError
      */
     static {
           int undefined = 1 / 0;
     }

     public String method() {
           return "from divide class";
     }
}

public class TestException {
     public static void main(String[] args) {
           DivideClass d = new DivideClass();
     }
}

Tuesday 15 March 2016

Java Timer and TimerTask – Reminder Class

Timer:
java.util.Timer is a utility class that provides facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.

TimerTask:
A task that can be scheduled for one-time or repeated execution by a Timer.

java.util.TimerTask is an abstract class that implements Runnable interface and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class.

Run a reminder timer task after a certain time period

import java.util.Timer;
import java.util.TimerTask;

public class TimerTaskExample {
     Timer timer;

     public TimerTaskExample(int seconds) {
           timer = new Timer();
           long millis = seconds * 1000;
           timer.schedule(new TaskReminder(), millis);
     }

     class TaskReminder extends TimerTask {
           public void run() {
                System.out.println("Timer Task is executing..!");
                /*
                 * TimerTask.cancel() method is used to
                 * terminate the Time Task.
                 */
                timer.cancel();
                System.out.println("Timer Task Finished..!");
           }
     }

     public static void main(String args[]) {
           System.out.println("Timer Task scheduled");
           int reminder_time = 3;
           new TimerTaskExample(reminder_time);
           System.out.println("It will execute after 3 sec...");
     }
}

Output:
Timer Task scheduled
It will execute after 3 sec...
Timer Task is executing..!
Timer Task Finished..!

Perform timer task repeatedly

import java.util.Timer;
import java.util.TimerTask;

public class RepeatTimerTaskExam {
     Timer timer;

     public RepeatTimerTaskExam(long intialDelay,long subsequentRate){
           timer = new Timer();

           timer.schedule(new TaskReminder(),intialDelay,subsequentRate);
     }

     class TaskReminder extends TimerTask {
           int loop = 5;

           public void run() {
                if (loop > 0) {
                     System.out.println("Timer task, Repeat# "+ loop);
                     loop--;
                } else {
                     timer.cancel();
                     System.out.println("Timer task.. Finished!");
                }
           }
     }

     public static void main(String args[]) {
           long intialDelay = 0; // time to start first Task
           long subsequentRate = 1000; // delay subsequent Task.
          
           new RepeatTimerTaskExam(intialDelay, subsequentRate);
           System.out.println("Task scheduled...");
     }
}
Output:
Task scheduled...
Timer task, Repeat# 5
Timer task, Repeat# 4
Timer task, Repeat# 3
Timer task, Repeat# 2
Timer task, Repeat# 1
Timer task.. Finished!

Thursday 3 March 2016

Binary searching versus linear searching

Linear search
In linear search, we start searching of value from start until the value is not found or end of file. If it is, then you can stop searching and report that you have found the record.

Input A[n + 1] and x.
Set i to 1.
Repeat this loop:
     If A[i] = x, then exit the loop.
     Set i to i + 1.
Return i.

Complexity: O(n).

Pros:
Serial searching is excellent if your records are unordered.
Compared to a binary search, serial searching is a very easy to implement.

Cons:
Serial searching isn’t very efficient. That's because it takes lots of comparisons to find a particular record in big files, compared to binary searching. It takes longer on average to find a record in a big file compared to binary searching.
Example: For a file of size 2^20, there are 2^20 comparisons required in worst case.


BinarySearch(A[0..N-1], value) {
      low = 0
      high = N - 1
      while (low <= high) {
          mid = (low + high)/2
          if (A[mid] > value)
              high = mid - 1
          else if (A[mid] < value)
              low = mid + 1
          else
              return mid
      }
      return not_found
}

Complexity: O(logn).

Pros:
Compared to a linear search, binary searching is a very efficient.
Example: For a file of size 2^20, there are 20 comparisons required in worst case.
Comparisons required: log(2^20) = 20.

Cons:
Binary searching cannot be applied on the unordered array.
It is little complex to write binary search compare to linear search.


Binary search algorithm : Java code

A binary search or half-interval search algorithm finds the position of a target value within a sorted array.

Step#1 Find the mid_element of array and compare it to target_value.

Step#2 If target_value == mid_element,
                        return position
       If target_value < mid_element,
                        then the search continues on the lower half of the array;
       If target_value > mid_element,
                        then the search continues on the upper half of the array.

Step#3 Repeat the Step#2 (eliminating half of the elements) until the target value is either found, or until the entire array has been searched.

Complexity
Worst case performance O(log n)
Best case performance O(1)
Average case performance O(log n)
Worst case space complexity O(1)

Recursive approach
class Recursive {
    static int binary_search(int[] array,int key,int imin,int imax){
        // test if array is empty
        if (imax < imin) {
            // set is empty, so return value showing not found
            return -1;
        } else {
            // calculate midpoint to cut set in half
            int imid = (imin+imax)/2;

            if (array[imid] > key) {
                // key is in lower subset
                return binary_search(array, key, imin, imid - 1);
            } else if (array[imid] < key) {
                // key is in upper subset
                return binary_search(array, key, imid + 1, imax);
            } else {
                // key has been found
                return imid;
            }
        }
    }
}

public class BinarySearch {
    public static void main(String[] args) {
        int[] array={1,4,5,7,8,9};
        int key=7;
        int idx=Recursive.binary_search(array,key,0,array.length-1);
        System.out.println("Using recursive approach.\n Index# "+idx);
    }
}

Output:
    Using recursive approach.
     Index# 3


Iterative approach
class Iterative {
    int binary_search(int array[], int key, int imin, int imax) {

        while (imin <= imax) {
            int imid = (imin+imax)/2;
            if (array[imid] == key) {
                // key found at index imid
                return imid;
            } else if (array[imid] < key) {
                // change min index to search upper subarray
                imin = imid + 1;
            } else {       
                // change max index to search lower subarray
                imax = imid - 1;
            }
        }
        // key was not found
        return -1;
    }
}

public class BinarySearch {
    public static void main(String[] args) {
        int[] array={1,4,5,7,8,9};
        int key=7;
                
        idx=Recursive.binary_search(array,key,0,array.length-1);
        System.out.println("Using iterative approach.\n Index# "+idx);
    }
}

Output:
    Using iterative approach.
     Index# 3
References:
Related Posts Plugin for WordPress, Blogger...