Sunday 31 March 2013

Arrays in JAVA

Leave a Comment
An array is a very common type of data structure where in all elements must be of the same data type.Once defined , the size of an array is fixed and cannot increase to accommodate more elements.

x[0]=0;
x[1]=1;
x[2]=2;
x[3]=3;
x[4]=4;
x[5]=5;
Using and array in your program is a 3 step process -
1) Declaring your Array
2) Constructing your Array
3) Initializing your Array Syntax for Declaring Array Variables is
int intArray[];
 // Defines that intArray is an ARRAY variable which will store integer values
int []intArray;

Constructing an Array
intArray = new int[10]; // Defines that intArray will store 10 integer values
Declaration and Construction combined
int intArray[] = new int[10];
Initializing an Array
intArray[0]=1; // Assigns an integer value 1 to the first element 0 of the array
 
intArray[1]=2; // Assigns an integer value 2 to the second element 1 of the array

Declaring and Initializing an Array
int intArray[] = {1, 2, 3, 4};
// Initilializes an integer array of length 4 where the first element is 1 , second element is 2 and so on.


Multidimensional Array To declare a multidimensional array variable, specify each additional index using another set of square brackets.
int twoD[ ][ ] = new int[4][5] ;


When you allocate memory for a multidimensional array, you need only specify the memory for the first (leftmost) dimension. You can allocate the remaining dimensions separately. In Java the length of each array in a multidimensional array is under your control.
int twoD[][] = new int[4][];
 
twoD[0] = new int[5];
 
twoD[1] = new int[6];
 
twoD[2] = new int[7];
 
twoD[3] = new int[8];



Read More...

Faces behind popular Programming Languages

Leave a Comment

1. Java (James Gosling)
image


2. C (Ken Thompson Left & Dennis Ritchie Right)
image
image

3. C++ (Bjarne Stroustrup)
image

4. Python (Guido van Rossum )
image

5. Fortran (John W. Backus)
image

6. Linux Kernel (Linus Benedict Torvalds)
image

7. Perl (Larry Wall)

image

8. C# (Development team led by Anders Hejlsberg)
image

9. Ruby (Yukihiro Matsumoto)
image

10. Ruby on Rails (RoR) (David Heinemeier Hansson)
image

11. JavaScript (Brendan Eich)
image

12. PHP (Rasmus Lerdorf)
image

Read More...

Friday 22 March 2013

Compare Images In Java

Leave a Comment
package defaultt;

import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.io.File;

import javax.imageio.ImageIO;

public class CompareImage {
 public static boolean compareImage(File fileA, File fileB) {        
     try {
         // take buffer data from botm image files //
         BufferedImage biA = ImageIO.read(fileA);
         DataBuffer dbA = biA.getData().getDataBuffer();
         int sizeA = dbA.getSize();                      
         BufferedImage biB = ImageIO.read(fileB);
         DataBuffer dbB = biB.getData().getDataBuffer();
         int sizeB = dbB.getSize();
         // compare data-buffer objects //
         if(sizeA == sizeB) {
             for(int i=0; i<sizeA; i++) { 
                 if(dbA.getElem(i) != dbB.getElem(i)) {
                     return false;
                 }
             }
             return true;
         }
         else {
             return false;
         }
     } 
     catch (Exception e) { 
         System.out.println("Failed to compare image files ...");
         return  false;
     }
 }
 
 public static void main(String[] args) {
  File a = new File("F:\\uu.jpg");
  File b = new File("F:\\uu.jpg");
  boolean flag = compareImage(a, b);
  
  System.out.println("Match: "+flag);
 }
}

Read More...

Tuesday 19 March 2013

Casting in Java - when error, when exception?

Leave a Comment
Parent p1 = new Child();     
        Parent p2 = new Parent();     
        Child c1 = (Child) p2;    
       Child c2 = (Parent) p1;   
The code above says,
1.
Create an object Child and assign it to a ref to Parent p1 -- Thats ok, all Child can be ref by Parent like All Dogs can be ref by Animal... Dog IS A Animal
2.
Create an object Parent and assign it to a ref of Parent p2 -- No doubt!.. that's prefect.
3.
Cast a Parent to Child and store it on Child, please note we are not creating any object here. Now compiler wont complain since you explicitly want an Animal to be a Dog, legal but not appropriate to cast without checking -- Runtime error in this case!!
4.
Cast a Parent ref (which holds a Child) to Parent and refer it using Child.... gotcha!.. Animal IS-A Dog?? that may not be true, and hence compiler complains.

Parent p = new Child();  
It's legal, but 'p' will only be able to do Parent things. The compiler says "all right... good to go"
Child c1 = (Child) p2;  
This will compile, because you're trying to tell the compiler "It's okay.... I know it's weird." The compiler believes you. But then the cast happens at runtime, there's an exception because the p2 object doesn't have all the "stuff" it needs to make it a Child object.
Read More...

Measuring elapsed time using Spring StopWatch

Leave a Comment

measuring elapsed time using Spring StopWatch

package Core;

import org.springframework.util.StopWatch;

public class ExecutionTimeStopWatch {
 void method() throws InterruptedException
 {
  System.out.println("Execution Start");
  Thread.sleep(2000);
  int b = 12+7*88/9;
  System.out.println("Execution End "+ b);
 }
 
 public static void main(String[] args) {
  try {
   StopWatch watch = new StopWatch();
   
   ExecutionTime obj = new ExecutionTime();
   watch.start();
   obj.method();
   watch.stop();
   System.out.println("Time Taken: "+ watch.getTotalTimeMillis());
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}


Read More...

Monday 18 March 2013

How To Calculate Execution Time Of Java Program

Leave a Comment

Using new Date.getTime();

package Core;

import java.util.Date;


public class ExecutionTime {
 void method() throws InterruptedException
 {
  System.out.println("Execution Start");
  Thread.sleep(2000);
  int b = 12+7*88/9;
  System.out.println("Execution End "+ b);
 }
 
 public static void main(String[] args) {
  try {
   ExecutionTime obj = new ExecutionTime();
   
   long startTime = new Date().getTime();
   obj.method();
   long endTime = new Date().getTime();
   System.out.println("Time Taken: "+ (endTime - startTime));
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}



Using System.currentTimeMillis()

package Core;

import java.util.Date;

public class ExecutionTimeSystem {
 void method() throws InterruptedException
 {
  System.out.println("Execution Start");
  Thread.sleep(2000);
  int b = 12+7*88/9;
  System.out.println("Execution End "+ b);
 }
 
 public static void main(String[] args) {
  try {
   ExecutionTime obj = new ExecutionTime();
   
   long startTime = System.currentTimeMillis();
   obj.method();
   long endTime = System.currentTimeMillis();
   System.out.println("Time Taken: "+ (endTime - startTime));
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}


Read More...

Thursday 14 March 2013

Java Hashtable & Hashing

Leave a Comment

Hashtable is an implementation of a key-value pair data structure in java. You can store and retrieve a ‘value’ using a ‘key’ and it is an identifier of the value stored. It is obvious that the ‘key’ should be unique.

java.util.Hashtable extends Dictionary and implements Map. Objects with non-null value can be used as a key or value. Key of the Hashtable must implement hashcode() and equals() methods. By the end of this article you will find out the reason behind this 
condition.Hashtable
Generally a Hashtable in java is created using the empty constructor Hashtable(). Which is a poor decision and an often repeated mistake. Hashtable has two other constructors
Hashtable(int initialCapacity)
and
Hashtable(int initialCapacity, float loadFactor)
. Initial capacity is number of buckets created at the time of Hashtable instantiation. Bucket is a logical space of  storage for Hashtable.

Hashing and Hashtable

Before seeing java’s Hashtable in detail you should understand hashing in general. Assume that, v is a value to be stored and k is the key used for storage / retrieval, then h is a hash function where v is stored at h(k) of table. To retrieve a value compute h(k) so that you can directly get the position of v. So in a key-value pair table, you need not sequentially scan through the keys to identify a value.

h(k) is the hashing function and it is used to find the location to store the corresponding value v. h(k) cannot compute to a indefinite space. Storage allocated for a Hashtable is limited within a program. So, the hasing function h(k) should return a number within that allocated spectrum.

Hashing in Java

Java’s hashing uses uses hashCode() method from the key and value objects to compute. Following is the core code from Hashtable where the hashCode ‘h’ is computed. You can see that both key’s and value’s hashCode() method is called.
h += e.key.hashCode() ^ e.value.hashCode();
It is better to have your hashCode() method in your custom objects. String has its own hashCode methode and it computes the hashcode value as below:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
If you don’t have a hashCode() method, then it is derived from Object class. Following is Javadoc Comment of hashCode() method from Object class:
* Returns a hash code value for the object. This method is
   * supported for the benefit of hashtables such as those provided by
   * <code>java.util.Hashtable</code>.
If you are going to write a custom hashCode(), then follow the following contract:
* The general contract of <code>hashCode</code> is:
    * <ul>
    * <li>Whenever it is invoked on the same object more than once during
    *     an execution of a Java application, the <tt>hashCode</tt> method
    *     must consistently return the same integer, provided no information
    *     used in <tt>equals</tt> comparisons on the object is modified.
The following is to improve performance of the Hashtable.
* <li>If two objects are equal according to the <tt>equals(Object)</tt>
   *     method, then calling the <code>hashCode</code> method on each of
   *     the two objects must produce the same integer result.
hashCode() guarantees distinct integers by using the internal address of the object.

Collision in Hashtable

When we try to restrict the hashing function’s output within the allocated address spectrue limit, there is a possibility of a collision. For two different keys k1 and k2, if we have h(k1) = h(k2), then this is called collision in hashtable. What does this mean, our hashing function directs us store two different values (keys are also different) in the same location.

When we have a collision, there are multiple methodologies available to resolve it. To name a few hashtable collision resolution technique, ‘separate chaining’, ‘open addressing’, ‘robin hood hashing’, ‘cuckoo hashing’, etc. Java’s hashtable uses ‘separate chaining’ for collision resolution in Hashtable.

Collision Resolution in java’s Hashtable

Java uses separate chaining for collision resolution. Recall a point that Hashtable stores elements in buckets. In separate chaining, every bucket will store a reference to a linked list. Now assume that you have stored an element in bucket 1. That means, in bucket 1 you will have a reference to a linked list and in that linked list you will have two cells. In those two cells you will have key and its corresponding value.

Hashtable Collision
Why do you want to store the key? Because when there is a collision i.e., when two keys results in same hashcode and directs to the same bucket (assume bucket 1) you want to store the second element also in the same bucket. You add this second element to the already created linked list as the adjacent element.

Now when you retrieve a value it will compute the hash code and direct you to a bucket which has two elements. You scan those two elements alone sequentially and compare the keys using their equals() method. When the key mathches you get the respective value. Hope you have got the reason behind the condition that your object must have hashCode() and equals() method.

Java has a private static class Entry inside Hashtable. It is an implementation of a list and you can see there, it stores both the key and value.

Hashtable performance

To get better performance from your java Hashtable, you need to
1) use the initialCapacity and loadFactor arguments
2) use them wisely

while instantiating a Hashtable.

initialCapacitiy is the number of buckets to be created at the time of Hashtable instantiation. The number of buckets and probability of collision is inversly proportional. If you have more number of buckets than needed then you have lesser possibility for a collision.

For example, if you are going to store 10 elements and if you are going to have initialCapacity as 100 then you will have 100 buckets. You are going to calculate hashCoe() only 10 times with a spectrum of 100 buckets. The possibility of a collision is very very less.

But if you are going to supply initialCapacity for the Hashtable as 10, then the possibility of collision is very large. loadFactor decides when to automatically increase the size of the Hashtable. The default size of initialCapacity is 11 and loadFactor is .75 That if the Hashtable is 3/4 th full then the size of the Hashtable is increased.
New capacity in java Hashtable is calculated as follows:
int newCapacity = oldCapacity * 2 + 1;
If you give a lesser capacity and loadfactor and often it does the rehash() which will cause you performance issues. Therefore for efficient performance for Hashtable in java, give initialCapacity as 25% extra than you need and loadFactor as 0.75 when you instantiate.
Read More...