Monday, December 1, 2014

Java Exceptions

  Exception Handling Keywords:--

                  Java provides specific keywords for exception handling purposes, we will look after them first and then we will write a simple program showing how to use them for exception handling.

  1.  throw :-
               We know that if any exception occurs, an exception object is getting created and then Java runtime starts processing to handle them. Sometime we might want to generate exception explicitly in our code, for example in a user authentication program we should throw exception to client if the password is null. throw keyword is used to throw exception to the runtime to handle it.

   2throws: 
               When we are throwing any exception in a method and not handling it, then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to it’s caller method using throws keyword. We can provide multiple exceptions in the throws clause and it can be used with main() method also.

  3try-catch :
              We use try-catch block for exception handling in our code. try is the start of the block and catch is at the end of try block to handle the exceptions. We can have multiple catch blocks with a try and try-catch block can be nested also. catch block requires a parameter that should be of type Exception.

  4finally: – finally block is optional and can be used only with try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block. finally block gets executed always, whether exception occurred or not.

      Look at following important points:-   
  • We can’t have catch or finally clause without a try statement.
  • A try statement should have either catch block or finally block, it can have both blocks.
  • We can’t write any code between try-catch-finally block.
  • We can have multiple catch blocks with a single try statement.
  • try-catch blocks can be nested similar to if-else statements.
  • We can have only one finally block with a try-catch statement.

      Below some questions related to try catch and finally block examples.

Question : Which is the base class of all Exception classes?

            Answer-  Throwable

Question:--
                          try{                       
                                  //some statements
                               }
                          catch(Exception e){                  
                                 System.out.println("Exception ");
                               }
                          catch(ArithmeticExcetion ex){
                                 System.out.println("AritmeticException ");
                               }
what is output?

Answer:-It will give the compile-time error at second catch block. Exception is the base class of all Checked and Unchecked Exception so ArithmeticException is the base class of Exception.
So always you can write Exception catch block at the end.

Question- See below code--
                            try{
                                          //some statements
                                  }                                                                        //line 1
                                System.out.println("end try block");
                              catch(Exception e){                                              //line 2
                                           System.out.println("Exception ");
                                       }

Answer:It will give compile-time error at line 1 and line 2 because for first line you haven't written catch or finally block & second it act as without try block.

Question:--check it below code
                           public int methodName(){
                                        try{
                                                 //some statements
                                                  return 1;
                                             }
                                     catch(Exception e){
                                                   return 2;
                                             }
                                      finally{
                                                    return 3;
                                             }
                                     }                                               //end method
    The above method will return which value 1 or 2 or 3. also answer me with exception & without exception.

Answer: In java finally block will execute all time except calling System.exit(). So above example it will return always 3 with exception or non-exception(not a matter).

Question:--see below code--
                                       try{
                                               int i=0; int j=1;
                                               int sum=j/i;                                             //line 1
                                               System.exit(0);                                      //line 2
                                            }
                                        catch(Exception e){
                                                    e.printStackTrace();
                                            }
                                       finally{
                                                    System.out.println("finally block");
                                            }
 what would be the output?finally block will execute or not?

Answer:--output is----------------java.lang.ArithmeticException
                                                   finally block

In the above code,at line 1,it will throw exception i.e catch block will execute and followed by finaaly block execute. It never return to the line 2.


Question:-In the above code,if there is no exception at line 1,then
                                         try{
                                               int sum=1/1;                                             //line 1
                                               System.out.println(sum);
                                               System.exit(0);                                        //line 2
                                            }
                                        catch(Exception e){
                                                    e.printStackTrace();
                                            }
                                       finally{
                                                    System.out.println("finally block");
                                            }
output?

Answer:--In the above code finally block won't execute because it will exit in try block itself.
               output is 1.
   
QuestionException Hierarchy in java



Error                An Error indicates that a non-recoverable condition has occurred that should not be caught. Error, a subclass of Throwable, is intended for drastic problems, such as OutOfMemoryError, which would be reported by the JVM itself.
 
Exception :
              An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. There are two types of Exceptions 1)Checked Exception 2) Unchecked Exception

Checked Exception:--

              These exceptions are the object of the Exception class or any of its subclasses except Runtime exception class.  These condition arises due to invalid input,problem with your network connectivity & problem in database.IOException,SQLException,DataAccessException,ClassNotFoundException & MalformedURLException are the Checked Exception.  This Exception is thrown when there is an error in I/O operation. In this case operation is normally terminated.

Unchecked Exception:--   

              These exceptions arises during run-time that occur due to invalid argument passed to method. The java compiler doesn't check the program error during compilation. e.gArithmeticException,NumberFormatException,NullPointerException,IndexOutOfBoundsException,
ClassCastException & IllegalArgumentException etc.
              


Question:--What happens when exception is thrown by main method?
         Answer:--When exception is thrown by main , Java runtime system terminates.


Question:--What is OutOfMemoryError in Java?

     Answer:--OutOfMemoryError 
is when the Java Virtual Machine cannot allocate
                 an object because it is out of memory, and no more memory could be
                made available by the garbage collector. OutOfMemoryError in Java is
                a subclass of VirtualMachineError.



Question:--What is difference between ClassNotFoundException and NoClassDefFoundError?
      Answer:-- ClassNotFoundException 
is thrown when an application tries to load in a class through its string name using:

    The forName method in class Class. 
    The findSystemClass method in class ClassLoader . 
    The loadClass method in class ClassLoader.

but no definition for the class with the specified name could be found.

NoClassDefFoundError 
is thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

Sunday, November 30, 2014

JVM Internals


Garbage Collection(GC)


Multithreading


Java Collections

Hashmap:



Building Blocks:

Internal Data Structure: Array - Entry[] table=new Entry[capacity];

   static class Entry<K,V>{
        final K key;
        V value;
        Entry<K,V> next;
        final int hash;
   }

Hash Collisions: If multiple key have same hash it results in to hash collision. To handle this a linkedlist is formed using next reference. While retrieval, this linkedlist has to be iterated and check for equality of the key object to return the corresponding value.

Capacity:  

 (Default value 16)

Capacity is the length of the array or number of buckets in the hashmap. A bucket corresponds to an index of the array. 
This can be initialized with different value. 
 Map<String,String> map = new HashMap<String,String>(capacity);

Load Factor:   (Default value 0.75)

Load factor is the measure how full is the hashtable allowed to get before its capacity is automatically increased.

Threshold: This is the next size of elemnts in hashmap at which hashmap will resize.
                Threshold= capacity * loadfactor.
 Capacity will be increased by twice once element size reaches to threshold.
if( size >= threashold){  //if size after last add call >= threashold then resize table
         resize(2*table.length);
    }

API Snippet




Related Interview Questions:
1. Equals and Hashcode
2. Concurrency
3. Immutability
4. Clone (shallow copy vs Deep Copy)
5. Why capacity size is poer of two?
6. Read/Write Performance



LinkedHashMap


Linkedhashmap extends Hashmap to maintain insertion order of elements. It also maintain the access order and can be used to implement LRU based cache.

It maintains doubly linkedlist running through all of its entries.

Entry:

   static class Entry<K,V> extends HashMap.Entry<K,V>{
         Entry<K,V> before, after;  
         Entry(int hash, K key, V value, HashMap.Entry<K,V) next){
             super(hash,key,value,next);
         }
   } 

Header:

Entry<K,V> header;
       //construction or initialization
       header = new Entry<>(-1, null, null, null);
       header.before = header.after = header;

AccessOrder :

       boolean accessOrder;

        public LinkedHashMap(){
             super();
             accessOrder = false;
        } 

Add Entry:
    void addEntry(int hash, K key, V value, int bucketIndex) {
        createEntry(hash, key, value, bucketIndex);

        // Remove eldest entry if instructed, else grow capacity if appropriate
        Entry<K,V> eldest = header.after;
        if (removeEldestEntry(eldest)) {
            removeEntryForKey(eldest.key);
        } else {
            if (size >= threshold)
                resize(2 * table.length);
        }

    }

    void createEntry(int hash, K key, V value, int bucketIndex) {
        HashMap.Entry<K,V> old = table[bucketIndex];
Entry<K,V> e = new Entry<K,V>(hash, key, value, old);
        table[bucketIndex] = e;
        e.addBefore(header);
        size++;

    }
        private void addBefore(Entry<K,V> existingEntry) {
            after  = existingEntry;
            before = existingEntry.before;
            before.after = this;
            after.before = this;
        }

      void recordAccess(HashMap<K,V> m) {
            LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
            if (lm.accessOrder) {
                lm.modCount++;
                remove();
                addBefore(lm.header);
            }

        }

Concurrent Hashmap



Data Structure and Algorithm

Graphs

Representation

1. Using Edge List

2. Using Adjacent Matrix

3. Using Adjacent List

AOP(Aspect Oriented Programming)


Restful webservices


SOAP Webservices


Unit Testing


Messaging (JMS, Tibco EMS, Oracle AQ, Spring JMS)


Database and PL-SQL


Oracle Coherence


Design Patterns


Hibernate Interview Questions


Spring Interview Questions


Thursday, November 27, 2014

JDK version features


JDK 1.5 Features

1)     Generics
2)     Enhanced For Loop
3)     Autoboxing/Unboxing
4)     TypeSafe enums
5)     Static import
6)     Declarative programming(Metadata/Annotations)
7)     Concurrent Package
8)     Var args
9)     Scanner

JDK 1.5 Concurrency
Limitations of JDK 1.4 Synchronization
1.        No way to back off or wait time out or cancellation once lock is held.
2.        Lock semantics can not be changed- Re-entrancy, read vs write protection or fairness
3.        No access control for synchronization
4.        Lock and unlock cannot be done outside of a method.
Concurrency Features
-           Task scheduling framework: Executor Framewrok
-           Concurrent Collections: Queue, Blocking Queue, Concurrent Hahshmap, List and Queue
-           Atomic Variables: AtomicInteger etc.
-           Locks:
-           Nanonsecond granularity timing
-           Utility classes for synchronization
o    Semaphore
o    CyclicBarrier
o    CountDownLatch
o    Exchanger

JDK 7 – New Features
1.        switch block with string
   for (String arg: args) {
         switch (arg) {
            case "-c": create = true; break;
            case "-v": verbose = true; break;
            case "-d": debug = true; break;
            default:
               System.out.println("invalid option");
               System.exit(1);
         }
      }
2.        Binary Literals with prefix 0b  e.g int number1 = 0b01010000101000101101000010100010;
3.        _ for numerical Literlas
short aShort = (short)0b0111_0101_0000_0101;
4.        Catching Multiple Exception Types
try {
   ......
} catch(ClassNotFoundException|SQLException ex) {
   ex.printStackTrace();
}
5.        The try-with-resource Statement (Auto-close resources)
public class FileCopyJDK7 {
   public static void main(String[] args) {
      try (BufferedReader in  = new BufferedReader(new FileReader("in.txt"));
           BufferedWriter out = new BufferedWriter(new FileWriter("out.txt"))) {
         int charRead;
         while ((charRead = in.read()) != -1) {
            System.out.printf("%c ", (char)charRead);
            out.write(charRead);
         }
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}
6.        Type Interference for Generic Instance Creation . e.g. List<String> lst1 = new ArrayList<String>();
7.        Fork and Join

JDK 8– New Features
1)     Lambda expressions
btn.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
        System.out.println("Hello World!");
    }
});

With lambda in java 8 you just have:

btn.setOnAction(
    event -> System.out.println("Hello World!")
);

2)     Remove the Permanent Generation
3)     Small VM
4)     Parallel Array Sorting
5)     Bulk Data Operations for Collections
6)     Define a standard API for Base64 encoding and decoding
7)     New Date & Time API
8)     Provide stronger Password-Based-Encryption (PBE) algorithm implementations in the SunJCE provider