Thursday 6 April 2017

Java Collection Basic Questions Part 4

1) How HashMap works in Java ? HashMap works On principle of Hashing.but it is not as simple as it sounds. Hashing is the mechanism of as... thumbnail 1 summary
1) How HashMap works in Java ?

HashMap works On principle of Hashing.but it is not as simple as it sounds. Hashing is the mechanism of assigning unique code to a variable or attribute using an algorithm to enable easy retrieval. A true hashing mechanism should always return the same hashCode() when it is applied to the same object.Read More....

2) Can we use any class as Map key?

Yes we can use class as key of HashMap. HashMap store data based on hashing algorithm so before using class as key below point should be consider:

  • Class should be immutable and if don’t keep it then hash code value can be change and when you try to pull value from hash map then possibility is you won’t get same value which you will see in below java class example
  • Class must override hashcode() and equals() method
import java.util.HashMap;
import java.util.Map;

public class ClassAsKey {

    public static void main(String[] args) {
    
    Map map = new HashMap();
    Person person = new Person();
    //Print hash code of person class
    System.out.println("Hash code: "+person.hashCode());
    map.put(person, "Java Honk");
    //Print hash code of person class again
    System.out.println("Hash code: "+person.hashCode());
    //This will return same value
    System.out.println("Value: "+map.get(person)+"\n");
    
    //Now check mutability, Because person class is
    //mutable let's change person name 
    person.setName("Java Honk");
    //Print hash code of person class again
    System.out.println("Hash code: "+person.hashCode());
    //It will return you null because hash code has
    //been changed
    System.out.println("Value: "+map.get(person));

    }

}

class Person{
    
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((name == null) ? 0 
        : name.hashCode());
    return result;
    }

    @Override
    public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Person other = (Person) obj;
    if (name == null) {
        if (other.name != null)
        return false;
    } else if (!name.equals(other.name))
        return false;
    return true;
    }
}

Output :

Hash code: 31
Hash code: 31
Value: Interview Guess

Hash code: 1319958103
Value: null


3) Why Map interface does not extend the Collection interface in Java Collections Framework ?

A good answer to this is “because they are incompatible“. Collection has a method add(Object o). Map can not have such method because it need key-value pair. There are other reasons also such as Map supports keySet, valueSet etc. Collection classes does not have such views.

4) What is EnumSet?

java.util.EnumSet is Set implementation to use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. EnumSet is not synchronized and null elements are not allowed. It also provides some useful methods like copyOf(Collection c), of(E first, E… rest) and complementOf(EnumSet s).

5) What is BlockingQueue?

java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

BlockingQueue interface is part of java collections framework and it’s primarily used for implementing producer consumer problem. We don’t need to worry about waiting for the space to be available for producer or object to be available for consumer in BlockingQueue as it’s handled by implementation classes of BlockingQueue.

Java provides several BlockingQueue implementations such as ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue etc.

6) How can we sort a list of Objects?

If we need to sort an array of Objects, we can use Arrays.sort(). If we need to sort a list of objects, we can use Collections.sort(). Both these classes have overloaded sort() methods for natural sorting (using Comparable) or sorting based on criteria (using Comparator).
Collections internally uses Arrays sorting method, so both of them have same performance except that Collections take sometime to convert list to array.

7) What is the Dictionary class?

The Java Dictionary class is an abstract class that allows all its derived classes to store data in the form of key-value pairs. Both keys and values can be objects of any type, but keys should be unique. Also, both keys and values cannot be null. For instance, if a key or value is referring to null and then inserted into a dictionary, a NullPointerException error occurs. Therefore, it’s mandatory to provide a non-null value for storing both keys and values.

8) What is  WeakHashMap ?

Elements in a weak hashmap can be reclaimed by the garbage collector if there are no other strong references to the key object, this makes them useful for caches/lookup storage.
Weak reference are not restricted to these hash tables, you can use WeakReference for single objects. They are useful to save resource, you can keep a reference to something but allow it to be collected when nothing else references it.

9) What is IdentityHashMap ?

IdentityHashMap extends AbstractMap and implements the Map interface. It uses reference equality (==) instead of object equality (equals()) when comparing keys and values.

10) Why can’t we write code as List<Number> numbers = new ArrayList<Integer>();?

Generics doesn’t support sub-typing because it will cause issues in achieving type safety. That’s why List<T> is not considered as a subtype of List<S> where S is the super-type of T. To understanding why it’s not allowed, let’s see what could have happened if it has been supported.
List listLong = new ArrayList();
listLong.add(Long.valueOf(10));
List listNumbers = listLong; // compiler error
listNumbers.add(Double.valueOf(1.23));

As you can see from above code that IF generics would have been supporting sub-typing, we could have easily add a Double to the list of Long that would have caused ClassCastException at runtime while traversing the list of Long.

11) What is Java Priority Queue?

PriorityQueue is an unbounded queue based on a priority heap and the elements are ordered in their natural order or we can provide Comparator for ordering at the time of creation. PriorityQueue doesn’t allow null values and we can’t add any object that doesn’t provide natural ordering or we don’t have any comparator for them for ordering. Java PriorityQueue is not thread-safe and provided O(log(n)) time for enqueing and dequeing operations.

12) Why can’t we create generic array? or write code as List<Integer>[] array = new ArrayList<Integer>[10];

It's because Java's arrays (unlike generics) contain, at runtime, information about its component type. So you must know the component type when you create the array. Since you don't know what T is at runtime, you can't create the array.

13) What are common algorithms implemented in Collections Framework?

Java Collections Framework provides algorithm implementations that are commonly used such as sorting and searching. Collections class contain these method implementations. Most of these algorithms work on List but some of them are applicable for all kinds of collections.
Some of them are sorting, searching, shuffling, min-max values.

14) While passing a Collection as argument to a function, how can we make sure the function will not be able to modify it?

We can create a read-only collection using Collections.unmodifiableCollection(Collection c) method before passing it as argument, this will make sure that any operation to change the collection will throw UnsupportedOperationException.

15) How remove(key) method works in HashMap ?

HashMap remove method calls removeEntryForKey method internally, which calculate the final hashValue of the key object, and then use that hashValue in the indexFor(int,int) method to find the first entry object in the appropriate bucket.

Since bucket is a LinkedList we start traversing from the first entry object which we retrieved indexFor method in the bucket. For each entry object in the bucket we compare whether hashValue and the key is equal to the calculated hashValue in the first step and the key passed as a parameter in the remove(key) method.

If desired Entry object is found , then we remove that single entry object from the LinkedList. Removing a single Entry object from the LinkedList is implemented just like removing a single object from the LinkedList.

Entry object returned by the removeEntryForKey method is then stored in the local variable e of type Entry in the remove(key) method. Return the removed entry if it is not null else return null.

16) How will you make Collections readOnly ?

We can create a read-only collection using Collections.unmodifiableCollection(Collection c) method. This will make sure that any operation to change the collection will throw UnsupportedOperationException.

Monday 27 March 2017

Internal Implementation of HashMap

Hash Map is one of the most used collection, though it will be surprising to know that maps themselves are not collections because they don... thumbnail 1 summary
Hash Map is one of the most used collection, though it will be surprising to know that maps themselves are not collections because they don't implement Collection interface. However collection view of a map can be obtained using entrySet() method. To obtain a collection-view of the keys, keySet() method can be used.

Internal working of the HashMap which is also a favourite Java Collections interview question
There are four things we should know about before going into the internals of how does HashMap work in Java -

1) HashMap works on the principal of hashing.
2) Map.Entry interface - This interface gives a map entry (key-value pair). HashMap in Java stores both key and value object, in bucket, as an object of Entry class which implements this nested interface Map.Entry.
3) hashCode() -HashMap provides put(key, value) for storing and get(key) method for retrieving Values from HashMap. When put() method is used to store (Key, Value) pair, HashMap implementation calls hashcode on Key object to calculate a hash that is used to find a bucket where Entry object will be stored. When get() method is used to retrieve value, again key object is used to calculate a hash which is used then to find a bucket where that particular key is stored.
4) equals() - equals() method is used to compare objects for equality. In case of HashMap key object is used for comparison, also using equals() method Map knows how to handle hashing collision (hashing collision means more than one key having the same hash value, thus assigned to the same bucket. In that case objects are stored in a linked list, refer figure for more clarity.
Where hashCode method helps in finding the bucket where that key is stored, equals method helps in finding the right key as there may be more than one key-value pair stored in a single bucket.
** Bucket term used here is actually an index of array, that array is called table in HashMap implementation. Thus table[0] is referred as bucket0, table[1] as bucket1 and so on.

How important it is to have a proper hash code and equals method can be seen through the help of the following program -

public class HashMapTest {
    public static void main(String[] args) {
        Map  cityMap = new HashMap();
        cityMap.put(new Key(1, "NY"),"New York City" );
        cityMap.put(new Key(2, "ND"), "New Delhi");
        cityMap.put(new Key(3, "NW"), "Newark");
        cityMap.put(new Key(4, "NP"), "Newport");

        System.out.println("size before iteration " + cityMap.size());
        Iterator  itr = cityMap.keySet().iterator();
        while (itr.hasNext()){
            System.out.println(cityMap.get(itr.next()));     
        }
        System.out.println("size after iteration " + cityMap.size());    
    }
 
}

// This class' object is used as key
// in the HashMap
class Key{
 int index;
 String Name;
 Key(int index, String Name){
  this.index = index;
  this.Name = Name;
 }
 
 @Override
 // A very bad implementation of hashcode
 // done here for illustrative purpose only 
 public int hashCode(){
  return 5;
 }
 
 @Override
 // A very bad implementation of equals
 // done here for illustrative purpose only 
 public boolean equals(Object obj){
  return true;
 }
 
}
Output

size before iteration 1
Newport
size after iteration 1

Lets get through the code to see what is happening, this will also help in understanding how put works internally.

Notice that I am inserting 4 values in the HashMap, still in the output it says size is 1 and iterating the map gives me the last inserted entry. Why is that?

Answer lies in, how hashCode() and equals() method are implemented for the key Class. Have a look at the hashCode() method of the class Key which always returns "5" and the equals() method which is always returning "true".

When a value is put into HashMap it calculates a hash using key object and for that it uses the hashCode() method of the key object class (or its parent class). Based on the calculated hash value HashMap implementation decides which bucket should store the particular Entry object.

In code the hashCode() method of the key class always returns "5". This effectively means calculated hash value, is same for all the entries inserted in the HashMap. Thus all the entries are stored in the same bucket.

Second thing, a HashMap implementation does is to use equals() method to see if the key is equal to any of the already inserted keys (Recall that there may be more than one entry in the same bucket). Note that, with in a bucket key-value pair entries (Entry objects) are stored in a linked-list (Refer figure for more clarity). In case hash is same, but equals() returns false (which essentially means more than one key having the same hash or hash collision) Entry objects are stored, with in the same bucket, in a linked-list.

In code, I am always returning true for equals() method so the HashMap implementation "thinks" that the keys are equal and overwrites the value. So, in a way using hashCode() and equals() I have "tricked" HashMap implementation to think that all the keys (even though different) are same, thus overwriting the values.

In a nutshell there are three scenarios in case of put() -

Using hashCode() method, hash value will be calculated. Using that hash it will be ascertained, in which bucket particular entry will be stored.
equals() method is used to find if such a key already exists in that bucket, if no then a new node is created with the map entry and stored within the same bucket. A linked-list is used to store those nodes.
If equals() method returns true, which means that the key already exists in the bucket. In that case, the new value will overwrite the old value for the matched key.

Pictorial representation of how Entry (key-value pair) objects will be stored in table array

How get() methods works internally

As we already know how Entry objects are stored in a bucket and what happens in the case of Hash Collision it is easy to understand what happens when key object is passed in the get method of the HashMap to retrieve a value.

Using the key again hash value will be calculated to determine the bucket where that Entry object is stored, in case there are more than one Entry object with in the same bucket stored as a linked-list equals() method will be used to find out the correct key. As soon as the matching key is found get() method will return the value object stored in the Entry object.

In case of null Key

As we know that HashMap also allows null, though there can only be one null key in HashMap. While storing the Entry object HashMap implementation checks if the key is null, in case key is null, it always map to bucket 0 as hash is not calculated for null keys.

HashMap changes in Java 8

Though HashMap implementation provides constant time performance O(1) for get() and put() method but that is in the ideal case when the Hash function distributes the objects evenly among the buckets.

But the performance may worsen in the case hashCode() used is not proper and there are lots of hash collisions. As we know now that in case of hash collision entry objects are stored as a node in a linked-list and equals() method is used to compare keys. That comparison to find the correct key with in a linked-list is a linear operation so in a worst case scenario the complexity becomes O(n).

To address this issue in Java 8 hash elements use balanced trees instead of linked lists after a certain threshold is reached. Which means HashMap starts with storing Entry objects in linked list but after the number of items in a hash becomes larger than a certain threshold, the hash will change from using a linked list to a balanced tree, this will improve the worst case performance from O(n) to O(log n).

Points to note -

HashMap works on the principal of hashing.
HashMap uses the hashCode() method to calculate a hash value. Hash value is calculated using the key object. This hash value is used to find the correct bucket where Entry object will be stored.
HashMap uses the equals() method to find the correct key whose value is to be retrieved in case of get() and to find if that key already exists or not in case of put().
Hashing collision means more than one key having the same hash value, in that case Entry objects are stored as a linked-list with in a same bucket.
With in a bucket values are stored as Entry objects which contain both key and value.
In Java 8 hash elements use balanced trees instead of linked lists after a certain threshold is reached while storing values. This improves the worst case performance from O(n) to O(log n).

Tuesday 14 March 2017

JDBC Interview Questions

1) What is JDBC? Java Database Connectivity (JDBC) is an application programming interface (API) for Java, which defines how a client m... thumbnail 1 summary
1) What is JDBC?

Java Database Connectivity (JDBC) is an application programming interface (API) for Java, which defines how a client may access a relational database. It provides methods to query and update data in a database. A JDBC-to-ODBC bridge enables connections to any ODBC-accessible data source in the Java virtual machine (JVM) host environment.

2) What is a JDBC Driver and what are the types of JDBC driver?

JDBC driver contains classes and interfaces that enables Java applications to interact with a database. There are 4 types of JDBC drivers:

Type 1 driver or JDBC-ODBC bridge driver – The JDBC-ODBC bridge driver uses native ODBC driver to connect to the database. It converts JDBC method calls into the ODBC function calls.
Type 2 driver or Native-API, partly Java driver – The Native API driver uses the client-side libraries of the database. The driver converts JDBC calls into database calls by using native API provided by database. This driver is database specific so once you switch from one database to another you need to change this driver. Native database library must be loaded on each client machine that uses this type of driver.
Type 3 driver or Network Protocol, pure Java driver – The Network Protocol driver uses server-side middleware that converts JDBC calls into the vendor-specific database protocol.
Type 4 driver or Native-protocol, pure Java driver – This is the most widely used driver nowadays. The driver converts JDBC calls directly into vendor-specific database protocol. Many of these protocols are proprietary, hence the database vendors themselves will be the primary source for this type of driver.

3) Which Driver should be Used?

If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4.
If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver.

4) What are the main steps to connect to database using JDBC connectivity?

Register the Driver

Class.forName() is used to load the driver class explicitly.

Example to register with JDBC-ODBC Driver

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Create a Connection

getConnection() method of DriverManager class is used to create a connection.

getConnection(String url)
getConnection(String url, String username, String password)
getConnection(String url, Properties info)
Example establish connection with Oracle Driver

Connection con = DriverManager.getConnection
          ("jdbc:oracle:thin:@localhost:1521:XE","username","password");

Create SQL Statement

createStatement() method is invoked on current Connection object to create a SQL Statement.

public Statement createStatement() throws SQLException
Example to create a SQL statement

Statement s=con.createStatement();

Execute SQL Statement

executeQuery() method of Statement interface is used to execute SQL statements.

public ResultSet executeQuery(String query) throws SQLException
Example to execute a SQL statement

ResultSet rs=s.executeQuery("select * from user");
  while(rs.next())
  {
   System.out.println(rs.getString(1)+" "+rs.getString(2));
  }

Closing the connection

After executing SQL statement you need to close the connection and release the session. The close() method of Connection interface is used to close the connection.

public void close() throws SQLException
Example of closing a connection

con.close();

5) What are the types of statements in JDBC?

There are 3 JDBC statements.

Statement - Use the for general-purpose access to your database. Useful when you are using static SQL statements at runtime. The Statement interface cannot accept parameters. An object of Statement class can be created using Connection.createStatement() method.
PreparedStatement - Use the when you plan to use the SQL statements many times. The PreparedStatement interface accepts input parameters at runtime.A SQL statement is pre-compiled and stored in a PreparedStatement object. An object of PreparedStatement class can be created using Connection.prepareStatement() method.
CallableStatement - Use when you want to access the database stored procedures. The CallableStatement interface can also accept runtime input parameters.An object of CallableStatement class can be created using Connection.prepareCall() method.

6) What is JDBC Connection interface?

The Connection interface maintains a session with the database. It can be used for transaction management. It provides factory methods that returns the instance of Statement, PreparedStatement, CallableStatement and DatabaseMetaData.

7) What is JDBC ResultSet interface?

The ResultSet object represents a row of a table. It can be used to change the cursor pointer and get the information from the database.

8) What is JDBC ResultSetMetaData interface?

The ResultSetMetaData interface returns the information of table such as total number of columns, column name, column type etc.

9) What is database connection pooling? What are the advantages of using a connection pool?

Connection pooling is the mechanism by which we reuse connection objects which are used to make connection with the database. It allows multiple clients to share a cached set of connection objects. Getting connection and disconnecting are costly operation, which can affect the application performance, so we should avoid creating multiple connection objects during multiple database interactions.
A pool contains set of database connection objects which are already connected to the database, and any client who wants to use it can take it from pool and it can be returned back to the pool when done with using.
Apart from performance this also saves you resources as there may be limited database connections available for your application.

10) How do you iterate ResultSet in the reverse order?

You can traverse a ResultSet backwards if you have a scrollable resultset. You can get this by passing ResultSet.TYPE_SCROLL_INSENSITIVE and ResultSet.CONCUR_READ_ONLY parameters when creating the statement object.

Then you can use resultset.afterLast() to move the cursor to the end of the ResultSet object, just after the last row and traverse backwards using resultset.previous() method.

Here is a sample code.
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                      ResultSet.CONCUR_READ_ONLY);
ResultSet resultSet = statement.executeQuery("select * from XX");
resultSet.afterLast();
while (resultSet.previous()) {
// do something
}

11) What are stored procedures? How to call stored procedure using JDBC API?

A stored procedure is a set of Structured Query Language (SQL) statements with an assigned name, which are pre-compiled and stored in a relational database management system as a group, so it can be reused and shared by multiple programs.Stored procedures can be compiled and executed with different parameters and results and may have any combination of IN/OUT parameters. Stored procedures can be called using CallableStatement class in JDBC API.
Example : 
CallableStatement cs = connection.prepareCall("{call STORED_PROCEDURE_NAME}");
ResultSet rs = cs.executeQuery();

12) What is DriverManager class?

The DriverManager class acts as an interface between user and drivers. It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. The DriverManager class maintains a list of Driver classes that have registered themselves by calling the method DriverManager.registerDriver().

13) What is the use of setAutoCommit() method?

When a connection is created, it is in auto-commit mode by default. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. By setting auto-commit to false no SQL statements will be committed until you explicitly call the commit() method.

14) What is a “dirty read”?

There can be a situation where one transaction can change a value, and a second transaction can read this value before the original change has been committed or rolled back. This is known as a dirty read scenario because there is always the possibility that the first transaction may rollback the change, resulting in the second transaction having read an invalid value.

Sunday 12 March 2017

Java Collection Basic Questions Part 3

1) What is the importance of hashCode() and equals() methods? You must override hashCode() in every class that overrides equals(). Fail... thumbnail 1 summary
1) What is the importance of hashCode() and equals() methods?

You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object.hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.
Let's try to understand it with an example of what would happen if we override equals() without overriding hashCode() and attempt to use a Map.
Say we have a class like this and that two objects of MyClass are equal if their importantField is equal (with hashCode() and equals() generated by eclipse)
public class MyClass {

    private final String importantField;
    private final String anotherField;

    public MyClass(final String equalField, final String anotherField) {
        this.importantField = equalField;
        this.anotherField = anotherField;
    }

    public String getEqualField() {
        return importantField;
    }

    public String getAnotherField() {
        return anotherField;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((importantField == null) ? 0 : importantField.hashCode());
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final MyClass other = (MyClass) obj;
        if (importantField == null) {
            if (other.importantField != null)
                return false;
        } else if (!importantField.equals(other.importantField))
            return false;
        return true;
    }

}

Override only equals

If only equals is overriden, then when you call myMap.put(first,someValue) first will hash to some bucket and when you call myMap.put(second,someOtherValue) it will hash to some other bucket (as they have a different hashCode). So, although they are equal, as they don't hash to the same bucket, the map can't realize it and both of them stay in the map.

Although it is not necessary to override equals() if we override hashCode(), let's see what would happen in this particular case where we know that two objects of MyClass are equal if their importantField is equal but we do not override equals().

Override only hashCode

Imagine you have this
MyClass first = new MyClass("a","first");
MyClass second = new MyClass("a","second");
If you only override hashCode then when you call myMap.put(first,someValue) it takes first, calculates its hashCode and stores it in a given bucket. Then when you call myMap.put(second,someOtherValue) it should replace first with second as per the Map Documentation because they are equal (according to the business requirement).

But the problem is that equals was not redefined, so when the map hashes second and iterates through the bucket looking if there is an object k such that second.equals(k) is true it won't find any as second.equals(first) will be false.

2) What is the difference between peek(),element() ,poll() and remove() method of the Queue interface ?

The peek() method retrieves the value of the first element of the queue without removing it from the queue. For each invocation of the method we always get the same value and its execution
does not affect the size of the queue. If the queue is empty the peek() method returns null.

The element() method behaves like peek(), so it again retrieves the value of the first element without removing it. Unlike peek ), however, if the list is empty element() throws a NoSuchElementException.

The poll() method retrieves the value of the first element of the queue by removing it from the queue. At each invocation it removes the first element of the list and if the list is already empty it returns null but does not throw any exception.

The remove() method behaves as the poll() method, so it removes the first element of the list and if the list is empty it throws a NoSuchElementException.

3) How to avoid ConcurrentModificationException while iterating a collection?

ConcurrentModificationException can come if two threads trying to modify one list at same time. E.g one thread is iterating over it and other is trying to remove elements from it. But more commonly it comes when you use Array List remove() method while iterating over list.
To avoid this always use iterator's  remove() method to delete elements while traversing.

4) Write java code showing insertion,deletion and retrieval of HashMap object ?

import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class Details {

   public static void main(String args[]) {

      /* This is how to declare HashMap */
      HashMap hmap = new HashMap();

      /*Adding elements to HashMap*/
      hmap.put(12, "Chaitanya");
      hmap.put(2, "Rahul");
      hmap.put(7, "Singh");
      hmap.put(49, "Ajeet");
      hmap.put(3, "Anuj");

      /* Display content using Iterator*/
      Set set = hmap.entrySet();
      Iterator itr1 = set.iterator();
      while(itr1.hasNext()) {
         Map.Entry entry = (Map.Entry)itr1.next();
         System.out.print("key is: "+ entry.getKey() + " & Value is: ");
         System.out.println(entry.getValue());
      }

      /* Get values based on key*/
      String var= hmap.get(2);
      System.out.println("Value at index 2 is: "+var);

      /* Remove values based on key*/
      hmap.remove(3);
      System.out.println("Map key and values after removal:");
      Set set2 = hmap.entrySet();
      Iterator itr = set2.iterator();
      while(itr.hasNext()) {
          Map.Entry entry1 = (Map.Entry)itr.next();
          System.out.print("Key is: "+entry1.getKey() + " & Value is: ");
          System.out.println(entry1.getValue());
       }

   }
}

Output:
key is: 49 & Value is: Ajeet
key is: 2 & Value is: Rahul
key is: 3 & Value is: Anuj
key is: 7 & Value is: Singh
key is: 12 & Value is: Chaitanya
Value at index 2 is: Rahul
Map key and values after removal:
Key is: 49 & Value is: Ajeet
Key is: 2 & Value is: Rahul
Key is: 7 & Value is: Singh
Key is: 12 & Value is: Chaitanya

5) What is UnsupportedOperationException?

UnsupportedOperationException is class which extends RuntimeException and this exception thrown to indicate that requested operation is not supported by API.
Reason is, when call java.util.Arrays.asList(String… a) method it returns fixed-size list backed by specified array so when you try to modify the list i.e. add or remove value from it will throw UnsupportedOperationException.
Below code will throw UnsupportedOperationException:

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class UnsupportedException {

 public static void main(String[] args) {

 String[] strings = { "Java", "Honk", "Test" };

 List list = Arrays.asList(strings);

 for (Iterator iterator = 
   list.iterator(); iterator.hasNext();) {
  String string = iterator.next();
  iterator.remove();
   }

 }

}

To fix UnsupportedOperationException use LinkedList constructor and pass collection object as parameter. Please see sample code below :
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class UnsupportedExceptionFix {

 public static void main(String[] args) {

 String[] strings = { "Java", "Honk", "Test" };

 List list2 = 
   new LinkedList(Arrays.asList(strings));
 for (Iterator iterator = 
   list2.iterator(); iterator.hasNext();) {
  String string = iterator.next();
  iterator.remove();
 }
 System.out.println("Removed all data from list");

 }

}

6) What is the difference between HashMap and ConcurrentHashMap ?

Significant difference between HashMap and ConcurrentHashMap is that ConcurrentHashMap is thread-safe and can be used in a concurrent environment without external synchronization. Though it doesn't provide the same level of synchronization as achieved by using Hashtable but it's enough for the most practical purpose.

HashMap can be synchronized by wrapping it on Collections.synchornizedMap(HashMap) which will return a collection which is almost equivalent to Hashtable, where every modification operation on Map is locked on whole Map object while in case of ConcurrentHashMap, thread-safety is achieved by dividing whole Map into different partition based upon Concurrency level and only locking particular portion instead of locking the whole Map.

ConcurrentHashMap is more scalable and performs better than Synchronized HashMap in the multi-threaded environment while in Single threaded environment both HashMap and ConcurrentHashMap gives comparable performance, where HashMap only slightly better.

Friday 3 March 2017

ExceptionHandling with MethodOverriding

An overriding method (the method of child class) can throw any unchecked exceptions, regardless of whether the overridden method (method... thumbnail 1 summary
An overriding method (the method of child class) can throw any unchecked exceptions, regardless of whether the overridden method (method of base class) throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw those checked exceptions, which have less scope than the exception(s) declared in the overridden method.

If the superclass method does not declare an exception

1) Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception.

import java.io.*;  
class Parent{  
  void msg(){System.out.println("parent");}  
}  
  
class TestExceptionChild extends Parent{  
  void msg()throws IOException{  
    System.out.println("TestExceptionChild");  
  }  
  public static void main(String args[]){  
   Parent p=new TestExceptionChild();  
   p.msg();  
  }  
}  

2) Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but can declare unchecked exception.

import java.io.*;  
class Parent{  
  void msg(){System.out.println("parent");}  
}  
  
class TestExceptionChild1 extends Parent{  
  void msg()throws ArithmeticException{  
    System.out.println("child");  
  }  
  public static void main(String args[]){  
   Parent p=new TestExceptionChild1();  
   p.msg();  
  }  
}  

If the superclass method declares an exception

1) Rule: If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.

import java.io.*;  
class Parent{  
  void msg()throws ArithmeticException{System.out.println("parent");}  
}  
  
class TestExceptionChild2 extends Parent{  
  void msg()throws Exception{System.out.println("child");}  
  
  public static void main(String args[]){  
   Parent p=new TestExceptionChild2();  
   try{  
   p.msg();  
   }catch(Exception e){}  
  }  
}  

Wednesday 1 March 2017

Java Collection Basic Questions Part 2

The Java Collections API's provide Java developers with a set of classes and interfaces that makes it easier to handle collections of... thumbnail 1 summary
The Java Collections API's provide Java developers with a set of classes and interfaces that makes it easier to handle collections of objects.


1) What is difference between an ArrayList and a vector?

a) Synchronization: ArrayList is non-synchronized which means multiple threads can work on ArrayList at the same time. For e.g. if one thread is performing an add operation on ArrayList, there can be an another thread performing remove operation on ArrayList at the same time in a multithreaded environment

while Vector is synchronized. This means if one thread is working on Vector, no other thread can get a hold of it. Unlike ArrayList, only one thread can perform an operation on vector at a time.

b) Resize: A Vector defaults to doubling size of its array . While when you insert an element into the ArrayList ,      it increases
its Array size by 50% .

c) Performance: Vector is slow as it is thread safe . In comparison ArrayList is fast as it is non synchronized . Thus     in ArrayList two or more threads  can access the code at the same time  , while Vector is limited to one thread at a time.

d) fail-fast: First let me explain what is fail-fast: If the collection (ArrayList, vector etc) gets structurally modified by any means, except the add or remove methods of iterator, after creation of iterator then the iterator will throw ConcurrentModificationException. Structural modification refers to the addition or deletion of elements from the collection.

As per the Vector javadoc the Enumeration returned by Vector is not fail-fast. On the other side the iterator and listIterator returned by ArrayList are fail-fast.

e) Who belongs to collection framework really? The vector was not the part of collection framework, it has been included in collections later. It can be considered as Legacy code. There is nothing about Vector which List collection cannot do. Therefore Vector should be avoided. If there is a need of thread-safe operation make ArrayList synchronized as discussed in the next section of this post or use CopyOnWriteArrayList which is a thread-safe variant of ArrayList.

2) What is different between Iterator and ListIterator?

a) Iterator is used for traversing List and Set both.
While ListIterator is used to traverse List only.

b) We can traverse in only forward direction using Iterator.
Using ListIterator, we can traverse a List in both the directions (forward and Backward).

c) We cannot obtain indexes while using Iterator
We can obtain indexes at any point of time while traversing a list using ListIterator using nextIndex() and previousIndex() are used for this purpose.

d) We cannot add element to collection while traversing it using Iterator, it throws ConcurrentModificationException when you try to do it.
We can add element at any point of time while traversing a list using ListIterator.

e) We cannot replace the existing element value when using Iterator.
By using set(E e) method of ListIterator we can replace the last element returned by next() or previous() methods.

f) Methods of Iterator:
  • hasNext()
  • next()
  • remove()

Methods of ListIterator:
  • add(E e)
  • hasNext()
  • hasPrevious()
  • next()
  • nextIndex()
  • previous()
  • previousIndex()
  • remove()
  • set(E e)

3) What is difference between fail-fast and fail-safe?

a)Fail-fast Iterator throws ConcurrentModfiicationException as soon as they detect any structural change in collection during iteration, basically which changes the modCount variable hold by Iterator. While fail-safe iterator doesn't throw CME.

b)Fail-fast iterator traverse over original collection class while fail-safe iterator traverse over a copy or view of original collection. That's why they don't detect any change on original collection classes and this also means that you could operate with stale value.

c)Iterators from Java 1.4 Collection classes e.g. ArrayList, HashSet and Vector are fail-fast while Iterators returned by concurrent collection classes e.g. CopyOnWriteArrayList or CopyOnWriteArraySet are fail-safe.

d)Fail fast iterator works in live data but become invalid when data is modified while fail-safe iterator are weekly consistent.

4) How  Fail  Fast Iterator  come to know that the internal structure is modified ?

The usual way is like this: The collection object keeps a "modCount(version)" variable that is incremented on every modification, and the iterator remembers the last "modification count" that it remembers (either from when the iterator was created, or the last modification that was done through the iterator). Every time the iterator is used, it checks its modification count against the collection's, and if it is different, it knows someone modified the collection without using it, and throws the exception.

Note : The 'remove' method also checks the count but, if successful, resets the count to the new value. It does this so that you can use the 'remove' method to remove an entry WITHOUT getting the exception.

5) What is the difference between ArrayList and LinkedList?

a)Search: ArrayList search operation is pretty fast compared to the LinkedList search operation. get(int index) in ArrayList gives the performance of O(1) while LinkedList performance is O(n).

Reason: ArrayList maintains index based system for its elements as it uses array data structure implicitly which makes it faster for searching an element in the list. On the other side LinkedList implements doubly linked list which requires the traversal through all the elements for searching an element.

b)Deletion: LinkedList remove operation gives O(1) performance while ArrayList gives variable performance: O(n) in worst case (while removing first element) and O(1) in best case (While removing last element).

c)Conclusion: LinkedList element deletion is faster compared to ArrayList.

Reason: LinkedList’s each element maintains two pointers (addresses) which points to the both neighbor elements in the list. Hence removal only requires change in the pointer location in the two neighbor nodes (elements) of the node which is going to be removed. While In ArrayList all the elements need to be shifted to fill out the space created by removed element.

d)Inserts Performance: LinkedList add method gives O(1) performance while ArrayList gives O(n) in worst case. Reason is same as explained for remove.

e)Memory Overhead: ArrayList maintains indexes and element data while LinkedList maintains element data and two pointers for neighbor nodes hence the memory consumption is high in LinkedList comparatively.

6) What is the difference between List and Set?

a)Ordering : List is an ordered collection it maintains the insertion order, which means upon displaying the list content it will display the elements in the same order in which they got inserted into the list.
Set is an unordered collection, it doesn’t maintain any order. There are few implementations of Set which maintains the order such as LinkedHashSet (It maintains the elements in insertion order).

b)DublicateValues : List allows duplicates while Set doesn’t allow duplicate elements. All the elements of a Set should be unique if you try to insert the duplicate element in Set it would replace the existing value.

c)Null Values : List allows any number of null values. Set can have only a single null value at most.

d)Iterator : ListIterator can be used to traverse a List in both the directions(forward and backward) However it can not be used to traverse a Set. We can use Iterator (It works with List too) to traverse a Set.

e)Legacy Class : List interface has one legacy class called Vector whereas Set interface does not have any legacy class.

7) What is the difference between HashSet and TreeSet?

a)Ordering : HashSet stores the object in random order . There is no guarantee that the element will be printed first in the output  which one is inserted first in the HashSet  .
Elements are sorted according to the natural ordering of its elements in TreeSet. If the objects can not be sorted in natural order than use compareTo() method to sort the elements of TreeSet object .

b)Null value : Null value can not be stored in TreeSet while in HashSet it is possible. If one try to store null object in TreeSet object , it will throw Null Pointer Exception.

c)Performance : HashSet take constant time performance for the basic operations like add, remove contains and size.While TreeSet guarantees log(n) time cost for the basic operations (add,remove,contains).

d)Speed : HashSet is much faster than TreeSet,as performance time of HashSet is constant against the log time of TreeSet for most operations (add,remove ,contains and size).

e)Internal implementation : HashSet are internally backed by hashmap. While TreeSet is backed by a TreeMap.

f)Functionality : TreeSet is rich in functionality as compare to HashSet. Functions like pollFirst(),pollLast(),first(),last(),ceiling(),lower() etc. makes TreeSet easier to use than HashSet.

g)Comparision : HashSet uses equals() method for comparison in java while TreeSet uses compareTo() method for maintaining ordering .

8) What is the difference between HashSet and HashMap?

a)Adding or Storing mechanism : HashMap internally uses hashing to add or store objects. HashSet internally uses HashMap object to add or store the objects.

b)Number of objects during add(put) operation :  HashMap requires two objects put(K key , V Value) to add an element to HashMap object.
HashSet requires only one object add(Object o).

c)Performance : HashMap is faster than HashSet because unique key is used to access object .

d)Storage : HashMap Stores data in form of  key-value pair while HashSet Store only objects.

e)Internal implementation : HashSet are internally backed by hashmap. HashMap  is an implementation of Map interface.

f)Duplicates  :  HashSet does not allow duplicate values.If the HashMap previously contain the mapping for the key, the old value is replaced. HashMap  does not allow duplicate keys but allow dublicate values.

9) What is the difference between HashMap and TreeMap?

a)Ordering : HashMap stores the object in random order . There is no guarantee that the element will be printed first in the output  which one is inserted first in the HashMap  .
Elements are sorted according to the natural ordering of its elements in TreeMap. If the objects can not be sorted in natural order than use compareTo() method to sort the elements of TreeMap object .

b)Implementation : Internal HashMap implementation use Hashing. TreeMap internally uses Red-Black tree implementation.

c)Null keys and Null value : TreeMap can not contain null keys but may contain many null values. HashMap can store one null key and many  null values.

d)Performance : HashMap  take constant time performance for the basic operations like get and put i.e O(1). TreeMap provides guaranteed log(n) time cost for the get and put method. Hence HashMap is much faster than TreeMap, as performance time of HashMap is constant against the log time TreeMap for most operations.

e)Interfaces implemented : HashMap implements Map interface while TreeMap implements NavigableMap interface.

10) What is the difference between HashMap and Hashtable?

a)Synchronization or Thread Safe : Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.

b)Null keys and null values : Hashtable does not allow null keys or values.  HashMap allows one null key and any number of null values.

c)Iterating the values :  Hashmap object values are iterated by using iterator .HashTable is the only class other than vector which uses enumerator to iterate the values of HashTable object.

11) What is the difference between Comparable and Comparator?

a)Sort sequence : Comparable provides single sorting sequence. In other words, we can sort the collection on the basis of single element such as id or name or price etc. Comparator provides multiple sorting sequence. In other words, we can sort the collection on the basis of multiple elements such as id, name and price etc.

b)Methods Used : Comparable provides compareTo() method to sort elements. Comparator provides compare() method to sort elements.

c)Modify Classes : Comparable affects the original class i.e. actual class is modified. Comparator doesn't affect the original class i.e. actual class is not modified.

d)Package : Comparable is found in java.lang package. Comparator is found in java.util package.

e)Objects needed for Comparision : If you see then logical difference between these two is Comparator in Java compare two objects provided to it , while Comparable interface compares "this" reference with the object specified. So only one object is provided which is then compared to "this" reference.

f)Example : We can sort the list elements of Comparable type by Collections.sort(List) method. We can sort the list elements of Comparable type by Collections.sort(List) method.

12) What is difference between Synchronized and Concurrent Collections in Java?

Synchronised collections are the "thread safe" , which addresses synchronization by making all the public methods of the collection "Synchronized". E.G : Collections.synchronizedMap(Map) will be a synchronized map and can be modified by one thread at a time. Synchronized : like a toilet, the object can be used by only one person (thread). However it is sharable even only one person can use it at one time.

Concurrent collections like ConcurrentHashMap are designed for concurrent access from Multiple threads. Instead of synchronizing every method on a common lock, restricting access to a single thread at a time, it uses a finer-grained locking mechanism called lock striping .For example ConcurrentHashMap introduced concept of segmentation, only certain part of it get locked to provide thread safety so many other readers can still access map without waiting for iteration to complete. Concurrent : like pond, where many person (threads) can solve their different needs. Like washerman washes, some take bath and so on.

Tuesday 21 February 2017

Java Collection Basic Questions Part 1

1) What is Collection ? A collection — sometimes called a container — is simply an object that groups multiple elements into a single un... thumbnail 1 summary
1) What is Collection ?

A collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.For example; a jar of chocolates, list of names etc.

2) What is a Collections Framework ?

The Java Collections Framework is a collection of interfaces and classes which helps in storing and processing the data efficiently. This framework has several useful classes which have tons of useful functions which makes a programmer task super easy.

3) What are the benefits of Java Collections Framework ?

Reduced development effort by using core collection classes rather than implementing our own collection classes.
Code quality is enhanced with the use of well tested collections framework classes.
Reduced effort for code maintenance by using collection classes shipped with JDK.
Reusability and Interoperability(the ability of computer systems or software to exchange and make use of information).

4) What is the root interface in collection hierarchy ?

The root interface of Collection hierarchy in Java is Collection interface.
But the Collection interface extends Iterable interface. Due to this some people consider Iterable interface as the root interface.

Iterable interface is present in java.lang package but Collection interface is present in java.util package. Oracle Java API docs mention that Collection interface is a member of the Java Collections framework.Whereas, Iterable interface is not stated as a part of Java Collections framework in Java docs.Due to this Collection interface is the root of Collections Framework.

5) What is the benefit of Generics in Collections Framework?

Java 1.5 came with Generics and all collection interfaces and implementations use it heavily. Generics allow us to provide the type of Object that a collection can contain, so if you try to add any element of other type it throws compile time error.
This avoids ClassCastException at Runtime because you will get the error at compilation. Also Generics make code clean since we don’t need to use casting and instanceof operator.

6) What is the difference between Collection and Collections ?

Collection Interface :

Collection is a root level interface of the Java Collection Framework. Most of the classes in Java Collection Framework inherit from this interface. List, Set and Queue are main sub interfaces of this interface. JDK doesn’t provide any direct implementations of this interface. But, JDK provides direct implementations of it’s sub interfaces. ArrayList, Vector, HashSet, LinkedHashSet, PriorityQueue are some indirect implementations of Collection interface. Map interface, which is also a part of java collection framework, doesn’t inherit from Collection interface. Collection interface is a member of java.util package.

Collections Class:

Collections is an utility class in java.util package. It consists of only static methods which are used to operate on objects of type Collection. For example, it has the method to find the maximum element in a collection, it has the method to sort the collection, it has the method to search for a particular element in a collection. Below is the list of some important methods of Collections class.

7) Which are some common methods in Collections utility class?

Collections.max() - This method returns maximum element in the specified collection.
Collections.min() - This method returns minimum element in the given collection.
Collections.sort() - This method sorts the specified collection.
Collections.shuffle() - This method randomly shuffles the elements in the specified collection.
Collections.synchronizedCollection() - This method returns synchronized collection backed by the specified collection.
Collections.binarySearch() - This method searches the specified collection for the specified object using binary search algorithm.
Collections.disjoint() - This method returns true if two specified collections have no elements in common.
Collections.copy() - This method copies all elements from one collection to another collection.
Collections.reverse()- This method reverses the order of elements in the specified collection.

8) Which collection classes are synchronized or thread-safe ?

Stack, Properties , Vector and Hashtable can be used in multi threaded environment because they are synchronized classes (or thread-safe).

9) Name the core Collection  interfaces ?

The core collection interfaces encapsulate different types of collections, which are shown in the figure below.

10) What is an Iterator?

Iterator interface provides methods to iterate over any Collection. We can get iterator instance from a Collection using iterator() method. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection during the iteration. Java Collection iterator provides a generic way for traversal through the elements of a collection and implements Iterator Design Pattern.

11) What is difference between Enumeration and Iterator interface?

Iterator interface is introduced from JDK 1.2 where as Enumeration interface is there from JDK 1.0.

This is the main difference between Enumeration and Iterator interface. Enumeration only traverses the Collection object. You can’t do any modifications to Collection while traversing the Collection using Enumeration. Where as Iterator interface allows us to remove an element while traversing the Collection object. Iterator has remove() method which is not there in the Enumeration interface. Below is the list of Enumeration and Iterator methods.

Enumeration is a legacy interface used to traverse only the legacy classes like Vector, HashTable and Stack. Where as Iterator is not a legacy code which is used to traverse most of the classes in the collection framework. For example, ArrayList, LinkedList, HashSet, LinkedHashSet, TreeSet, HashMap, LinkedHashMap, TreeMap etc.

As Iterator is fail-fast in nature and doesn’t allow modification of a collection by other threads while iterating, it is considered as safe and secure than Enumeration.

12) Why Iterator don’t have a method to get next element directly without moving the cursor?

It can be implemented on top of current Iterator interface but since it’s use will be rare, it doesn’t make sense to include it in the interface that everyone has to implement.

13) What are different ways to iterate over a list?

There are 5 ways you can iterate through List :
For Loop
  • Advanced For Loop
  • Iterator
  • While Loop
  • Collections’s stream() util (Java8)
package interviewguess.com.tutorial;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
/**
 * @author interviewguess.blogspot.com
 */
 
public class InterviewGuessIterateThroughList {
 
 public static void main(String[] argv) {
 
  // create list
  List list = new ArrayList();
 
  // add 4 different values to list
  list.add("Apple");
  list.add("Orange");
  list.add("Banana");
  list.add("Mango");
 
  // iterate via "for loop"
  System.out.println("==> For Loop Example.");
  for (int i = 0; i < list.size(); i++) {
   System.out.println(list.get(i));
  }
 
  // iterate via "New way to loop"
  System.out.println("\n==> Advance For Loop Example..");
  for (String temp : list) {
   System.out.println(temp);
  }
 
  // iterate via "iterator loop"
  System.out.println("\n==> Iterator Example...");
  Iterator iterator = list.iterator();
  while (iterator.hasNext()) {
   System.out.println(iterator.next());
  }
 
  // iterate via "while loop"
  System.out.println("\n==> While Loop Example....");
  int i = 0;
  while (i < list.size()) {
   System.out.println(list.get(i));
   i++;
  }
 
  // collection stream() util: Returns a sequential Stream 
                // with this collection as its source
  System.out.println("\n==> collection stream() util....");
  list.forEach((temp) -> {
   System.out.println(temp);
  });
 }
}

Tuesday 14 February 2017

Multithreading Interview Questions

1) What is the difference between Process and Thread? A process is a self contained execution environment and it can be seen as a program... thumbnail 1 summary
1) What is the difference between Process and Thread?

A process is a self contained execution environment and it can be seen as a program or application whereas Thread is a single task of execution within the process. Java runtime environment runs as a single process which contains different classes and programs as processes. Thread can be called lightweight process. Thread requires less resources to create and exists in the process, thread shares the process resources.

2) What is Multithreading in Java ?

Multithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation etc.

3) What are the different ways of creating thread?

Extend the Thread class and override the run() method in your class. Create an instance of the subclass and invoke the start() method on it, which will create a new thread of execution.
public class NewThread extends Thread{
  public void run(){ 
    // the code that has to be executed in a separate new thread goes here
    } 
    public static void main(String [] args){ 
    NewThread c = new NewThread(); 
    c.start(); 
  }              
}

Implements the Runnable interface.The class will have to implement the run() method in the Runnable interface. Create an instance of this class. Pass the reference of this instance to the Thread constructor a new thread of execution will be created.
public class NewThread implements Runnable{
  public void run(){ 
  // the code that has to be executed in a separate new thread goes here
    } 
  public static void main(String [] args){ 
     NewThread c = new NewThread(); 
     Thread t = new Thread(c);
     t.start();
    }
}

4) What is Life cycle of a Thread (Thread States)?

The different states of threads are as follows:

New – When a thread is instantiated it is in New state until the start() method is called on the thread instance. In this state the thread is not considered to be alive.
Runnable – The thread enters into this state after the start method is called in the thread instance. The thread may enter into the Runnable state from Running state. In this state the thread is considered to be alive.
Running – When the thread scheduler picks up the thread from the Runnable thread’s pool, the thread starts running and the thread is said to be in Running state.
Waiting/Blocked/Sleeping – In these states the thread is said to be alive but not runnable. The thread switches to this state because of reasons like wait method called or sleep method has been called on the running thread or thread might be waiting for some i/o resource so blocked.
Terminated – When the thread finishes its execution i.e. the run() method execution completes, it is said to be in dead state. A dead state can not be started again. If a start() method is invoked on a dead thread a runtime exception will occur.

5) What is use of synchronized keyword?

Synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at a time can access synchronized methods and if there are multiple threads trying to access the same method then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a lock on the object and thus prevents race condition.
public void synchronized method(){} 
  public void synchronized staticmethod(){}
  public void myMethod(){
     synchronized (this){ 
        //synchronized keyword on block of code
     }
  }

6) What is Static synchronization & non static synchronization?

A synchronized method or block works on a given monitor. Synchronized non-static methods all synchronize on the Java instance of a class. Each instance has a lock monitor. For the case of static methods, what object does static synchronized methods use for locking? The static synchronized statements obtain a lock on the Class object.
If you make any static method as synchronized, the lock will be on the class not on object.

7) What is a volatile keyword?

In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased so the count variable is declared as volatile.

The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues.

8) Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?

It is because they are related to lock and object has a lock.

9) Why wait(), notify(), notifyAll() must be called inside a synchronized method/block?

We use wait(), notify(), or notifyAll() method mostly for inter-thread communication in Java.
One thread is waiting after checking a condition e.g. In the classic Producer-Consumer problem, the Producer thread waits if the buffer is full and Consumer thread notify Producer thread after it creates a space in the buffer by consuming an element.

Calling notify() or notifyAll() methods issues a notification to a single or multiple thread that a condition has changed and once notification thread leaves synchronized block, all the threads which are waiting fight for object lock on which they are waiting and lucky thread returns from wait() method after reacquiring the lock and proceed further. Read More....

10) What is ThreadLocal variables? How can it be used?

Below are some key points about ThreadLocal variables

  • A thread-local variable effectively provides a separate copy of its value for each thread that uses it.
  • ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread
  • In case when multiple threads access a ThreadLocal instance, separate copy of Threadlocal variable is maintained for each thread.
  • Common use is seen in DAO pattern where the DAO class can be singleton but the Database connection can be maintained separately for each thread. (Per Thread Singleton)
11) What is the difference between yield() and sleep()?

yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent. If doesn't release the lock on the objects acquired.
sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t releases the lock.

12) What is the difference between wait() and sleep()?

The major difference is that wait() releases the lock or monitor while sleep() doesn’t releases any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution

13) What is join() method?

The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.

14) Is it possible to start a thread twice?

No, there is no possibility to start a thread twice. If you does so, an IllegalThreadStateException is thrown.

Monday 13 February 2017

Why wait(), notify(), notifyAll() must be called inside a synchronized method/block

We use wait(), notify(), or notifyAll() method mostly for inter-thread communication in Java. One thread is waiting after checking a condi... thumbnail 1 summary
We use wait(), notify(), or notifyAll() method mostly for inter-thread communication in Java.
One thread is waiting after checking a condition e.g. In the classic Producer-Consumer problem, the Producer thread waits if the buffer is full and Consumer thread notify Producer thread after it creates a space in the buffer by consuming an element.

Calling notify() or notifyAll() methods issues a notification to a single or multiple thread that a condition has changed and once notification thread leaves synchronized block, all the threads which are waiting fight for object lock on which they are waiting and lucky thread returns from wait() method after reacquiring the lock and proceed further.

Let's understand the problem with an example :
One thread read data from a buffer and one thread write data into buffer. The reading data thread needs to wait until the writing data thread completly write a block data into the buffer. The wirting data thread needs to wait until the reading data thread completly read the data from the buffer. If wait(), notify(), and notifyAll() methods can be called by a ordinary method , the reading thread calls wait() and the thread is being added to waiting queue . At just the same moment, the writing thread calls notify() to signal the condition changes.So due to Race Condition the reading thread misses the change and waits forever.

Now let's think how does this potential race condition get resolved? This race condition is resolved by using synchronized keyword and locking provided by Java. In order to call the wait (), notify () or notifyAll () methods in Java, we must have obtained the lock for the object on which we're calling the method.

Since the wait() method in Java also releases the lock prior to waiting and reacquires the lock prior to returning from the wait() method, we must use this lock to ensure that checking the condition (reading is complete or not) and setting the condition (you can write) is atomic which can be achieved by using synchronized method or block in Java.

Note : We call wait (), notify () or notifyAll method in Java from synchronized method or synchronized block in Java to avoid:

1) IllegalMonitorStateException in Java which will occur if we don't call wait (), notify () or notifyAll () method from synchronized context.

2) Any potential race condition between wait and notify method in Java.

Thursday 9 February 2017

How does clone method work

java.lang.Object provides default implementation of clone() method in Java. It's declared as protected and native in Object class, so i... thumbnail 1 summary
java.lang.Object provides default implementation of clone() method in Java. It's declared as protected and native in Object class, so implemented in native code. Since its convention to return clone() of an object by calling super.clone() method, any cloning process eventually reaches to java.lang.Object clone() method. This method, first checks if the corresponding object implements Cloneable interface, which is a marker interface. If that instance doesn't implement Cloneable then it throws CloneNotSupportedException in Java, a checked exception, which is always required to be handled while cloning an object.
In java, if a class needs to support cloning it has to do following things:

A) You must implement Cloneable interface.
B) You must override clone() method from Object class. [Its weird. clone() method should have been in Cloneable interface.]

Java docs about clone() method are given below (formatted and extract).
/*
Creates and returns a copy of this object. The precise meaning of  "copy" may depend on the class of the object.
The general intent is that, for any object x, the expression:
1) x.clone() != x will be true //guarantees that cloned object will have separate memory address assignment.
2) x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements.//original and cloned objects should have same class type, but it is not mandatory.
3) x.clone().equals(x) will be true, this is not an absolute requirement.//original and cloned objects should have be equal using equals() method, but it is not mandatory.
*/

Lets see an Example :
public class MyClone {
    int x;
    public static void main(String[] args) throws
       CloneNotSupportedException {
        MyClone c = new MyClone();
        MyClone a = (MyClone) c.clone();  // Type-cast is required
    }
}

Because clone() is a part of the Object class, and Object won't implement the Cloneable interface, when our own class will not implement the Cloneable interface, the JVM will not know that this class is eligible for cloning, so CloneNotSupportedException comes out.

Only two thing are possible when we say MyClone a = (MyClone) c.clone();:

Either it will return the cloned object.

Or it will throw CloneNotSupportedException.

As it is clear that it is not mandatory to implement clone() in your class when you want to clone the object, if you don't, the clone() method in Object is declared protected — only subclasses and members of the same package will be able to invoke clone() on the object. If you want to change that, you should override it and make it public.

Checks before the clone() method call:
if(c instanceof Cloneable) {
    MyClone a = (MyClone) c.clone();
}

Note: No constructor gets called when clone() gets called. It's our responsibility to properly set all the member variables of that class.

Implementation
Room.java
public class Room {
 private String roomSize;
 public Room(String roomSize){
  this.roomSize = roomSize;
}
 //Any Getters-Setters goes here
}
Flat.java
public class Flat implements Cloneable {
 private String flatNumber;
 private Room room;
 public Flat(String size,Room room){
   this.size = size;
   this.room = room;
 }
 public Object clone() {
  try {
   return (Flat)super.clone();
 }
  catch (CloneNotSupportedException e) {
   System.out.println("CloneNotSupportedException comes out : "
   +e.getMessage());
  }
 }
//Any Getters-Setters goes here
}
Main.java
public class Main {
  public static void main(String[] args) {
   Room room = new Room("40 X 40");
   Flat flat1 = new Flat(403 , room);
   Flat flat2 = (Flat)flat1.clone();
  }
}

Here super.clone() is getting called inside clone(). As we know, clone() is declared in Object, so it is inherited by every Java object. Calling super.clone() copies our superclass' fields and makes bitwise copies of the fields. This known as shallow copy, which means when you copy Flat using clone(), the field's flatNumber is getting copied with their respective values, but room is copied by reference — bit by bit, the memory address is getting copied.

Any changes you make to room of the original object will be reflected in the cloned object and vice versa. To solve this, we need deep copy. Now, we need to change the Room class as well implement the "Cloneable" interface and clone() method, then call the clone() method of the Room object inside the clone() method of the Flat object.

New Implementation
Room.java
public class Room {
    private String roomSize;
    public Room(String roomSize){
       this.roomSize = roomSize;
   }
    public Object clone() {
       try {
         return (Room)super.clone();
     }
      catch (CloneNotSupportedException e) {
       System.out.println("CloneNotSupportedException comes out : "
    +e.getMessage());
     }
   }
   //Any Getters-Setters goes here
}
Flat.java
public class Flat implements Cloneable {
    private String flatNumber;
 private Room room;
 public Flat(String size,Room room){
   this.size = size;
   this.room = room;
 }
    public Object clone() {
      Flat flat = null;
      try {
         flat = (Flat)super.clone();
     }
      catch (CloneNotSupportedException e) {
          System.out.println("CloneNotSupportedException comes out : "
    +e.getMessage());
     }
     flat.room = (Room) room.clone();
         return flat;
   }
    //Any Getters-Setters goes here
}
Main.java
public class Main {
    public static void main(String[] args) {
       Room room = new Room("40 X 40");
       Flat flat1 = new Flat(403, room);
       Flat flat2 = (Flat)flat1.clone();
   }
}

I hope that this will give a better understanding of cloning and its implementation.

Tuesday 7 February 2017

String Interview Questions

1) What is string constant pool? String objects are most used data objects in Java. Hence, java has a special arrangement to store t... thumbnail 1 summary
1) What is string constant pool?

String objects are most used data objects in Java. Hence, java has a special arrangement to store the string objects. String Constant Pool is one such arrangement. String Constant Pool is the memory space in heap memory specially allocated to store the string objects created using string literals. In String Constant Pool, there will be no two string objects having the same content.
Whenever you create a string object using string literal, JVM first checks the content of the object to be created. If there exist an object in the string constant pool with the same content, then it returns the reference of that object. It doesn’t create a new object. If the content is different from the existing objects then only it creates new object.

2) What is special about string objects as compared to objects of other derived types?

One special thing about string objects is that you can create string objects without using new operator i.e using string literals. This is not possible with other derived types (except wrapper classes). One more special thing about strings is that you can concatenate two string objects using ‘+’. This is the relaxation java gives to string objects as they will be used most of the time while coding. And also java provides string constant pool to store the string objects.

3) What do you mean by mutable and immutable objects?

Immutable objects are like constants. You can’t modify them once they are created. They are final in nature. Where as mutable objects are concerned, you can perform modifications to them.

4) Why string objects are immutable in java?

String is immutable for several reasons, here is a summary:

  • Security: parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.
  • Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues.
  • Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object).
  • Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).

That being said, immutability of String only means you cannot change it using its public API. You can in fact bypass the normal API using reflection.

5) How many ways we can create the string object?

There are two ways to create the string object, by string literal and by new keyword.
We can create String object using new operator like any normal java class or we can use double quotes (string literal) to create a String object.
String str = new String("abc");
String str1 = "abc";

When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.
When we use new operator, JVM will create a new string object in normal(non pool) heap memory and the literal "abc" will be placed in the string constant pool. The variable str will refer to the object in heap(non pool).

6) Which one will you prefer among “==” and equals() method to compare two string objects?

I prefer equals() method because it compares two string objects based on their content. That provides more logical comparison of two string objects. If you use “==” operator, it checks only references of two objects are equal or not. It may not be suitable in all situations. So, rather stick to equals() method to compare two string objects.
String s1 = "JAVA";
 
String s2 = "JAVA";
s1 == s2 —> will return true as both are pointing to same object in the constant pool.
s1.equals(s2) —> will also return true as both are referring to same object.
String s1 = new String("JAVA");
 
String s2 = new String("JAVA");
s1 == s2 —> will return false because s1 and s2 are referring to two different objects in the memory.
s1.equals(s2) —> will return true as both the objects have same content.

7) What is Difference Between String , StringBuilder And StringBuffer Classes?

String
String is immutable  ( once created can not be changed )object  . The object created as a String is stored in the  Constant String Pool  .
Every immutable object in Java is thread safe ,that implies String is also thread safe . String can not be used by two threads simultaneously.
String  once assigned can not be changed.
String  demo = " hello " ;
// The above object is stored in constant string pool 
// and its value can not be modified.

demo="Bye" ;     //new "Bye" string is created in constant pool 
// and referenced by the demo variable            
// "hello" string still exists in string constant pool and its value 
// is not overrided but we lost reference to the  "hello"string  

StringBuffer
StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap . StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .
Due to this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .
But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.
StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .
String Buffer can be converted to the string by using
toString() method.
StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed .
demo1=new StringBuffer("Bye");
// Above statement is right as it modifies the value 
// which is allowed in the StringBuffer

StringBuilder
StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe.
StringBuilder is fast as it is not thread safe .  
StringBuilder demo2= new StringBuilder("Hello");
// The above object too is stored in the heap and its value can be 
// modified
demo2=new StringBuilder("Bye"); 
// Above statement is right as it modifies the value which is 
// allowed in the StringBuilder

8) How to create Immutable class?

To create immutable class in java, you have to do following steps.
  • Declare the class as final so it can’t be extended.
  • Make all fields private so that direct access is not allowed.
  • Don’t provide setter methods for variables
  • Make all mutable fields final so that it’s value can be assigned only once.
  • Initialize all the fields via a constructor performing deep copy.
  • Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.
import java.util.HashMap;
import java.util.Iterator;

public final class FinalClassExample {

 private final int id;
 
 private final String name;
 
 private final HashMap testMap;
 
 public int getId() {
  return id;
 }


 public String getName() {
  return name;
 }

 /**
  * Accessor function for mutable objects
  */
 public HashMap getTestMap() {
  //return testMap;
  return (HashMap) testMap.clone();
 }

 /**
  * Constructor performing Deep Copy
  * @param i
  * @param n
  * @param hm
  */
 
 public FinalClassExample(int i, String n, HashMap hm){
  System.out.println("Performing Deep Copy for Object 
                initialization");
  this.id=i;
  this.name=n;
  HashMap tempMap=new HashMap();
  String key;
  Iterator it = hm.keySet().iterator();
  while(it.hasNext()){
   key=it.next();
   tempMap.put(key, hm.get(key));
  }
  this.testMap=tempMap;
 }
 
 
 /**
  * Constructor performing Shallow Copy
  * @param i
  * @param n
  * @param hm
  */
 /**
 public FinalClassExample(int i, String n, HashMap hm){
  System.out.println("Performing Shallow Copy for Object 
                initialization");
  this.id=i;
  this.name=n;
  this.testMap=hm;
 }
 */
 
 /**
  * To test the consequences of Shallow Copy and how to avoid it
         * with Deep Copy for creating immutable classes
  * @param args
  */
 public static void main(String[] args) {
  HashMap h1 = new HashMap();
  h1.put("1", "first");
  h1.put("2", "second");
  
  String s = "original";
  
  int i=10;
  
  FinalClassExample ce = new FinalClassExample(i,s,h1);
  
  //Lets see whether its copy by field or reference
  System.out.println(s==ce.getName());
  System.out.println(h1 == ce.getTestMap());
  //print the ce values
  System.out.println("ce id:"+ce.getId());
  System.out.println("ce name:"+ce.getName());
  System.out.println("ce testMap:"+ce.getTestMap());
  //change the local variable values
  i=20;
  s="modified";
  h1.put("3", "third");
  //print the values again
  System.out.println("ce id after local variable change:"
                +ce.getId());
  System.out.println("ce name after local variable change:"
                +ce.getName());
  System.out.println("ce testMap after local variable change
                :"+ce.getTestMap())
  
  HashMap hmTest = ce.getTestMap();
  hmTest.put("4", "new");
  
  System.out.println("ce testMap after changing variable 
                from accessor methods:"+ce.getTestMap());

 }

}
Output of the above immutable class in java example program is:

Performing Deep Copy for Object initialization
  • true
  • false
  • ce id:10
  • ce name:original
  • ce testMap:{2=second, 1=first}
  • ce id after local variable change:10
  • ce name after local variable change:original
  • ce testMap after local variable change:{2=second, 1=first}
  • ce testMap after changing variable from accessor methods:{2=second, 1=first}

Now let’s comment the constructor providing deep copy and uncomment the constructor providing shallow copy. Also uncomment the return statement in getTestMap() method that returns the actual object reference and then execute the program once again.

Performing Shallow Copy for Object initialization
  • true
  • true
  • ce id:10
  • ce name:original
  • ce testMap:{2=second, 1=first}
  • ce id after local variable change:10
  • ce name after local variable change:original
  • ce testMap after local variable change:{3=third, 2=second, 1=first}
  • ce testMap after changing variable from accessor methods:{3=third, 2=second, 1=first, 4=new}
  • As you can see from the output, HashMap values got changed because of shallow copy in the constructor and providing direct reference to the original object in the getter function.