Sunday, 10 March 2013

How Hash Map works internally


General answer :
HashMap accept null while Hashtable doesn't,
HashMap is not synchronized,
HashMap is fast and so on along with basics like its stores key and value pairs etc.

Experts answer :
------------ ----               ----------------                  ----------------
|                        |.................|                     | .................|                     |....................
| Bucket1        |                |Node1          |                  |                     |
------------- ---               ----------------                  ----------------
    :
    :
------------ ----               ----------------                  ----------------
|                        |.................|                     | .................|                     |........................
| Bucket2        |                |Node1          |                  |                     |
------------- ---               ----------------                  ----------------
      :
      :
------------ ----               ----------------                  ----------------
|                        |.................|                     | .................|                     |...........................
| BucketN       |                |Node1          |                  |                     |
------------- ---               ----------------                  ----------------

  HashMap works on principle of hashing,
we have put(key, value) and get(key) method for storing and retrieving Objects from HashMap.
When we pass Key and Value object  to put() method on Java HashMap, HashMap implementation calls hashCode method on Key object and applies returned hashcode into its own hashing function to find a bucket location for storing Entry object, here important point to mention is that HashMap in Java stores both key and value object as Map.Entry in bucket , not only value
What happens when two different objects have same hashcode :

Basically hascode implementation says below rules:
rule 1: If obj1 and obj2 are same it must give same hashcode ,
rule 2: If obj1 and obj2 have same hashcode then they are not need to be equals

Basically Map uses the linkedlist to store Map.Entry object Entry would be having key and value pair
If the different object is also having same hash code then Map will store the Entry  object in the same bucket but in the linked list next consequent node
How it retrieves :
When retriving first it gets hash code by calling hashcode() then it identify the target bucket , but when retrieving it calls equals method to get exact object ,if it calls equals method on key object it gives the desired object even if the two different objects having hash code

Which is best practice to implement hashcode and equals ()?

User immutable objects i.e final object with proper equals() and hashcode()
Generally Immutability also allows caching there hashcode of different keys which makes overal process very fast
User wrapper classes like String,Integer...
If used custom objects make it immutable

what happens  when resizing HashMap in multithreding scenarios:

Hash map uses the default initial capacity is 16 and load factor is 0.75f
since it is not synchronized it is not suggestable to use in multithreading scenario
if it is really required make it synchronize:
 Map map = Collections.synchronizedMap(new HashMap(...))

Tuesday, 5 March 2013

Which one returns the value when try return and finally returns are there

This is some tricky question

Lets say below code

public int getValue()
   {
        try
        {
          return 2;
       }
       finally
        {
           return 3;
        }
   }

when called the above method System.out.println(getValue()) what is the output

It always returns thr finally return , i.e the answer is 3

Friday, 1 March 2013

Java class loaders

Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is 
already running  in the JVM. So, how is the very first class loaded? The very first class is especially loaded with the help of static main( ) method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader.

Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader. Let us look at the class loaders created by the JVM.


Bootstrap (primordial)     :

Loads JDK internal classes,
java.*
packages. (as defined in the sun.boot.class.pathsystem property, typically loads rt.jar and i18n.jar)

Extensions :

Loads jar files from JDK extensions directory (as defined in the java.ext.dirs system
property – usually lib/ext directory of the JRE)

System :

 Loads classes from system classpath (as defined by the java.class.path property,which
is set by the CLASSPATH environment variable or -classpath or -cp command line options)
Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded


SAX VS DOM

DOM Stands for Document Object Model and it represent an XML Document into tree format which each element representing tree branches.
 
SAX Stands for Simple API for XML Parsing. This is an event based XML Parsing and it parse XML file step by step so much suitable for large XML Files.

Here are few high level differences between DOM parser and SAX Parser in Java:
 

 
1) DOM parser loads whole xml document in memory while SAX only loads small part of XML file in memory.

2) DOM parser is faster than SAX because it access whole XML document in memory.

3) SAX parser in Java is better suitable for large XML file than DOM Parser because it doesn't require much memory.

4) DOM parser works on Document Object Model while SAX is an event based xml parser.
 
I suggests use DOM parser over SAX parser if XML file is small enough and go with SAX parser if you don’t know size of xml files to be processed or they are large.

NoClassDefFoundError vs ClassNotFoundException

Difference between ClassNotFoundException vs NoClassDefFoundErrorBefore seeing the differences between ClassNotFoundException and NoClassDefFoundError let's see some similarities which are main reason of confusion between these two errors:

1) Both NoClassDefFoundError and ClassNotFoundException are related to unavailability of a class at run-time.
2) Both ClassNotFoundException and NoClassDefFoundError are related to java classpath.

Now let's see the difference between NoClassDefFoundError and ClassNotFoundException:

1) ClassNotFoundException comes in java if we try to load a class at run-time using with Class.forName() or ClassLoader.loadClass() or ClassLoader.findSystemClass() method and requested class is not available in Java. the most of the time it looks like that we have the class in classpath but eventually it turns out to be issue related to classpath and application may not be using classpath what we think it was using e.g. classpath defined in jar's manifest file will take precedence over CLASSPATH or -cp option, for more details see How classpath works in java. On the other hand NoClassDefFoundError is little different than ClassNotFoundException, in this case culprit class was present during compile time and let's application to compile successfully and linked successfully but not available during run-time due to various reason.

2) ClassNotFoundException is a checked Exception derived directly from java.lang.Exception class and you need to provide explicit handling for it while NoClassDefFoundError is an Error derived from LinkageError.

3) If you are using classloaders in Java and have two classloaders then if a classloader tries to access a class which is loaded by another classloader will result in ClassNoFoundException.

4) ClassNotFoundException comes up when there is an explicit loading of class is involved by providing name of class at runtime using ClassLoader.loadClass, Class.forName while NoClassDefFoundError is a result of implicit loading of class because of a method call from that class or any variable access.