Monday, September 21, 2015

Move all zeroes to end of array

http://www.geeksforgeeks.org/move-zeroes-end-array/


void pushZerosToEnd(int arr[], int n)
{
    int count = 0;  // Count of non-zero elements
 
    // Traverse the array. If element encountered is non-zero, then
    // replace the element at index 'count' with this element
    for (int i = 0; i < n; i++)
        if (arr[i] != 0)
            arr[count++] = arr[i]; // here count is incremented
 
    // Now all non-zero elements have been shifted to front and 'count' is
    // set as index of first 0. Make all elements 0 from count to end.
    while (count < n)
        arr[count++] = 0;
}
 
// Driver program to test above function
int main()
{
    int arr[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9};
    int n = sizeof(arr) / sizeof(arr[0]);
    pushZerosToEnd(arr, n);
    cout << "Array after pushing all zeros to end of array :\n";
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    return 0;
}

[Java] Java Knowledge

What is difference between an array and an ArrayList in Java? (answer)
What is difference between ArrayList and Vector in Java? (answer)
Difference between LinkedList and ArrayList in Java? (answer)
What is difference between HashSet and ArrayList in Java? (answer)
What is difference between ArrayList and HashMap in Java? (answer)





https://upload.wikimedia.org/wikipedia/commons/f/f8/Java_collection_framework.jpg 


How hashtable make their method synchronized

1. not allow null key or values[don’t know it is really null or just being deleted,], 2. synchronized all methods(    size(), containsKey(), get(), put() ), 3.map wide lock
This synchronized keyword in method of Hashtable class makes Hashtable thread safe.


public synchronized int size() {
   return count;
}
public synchronized boolean containsKey(Object key) {
   Entry tab[] = table;
   int hash = key.hashCode();
   int index = (hash & 0x7FFFFFFF) % tab.length;
   for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
       if ((e.hash == hash) && e.key.equals(key)) {
       return true;
       }
   }
   return false;
}
    
public synchronized V get(Object key) { // concurrentHashMap do not block on retrieval
   Entry tab[] = table;
   int hash = key.hashCode();
   int index = (hash & 0x7FFFFFFF) % tab.length;
   for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
       if ((e.hash == hash) && e.key.equals(key)) {
       return e.value;
       }
   }
   return null;
}
    
public synchronized V put(K key, V value) {
   // Make sure the value is not null
   if (value == null) {
       throw new NullPointerException();
   }
   // Makes sure the key is not already in the hashtable.
   Entry tab[] = table;
   int hash = key.hashCode();
   int index = (hash & 0x7FFFFFFF) % tab.length;
   for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
       if ((e.hash == hash) && e.key.equals(key)) {
       V old = e.value;
       e.value = value;
       return old;
       }
   }
   modCount++;
   if (count >= threshold) {
       // Rehash the table if the threshold is exceeded
       rehash();
           tab = table;
           index = (hash & 0x7FFFFFFF) % tab.length;
   }
   // Creates the new entry.
   Entry<K,V> e = tab[index];
   tab[index] = new Entry<K,V>(hash, key, value, e);
   count++;
   return null;
}
Reference:


How ConcurrentHashMap make it separate synchronized

1. get() do not synchornized, 2.each thread work on different bucket,3.iterator -safe,4. not allow null key so unlike HashMap[don’t know it is really null or just being deleted,]
HashMap[putForNullKey(V value) and getForNullKey()]

The hash map is built on an array, where the hash function maps an object to an element in the underlying array. Let's say the underlying array has 1024 elements - ConcurrentHashMap actually turns this into 16 different sub-arrays of 64 elements, e.g. {0, 63}, {64, 127}, etc. Each sub-array has its own lock, so modifying the {0, 63} sub-array doesn't impact the {64, 127} sub-array - one thread can write to the first sub-array while another thread writes to the second sub-array.
1.The constructor of ConcurrentHashMap looks like this :

public ConcurrentHashMap (int initialCapacity, float loadFactor, int concurrencyLevel)
static final int DEFAULT_INITIAL_CAPACITY = 16;//16 locks
static final int DEFAULT_CONCURRENCY_LEVEL = 16;//  16 threads

initial capacity parameter and concurrency level parameters of ConcurrentHashMap constructor (or Object) are  set to 16 by default.
Thus, instead of a map wide lock, ConcurrentHashMap maintains  a list of 16 locks by default ( number of locks equal to the initial capacity , which is by default  16) each of which is used to lock on a single bucket of the Map.This indicates that 16 threads (number of threads equal to the concurrency level , which is by  default 16) can modify the collection at the same time , given ,each thread works on different bucket. So unlike hashtable, we perform any sort of operation ( update ,delete ,read ,create) without locking on entire map in ConcurrentHashMap.

Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove).
Retrievals reflect the results of the most recently completed update operations holding upon their onset.

2. Interviewer : Can two threads update the ConcurrentHashMap simultaneously ?

                                                    
Yes it is possible that two threads can simultaneously write on the ConcurrentHashMap. ConcurrentHashMap default implementation allows 16 threads to read and write in parallel.
But in the worst case scenario , when two objects lie in the same segment or same partition, then parallel write would not be possible.

Using a significantly higher value than you need can waste space and time, and a significantly lower value can lead to thread contention

3.Interviewer : Why ConcurrentHashMap does not allow null keys and null values ?


you can't detect whether the key explicitly maps to null vs the key isn't mapped. In a non-concurrent map, you can check this via map.contains(key), but in a concurrent one, the map might have changed between calls.

if (map.containsKey(k))// Thread 1 read not null while  Thred2 is Deleting
{
    return map.get(k);// Thread 1 get null since Thread2 finish deleting
                                // And we don’t know it is really null or just being deleted, SO concurrentHashMap doesn’t allow NULL key. And we know when null it must just be deleted
}
else
{
    throw new KeyNotPresentException();
}

It might be possible that key k might be deleted in between the get(k) and containsKey(k) calls. As a result , the code will return null as opposed to KeyNotPresentException (Expected Result if key is not present).

4.Interviewer : Can multiple threads read from the Hashtable concurrently ?

No multiple threads can not read simultaneously from Hashtable. Reason, the get() method of  Hashtable is synchronized. As a result , at a time only one thread can access the get() method .
It is possible to achieve full  concurrency for reads (all the threads read at the same time) in  ConcurrentHashMap by using volatile keyword.

5.Interviewer: Does ConcurrentHashMap Iterator behaves like fail fast iterator or fail safe Iterator?

ConcurrentHashMap iterator behaves like fail safe iterator. It will not throw ConcurrentModificationException . We have already discussedFail Fast Iterator vs Fail Safe Iterator.

6.
Recap : Difference between Fail Fast Iterator and Fail Safe Iterator 


Fail Fast IteratorFail Safe Iterator
Throw ConcurrentModification ExceptionYesNo
Clone objectNoYes
Memory OverheadNoYes
ExamplesHashMap,Vector,ArrayList,HashSet
CopyOnWriteArrayList,
ConcurrentHashMap
http://javahungry.blogspot.com/2014/04/fail-fast-iterator-vs-fail-safe-iterator-difference-with-example-in-java.html

import java.util.concurrent.ConcurrentHashMap;
import java.util.Iterator;


public class ConcurrentHashMapExample
{
   
   
   public static void main(String[] args)
   {
       ConcurrentHashMap<String,String> premiumPhone = new ConcurrentHashMap<String,String>();
       premiumPhone.put("Apple", "iPhone6");
       premiumPhone.put("HTC", "HTC one");
       premiumPhone.put("Samsung","S6");
       
       Iterator iterator = premiumPhone.keySet().iterator();
       
       while (iterator.hasNext())
       {
           System.out.println(premiumPhone.get(iterator.next()));
           premiumPhone.put("Sony", "Xperia Z");
       }
       
   }
   
}
Output :
S6
HTC one
iPhone6

What is difference between an array and an ArrayList in Java?
Array
ArrayList
1)SIZE First and Major difference between Array and ArrayList in Java is that Array is a fixed length data structure while ArrayList is a variable length Collection class. You can not change length of Array once created in Java but ArrayList re-size itself when gets full depending upon capacity and load factor. Since ArrayList is internally backed by Array in Java, any resize operation in ArrayList will slow down performance as it involves creating new Array and copying content from old array to new array.
fixed size vs. dynamic size

2)DATA TYPE Another difference between Array and ArrayList in Java is that you can not use Generics along with Array, as Array instance knows about what kind of type it can hold and throws ArrayStoreException, if you try to store type which is not convertible into type of Array. ArrayList allows you to use Generics to ensure type-safety.
Primitive data type vs. Object

3)LENGTH You can also compare Array vs ArrayList on How to calculate length of Array or size of ArrayList. All kinds of Array provides length variable which denotes length of Array while ArrayList provides size() method to calculate size of ArrayList in Java.
.length vs. .size()

4)OBJECT One more major difference between ArrayList and Array is that, you can not store primitives in ArrayList, it can only contain Objects. While Array can contain both primitives and Objects in Java. Though Autoboxing of Java 5 may give you an impression of storing primitives in ArrayList, it actually automatically converts primitives to Object. e.g.
char[],int[],double[] vs. List<Character>,List<Inetger>,List<Double>

5)ADD() Java provides add() method to insert element into ArrayList and you can simply use assignment operator to store element into Array e.g. In order to store Object to specified position use
[i] = 5 vs. .add(5)

6)SIZE SPECIFYING One more difference on Array vs ArrayList is that you can create instance of ArrayList without specifying size, Java will create Array List with default size but its mandatory to provide size of Array while creating either directly or indirectly by initializing Array while creating it. By the way you can also initialize ArrayList while creating it.
new int[5] vs. new ArrayList<Integer>()



What is difference between an ArrayList and Vector in Java?
ArrayList:array and size

Not Thread-Safe

But how to make it Thread-Safe? Java5 add another feature as below !!!

ConcurrentHashMap for Hashtable and CopyOnWriteArrayList for ArrayList

1. read only ArrayList =>Collections.unmodifiableList()

2. synchronized list[1] => Collections.synchronizedList()

3. (# of read > # of write, size is tiny )[2][3] =>new CopyOnWriteArrayList()


[1]number of write operation is high then sticking with synchronized list is better option because cost of copying list would outweigh gain made by sacrificing locking
[2]consider is size of ArrayList, if its big then obviously cost of copying after a write operation is high enough to compensate cost of locking but if 
[3]ArrayList is really tiny then you can still use CopyOnWriteArrayList.
Vector

Thread-Safe
SIMILARITY

1) Vector and ArrayList are index based and backed up by an array internally.
2) Both ArrayList and Vector maintains the insertion order of element. Means you can assume that you will get the object in the order you have inserted if you iterate over ArrayList or Vector.
3) Both Iterator and ListIterator returned by ArrayList and Vector are fail-fast.(vector’s elements () method which is not fail-fast )
4) ArrayList and Vector also allows null and duplicates.

DIFFERENCE

1) Synchronization and thread-safety

all the method which structurally modifies Vector e.g. add () or remove () are synchronized
Not Thread-safe vs. Thread safe

2) Speed and Performance

ArrayList is way faster than Vector. You can also useArrayList in a multi-threaded environment if multiple threads are only reading values from ArrayList or you can create read only ArrayList as well.
Faster vs. Slower

3) Capacity

Vector  increases itself by value specified in capacityIncrement field
ArrayList ensureCapacity () method.
.ensureCapacity() vs. .capacityIncrement

4) Enumeration and Iterator

Vector can return enumeration of items it hold by calling elements () method which is not fail-fast
Iterator and ListIterator returned by ArrayList.
Iterator/ListIterator fail-fast vs. elements() not fail-fast

5) Legacy

Vector JDK 1.0 and initially not part of Collection framework but in later version it's been re-factored to  implement List interface so that it could become part of collection framework

Think for CopyOnWriteArrayList  over Vector, if you have multiple readers and few writers because it can provide thread-safety without impacting performance too much.
CopyOnWriteArrayList vs. Vector


1.Java 5 adds another implementation of List interface which is similar to Vector and ArrayList but provides better concurrency access than Vector, its called CopyOnWriteArrayList.


public class MyArrayList
{ //  COnstructor(), size(), add(), get(), remove(), resize()


      private Object[] myStore;
      private int actSize = 0;


      /*Constructor*/
      public MyArrayList()
      {
            myStore = new Object[10];      
      }



      /*O(1), Get the object given the index*/
      public Object get(int index)
      {
              if (index < actSize)
                    return myStore[index];
              else
                    throw new ArrayIndexOutOfBoundsException();
      }


      /*O(1), Add Object into the array Given the Object */
     public void add(Object obj)
     {
             //validate input ?(null allowed), append, size out of bound,
             if (  myStore.length - actSize <= 5 )
                   increaseListSize();
             myStore[actSize++] = obj;
     }

 
     /*O(n), Remove Object from the array given the index*/
     public Object remove(int index)
     {
              // validate the input, empty or not, reindexing after remove specific index out
              // idx 0  1  2  3  4  5
              //       a  b  s  o  l   u
              //               X
              //       a  b  “”  o  l  u  (nullify)
              //       a  b  o  l   u  “” (compact)
              if (index < actSize)
              {
                     Obejct obj = myStore[index];
                     myStore[index] = null;
                     int tmp = index;
                     while ( tmp < actSize) // O(n)
                     {
                           myStore[tmp]= mySotre[tmp+1];
                           myStore[tmp+1] = null;
                           tmp++;
                     }
                     actSize--;
                     return obj;
              }
              else
              {
                     throw new ArrayIndexOutOfboundsException();
              }
     }

      
     /* Get the size of the array*/
     public int size()
     {
              return actSize;
     }     


    /* Increase the size of the array when about to exceed the capacity*/
    private void increaseListSize()
   {
              // size make it bigger , but put all the old elements inside it
              myStore = Arrays.copyOf(mystore, myStore.length*2);
   }

public static int[] copyOf(int[] original, int newLength) {
  int[] copy = new int[newLength];
  System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));
  return copy;
}

}  





What is difference between an ArrayList and LinkedList in Java?
When to use ArrayList vs LinkedList in Java

ArrayList and LinkedList
vs. get()             O(1)            O(n)[O(n/2) traverse]
vs. add()            O(1) [O(logn) if resize]           O(1)
vs. remove(index)     O(n)[remove and shift around COPY operation]             O(n)[O(n/2) traverse from either direction]


Memory      less[except resize()] more
0. LinkedList FIFO, Dequeue Itnerface, add() and poll(), doubly-linked list and navigation happen from either end
  1. uses a wrapper object, Entry,  which is a static nested class for storing data and two nodes next and previous VS  just store data in Array
  2. Array performs re-size operation, when it copies content from one Array to another. If Array is large enough it may take lot of memory at that point and trigger Garbage collection, which can slow response time.

1.implementation of List interface
3.maintain insertion order
4.allows duplicates and null unlike any other List implementation e.g. Vector
5. fail-fast which means they will throw ConcurrentModificationException
6.Array vs LinkedList.


What is difference between an ArrayList and HashSet in Java?

Difference between ArrayList and HashSet in Java

DIFFERENCE
List implementation VS Set implementation
Array VS hashMap
get() VS no get() [contains() and add()]
duplicate vs no duplicate
ORdered VS not Guaranteed
Random access (index) VS Iterate
SIMILARITIES
  1. Collection class
  2. Not synchronized(  Collections.synchronizedCollection()  )
  3. fail-fast, i.e. they will throwConcurrentModificationException


What is difference between an ArrayList and HashMap in Java?

Difference between HashMap and ArrayList in Java

SIMILARITIES
1.Collection class
2.store objects
3.not synchronized
4.fail-fast
5.allow null
6.allow duplicate
7.get() O(1) and get() O(1)
8.ArrayList <-array and HashMap <-array [get() O(1)] and BST[get() O(logn)]
9.traversed through Iterator
DIFFERENCES
1.
ArrayList: contains()  method of ArrayList will use equals() method to see if that object already exists or not
HashMap :    keys of HashMap must implements equals and hashCode method correctly
2.
ArrayList: allows duplicates
HashMap: doesn't allow duplicates key, though it allows duplicate values



How HashSet Internally Works in Java
boolean add()[use put()], boolean contains()[use equals() method for comparing object for matching.], get()[return map.keySet().iterator()]
1.HashSet:it uses same values for all keys
2. Remember to override equals() and hashCode() for any object you are going to store in HashSet, since your object is used as key in backup Map, it must override those method.
3.Make your object Immutable or effective immutable if possible
Since element of HashSet is used as key in backup HashMap
/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
 * default initial capacity (16) and load factor (0.75).
 */
public HashSet() {
  map = new HashMap<>();
}
As you can see below, a call to add(Object) is delegate to put(Key, Value) internally, where Key is the object you have passed and value is another object,  called PRESENT, which is a constant in java.util.HashSet as shown below

private transient HashMap<E,Object> map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public boolean add(E e) {
  return map.put(e, PRESENT)==null;
}
Since PRESENT is a constant, for all keys we have same value in backup HashMap called map.
map.keySet().iterator() method.
      /**
   * Returns an iterator over the elements in this set.  The elements
    * are returned in no particular order.
    *
    * @return an Iterator over the elements in this set
    * @see ConcurrentModificationException
    */
   public Iterator<E> iterator() {
       return map.keySet().iterator();
   }






HashTable and HashMap
HashTable
1.ConcurrentModificationException
HashMap
1.ConcurrentModificationException
-1.Concept of hashing
-2.Collision resolution in HashMap
-3.Use of equals () and hashCode () and there importance in HashMap?
-4.Benefit of immutable object?
-5.Race condition on HashMap  in Java
-6.Resizing of Java HashMap
Step1.5:applying hashing on that hashcode
Ste2: stored in next node of linked list
Map.Entry object

Important 0:
How null key is handled in HashMap? Since equals() and hashCode() are used to store and retrieve values, how does it work in case of null key?

Null key is handled specially in HashMap, there are two separate method for that putForNullKey(V value) and getForNullKey(). Later is offloaded version of get() to look up null keys.  Null keys always map to index 0.  This null case is split out into separate methods for the sake of performance in the two most commonly used operations (get and put), but incorporated with conditionals in others. In short, equals() and hashcode() method are not used in case of null keys in HashMap.

here is how nulls are retreived from HashMap

  private V getForNullKey() {
      // Case1: Empty
      if (size == 0) {
           return null;
       }
      // Case2: search table[0] for key == null
       for (Entry<K,V> e = table[0]; e != null; e = e.next) {
           if (e.key == null)
               return e.value;
       }
       // Case3: Not Found, just return null
       return null;
   }

used HashMap as cache in electronic trading application I have worked
A cache is an area of local memory that holds a copy of frequently accessed data that is otherwise expensive to get or compute. Examples of such data include
1.a result of a query to a database,
2.a disk file or a report.

Important 1:
HashMap Changes in JDK 1.7 and JDK 1.8?

Problem1: which reduce memory consumption. Due to this empty Map are lazily initialized and will cost you less memory. Earlier, when you create HashMap e.g. new HashMap() it automatically creates array of default length e.g. 16. After some research, Java team founds that most of this Map are temporary and never use that many elements, and only end up wasting memory.

Problem2: Since a poor hash function e.g. which always return location of same bucket, can turn a HashMap into linked list, i.e. converting get() method to perform in O(n) instead of O(1) and someone can take advantage of this fact, Java now internally replace linked list to a binary tree once certain threshold is breached. This ensures performance or order O(log(n)) even in worst case where hash function is not distributing keys properly.



Important 1:
Do you Know how HashMap works in Java or How does get () method of HashMap works in Java ?

HashMap works on principle of hashing, we have put(key, value) and get(key) method for storing and retrieving Objects from HashMap. When we pass Key and Value object  to put() method on Java HashMap, 1.HashMap implementation calls hashCode method on Key object and
2.applies returned hashcode into its own hashing function to find a bucket location for storing Entry object,
3.important point to mention is that HashMap in Java stores both key and value object as Map.Entry in bucket which is essential to understand the retrieving logic.
Important 2:
What will happen if two different objects have same hashcode?

1.hashCode() and equals() contract  that two unequal object in Java can have same hash code.
2.Since hashcode is same, bucket location would be same and collision will occur in HashMap, Since HashMap use LinkedList to store object, this entry (object of Map.Entry comprise key and value )  will be stored in LinkedList.

Important3:
How will you retrieve Value object  if two Keys will have same hashcode?

1. call get() method and HashMap uses Key Object's hashcode to find out bucket location
2.we will call keys.equals() method to identify correct node in LinkedList and return associated value object for that key in Java HashMap
3.immutable, final object with proper equals()
4,Immutability also allows caching there hashcode of different keys which makes overall retrieval process very fast and suggest that String and various wrapper classes e.g. Integer very good keys in Java HashMap.


Important4:
What happens On HashMap in Java if the size of the HashMap  exceeds a given threshold defined by load factor ?
1.if load factor is .75 it will act to re-size the map once it filled 75%

2.Java HashMap re-size itself by creating a new bucket array of size twice of previous size of HashMap ,
3.and then start putting every old element into that new bucket array.
4.This process is called rehashing because it also applies hash function to find new bucket location

Important5:
do you see any problem with resizing of HashMap  in Java

1.multiple thread accessing the Java HashMap and potentially looking for race condition on HashMap  in Java

2.potential race condition exists while resizing HashMap in Java, if two thread at the same time found that now HashMap needs resizing and they both try to resizing

3.on the process of resizing of HashMap in Java , the element in bucket which is stored in linked list get reversed in order during there migration to new bucket because Java HashMap  doesn't append the new element at tail instead it append new element at head to avoid tail traversing. If race condition happens then you will end up with an infinite loop


Important 6:
Why String, Integer and other wrapper classes are considered good keys ?
1.String is most frequently used key as well because String is immutable and final,and overrides equals and hashcode() method
2.Immutabiility is required, in order to prevent changes on fields used to calculate hashCode() because if key object return different hashCode during insertion and retrieval than it won't be possible to get object fromHashMap
3.Immutability is best as it offers other advantages as well like thread-safety, If you can  keep your hashCode same by only making certain fields final, then you go for that as well
4.Since equals() and hashCode() method is used during reterival of value object from HashMap, its important that key object correctly override these methods and follow contact.

5. Ofcourse you can use any Object as key in Java HashMap provided it follows equals and hashCode contract and its hashCode should not vary once the object is inserted into Map.If custom object is Immutable than this will be already taken care because you can not change it once created




Reference:
synchronized
not allow null keys or values
Iterator not Fail-Fast and throw ConcurrentModificationException[if any other Thread modifies the map structurally  by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort. This is also an important difference between Enumeration and Iterator in Java. Read more: http://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.html#ixzz3lSOMhIqd]

No LinkedHashTbale

map.put(3, null) throw NullPointerException at runtime
    









  1. not synchronized [ConcurrentHashMap which is an alternative of HashTable and provides better scalability than HashTable in Java]
  2. allow ONE null key and any number of null vlaues
  3. Fail-fast iterator
  4. LinkedHashMap to get insertion order
  5. Map m = Collections.syncrhonizedMap(hashmap)[HashMap can be synchronized by]

synchronized(mymap){
  if ( !map.containsKey(“tomato”))
      mymap.put(“tomato”,”red”)
}
  
map.put(3,null);// okay
map.put(null, “UK”); // okay
Since searching in lined list is O(n) operation, in worst case hash collision reduce a map to linked list. This issue is recently addressed in Java 8 by replacing linked list to tree to search in O(logN) time.







HashTable and ConcurrentHashMap
ConcurrentHashMap

ConcurrentHashMap ( get() do not synchornized ) and CopyOnWriteArrayList (provides reading without lock)
HashTable( synchronized collection classes: Vector, Collections.synchronizedMAp(), Collections.synchronizedList() => single collection-wide lock is an impediment to scalability and often lock a collection for a considerable time during iteration to prevent ConcurrentModificationException)
Synchronized Map
  1. It is also very scalable (16 threads) of stripped locking technique used in internal implementation of ConcurrentHashMap class.
  2. [Unlike hashtable and synchronized map], it NEVER lock whole map, instead it divides the map in segments and locking is done on those.
  3. hashtable and vector become bottleneck due to lack of SCALABILITY.
  4. ConcurrentHashMap and CopyOnWriteArrayList
  5. Segmentation make how large it becomes only certain part of it get locked to provide thread-safety

- the overhead created by Hashtable  (locking the entire map) can be ignored under normal load. But under heavy load , the overhead of locking the entire map may prove fatal and may lead to delay response time and   overtaxing of the server
-only provide method-level (when two threads call PUT at the same time)protection against race conditions
- will not become internally corrupted if multiple threads are concurrently trying to modify the data
- Not a higher -level synchonization, the possibility of having a race when calling multiple methods outside of a synchronized block, so you need a synchronized block anyway, use lower-overhead HashMap rahter than a Hashtable
if(!hashtable.contains(key)){ hashtable.put(key,value); }

synchronized { if(!hashtable.contains(key)){ hashtable.put(key,value); }
}

  1. uses synchronized methods to achieve thread-safety. All methods of HashTable are synchronized which make them quite slow due to contention(lock entire map bucket ) if number of thread increases.


  1. [Hashtable vs synchronized map] the later is not a legacy and you can wrap any map to create it’s synchronized version by using Collections.synchronizedMap() method.


even with a thread safe data structue (be it a HashTable or a ConcurrentMap), you still need to deal with concurrency issues such as atiomcity


double johnBalance = balance.get(“John”);// read
if (  johnBalance > paymentAmount )
       authorisePayment();
else
      declinePayment();

There is an atomicity issue: the balance on John’s account might have changed berween the call to balance.get(..) and the payment authorization.

Use assitonal layer of sybchronization






Abstract class
skeletal, default implementation
base class is evolving and keep changing.

COupling
Interface
contract, only
change every single implementation to include that change
decoulping
return type or argumnet(dependence injection)
designing should lead to
reduce coupling
increased cohesion,
ease of maintenance
understanding of OOPS concepts like Polymorphism, Encapsulation, Abstraction and Inheritance.

----DIFFERENCE ---
1) Interface only contains declaration. not concrete methods inside.
abstract class both abstract and concrete methods, ideal place to provide common or default functionality.
no implementation/part of implementation VS. no implementation
2) interface extend multiple interface Java class can implement multiple interfaces, more Polymorphism support than abstract class .
abstract class, a class can only participate in one Type hierarchy but by using interface it can be part of multiple type hierarchies.
E.g. a class can be Runnable and Displayable at same time.
GUI application in J2ME, where  class extends Canvas and implements CommandListener to provide bothgraphic and event-handling functionality.
one inheritance VS. multiple inheriance
3) interface need to provide implementation of all methods, which is very painful.
abstract class may help you in this case by providing default implementation.
If you look JDK or any framework like Spring, which I does to understand OOPS and design patter better,
interface contains only one or two methods e.g. Runnable, Callable, ActionListener etc.
extend abstract class=> part implementation VS. implement interface =>full implemntation

---WHEN TO USE ----
1) multiple inheritance is not supported in Java.
abstract class over interface than you lost your chance to extend another class, implement multiple interfaces to show that you have multiple capability.
common example, in favor of interface over abstract class is Thread vs Runnable case.
execute a task and need run()method better to implement Runnable interface than extending Thread class.
2) abstract class can include concrete methods, it’s great for maintenance point of view, particularly when your base class is evolving and keep changing. just define new functionality in abstract super class and every sub class will automatically gets it.
interface you need to change every single implementation to include that change
abstract class are great in terms of evolving functionality.need to exercise extra care while defining contracts because its not easy to change them once published.
3) Interface in Java is great for defining Types. Programming for interfaces than implementation is also one of the useful Object oriented design principle which suggests benefit of using interface as argument to function, return type etc.
4) abstract class and interface form a IS-A hierarchy or CAN-DO-THIS hierarchy.
IS-A hierarchy: Circle, Square than it's better to create an abstract class Shape which can have area() and perimeter() as abstract method, rathe than defining Shape as interface
CAN-DO-THIS hierarchy: can fly, you can use interface Flyable instead of abstract class.
5) Interface generally define capability e.g. Runnable can run(), Callable can call(), Displayable can display().
define capability, consider using interface. have multiple capabilities i.e. a class can be Runnable as well asDisplayable at same time.
java does not allow multiple inheritance at class level, only way to provide multiple capability is via interfaces.
6)model other things along with Birds, which can fly e.g. Airplanes, Balloons or Kites than it's better to create interface Flyable to represent flying functionality
functionality which is used by same type of class than use Abstract class and
functionality can be used by completely unrelated classes than use interface.
7) Abstract class providing skeletal using abstract class.
interface is defining contract
java.util.List from Java collection framework is a good example of this pattern.
List is declared as interface and extends Collection and Iterable interface and AbstractList is an abstract class which implements List.
AbstractList provides skeletal implementation of List interface.
Benefit of using this approach is that it minimize the effort to implement this interface by concrete class e.g. ArrayList or LinkedList.
If you don't use skeletal implementation e.g. abstract class and instead decide to implement List interface than not only you need to implement all List methods but also you might be duplicating common code. Abstract class in this case reduce effort to implement interface.
8) Interface also provide more decoupling
abstract class may contain default implementation which may couple them with other class or resource.
9) interface help implement Dependency Injection design pattern and makes testing easy. Many mock testing framework utilize this behavior.




Why multiple inheritance are not supported in Java?

1. ambiguity around Diamond problem
               A foo()
     B foo()       C foo()
               D foo()
compiler will not be able to decide which foo() it should invoke. WHY C++ can?
2. multiple inheritances does complicate the design and creates problem during casting, constructor chaining . Since interface only have method declaration and doesn't provide any implementation there will only be just one implementation of specific method hence there would not be any ambiguity.



Why String is immutable in Java? Security and String pool
  1. String is Immutable in Java because String objects are cached in String pool. Since cached String literal is shared between multiple client there is always a risk, where one client's action would affect all other client.
  2. At the same time, String was made final so that no one can compromise invariant of String class e.g. Immutability, Caching, hascode calculation etc by extending and overriding behaviors
  3. Mutable String would produce two different hashcode at the time of insertion and retrieval if contents of String was modified after insertion, potentially losing the value object in map.
  4. String has been widely used as parameter for many Java classes e.g. for opening network connection, you can pass hostname and port number as string , you can pass database URL as string for opening database connection, you can open any file in Java by passing name of file as argument to File I/O classes.
  5. Since String is immutable it can safely shared between many threads ,which is very important for multithreaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, means you don't need to synchronize String operation externally. Another important point to note about String is memory leak caused by SubString, which is not a thread related issues but something to be aware of.
  6. Another reason of Why String is immutable in Java is to allow String to cache its hashcode ,which guarantees hashCode of String to be same on multiple invocation
  7. it is used by the class loading mechanism, and thus have profound and fundamental security aspects. Had String been mutable, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter"
  8. subclass doesn't break immutability


Difference between Method Overloading and Overriding in Java?
signature change VS the same
in class VS sublass
static, private,final fine VS static, private,final not fine
free to modify throws clause VS This restriction is only for checked Exception for RuntimeException you can throw any RuntimeException

1. overloading is resolved during compile time,
overriding is resolved at runtime
2.static and final method cannot be overriding but can overload.
overriding both name and signature of method remain same(derived class or sub class)
overloading signature must be different (co-exists in same class )
overloaded using static binding
overridden using dynamic binding
OVERLOAD
1.different set of arguments to perform something based on different number of input
occurs during compile time and overloaded calls resolved using static binding
change number of argument, type of argument or order of argument
return type is not part of method signature simply changing return type will result in duplicate method and you will get compile time error
2.overload static method in Java,
overload private and final method in Java
but you can not override them
OVERRIDE
1.create a child class which extends parent
but can only be overridden in sub class
2.Original method defined inside interface or base class, abstract as well
JVM resolves correct overridden method based upon object at run-time by using dynamic binding in Java

equals(), hashcode() and compareTo() methods are classic example of overridden methods
3.can not override static, private and final method in Java because they are associated with Class rather than object and resolved and bonded during compile time and that’s the reason you cannot override main method in Java
5.Overriding method can not throw higher Exception than original or overridden method. means if original method throws IOException than overriding method can not throw super class of IOException e.g. Exception but it can throw any sub class of IOException or simply does not throw any Exception. This rule only applies to checked Exception in Java, overridden method is free to throw any unchecked Exception
6.Overriding method can not reduce accessibility of overridden method , means if original or overridden method is public than overriding method can not make it protected
7.Covariant Method Overriding in Java
This will remove type casting on client side
Java 5, you're allowed to change the return type in the overriding method as long as the new return type is a subtype of the declared return type of the overridden (super class) method


Difference between Association, Composition and Aggregation in Java, UML and Object Oriented Programming
This relationship between two object is known as association in  object oriented general software design, and depicted by an arrow in Unified Modelling language or UML
composition, when one class owns other class and other class can not meaningfully exist, when it's owner destroyed, for example Human class is composition of several body parts including Hand, Leg and Heart. When human object dies, all it's body part ceased to exist meaningfully
relationship between two objects is referred as association, and an association is known as composition when one object owns other, while an association is known as aggregation when one object uses other object. I