Thursday, 29 September 2016

Threads-Why wait(), notify() and notifyAll() methods are defined in Object and not in Thread

This is very important concept to understand Java concurrency/multi-threading. This is a very popular interview question also specially in investment banks.There are several reasons why wait(), notify() and notifyAll() methods are defined in Object and not in Thread class.

First we will try to understand what are these wait(), notify() and notifyAll() methods. wait(), notify() and notifyAll() methods are used for inter-thread communication. In Java 5 different API's were introduced to handle the thread communications like - NonBlockingQueues and Executor framework, but before Java 5 wait(), notify() and notifyAll() methods were the only way for thread communication. Before Java 5 wait(), notify() and notifyAll() were the only way to design the classic Producer-Consumer problem.

wait() - wait() method is used to put the running thread in waiting state and release the lock to use by other threads.

notify() - notify() method notifies only a single thread waiting for the same lock, but if multiple thread are waiting for the same lock than there is no guarantee that which thread will be notified. This is totally depend on operating system and implementations of JVM.

notifyAll() - notifyAll() method notifies All the threads which are waiting for the same lock, but only one thread will acquire the lock and others will again go to waiting state. Which thread will acquire the lock is again depends on operating system and implementation of JVM.

Why wait(), notify() and notifyAll() methods are defined in Object class-
wait(), notify() and notifyAll() methods handles inter-thread communication acquiring and releasing the locks on objects as per requirement from synchronized(thread-safe) resources. Locks are associated object. Object class is the parent class of all classes in Java, So Object class is best place to put wait(), notify() and notifyAll() methods to make them available to each object.

Why wait(), notify() and notifyAll() methods are not defined in Thread class -
If Thread class have wait(), notify() and notifyAll() than every thread must have their own monitor and if every thread will have their own monitor then thread communication will not be possible, because one thread will not know that which thread hold the lock.

If you have any doubts please put in comments, I will try to resolve ASAP.

Ways of Iterating a Collection in Java

We already studied a lot of good Java Collection's interview questions in previous posts. But one thing that is very important while talking about collections is "Iterating the collection", because whenever we use collection in any application we always iterate it. We have a lot of ways to iterate over a collection and in this post I am going to explain the different ways of iterating the collection.

The main ways of iterating over a collection are -

  • Iterating the collection with a simple loop.
  • Iterating the collection with Java's Iterator interface.
  • Iterating the collection with Java 5 enhanced for-each loop
  • Iterating the collection with Java 8 Iterable's foreach method & Consumer interface.
Iterating the collection with a simple loop -  In this technique we use a simple loop to iterate the collection, but with this ways we can only iterate the indexed collections only. Code sample to use -

// Iterating with simple for loop
Collection<String> collection = Arrays.asList("Vijendra", "Yadav", "javaprinciples", "blog");
ArrayList<String> arrayList = new ArrayList<String>(collection);
for (int i = 0; i < arrayList.size(); i++) {
System.out.println(arrayList.get(i));
}


Iterating the collection with Java's Iterator interface - Iterator interface is present in java.util package. Different collection classes have specific implementation for iterator. All classes which implements Iterable interface can be iterated using Iterator interface. Iterators allow the caller to remove elements from the underlying collection during the iteration.  
Code sample to use -

// Iterating with Java Iterator
Collection<String> collection = Arrays.asList("Vijendra", "Yadav", "javaprinciples", "blog");
Iterator<String> collectionIterator = collection.iterator();
while (collectionIterator.hasNext()) {
System.out.println(collectionIterator.next());
}

Iterating the collection with Java 5 enhanced for-each loop - In Java 5 new enhanced loop was introduced to iterate over the collections and arrays. For-each loop was introduced to mainly increase the code readability and minimize the chances of bugs.
Code sample to use -

// Iterating with Java 5 enhanced for-each loop
Collection<String> collection = Arrays.asList("Vijendra", "Yadav", "javaprinciples", "blog");
for (String elemnet : collection) {
System.out.println(elemnet);

}

Iterating the collection with Java 8 Iterable's forEach method & Consumer interface - This method was introduced in Java 8. Consumer interface is used with Java 8 Iterables forEach to iterates the collections. 
java.util.functional.Consumer is a functional interface, which accepts one parameter and return no results.
Code sample to use -

// Iterating with Java 8 Iterable's foreach method & Consumer interface using Lambda exp.
Collection<String> collection = Arrays.asList("Vijendra", "Yadav", "javaprinciples", "blog");

collection.forEach(s -> System.out.println(s));

OR

Collection<String> collection = Arrays.asList("Vijendra", "Yadav", "javaprinciples", "blog");
Consumer<String> style = (String s) -> System.out.println(s);

collection.forEach(style);

So, That's All.
Below is the complete class that you can copy and run directly.

package javaprinciples.collections;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

public class IterateCollection {

public static void main(String[] args) {
Collection<String> collection = Arrays.asList("Vijendra", "Yadav", "javaprinciples", "blog");

// Iterating with simple for loop
System.out.println("Iterating with simple for loop ..............");
ArrayList<String> arrayList = new ArrayList<String>(collection);
for (int i = 0; i < arrayList.size(); i++) {
System.out.println(arrayList.get(i));
}

// Iterating with Java Iterator
System.out.println("Iterating with Java Iterator ...........");
Iterator<String> collectionIterator = collection.iterator();
while (collectionIterator.hasNext()) {
System.out.println(collectionIterator.next());

}

// Iterating with Java 5 enhanced for-each loop
System.out.println("Iterating with Java 5 enhanced for-each loop...........");
for (String elemnet : collection) {
System.out.println(elemnet);
}

// Iterating with Java 8 Iterable's foreach method & Consumer interface
// using Lambda exp.
System.out.println("Iterating with Java 8 Iterable's foreach method...........");
collection.forEach(s -> System.out.println(s));
}

}

If you have any doubts please put in comments, I will try to resolve ASAP.

Friday, 9 September 2016

Java - Insertion Sort Algorithm

We have studied about searching algorithms Linear Search and Binary Search and sorting algorithm Bubble Sort in previous posts.
  • Insertion sort is very simple sorting algorithm. 
  • Insertion sort is good for small size collections but it is not a good algorithm for bigger size collections. 
  • Insertion sort is an in-place sorting algorithm that means it uses only the given array and not required extra for temporary purpose. It only uses a constant memory space for all implementation.
  • Insertion sort doesn't change the order of equal elements.
Insertion Sort -
Insertion sort simply works like we sort the playing cards. Insertion sort simply iterates through the collection once for each element and add the processed element in sorted list. It removes one element on each iteration from the given collection and put it in the correct location in the sorted collection. It process the whole collection till end and finally return the sorted collection.

Simple steps to perform bubble sort - 
  • Given : An array of n elements in unsorted order.
  • Required : An array of n elements in ascending order. 
  • Start a loop from i= 1 to n-1 and key <- Array[i]
  • Check the key with all items in sorted array Array[0--i-1] from last to first and insert the key in proper place.
  • Return the sorted array.
Pseudo code (Ascending order)- 
# Input: Array elements of length n in unsorted order
# Output: Array elements of length n in ascending order
    n = length(elements)
    for i=1 to n-1
       for j = i to 1
          if elements[j] < elements[j-1] then
             swap(elements[j-1], elements[j])
          end if
       End for loop.
    End while loop.


Asymptotic Analysis of Insertion Sort Algorithm -

Best Case Scenario - If the given array or collection is already in sorted order. Best case time complexity for insertion sort is O(n).


Worst Case Scenario - If the given array or collection in reversed sorted order.  Worst case time complexity for insertion sort is О(n2).


Average-Complexity - Complexity of insertion sort algorithm is О(n2)

Insertion Sort Implementation in Java  -

package javaprinciples.dsa;

public class InsertionSort {

public static void main(String[] args) {
int elements[] = { 4, 12, 56, 2, 7, 123, 6, 78 };

System.out.print("Input unsorted array : ");
for (int element : elements) {
System.out.print(element + " ");
}

insertionSort(elements);
System.out.print("\nOutput sorted array : ");
for (int element : elements) {
System.out.print(element + " ");
}
}

static void insertionSort(int[] elements) {
int n = elements.length;
int temp = 0;
for (int i = 1; i < n; i++) {
for (int j = i; j > 0; j--) {
if (elements[j] < elements[j - 1]) {
temp = elements[j];
elements[j] = elements[j - 1];
elements[j - 1] = temp;
}
}
}
}
}

Output -

Input unsorted array : 4 12 56 2 7 123 6 78 
Output sorted array : 2 4 6 7 12 56 78 123 

Thursday, 1 September 2016

Top 10 Exception Handling Interview Questions

Excepting handling is very important topic for Java programming and for cracking any Java/J2EE interview also. I prepared this list of all important exception handling interview question. This will help you to answer any exception handling related question in interviews.

1.) What is Exception in Java?

Exception is any abnormal situation that occurs during program execution and disturb the normal flow of the execution.

2.) What is Exception hierarchy in Java?



Throwable - Throwable is the root of all Exception hierarchy in Java. All Errors and Exceptions comes under Throwable class. 

Error - Errors are irrecoverable situations which mostly occurs due to system failure. Some of the examples of Errors are like OutOfMemory or some hardware failure that can not be recovered and they are not related to application scope.

Exception - Exception is abnormal situation which can be handled by the application. Exception is further divided into two types. One is checked (Compile-time) exception and second is Unchecked(run-time) exceptions.

Checked Exceptions - Checked exceptions are checked by java compiler at compile time and if not handled in program then compiler will throw compile time error. Java compiler forces us to either catch the exception or declare it in the method signature in throws clause. Some of the checked exceptions are FileNotFoundException, SQLException and ClassNotFoundException etc. 

Unchecked Exceptions - Unchecked exceptions are not checked by compiler at compile time. unchecked exception mostly occurs because of bad coding practice. Some of the examples of unchecked exceptions are NullPointerException, ArrayIndexOutOfBoundException and ArithmeticException etc.

3.) How to handle exceptions in Java?

Exceptions in Java can be handled in two ways -

  1. By declaring in throws clause of method signature
  2. By using try-catch
Handling Exception by declaring in throws clause -
If we don't want to handle exception in our program then we can declare it in throws clause of method signature. When some exception is declared in throws clause it is actually propagated to the caller method where caller method can handle it or can declare again to throws clause to pass to his caller.
Multiple exceptions can be declared in throws clause.

Handling Exception using try-catch 
To handle exception in our program try-catch is used. Suspected code is wrapped in try block and after try immediately catch block attached. Catch block requires a Exception object.

So if any exception occurs in try block the control directly goes to catch block where handling code is written. There can be multiple catch block with a single try block. Try-catch block can be nested also.

4.) Does order matters while declaring multiple catch block with a try block?

Yes, we should always catch the sub class exceptions before super class exceptions. If we change the order compiler will throw unreachable code error. 

5.) What is finally ?

Finally block is used in exception handling with try-catch blocks. Finally block will always executed weather exception is occurred or not. The main purpose of finally block to write code for freeing the resource or connection used.

Finally can be written with try block directly, its not mandatory to have catch block between try and finally.

 try{

// Code which can throw exception
}catch (Exception e) {
// TODO: handle exception
}finally {
//close open connections and free the resources

}
Imp Note - Finally block will not be executed if System.exit(0) called or power off the system.

6.)  What is throw keyword ? What is the difference between throw and throws ?

Throw - throw keyword is used to throw some exception in some specific situation.

So throw is used to throw some exception while throws is used declare the exception which we are not going to handle in program and they will propagated to the caller of the method.

7.) How to create a custom exception class in Java?

We can write a custom exception by extending Exception or any of its sub class. Below is a sample custom exception class.


package javaprinciples.exceptions;

public class CustomException extends Exception {

private static final long serialVersionUID = 1L;

public CustomException(String message) {
super(message);
}

}

8.) What is difference between final, finally and finalize in Java ?

final - final keyword is used with classes, methods or variables. final classes can not be extended. final methods can not be overridden and value of final variable can not be changed.

finally - finally keyword is used in exception handling to write some code which will be executed whether any exception is thrown or not.

finalize - finalise is a method which is used to write code to free the resources or make the objects again reachable. finalise is called before the object is garbage collected.

9.) What is multi catch feature added in Java7 ?

Prior Java7 only one exception can be caught in one catch block. In Java7 new feature was added so now we can catch multiple exception in a single catch block which can be separated by "|" to declare.

Sample code -


try {
    // execute code that may throw any exception from below 3.
} catch(SQLException | IOException e) {
    //Exception handling code
} catch(Exception e) {
//Exception handling code

}

10.) What is try-with-resource feature in exception handling ?

try-with-resource feature was introduced in Java7 to make code easy and error free. Before Java7 we always needs to write code in finally block to make the resources free after execution. 

But now we can write code using try-with-resource where we create resource object in try statement and use it in the try block. We don't need to write code for closing the resources in finally. JRE will automatically close the resource after execution completion.

Sample code -

try (AnyResource resource = new AnyResource()) {
            // use resource here
        } catch (Exception e) {
            // Exception handling code
        }

So these are the important questions from exception handling in Java. I hope this will help you. If you have any doubts please put in comments, I will try to resolve ASAP.

Check below links also-
Top 20 Collection Framework Interview Questions
Core Java Interview Questions - OOps and Basics
Core Java Interview Questions - String
Servlet Interview Questions
Bubble Sort Algorithm analysis and implementation in Java
Linear Search Algorithm analysis and implementation in Java
Binary Search Algorithm analysis and implementation in Java

Top 20 Collection Framework Interview Questions

Collection is the most important topic in any Java/J2EE programming interview. I have created a list of important JCF interview question and sharing the same with you. I hope it will help you . 

1.) What is Collection Framework in Java? What is root of collection interface framework?

Collection simply represent a group of Objects in java. Collection Framework is a java library that provides a unified architecture for 

working(representing, manipulating, searching and sorting etc.) with collections.

Collection interface is the root interface of collection framework.


Benefits - Collection framework makes the development easy and fast and provide different type of collection interfaces(Map, Set, List, Queue and Dqueue) and their implementations classes(ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue etc.) to make developement work easier. Collection classes implementations are optimized, So they makes out code good in quality and faster in performance.


2.) What are Collection and Collections in JCF?


Collection - Collection is root interface of JCF (Java Collection Framework).

Collections - Collections is a utility class in JCF which provides a lot of utility methods for collection classes. Like methods for sorting of collection.

3.) What are the important interfaces and classes in JCF?


The core interfaces in JCF are Collection, Set, List, Map and Queue. Other than these some important framework are SortedSet, SortedMap, ListIterator and Dqueue also.


JCF also provides implementation class for different interfaces like ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue , Properties, Hashtable etc.


4.) What are List and Set and Map interfaces?


SetSet can contains unique elements only. Set doesn't maintains the order of insertion. HashSet and TreeSet are the implementation classes of Set interface.


List - List can contain duplicate elements. List is indexed based collection and maintain the order in which elements are added. ArrayList, Vector and LinkedList are the implementation classes of List interface. Vector is a legacy class and synchronized(thread-safe). Vector can be used in multi-threaded environment.


Map - Map is not a collection of objects like List and Set. Map is collection of entrySet objects which represent a key-value pair. HaspMap, HashTable and Properties are the implementation classes of Map interface. HashTable is legacy class and synchronized(thread-safe). HashTable can be used in multi-threaded environment.


5.)What is an iterator and Enumeration? What is different between them?


Iterator - Iterator is an interface in java's util package. Iterator is used to iterate over collections. Iterator have three methods which are -

  • hasNext()
  • next()
  • remove()
Enumeration - Enumeration is a legacy interface to enumerate over collections. Enumeration is used with legacy classes like Vector and Properties. Enumeration has two methods to enumerate which are - 
  • hasMoreElements( ) 
  • nextElement().
Similarities between Iterator and Enumeration -
  • Both are used to iterate over collection classes.
  • Both are designed on the basis of Iterator design pattern.
Difference between Iterator and Enumeration -
  • Enumerations can only perform read only operations(traverse and fetch), while Iterator can add or remove elements while iterating over the collection.
  • Enumerations are fail-safe while Iterators are fail-fast. That means Iterator do not allow one thread to modify a collection while some other thread is using the same. It will throw ConcurrentModificationException in that case.
  • Enumeration methods name are bigger while Iterator have shorter method names.

6.) What is the difference between Iterator and ListIterator?
  • Iterator cab be used to traverse in forward direction only while ListIterator van traverse in forward and backward direction both.
  • Iterator can be used to iterate over List and Set, but ListIterator is only specific to List.
  • Iterator can not add or update existing element, but we can add or update existing elements while using ListIterator.
  • Iterator doesn't provide indexes while traversing, but ListIterator have methods to get next and previous index while traversing.
7.) What is the difference between Vector and ArrayList?

Vector and ArrayList are two different implementations of List interface. Vector is legacy class present from Java1.1 while ArrayList was added with JCF in Java1.2. The main differences between Vector and ArrayList are -
  • Vector in Java are synchronised while ArrayList are not synchronised. Because of that ArrayList is faster than Vector.
  • Vector and ArrayList both are based on dynamic array. But after exceeding Vector make 100% increase in size while ArrayList increase its size by 50% of current size.
  • Enumeration and Iterator both can be used for traversal of Vector elements while we can only use Iterator with ArrayList.
8.) What is the difference between Array and ArrayList in Java ?
  • Array size is fixed that is defined while creating the array. After creation Array size can not be changed. But ArrayList is dynamic in size. Default size of ArrayList is 10, which is dynamically increased by 50% after exceeding the current capacity.
  • Array can store both primitive and objects while ArrayList can only store objects.
9.) What is the difference between ArrayList and LinkedList ? How to choose from them?

ArrayList and LinkedList both are implementation of List in JCF. But they have difference in their implementation and methods. Below are the main differences between ArrayList and LinkedList -
  • ArrayList uses array data structure implementation while LinkedList is implemented with Doubly Linked List data structure.
  • Insertion and deletion of elements is faster than ArrayList in LinkedList while searching is faster in ArrayList. 
When to use ArrayList - Search in ArrayList is indexed based and faster than LinkedList. So ArrayList should be used for more search and less insert/delete operation.

When to use LinkedList - LinkedList should be used for more insertion/deletion and less search operation scenarios.

10.) What is the difference between HashSet, LinkedHashSet and TreeSet ?

HashSet, LinkedHashSet and TreeSet all are implementation of Set interface. All are used to store unique values. The main differences between these three are -
  • HashSet is implemented using HashTable so HashSet does not maintain the order of elements. HashSet stores the elements in random order.
  • LinkedHashSet is implemented using HashSet and LinkedList, that's why LinkedHashSet stores the elements in insertion order.
  • TreeSet extends the SortedSet and implemented using Red-Black tree. So TreeSet stores the elements in sorted order.
11.) What is Map interface? Why Map interface doesn't extends Collection interface?

Map interface represents a collection of key-value pairs. Map interface do not extends the Collection because Map interface is designed to store data in key-value pair, where as Collection store the single objects. Map contains three different collections which are keySet, valueSet and EntrySet.

12.) What is the differences between HashTable and HashMap ?

HashTable and HashMap both are implementation of Map interface. HashTable is a legacy class while HashMap was added in Java1.2. Below are the main differences between HashTable and HashMap -

  • HashTable is synchronized while HashMap is not synchronized. So HashTable is slower than HashMap and can be used in multi-threaded environment.
  • HashTable does not allow any null key or value, while HashMap allows one null key and any number of null values.
  • HashTable can use Iterator and Enumerator both while HashMap can only be traversed with Iterator.
  • Enumerator of HashTable are not fail-fast while Iterator of HashMap is fail-fast.
13.) What is the difference between HashMap and ConcurrentHashMap ?

ConcurrentHashMap was introduced in Java5 as an alternative of HashTable. Main differences between HashMap and ConcurrentHashMap are -



  • HashMap are not synchronised while ConcurrentHashMap are synchronised.
  • HashMap allows one null key and multiple null values while ConcurrentHashMap does not allow any null key or value.
  • HashMap are faster in performance than ConcurrentHashMap.
14.) Can we convert a HashMap or HashSet in synchronised HashMap are synchronised HashSet ?

Yes, we can convert collection classes in synchronized collection classes. Collections utility class provides us methods to convert collection classes in synchronized collection classes.
  • Collections.synchronizedMap(Map) to convert HashMap in synchronized HashMap.
  • Collections.synchronizedSet(Set) for Set and Collections.synchronizedList(List) for Lists. Also provides a general method for Collection Collections.synchronizedCollection(Collection).
15.) Difference between Comparable and Comparator interfaces.

Comparable and Comparator both are used to sort a given collection. Comparable sort the collection in natural order and implemented on the class itself while Multiple comparator can be created for sorting on the basis of different parameters in the class.

For more details on Comparable and Comparator Check HERE.

16.) Which concurrent collection classes added in Java5 ? How they are different from existing collections ?

Concurrent collection classes added in Java5 are -
  • ConcurrentHashMap
  • CopyOnWriteArrayList
  • CopyOnWriteArraySet
  • BlockingQueue etc.
These classes are alternative for synchronization of existing HashMap. ArrayList and HashSet's. These classes can be used in multithreaded environment and allow one thread to modify the collection while others are reading. Concurrent classes does not throw ConcurrentModificationException.

I Java6 also some other important concurrent classes were added like BlockingDqueue and ConcurrentSkipListMap and ConcurrentSkipListSet etc.


17.) What is BlockingQueue in JCF? 

As discussed in previous question, BlockingQueue was added in Java5. Blocking queue is implementation of Queue interface. 

BlockingQueue waits for element insertion if queue is already full and waits on retrieval if queue is empty.

Classical problem of Producer-Consumer can be resolved in very easy way using BlockingQueue, as we don't need to write synchonization and wait-notify code. It is handled by BlockingQueue.


18.) How to make a Collection read only ?


This is very important and asked in many interviews. Collections utility class provides methods for Collection, List, Set and Map to make them unmodifiable/read only. Below are the methods to make Collection classes unmodifiable- 



  • Collections.unmodifiableCollection(Collection)
  • Collections.unmodifiableList(List)
  • Collections.unmodifiableSet(Set)
  • Collections.unmodifiableMap(Map).
19.) How HashMap works in Java?

HashMap internally implemented using Array and LinkedList data structure. In Java8 LinkedList was replaced with BinaryTree. HashMap works on hashing technique.

To learn HashMap working in detail Read my article How HashMap works in Java.

20.) What is  WeakHashMap and IdentityHashMap? 

WeakHashMap 


WeakHashMap class is implementation of Map interface with weak keys. An entry in WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector. 
WeakHashMap allows null key and values to store. WeakHashMap is not synchronized.

IdentityHashMap 

IdentityHashMap as name suggests uses the equality operator(==) for comparing the keys. So when you put any Key Value pair in it the Key Object is compared using == operator. On the other hand HashMap uses equals method to determine the uniqueness of the Key.

This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.

These are the important Java Collection Framework interview questions. Please let me know if some are missed. I will add the same.

Check below links also-
Core Java Interview Questions - OOps and Basics
Core Java Interview Questions - String
Servlet Interview Questions
Bubble Sort Algorithm analysis and implementation in Java
Linear Search Algorithm analysis and implementation in Java
Binary Search Algorithm analysis and implementation in Java