Friday, August 14, 2015

[Java] Java Interview Questions 08/14





Java Basics
1. [String] Two major differences between StringBuffer and StringBuilder? [P.3 #7][OpenX]
2. [Exception]Two major subclasses under class Exception?[P.4 #1][OpenX]
3. [Exception]When will you use the keyword "throw" in java?[P.4#3][OpenX]
4. [GC] how to do the garbage collection [India#2][OpenX]
6. [Feature] difference between constructor and method[P.9#2][OpenX]
7. [OS] Explain deadlock[OpenX]
7. [MVC] Explain MVC[OpenX]
9. [Algorithm] Explain recursion[OpenX]
10. [C] C arrays declared and allocated[OpenX]
11. [Collection] Difference between ArrayList and Vector
12.[OOP] Inheritance and its advantage[Google]
13. [OOP]Procedural or Object-Oriented[Google]
14. [OOP]Polymorphism and its advantage[Google]
15. [AM] public, protect, private, default[Google]
16. [AM] private mechanism[Google]
17. [Data Structure] list,set,...[OpenX]



1. [String] Two major differences between StringBuffer and StringBuilder? [P.3 #7][OpenX]



StringBuffer
-Thread safety
StringBuilder
-Faster


2. [Exception]Two major subclasses under class Exception?[P.4 #1][OpenX]



IOException
checked exception:
-user error or a problem cannot be foreseen,
-for example, file cannot be found.
-cannot simply be ignored at the time of compilation [P.3#12]
RuntimeException
runtime exception:
- could have been avoided
- can be ignored at the time of compilation [P.3 #13]




3. [Exception]When will you use the keyword "throw" in java?[P.4#3][OpenX]

throw
(I)
By using the throw keyword, a exception can be thrown, either a newly instantiated one or an exception that you just caught.
Ex.
if (prerequisites == null ) { throw new IlleagalArgumentException("illegal prerequisites array"); }
throws
(System)
By using the throws keyword, a method declare a checked exception. The throws keyword appears at the end of a method’s signature.[P.4 #2]

4. [GC] how to do the garbage collection [India#2][OpenX]


1.How
1.Set all available object references to null
2.Make the reference variable to refer to another object
3.Creating Islands of Isolation


1.Set all available object references to null
public class GarbageCollnTest1 {
  public static void main (String [] args){
     String str = "Set the object ref to null";
       //String object referenced by variable str is not eligible for GC yet
       str = null;
   /*String object referenced by variable str becomes eligible for GC */
   }
 }
2.Make the reference variable to refer to another object
publc class GarbageCollnTest2 {
 public static void main(String [] args){
 String str1 = "Garbage collected after use";
 String str2 = "Another String";
 System.out.println(str1);
 //String object referred by str1 is not eligible for GC yet
 str1 = str2;
 /* Now the str1 variable referes to the String object "Another String" and the object "Garbage collected after use" is not referred by any variable and hence is eligible for GC */
 }
}
3.Creating Islands of Isolation
public class GCTest3 {
   GCTest3 g;    
  public static void main(String [] str){
       GCTest3 gc1 = new GCTest3();
       GCTest3 gc2 = new GCTest3();
       gc1.g = gc2; //gc1 refers to gc2
       gc2.g = gc1; //gc2 refers to gc1
       gc1 = null;
       gc2 = null;
       //gc1 and gc2 refer to each other and have no other valid //references
       //gc1 and gc2 form Island of Isolation
     //gc1 and gc2 are eligible for Garbage collection here
   }
}
class Person {
   public Person firend;
   public static void main(String[] args) {
     Person obj1 = new Person();
     Person obj2 = new Person();
     obj2.firend = obj1;

     obj1 = null;  //Line A
     obj2 = null;  //Line B
     .....
   }
}
After Line A executes, The object obj2 still has a reference to the object obj1 and the objectobj2 is still referenced by the variable obj2. Therefore, the object obj1 can not be eligable for garbage collection. After Line B exectues, there are no more references to the object obj2. There still is a reference to object obj1 inside the object obj2. Now, the object obj1 and obj2 has no reference from root set of references. Therefore, both of objects are eligible for garbage collection.
http://www.xyzws.com/javafaq/what-is-islands-of-isolation-in-garbage-collection/42 
2. What


-identify and discard objects that are no longer needed by a program
-their resources can be reclaimed and reused
- java object is subject to GC when it becomes unreachable to the program where it is used
- program that do not deallocate memory can eventually crash when there is no memory left in the system to allocate. These programs are said to have memory leaks.
- If you want to make your object eligible for Garbage Collection, assign its reference variable to null
-Primitive types are not objects. They cannot be assigned null.
- X int count = null;



class Student{
int a;
int b;


 public void setData(int c,int d){
   a=c;
   b=d;
 }
 public void showData(){
   System.out.println("Value of a = "+a);
   System.out.println("Value of b = "+b);
 }
 public static void main(String args[]){
   Student s1 = new Student();
   Student s2 = new Student();
   s1.setData(1,2);
   s2.setData(3,4);
   s1.showData();
   s2.showData();
   //Student s3;
   //s3=s2;
   //s3.showData();
   //s2=null;             // object (3,4) still has reference s3
   //s3.showData();
   //s3=null;             // object (3,4) still has no reference => Garbage collection
   //s3.showData();   }
}


3. How inner
1.Marking
2.Normal Deletion
3.Deletion with compacting


Marking
Marking means identifies which pieces of memory are in use and which are not.
All the objects are scanned in this phase to make this determination. This can be very time consuming process if all objects in a system must be scanned.
Normal
Deletion
In this phase, normal deletion removed the unreferenced objects leaving referenced object and pointers to free space.
Deletion with compacting
For further performance improvement, in addition to deleting unreferenced objects, you can compact the remaining referenced objects. By doing this, this makes memory allocation much easier and faster.


Reference

6. [Feature] difference between constructor and method[P.9#2][OpenX]


Constructor
-same name as the class
-no return value
-are only called once
- use new keyword to invoke
Method
-different name
- can return any value or void
- are called many times
- use dot operator to invoke


7. [OS] Explain deadlock[OpenX]


Deadlock Conditions
Two process sharing the same resource and resource is only accessed by one process at a time 1. one is waiting another 4.
Mutually Exclusion
Only one process can use a  resource at a given time
Hold and wait
processes already holding a resource can request new ones.
No preemption
one process cannot forcibly remove another process’ resource.
Circular Wait
two or more process form a circular chain where each process is waiting on another resource in the chain.
 ->
|    |
<-
Deadlock Prevention
Deadlock prevention essentially entails(must) removing one of the above conditions, but many of these conditions are difficult to satisfy.
For instance, removing #1 is difficult because many resources can only be used by  one process at a time (printers, etc).
Most deadlock prevention algorithm focus on avoiding #4: circular wait.
Ordered resources requests are sufficient to avoid deadlock, but not necessary.

A Simple Java Thread
two ways in which thread can be created:
1. implementing Runnable interface
2. extending the Thread class


class Foo implements Runnable
{
       public void run()
       {
            while(true)
            {
                 beep();
            }
       }
}


Foo foo = new Foo();
Thread myThread = new Thread(foo);
myThread.start();
Reference: 150 Cracking code

Deadlock Prevention
Deadlock Avoidance
Traffic light
Police officer directing traffic
    • Preventing deadlocks by constraining how requests for resources can be made in the system and how they are handled (system design)
    • The goal is to ensure that at least one of the necessary conditions for deadlock can never hold.
    • The system dynamically considers every request and decides whether it is safe to grant it at this point,
  • The system requires additional apriori information regarding the overall potential use of each resource for each process.
  • Allows more concurrency.

Reference:
https://courses.engr.illinois.edu/cs241/sp2012/lectures/28-deadlock-solutions.pdf
http://www.cs.jhu.edu/~yairamir/cs418/os4/tsld011.htm


8. [MVC] Explain MVC[OpenX]



MVC
Model View Controller is a design pattern it decouples data access logic from business logic.


Model
-It represents the application data domain.
-business logic is contained within the MODEL.
-The model contains the core of application’s functionality.
-The model encapsulates the state of the application.
-Sometimes the only functionality it contains is state.
-It knows nothing about view or controller.
View
get model
model change, it change
-It represents the user interface, with which the end user communicates.
-user interface logic is contained within the VIEW
-The view provides the presentation of model.
-It is the look of the application.
-The view can access the model getters, but it has no knowledge of the setters.
-In addition, it knows nothing about the controller.
-The view should be noticed when changes to the model occurs.
Controller
set model
-It represents the answers to user actions.
-user input logic is contained within the CONTROLLER.
-The controller reacts to the user input. It creates and sets the model.
References:

9. [Algorithm] Explain recursion[OpenX]


Recursion
-any routine(methods or functions) that calls itself is a recursive routine
-large task can be broken down into a repetitive “sub-task”
-a recursive routine calls itself to perform those sub-tasks, eventually the routine will come across a sub-task that it can handle without calling itself. This is known as a base case.
-base case stops the recursion


How to Recognize
-A good hint that problem is recursive is that it appears to built off sub-problems.
- A good candidate for recursion
 - Design an algorithm to compute nth
 - Write code to list the first n
 - Implement a method to compute all
How to Approach
-Recursive Solution, by definition, are built off solutions to sub-problems.
-Many times, this will mean simply to compute f(n) by adding something, removing something, or otherwise changing the solution for f(n-1).
- In other cases,  you might have to do something more complicated.
-Regardless, we recommend the following approach:
1.Think about what the sub-problem is. How many sub-problems does f(n) depend on?
-That is , in a recursive binary tree problem, each part will likely depend on two problems.
-In a linked list problem, it will probably be just one.
2.Solve for a “base case.”
-that is, if you need to compute f(n), first compute it for f(0) or f(1)
-That is usually a hard-coded value.
3.Solve for f(2)
4.Understand how to solve for f(3) using f(2) (or previous solutions).
-that is, understand the exact process of translating the solutions for sub-problems into a real solution.
5.Generalize for f(n)
-this “bottom-up” recursion is often the most straight-forward.
-Sometimes, though, it can be useful to approach problems “top down”,where you essentially jump directly into breaking f(n) into its subproblems.
Things to Watch Out For
  • All problems can be solved recursively can also be solved iteratively (though the code may be much more complicated). Before diving into a recursive code, ask yourself how hard it would be to implement this algorithm iteratively. Discuss the trade-off with your interviewer.
  • Recursive algorithms can be very space inefficient. Each recursive call adds a new layer to the stack, which means that if your algorithm has O(n) recursive calls then it uses O(n) memory. Ouch! This is one reason why an iterative algorithm may be better


Reference:
150 Cracking code
http://www.programmerinterview.com/index.php/recursion/explanation-of-recursion/


10. [C] C arrays declared and allocated[OpenX]


C Array Declared and Allocated


statically declared arrays
int a1[100];   
char c1[50];  
int matrix[50][100];
fixed size
pointer arithmetic
a1 point to a1[0]’s address
a1++ point to a1[1]’s address
...
-These are arrays whose number of dimensions and their size are known at compile time.
-Array bucket values are stored in contiguous locations (thus pointer arithmetic can be used to iterate over the bucket values )
- 2D arrays are allocated in row-major order (i.e., the memory layout is all the values in row 0 first, followed by the values in row 1, followed by values in row2 ...)
-Statically declared arrays can be declared as either global or local variables.
int a1[100];   // declare a static array, a1 of 100 ints
char c1[50];  // declare a static array, c1 of 50 chars
int matrix[50][100]; // declared a static 2D array of 50 rows, 100 cols


// accessing array elements using indexing
for (int i= 0 ;i < 100 ; i++ )
{
   a1[i] = 0;
}
for(int i = 0 ; i < 50 ; i++)
{
   for (int i = 0 ; i < 100 ; i ++)
   {
       matrix[i][j] = 0;
   }
}


// accessing array elements using pointer arithmetic
// In general, I recommend AVOIDING USING POINTER ARITHMETIC
// (it is easy to make errors and hard to debug when you do)
char *cptr = NULL;
int *iptr = NULL;


// make the pointer point to the first bucket in the array
// the address of the start of an array is given two ways:
// &(array[0] ) the address of bucket 0
// array     also the address of bucket 0


cptr = &(c1[0]); // initialize cptr to point to the start of c1
iptr = a1;            // initialize iptr to point to the start of a1
for ( i =0 ; i < 50 ;i++)
{
      *cptr = ‘a’;
      *iptr = i;
       cptr++;   // point to the next valid char address
       iptr++;   // point to the next valid int address
}
// set first matrix to:
// row 0:     0,    1,       99
// row 1: 100,110,.....199
iptr = &(matrix[0][0]);
for ( i = 0 ; i < 50*100)
{
    *iptr = i;
     iptr++;
}
dynamically allocated arrays
heap at run-time
malloc(sizeof(type)* #)
free ((void*) array)
-The heap space can be assigned to global or local pointer variables that store the address of the allocated heap space (point to the first bucket).
-To dynamically allocate space, use calls to malloc passing in the total number of bytes to allocate (always use the sizeof to get the size of a specific type).
- A single call to malloc allocates a contiguous chunk of heap space of the passed size.
// declare a pointer variable to point to allocated heap space
// Specifically, the start address index
p_array -> 223343
d_array -> 119890


int *p_array;
double *d_array;


// call malloc to allocate that appropriate number of bytes for the array
// Specifically, how big the address will occupy


p_array = (int*) malloc(sizeof(int)*50);         // allocate  50 ints
d_array = (int*)malloc(sizeof(double)*100); // allocate 100 doubles



// use [] notation to access array buckets
for ( i = 0 ; i< 50;i++)
{
   p_array[i] = 0;
}


// or use pointer arithmetic
double *dptr = d_array; // = &(d_array[0])
for ( i = 0 ; i < 100 ;i++)
{
    *dptr = 0;
    dptr++;
}
dynamically allocated 2D arrays
  • Allocate a single chunk of N*M heap space like example 1
  • Allocate an array of arrays: allocate 1 array of N pointers to arrays, and allocate N*M bucket array of values(on for each row).  You could also allocate each column independently and have an array of column arrays.


(1)a single N*M chunk
int *2d_array;
2d_array = (int*) malloc(sizeof(int)*N*M);
// in memory
// 2d_array ----> [0 ,0 ,......., 0,0,......,0,0….]
//                          row0         row1     row2
// access using [] notation
for (i;i<N)
{
   for (j; j<M )
   {
       2d_array[i*m+j]=0;
   }
}
// access using pointer
int*iterating_ptr = 2d_array;
for (i ; i<N)
{
     for (j;j <M)
     {
          *ptr = 0;
            ptr++;
     }
}



(2)N mallocs, one for each row, plus one malloc for array of row arrays
int **2d_array;// an array of int arrays(a pointer to point to ints)
2d_array = (int**) malloc(N*sizeof(int*));
for ( i = 0 i < N ;i++)
{
    2d_array[i] = (int*)malloc(M*sizeof(int));
}


// in memory
// 2d_array ----->    | *-|----> [0,0,0…..0] row0
//                             | *-|----> [0,0,0…..0] row1
//                             .
//                             .
// accessing using [] notation
for (i = 0; i < N;i++)
{
    for (j=0;j<M;j++)
    {
         2d_array[i][j]=0;
    }
}
// accessing using pointer arithmetic
int *iterating_ptr;
for (i = 0 ; i < N ; i++)
{
     *iterating_ptr = 2d_array[i];
     for (j=0;j<M;j++)
     {
           *iterating_ptr = 0;
             iterating_ptr++;
     }
}


char **a,i; // 2-D
// pointer unit
a = (char**) malloc(m*sizeof(char*))
for ( i = 0 ; i < m ;i++)
{
   a[i] =(char*) malloc(n*sizeof(char))
}


int i;
for (i = 0 ; i < m i++)
 free((void*) a[i] )
free((void*) a)


char***a,i,j; // 3-D
a= (char***) malloc(m*sizeof(char**));
for (i = 0 ;i < m ; i++)
  a[i] = (char**) malloc(n*sizeof(char*));
for (i = 0; i < m ; ++i)
for (j=0;j<n;++j)
  a[i][j] = (char*) malloc(p*sizeof(char));
Reverse release
int i ,j;
for (i = 0; i < m ;i++)
for (j = 0 ; j <n ; j++)
free((void*) a[i][j]);
for (i=0;i<m;i++)
free((void*) a[i]);
free((void*)a);



Reference:


11. [Collection] Difference between ArrayList and Vector


ArrayList
1.Not Synchronized: multiple thread can work in ArrayList at the same time.
-Structural modifications means addition or deletion of elements from the list.
-Setting the value of an existing element is not a structural modification.
2.Data growth 1.5X
- SAME: hold onto their content using an array
- SAME: dynamically expand the size of array if run out of room
3. Performance: better
4. Fail-fast:  The iterator will throw concurrentModificationException
if the collection gets structurally modified by any means, except the add or remove methods of iterator, after creation of iterator
Vector
1.Synchronized: (thread safe) only one operation at a time add or delete
2.Data Growth 2X
- SAME: hold onto their content using an array
- SAME: dynamically expand the size of array if run out of room
- Avector defaults doubling the size of its array, while ArrayList increases its array size by 50 percent.
3. Performance: worser due to thread lock
4. Not Fail-fast:
SIMILARITIES
1. growable array data structure
2. The iterator and listiterator returned by these classes are fail-fast
3. both maintain the elements insertion order and are ordered collection classes
4. both allows duplicate and null values
5. grows and shrinks automatically when overflow and deletion happens
make ArrayList sunchronized
// use Collections.synchronizedList method
List list = Collections.synchronizedList(new ArrayList());
….
// if you wanna use iterator on the synchronized list, use it
// like this. It should be in synchronized block
synchronized(list)
{
    Iterator itr = list.iterator();
    while( iterator.hasNext()  )
   {
         ...
         itr.next();
         ...
   }
}
Reference
http://beginnersbook.com/2013/12/difference-between-arraylist-and-vector-in-java/



12.[OOP] Inheritance and its advantage[Google]

13. [OOP]Procedural or Object-Oriented[Google]
14. [OOP]Polymorphism and its advantage[Google]
15. [AM] public, protect, private, default[Google]



class
package
(package com.xxx
subclass
(extends “Class Name”)
other package
(import com.xxx.”ClassName”)
can modify class ?
public
O
O
O
O
O class name same as file name
protect
O
O
O
X
X
default
O
O
X
X
O class name same as file name
private
O
X
X
X
X
16. [AM] private mechanism[Google]
17. [Data Structure] list,set,...[OpenX]






Java Advanced


1. Java pass by value or pass by reference[Google]
2. How LinkedHashMap works[Google]
3. How HashMap works
4. How TreeMap works
5. Factory pattern[Google]
6. Singleton[Google]
7. Java: Why does my compiler warn me about overriding equals() in my class without overriding hashCode()?[Google]
8. Static keyword
9. Final keyword
10. error condition for writing stored procedure or accessing stored procedure?
11. difference between Executor.submit() and Executer.execute() method?
12. write code for iterating over hashmap?
13. synchronize critical section of getInstance() method or whole getInstance() method?
14. Difference between creating string using String new() and String literal?
15. Overriding hashCode() method has any performance implication
16. What's wrong using HashMap in multi-threading environment? When get() method go to infinite loop?
17. Thread-safety ? Why is it required? How to achieve it?
18. What will happen to call return statement or System.exit on try or catch block? will finally block execute?
19. Can you override private or static method in Java?
20. What will happen to put a key object in a HahMap which is already there?
21. If a method throws NullPointerException in super class, can we override it with a method which throws RuntimeException?
22. What is the issue with following implementation of CompareTo() method?
23. How do you ensure that N thread can access N resourced without deadlock?
24. Difference between CyclicBarrier and CountDownLatch in Java?
25. Can you access non static variable in static context?
26. Difference between Comparable and Comparator Itnerface?
27. Difference between String ,StringBuilder and StringBuffer Classed?
28. Constructor: Overloading ,Examples, Basics, Rules ,Important Points?
29. What are inner Classes and its types(Regular method local, anonymous)?

1. Java pass by value or pass by reference



Java is ALWAYS pass-by-value (meaning make another new copy ).
That’s why when we change object’s value within function, the original object’s value is untouchable.
public class Main
{
     public static void main (String[] args)
     {
             Foo f = new Foo(“f”);
             changeReference(f);
             modifyReference(f);
      }
}
enter image description here
public class Main
{
     public static void main (String[] args)
     {
             Foo f = new Foo(“f”);
             changeReference(f);
             modifyReference(f);
      }


     public static void changeReference (Foo a)
     {
        Foo b = new Foo(“b”);
        a=b;
      }
}
enter image description here
public class Main
{
     public static void main (String[] args)
     {
             Foo f = new Foo(“f”);
             changeReference(f);
             modifyReference(f);
      }
     public static void changeReference (Foo a)
     {
        Foo b = new Foo(“b”);
        a=b;
      }
}
enter image description here
public static void changeReference (Foo a)
{
        Foo b = new Foo(“b”);
        a=b;
}
enter image description here
public static void changeReference (Foo a)
{
        Foo b = new Foo(“b”);
        a=b;
}
enter image description here
public class Main
{
     public static void main (String[] args)
     {
             Foo f = new Foo(“f”);
             changeReference(f);
             modifyReference(f);
      }


     public static void changeReference (Foo a)
     {
        Foo b = new Foo(“b”);
        a=b;
      }
      public static void modifyReference (Foo c)
      {
            c.setAttribute(“c”);
       }
}
enter image description here
public class Main
{
     public static void main (String[] args)
     {
             Foo f = new Foo(“f”);
             changeReference(f);
             modifyReference(f);
      }


     public static void changeReference (Foo a)
     {
        Foo b = new Foo(“b”);
        a=b;
      }
      public static void modifyReference (Foo c)
      {
            c.setAttribute(“c”);
       }
}
enter image description here
Reference:


2. How LinkedHashMap works


HashSet uses HashMap object internally to store its elements whereas LinkedHashSet uses LinkedHashMap object internally to store and process its elements.


public LinkedHashSet(int initialCapacity, float loadFactor)
{
      super(initialCapacity, loadFactor, true);
}
public LinkedHashSet(int initialCapacity)
{
     super(initialCapacity, .75f,true);
}
public LinkedHashSet()
{
    super(16, .75f, true);
}
public LinkedHashSet(Collection<? extends E> c)
{
    super (Math.max(2*c.size(),11), .75f,true);
    addAll(c);
}


boolean dummy value is just to differentiate this constructor from other constructors of HashSet class which take initial capacity and load factor as their arguments.
HashSet(int initialCapacity, float loadFactor, boolean dummy)
{
     map = new LinkedHashMap<>(initialCapacity, loadFactor);
}


All method is inherited from its super class - HashSet. So all operations work in the same manner as that of HashSet. The only change is the internal object used to store elements.
In HashSet, elements you insert are stored as keys of LinkedHashMap object.
The values of these keys will be the same constant i.e., “PRESENT”
How LinkedHashSet Maintains Insertion Order?
The elements you insert in the LinkedHashSet are stored as keys of this LinkedHashMap object.
Each key, value pair in the LinkedHashMap are instances of its static inner class Entry<K,V>
This Entry<K,V> extends HashMap.Entry class.
The insertion order of elements into LinkedHashMap are maintained by adding two new fields to this class. They are before and after.
These two fields hold the reference to previous and next elements. These two fields make LinkedHashMap to function as a doubly linked list.


private static class Entry<K,V> extends HashMap.Entry<K,V>
{
     // These fields comprise the doubly linked list used for iteration
     Entry<K,V> before ,after;
     Entry(int hash, K key, V value, HashMap.Entry<K,V> next)
     {
           super(hash,key,value,next);
     }
}


/*store the head of doubly linked list*/
private transient Entry<K,V> header;


Entry Objects are arranged in two different manner . One is the HashMap and another is Doubly linked list. The Entry objects just sits on heap memory, unaware of that they are part of two different data structures.


public class LinkedHashSetExample
{
   public static void main (String[] args)
   {
          LinkedHashSet<String> set = new LinkedHashSet<String>();
         set.add(“BLUE”);
        set.add(“RED”);
        set.add(“GREEN”);
        set.add(“BLACK”);
   }
}


LinkedHashSet ⇒ LinkedHashSet constructor => LinkedHashMap


public boolean add(“BLUE”)
return map.put(“BLUE”,PRESENT) == null;
before
key
value
after------



---before
key
value
after
Reference:



3.How HashMap works

-HashMap works on the principle of Hashing.
-Hash Function: int hashCode()
-Hash Value: the int value returned by the hash function
-Bucket: store key value pairs. It can be multiple and use simple linked list to store objects


Get(Object key)
STEP1: hashCode hash hashValue
STEP2: equals()
Public  V get(Object key)
{
     if (key == null)
     …


     int hash = hash(key.hashCode());
     // if key found in hash table then return value
     // else return null
}
hash(key.hashCode()) : to find a bucket location (backing array) where keys and values are stored in form of a nested class called Entry(Map.Entry).


Is that only value stored in the bucket?
Answer: No. Both key and value is stored in the bucket as a form of Entry object.


call get(Key k) method on the HashMap object
if key is null, then Null keys always map to hash 0, thus index 0


Why we are calculating the hash value again using hash(hashValue)?
Answer: it depends against poor quality hash functions.


Answer: Entry object stores in the bucket like this (hash,key,value,bucket index)


What if when two different keys have the same hashcode ?
Solution: equals() method comes to rescue.


Answer: The bucket is the linked list effectively. It’s not a LinkedList as in a java.util.LinkedList - it’s a separate (simpler ) implementation just for the map


Answer: So we traverse through linked list, comparing keys in each entries using keys.equals() until it return true. Then the corresponding entry object Value is returned.


When the function ‘equals’ traverses through the linked list does it traverses from the start to end one by one ….. Or the linked list is sorted based on key and then it traverses?
Answer: the end is found and the element is added or the key is matched and the value is returned
  1. key.hashCode() to get initial hash value hashvalue1
  2. hash(hashvalue1) to calculate the final hash value hashvalue2
  3. indexFor(int hashvalue2, int CONSTANT)
  4. /* return index for hash code h*/
  5. static int index (int h, int length)
  6. {
  7.    return h & (length-1); // 256-1 =255     , 0X100 - 0X1 = 0XFF,
  8.    // E.g., a hash of 257 (0X101) get bitwise anded with 0XFF to yield a bucket number of 1
  9. }


What if when two keys are same and have the same hashcode?
Answer: if key needs to be inserted and already inserted hashkey’s hashcode are same, and keys are also same (via reference or using equals() method) then override the previous key value pair with the current value pair.
Any class(String etc.) can serve as a key if and only if it overrides the equals() and hashCode() method.


How will you measure the performance of HashMap?
Answer: two parameters affect its performance: initial capacity and load factor
The capacity is the number of buckets in the hashtable (hashMap class is rougly equivalent to HashTable, except that it is unsynchronized and permits null), and the initial capacity is simply the capacity at the time the hash table is created.
The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When overflow the number of entries exceed the product of the load factor and the current capacity, the hash table is rehashed , twice the number of buckets.


What is the time complexity of HashMap get() and put()?
Both O(1), assume the hash function disperses the elements properly among the buckets.


What is the difference between HashMap and ConcurrentHashMap?
Answer: the later is thread-safe
Map<String,String> syncMap = Collections.synchronizedMap(map)


HashMap
-Collections.synchronizedMap
-allow NULL keys
-faster
ConcurrentHashMap
-thread-safe
-Not allowed NULL keys
-slower


Reference:


4. How TreeMap works



-sort the key in ascending order
-log(n) containsKey, get, put and remove
- red-black tree based NavigableMap implementation
  1. color of every node in the tree is either red or black
  2. root node must be Black in color.
  3. Red node can not have a red color neighbor node
  4. All paths from the root node to the null should consist the same number of black nodes
Rotations maintains the inorder ordering of the keys (x,y,z)
A rotation can be maintained in O(1) time.
Why and when we use TreeMap?
Answer: get the sorted list of keys in ascending order.


What is the runtime performance of the get() method in TreeMap and HashMap, where n represents the number of elements?
Answer: log(n) for all operations in TreeMap , HashMap is O(1) assume hash function disperses elements properly among the buckets.


What is “natural ordering ” in TreeMap?
Answer: “Natural” ordering is the ordering implied by the implementation of the Comparable interface by the objects used as keys in the TreeMap. Essentially, RBTree must be able to tell which key is smaller than the other key, and there are two ways to supply that logic to the RBTree implementation:
  1. Implement Comparable interface in the classes used as keys to TreeMap, or
  2. Supply an implementation of the Comparator that would do comparing outside the key class itself.
Natural ordering is the order provided by the Comparable interface. If somebody puts the key that do not implement natural order then it will throw ClassCastException.


*Why do we need TreeMap when we have sortedMap?
sortedMap is a interface and TreeMap is the class implementing it. As we know one can not create objects of the interface.  Interface tells us which methods a sortedMap implementation should provide. TreeMap is such an implementation.


Which data structure you will prefer in  your code : HashMap or TreeMap?
HashMap is faster, just insert and retrieve, then HashMap
Alphabetically sorted, TreeMap


What happens if the TreeMap is concurrently modified while iterating the elements
The iterator fails fast and quickly if structurally modified at any time after iterator is created (in any way except through the iterator’s own remove method.)


*Which copy technique (deep or shallow) is used by the TreeMap clone() method?
clone() return the shallow copy of the TreeMap instance. In shallow copy Obejct A  points to Object B location in memory. In other words,  both Object A and B sharing the same elements. The keys and values themselves are not cloned.


*why java’s treeMap does not allow an initial size?
HashMap reallocates its internals as the new one gets inserted
while TreeMap does not reallocate nodes on adding new ones. Thus,
the size of the TreeMap dynamically increases if needed, without shuffling the internals.
So it is meaningless to set the initial size of the TreeMap.


Reference:
http://javahungry.blogspot.com/2014/06/how-treemap-works-ten-treemap-java-interview-questions.html



5. Factory pattern




Factory
- provide a way for interface to create object and object.interface’s method()


1.What
-Factory Design Pattern is based on Encapsulation object oriented concept.
-Factory method is used to create different object from factory often refereed as item and it encapsulate the creation code.
-Instead of having object creation code on client side we encapsulate inside Factory method in Java.
-valueOf(), getInstance(), newInstance(), getType(), newType()
-Encapsulation and delegation


2. Why
-Problem1: We can not create object of interface or abstract class so main problem is framework knows when it has to create but don’t know what kind of object. Whenever we create object using new() we violate principle of programming for interface rather than implementation.
-Problem2: class needs to contain objects of other classes or class hierarchies within it; this can be very easily achieved by just using the new keyword and the class contructor. The problem with this approach is that it is a very hard coded approach to create objects as this creates dependency between two classes.


3. When
-Static Factory methods are common in frameworks where library code needs to create objects of types which may be sub classed by application using the framework.
-some or all concrete products can be created in multiple ways, or we want to leave open the option that in the future there may be new ways to create concrete product.
-Factory method is used when Products don’t need to know how they are created.
-We can use factory pattern where we have to create an object of any one of sub-classes depending on the data provided


4. How


interface Currency
{
    String getSymbol();
}
// Concrete Rubee class code
class Rupee implements Currency
{
     @Override
     public String getSymbol()
     {
            return “Rs”;
     }
}
// Concrete SGD class code
class SGDDollar implements Currency
{
     @Override
     public String getSymbol()
     {
           return “SGD”;
     }
}
// Concrete US Dollar code
class USDollar implements Currency
{
    @Override
    publci String getSymbol()
   {
           return “USD”;
    }
}
// Factory Class code
class CurrencyFactory
{
      public static Currency createCurrency (String country)
      {
              if (country.equals(“Indis”))
              {
                    return new Rupee();
              }
              else if (country.equalsIgnoreCase(“Singapore”))
              {
                     return new SGDollar()
              }
              else if ( country.equalsIgnoreCase(“US”))
              {
                      return new USDollar();
              }
              throw new IllegalArgumentException(“No such currency”);
      }
}


// Factory client code
public class Factory
{
        public static void main (String args[])
        {  
               String country = args[0];
              // create an object of interface Currency without keyword new
               Currency us = CurrencyFactory.createCurrency(country);
              // an object of interface to call its method
              System.out.println(us.getSymbol());
        }
}
5.advantage
1. Factory method design pattern decouples the calling class from the target class, which result in less coupled and highly cohesive code. E.g., JDBC is a good example, Factory methods to get Connections, Statements, and other objects to work with.
2. Factory pattern in java enable the subclassed to provide extended version of an object (-ex. AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory etc. Each individual factory would be responsible for creation of objects in that genre)
3.encourages consistency in Code since every time object is created using Factory rather than using different constructor at different client side(like multiple concrete class implements interface will have multiple constructors).
4.easy to debug and troubleshoot since every client is getting object from the same place
5. enforces use of interface than implementation
Map sychronizedMap = Collectiond.synchronizedMap(new HashMap());
6. since return type as interface, it allows you to replace implementation with better performance version in newer release.
7. cache frequently used object and eliminate duplicate object creation Boolean.valueOf()
Abstract Factory
Factory is an abstract class and cannot be used to create a object, so we use another facotry class which can be used to create an object
-one more level of abstraction
-different factories each extended from an Abstract Factory and responsible for creation of different hierachies of objects based on the type of factory.
-ex. AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory etc. Each individual factory would be responsible for creation of objects in that genre.
Rerence:


6. Singleton


1.What only one instance of whole application
It is the most used design pattern in web applications.
Singleton in Java is a class with just one instance in whole data java application and provides a getInstance() method to access the singleton instance .For example, java.lang.Runtime is a singleton class. Creating Singleton was tricky prior Java 4 but once java 5 introduced Enum its very easy.
2. How
write Java singleton using double checked locking. Remember to use volatile variable to make Singleton thread-safe.
-create a static variable
private stati JavaHungrySingleton uniqueInstance;
-declare the constructor private
private JavaHungrySingleton() {}
-getInstance()
-public static synchronized JavaHungrySingleton getInstance(){}
-if (uniqueInstance == null )
uniqueInstance = new JavaHungrySingleton();
return uniqueInstance;


1. Method1-  synchronized JavaHungrySingleton getInstance()
public class JavaHungrySingleton
{
    // 1. common for all object
    // 2. directly used in all method
     private static JavaHungrySingleton uniqueInstance;


     private JavaHungrySingleton(){}
    // access variable w/o using object of class
    //2. one for class, not one for each object
    //1. attach to a class, not an object
     public static synchronized JavaHungrySignleton getInstance ()
     {
           if (uniqueInstance == null)
           {
                  uniqueInstance = new JavaHungrySignleton();
           }
           return uniqueInstance;
     }
}


Lazy initialization: Last moment to have an object. We create the object of the class only when it is about to use in the program code.
Early initialization: we create the object when the class is getting loaded into the JVM.


2. Method2 - Early initialization
public class JavaHungrySingleton
{
     private static JavaHungrySingleton uniqueInstance  = new JavahungrySingleton();
     private JavaHungrySingleton(){}
     // cannot be accessed by object
     public static JavaHungrySingleton getInstance()
     {
           return uniqueInstance;
     }
}


double checked locking: first we check if the object is created, if not then we create one using synchronized block.


3. Method 3 - double checked locking : volatile establishes happens-before relation between reads and writes, and fixes the broken pattern.

reduce the overhead of acquiring a lock by first testing thelocking criterion (the "lock hint") without actually acquiring the lock

public class JavaHungrySingleton
{
     private static volatile JavaHungrySingleton uniqueInstance;
     private JavaHungrySingleton(){}
     public static JavaHungrySingleton getInstance()
     {
            if (uniqueInstance == null)
            {
                    synchronized(JavaHungrySingleton.class)
                    {
                          if (uniqueInstance == null)
                          {
                                   uniqueInstance = new JavaHungrySingleton();
                           }
                     }
            }
            return uniqueInstance;
      }
}



volatile is here because without it


by the time second thread passes instance == null, first thread might not construct new Singleton() yet: no one promises that assignment to instance happens-before creation of the object for any thread but the one actually creating the object.





volatile inturn establishes happens-before relation between reads and writes, and fixes the broken pattern.


Reference:http://stackoverflow.com/questions/7855700/why-is-volatile-used-in-this-example-of-double-checked-locking 







Reference:


7. Java: Why does my compiler warn me about overriding equals() in my class without overriding hashCode()?


Q: When do you override hashcode and equals()?
Whenever necessary especially if you want to do equality check or want to use your object as key in HAshMap.
Q: What will be  the problem if you don’t override hashcode() method?
You will not be able to  recover your object from hashmap if that is used as key in HashMap
References:



8.[Java] static keyword




static class
anything you want to share between all objects can be made static e.g., singleton instance of a Singleton Class in Java
1.nested
2.utility class
-1. nested static class: can have an instance of nested class w/o any instance of outer class
public class StaticClass
{
        public static void main (String args[])
        {
              StaticClass.NestedStaticClass ns = new StaticClass.NestedStaticClass();
              System.out.println(ns.)
        }
        static class NestedStaticClass
        {
                   public String NestedStaticDEscription =”Example of Nested Static Class in Java”; // put in the string pool w/o String.itnern()
                   public String getDescription()
                   {
                           return NestedStaticDEscription;
                   }
        }
}
Output:
Example of Nested Static Class in Java
2. when to use: utility class which are required by all components and which itself doesn’t have any state. a single resource to be shared between all instances
static class
-completely stateless
-work on provided data
singleton



-there is only one copy of static variable will be present in Java heap memory
- cannot be applied to top level class
-bounded using static binding at compile time so they are comparatively faster than there non-static counter part which were bounded during runtime.
static method
  1. not depennd on object state
  2. uitility methods
  3. global access e.g, singleton pattern, Factory pattern
Disadvantage: not override, create bug in consurrent environment
E.g.,
java.util.Collections
java.lang.Math
BorderFactory
java.lang.Runtime
1.one for class (main())
2. access class variable w/o using object of class
3. cannot be overridden implicitly final, because overriding is done based on the type of object
4. so it can be shadowed(since cannot be overriden) by another static method in subclass, “method hiding
5. Most utility methods are declared as static method
-being direct accessed in static or non-static method
-access non-static method or variable using object of class
static variable
1. shared common for all the objects
2. can be accessed or altered by any object
3. multi-threading environment, access to static variable must be synchronized.
4. static belong to class
5. non-static belong to object
6. memory allocation(initialized) only happen once when class load in the memory
-being accessed directly in static and non-static block
- non-static variable can be accessed by using object of class
static block
1.holds piece of code to be executed when class is loaded in Java
static
{
     String category =”ee cs”;
     System.out.println(“example of static block in java”);
}
throw exception like java.lang.NoClassDefFoundError when class failed to load
Reference

9. Final keyword


Final
-along with static to make static final constant
-raise compilation error if you try to re-initialized final variables in java
-improves performance
-multi-threading environment without any additional synchronization overhead.
- immutable class, cannot be modified like String, read-only
-!= finally keyword in Exception handling
-!=finalize() keyword declared and called before an object is garbage collected by JVM
- All variables declared inside java Interface are implicitly final
-Final and abstract are two opposite keyword
Final class
-is complete in nature
-cannot be subclassed or inherited
-String, Integer, Double and other wrapper classes
Final method
-cannot be overriden in sub-class
-it’s complete and its behavior should remain constant in sub-class
-faster because they are not required to be revised during run-time and they are bounded on compile time
Final variable
-constant
-must be initialized during declaration or in constructor either explicitly or by calling this()
Reference


10. error condition for writing stored procedure or accessing stored procedure?


**stored procedure
-Is a set of statement/commands which reside in the database.
-The stored procedure is precompiled.
-Each database has its own stored procedure language

-stored procedure should return error code if some operation fails
-but if stored procedure itself fail then catching SQLException is only choice
Reference:


11. difference between Executor.submit() and Executor.execute() method?


*Executor.submit()
- exception submit with submit
-any thrown exception, checked exception or not, is then part of the task return’s status
-the future.get will re-throw this exception, wrapped in an ExecutionException
*Executor.execute()
-exception submit with execute
-this exception will go to uncaught exception handler (print the stack trace toSystem.err)



12. write code for iterating over hashmap?


using while and for loop
for (Entry<K,V> entry: map.entrySet() )
{
}
for ( K key:map.keySet() )
{
}
for ( V vlaue: map.vlaueSet() )
{
}


13. synchronize critical section of getInstance() method or whole getInstance() method?


Answer is critical section because if we lock whole method than every time someone call this method will have to wait even though we are not creating any object


14. Difference between creating string using String new() and String literal?


new()
-created in heap
-not added in the string pool
literal
-created in String pool
-String pool exist in Perm area of heap


15. Overriding hashCode() method has any performance implication


poor hashCode() function will result in frequent collision in HashMap which eventually increase time for adding an object into HashMap


16. What's wrong using HashMap in multi-threading environment? When get() method go to infinite loop?


during concurrent access and re-sizing


17. Thread-safety ? Why is it required? How to achieve it?



-A real barrier invalidated the local memory (cache, registers, etc) and read the contents from the main memory, so changes made by other threads becomes visible to current thread
-A write barrier flushed out the contents of the processor’s local memory to the main memory, so that changes made by current Thread becomes visible to the other threads.  
Method1 - synchronized
-when a thread acquires monitor of an object, by entering into a synchronized block of code, it performs a read barrier (invalidates the local memory and read from the heap instead)
-Similarly, exiting from a synchronized block as part of releasing the associated monitor, it performs a write barrier(flushes changes to the main memory)
Method 2 -volatile
-read and write to volatile variables have same memory semantics as that of acquiring and releasing a monitor using synchronized code block.
- When Thread A writes to a variable V, and afterwards Thread B reads from variable V, any variable that were visible to A at the time V was written are guaranteed now to be visible to B.
Data data = null;
volatile boolean flag = false;

ThreadA
---------------
data = new Data();
flag = true; // flush the data as well as flag to main memory

Thread B
----------------
if (flag)
{
  use data;
}
Method 3- final
-multi-threading environment without any additional synchronization overhead.
- immutable class, cannot be modified like String, read-only


18. What will happen to call return statement or System.exit on try or catch block? will finally block execute?


return statement in try or catch
-not execute return and finally block will execute
System.exit in try or catch
-execute system.exit and finally block won’t run


19. Can you override private or static method in Java?


No, you cannot override private or static method in Java, if you create similar method with same return type and same method arguments that’s called method hiding.


20. What will happen to put a key object in a HashMap which is already there?


it will replace the old mapping because hashMap doesn’t allow duplicate keys


21. If a method throws NullPointerException in super class, can we override it with a method which throws RuntimeException?


-overloading and overriding
-Answer is you can very well throw super class of RuntimeException in overriden method
- you cannot do same if it’s checked Exception


22. What is the issue with following implementation of CompareTo() method?


public int compareTo(Object o)
{
   Employee emp = (Employee) emp;
   return this.id - o.id;
}


23. How do you ensure that N thread can access N resourced without deadlock?


-deadlock and race conditions
-key point here is order, if you acquire resources in a particular order and release resources in reverse order you can prevent deadlock.


24. Difference between CyclicBarrier and CountDownLatch in Java?


*CyclicBarrier
-reuse even if Barrier is broken
*CountDownLatch
-cannot reuse


25. Can you access non static variable in static context?


NO, you cannot access non-static variable from static method.
Reason: those variables are not yet created.  instance variable(non-static variable) has different value for each instances and they get created when instance of an object is created either using new() operator or using reflection like Class.newInstance().[static variable initialized when class is loaded into JVM]
Solution: use instance object of class to access it

access static variable in non static context.
Solution: YES you can. Imagine that this static variable will be the same for all instances of that class, so any instance can access it.
Reference:


26. Difference between Comparable and Comparator Interface?


Comparable
- Interface
-public interface which is used to impose an natural ordering
-default sorting by ASCII values
-Collections.sort() and Arrays.sort()
-1. Sort sequence: only one
-2. Methods public int compareTo(Object o)
-3. Objects needed for Comparison: this
-4.Modify Classes:X
-5.Package:java.lang.package => provided by default
-use a key in a sortedmap like treeMap or clements in a sortedSet for example TreeSet, without specifying any Comparator

public class Country implements Comparable<Country
>
{
          @ Override
          public int compareTo(Country country)
         {
              return (this.contryId < country.countryId)?-1;(this.countryId > country.countryId)?1:0;
       }
}
Comparator -class
-a comparator function, which is used to impose ordering on some collection of bjects. To allow precisely control over sort order, Comparators can be passed to a sort method (e.g, Collections.sort())
- TreeSet or TreeMap can also be sorted using Comparator
-1. Sort sequence: many
-2.Methods used: public int compare (Object o1, Object o2)
-3.Objects needed for Comparison: two objects
-4. Modify Classes: O. has to modify the class whose instances you want to sort
-5.Package:java.util.package=>utility to sort objects

Case1: Collections.sort(listOfCourses);
Case2: Collections.sort(listOfCourses, new CountrySortByIdComparator());
public class Country
{
}
public class CountrySoredByIdComparator implements Comparator<Country>{
     @Override
     publci int compare(Country country1, Country country2)
     {
             return country1.getCountryId() < country2.getCountryId() ? -1 : ( > ) ?1:0
     }
}
Case3:
Collections.sort(listCoursed, new Comparator<Country>()
{
     @Override
     public int compare (Country o1, Country o2)
    {
            return o1.getCountryName().compareTo(o2.getConuntryName())
    }
}
);
Reference:


27. Difference between String ,StringBuilder and StringBuffer Class?



String
StringBuffer
StringBuilder
Storage Area
Modifiable
Thread Safe
Performance
Consistent String Poll
No(immutable)
Yes
Fast
Heap
Yes(Mutable)
Yes
Very slow
Heap
Yes(Mutable)
No
Fast

http://javahungry.blogspot.com/2013/06/difference-between-string-stringbuilder.html




28. Constructor: Overloading ,Examples, Basics, Rules ,Important Points? abstract class have at least one constructor


-create objects
1.name is the same as the name of the class
2. no return type
3. calls the constructor of the superclass first, which is also known as constructor chaining. Internally, an implicit super() has been made
4. can use any modifier private or public
5. no constructor(), compiler put one implicitly in the code
6. The default constructor is always no argument constructor
7. cannot make a call to instance method, or access in an instance variable, until after the super constructor runs.
8. Abstract classes always has constructor, and those constructors are called when a concrete subclass is instantiated.
9.interface do not have constructors
10. First line of constructor super() or this(), never both
11. Every class , even an abstract class have at least one constructor
12. Never inherited and cannot be overriden
13. Overloading a constructor => multiple version of constructor
Reference:


29. What are inner Classes and its types(Regular method local, anonymous)?


1. To create the instance of the inner class you need to have the instance of the outer class

public static void main (String args[])
{
     Outer outerclassobject = new Outer();
     Outer.Inner  innerclassobject = outerclassobject.new Inner();
// new Outer().new Inner();
}

2. Method local Inner Class
A method local inner class cannot use variables declared within the method
(including parameters) unless those variables are marked final

class Outer2
{
    private String x = “Outer2”;
     void doStuff()
    {
           class Inner{
                 public void seeOuter()
                {}
           }
    }
    Inner one = new MyInner();
    one.seeOuter();
}

3. Anonymous Inner class
  • can extend one subclass or implement one interface
class Apple
{
public void iphone(){System.out.println(“ iphone”)};
}
class Mobile
{
Apple apple = new Apple();
public void iphone(){System.out.println(“anonymous iphone”)};
}



30. Difference between == and equals() method?


==, check references
equals(), check content
-only be true if two String point to the same underlying String object

String a = new String(“a”);
String b = new String(“a”);
a==b => false=> they are two different objects
Integer i = new Integer(10);
Integer j = new Ineger(10);
i==j => false=> they are two different objects
-compare two strings character by character to determine equality while “==” checks whether 2 string objects are identical
-faster than ( String.compareTo(String) == 0 ) , ==0 take extra cycle
String a = new String (“a”);
String b = new String(“a”);
a.equals(b) =>true
reference
http://javahungry.blogspot.com/2013/06/difference-between-equals-and-double-equals-method-with-example-java-collections-interview-question.html

31.http://javahungry.blogspot.com/2013/06/jdbc-interview-questions-in-java-top-15-core-java-technical-round.html

1 comment: