Saturday, 22 July 2017

Singleton Design Pattern


package com.help4j.advance.pattern;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;

/**
 * @author aklahoti
 *
 */
public class Singleton implements Serializable, Cloneable{

 public static void main(String[] args) throws CloneNotSupportedException, FileNotFoundException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException{
  
  // Test creating an object of Singleton Class
  Singleton obj = Singleton.getInstance();
  System.out.println(obj);
  
  // Test serialzation/deserialization of singleton object. It should not create new object and return same object.
  ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("resources/singleton.ser"));
  os.writeObject(obj);
  ObjectInputStream is = new ObjectInputStream(new FileInputStream("resources/singleton.ser"));
  Singleton deserObj = (Singleton) is.readObject();
  System.out.println("***Deserialized Singleton Object***");
  System.out.println(deserObj);
  
  // Test cloning of singleton object.  It should not create new object and return same object.
  Singleton cloneObj = (Singleton) obj.clone();
  System.out.println("***Cloned Singleton Object***");
  System.out.println(cloneObj);
  
  // Test reflexion of singleton object. It should throw exception.
  Class<Singleton> classObj = (Class<Singleton>) Class.forName("com.java.test.pattern.Singleton");
  System.out.println(classObj.newInstance());
  
 }
 private static final long serialVersionUID = 1L;

 private static Singleton instance = null;
 
 private static Object DUMMY_OBJECT = new Object();
 
 private Singleton(){
  /*To prevent object creation using reflection*/
  if(instance!=null){
   throw new InstantiationError( "Singleton Object is already created." );
  }
 }
 
 public static Singleton getInstance(){
  /*Double checked locking*/
  if(instance == null){
   synchronized (DUMMY_OBJECT) {
    if(instance == null){
     instance = new Singleton();
    }
   }
  }
  return instance;
 }
 
 public static void print(){
  System.out.println("I am a singleton class.");
 }
 
 /*To prevent object creation using deserialization*/
 private Object readResolve() throws ObjectStreamException{
  return instance;
 }
 
 /*To prevent object creation using cloning*/
 @Override
 protected Object clone() throws CloneNotSupportedException {
  return instance;
 }
}

Sunday, 26 March 2017

Spring Interview Questions

Spring Bean Life Cycle

  1.  Default constructor will be called.
  2.  All properties setter methods will be called.
  3.  If class implements BeanNameAware then setBeanName method will be called.
  4.  If class implements BeanFactoryAware then setBeanFactory method will be called.
  5.  If class implements ApplicationContextAware then setApplicationContext method will be called.
  6.  If class implements BeanPostProcessor then its postProcessBeforeInitialization will be called.
  7.  If class implements InitializingBean then afterPropertiesSet method will be called.
  8.  If class has custom init method defined then it will be called.
  9.  If class implements BeanPostProcessor then its postProcessAfterInitializationwill be called.
  10.  If class implements DisposableBean then destroy method will be called.
  11.  If class has custom destroy method defined then it will be called. 
Spring MVC flow

1. Dipatcher Servlet which is also know as front controller of Spring application handles all the request mapped to it in web.xml and ask for appropriate controller from Handler Mapping

2. Handler Mapping is a configuration for url and controller mapping. It look for controller:

Popular Implentations of HandlerMapping:

BeanNameUrlHandlerMapping - This is a default spring handler mapping. Name of bean considered as URL.


<bean name="/welcome.htm" class="com.help4j.controller.WelcomeController" />

SimpleUrlHandlerMapping - Map with key value pair of URL and controller bean name.

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
   <property name="mappings">
  <props>
     <prop key="/welcome.htm">welcomeController</prop>
   </props>
   </property>
</bean>

<bean id="welcomeController" class="com.help4j.controller.WelcomeController" />


DefaultAnnotationHandlerMapping - Annotation based @RequestMapping at class and method level.
WelcomeController.java
package com.help4j.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/welcome")
public class WelcomeController{

 @RequestMapping(method = RequestMethod.GET)
 public ModelAndView helloWorld(){

  ModelAndView model = new ModelAndView("WelcomePage");
  model.addObject("msg", "hello world");

  return model;
 }
}


3. Controller calls service layer to execute business logic and retrurn ModelAndView, which is wrapper for model object and view name.

Popular Controller Types:

AbstractController
AbstractCommandController
SimpleFormController


4. View Resolver look for appropriate view JSP/HTML based on view name and return to user.

Popular Implentations of ViewResolver:

InternalResourceViewResolver


Saturday, 7 January 2017

Top Java Interview Questions 2017 for experienced candidates

I have prepared this list from my personal experience of recent interviews. Topics are in the order of recent interview trend.

Singleton Pattern

This is one of the most commonly asked question in interviews. Interviewer starts this question asking about design patterns. Candidate generally answers singleton and factory patterns. Then interviewer asks to write a singleton class. You should learn how to create a singleton class with private constructor, static getInstance method, double checked locking. You should also learn enum based singleton class. Follow up questions in singleton pattern are as follows:
  • How to make singleton class thread safe?
  • How to prevent deserialization to create new object of singleton class? 
  • How to prevent cloning and reflexion to create new object of singleton class?
You can find the singleton pattern implementation here.

HashMap

This is also most commonly asked question in collections. Interviewer start this question asking about collections and what are the data structure/collection you have used in development. Candidate generally answers HashMap, LinkedList, ArrayList, HashSet.  Then interviewer check your knowledge of equals, hashcode and hashing algorithm. You should be aware of HashMap class internal implementation. Follow up questions in HashMap are as follows: 
  • How to use HashMap in multi threading environment ? You should know that HashTable is thread safe. You can make HashMap thread safe by using Collections.synchronizedMap(Map)  
  • What is concurrent hashmap ? How concurrent hashmap is better then thread safe hashmap in multi threading environment ?

LinkedList

LinkedList is something where interviewer can judge your knowledge of collections and algorithm at the same time. 
  1. Collections: What is the difference in ArrayList and LinkedList ? 
  2. Algorithm: How to find a loop in LinkedList ? If you answer it then follow up question may asked:
    • How to find the starting point of loop in LinkedList ?
    • How to find the length of the loop in LinkedList ? 

MultiThreading

Interviewer can ask you any of following questions:

1. How to run 5 threads sequentially.
2. Print number 1 to 10 using two threads where thread 1 prints even number and thread 2 prints odd number.
3. Producer consumer implementation using wait notify.
4. What is deadlock ? How to identify deadlock in java application ? How to prevent deadlock situations in application development ?
5. CountDownLatch vs CyclicBarrier ?


String

1. What is immutable object ? How can you write Immutable Class ? If you know the internal implementation of String class and know how String is immutable, you can answer it easily.
2. Difference between String object created using new and literal.
3. Difference between StringBuilder and StringBuffer.
4. Why character array is used over String to store password ? 

Advance Java

1. How many ways you can create an object in java ?
        Answer: New Keyword, Cloning, Deserialization and Reflection.
2. Explain Java Memory Model with Heap structure. Explain here three parts of heap i.e. Young, Old and Permanent Generation. Also Explain Minor and Major GC
3. How to do JVM performance tuning ? Explain here parameters 
             a) Heap Memory: -Xms, -Xmx, -Xmn,
             b) Permanent Generation Memory: -XX:PermSize, -XX:MaxPermSize
             c) Garbage Collection i.e. 
                 -XX:+UseSerialGC, 
                 -XX:+UseParellelGC (-XX:ParellelGCThreads=<N>), 
                 -XX:+UseParellelOldGC, 
                 -XX:+UseConcMarkSweepGC (-XX:ParellelCMSThreads=<N>), 
                 -XX:+UseG1GC

 4. What is classloader in java ? How to write custom class Loader ? What is linkage error ?
 5. Give example of 5-6 design patterns being used in Java classes. 
 6. Do you know about anti patterns ? What is god class ?

 7. Do you know about serialization ? When should we use that ? What is the role of Serialization id ? serializable vs externalizable ?


Collection

These are legacy interview questions which are not asked frequently now a days but they are good to know.

1. Difference between ArrayList and LinkedList.
2. Difference between ArrayList and Vector.

Wednesday, 9 September 2015

How to use superscript in HighChart labels

This is how you can use superscript in HighChart labels using useHTML property :

(you can run and edit below code here  : http://jsfiddle.net/lahoti32/j0ue1naf/ )

$(function () {
    $('#container').highcharts({
chart: {
            type: 'column'
        },
        credits : {
            enabled : false
        },
        title: {
            text: 'Chart Title<sup>1</sup>',
            useHTML : true,
        },
        xAxis: {
categories: [ 'label1','label2','label3<sup>4</sup>','label4'],
            title:{
                enabled: false
            },
            labels: {
                useHTML : true,
                title: {
                    enabled: false
                }         
            },
        },
        yAxis: {
            title: {
                enabled: false
            },
            labels: {
                useHTML : true,
                formatter:function(){
                    if(this.value != 10){
                        return this.value;
                    }else{
                        return this.value + '<sup> 2</sup>';
                    }
                }
            }
        },
        legend: {
            useHTML : true,
            borderWidth: 0,
            labelFormatter:function(){
                if(this.name != 'legend1'){
                    return this.name;
                }else{
                    return this.name + '<sup> 5</sup>';
                }
            }
        },
        plotOptions: {
            column: {
                dataLabels: {
                    enabled: true,
                    useHTML : true,
                    y:-1,
                    formatter:function(){
                        if(this.y != 0){
                            if(this.y > 8 && this.y < 10){
                                return this.y + '<sup> 3</sup>';
                            }else{
                                return this.y;
                            }

                        }else{
                            return null;
                        }
                    }
                }
            }
        },
        series: [{ 
            data: [{ 
                y: 14.913
            }, { 
                y: 8.281
            }, { 
                y: 3.592
            }, { 
                y: 3.017
            }], 
            showInLegend: false,
        },{
            name: 'legend1',
            color: 'rgb(14,178,89)'      
        },{
            name: 'legend2',
            color: 'rgb(100,100,9)'      
        }]
    });
});

Sunday, 12 July 2015

fibonacci series in java

Fibonacci series implementation in java is frequently asked question in interview at fresher level. Moreover, it is a very famous example to show how to use recursive function in java.


public class Fibonacci {

    public static void main(String[] args){
        fibonacci(15);
    }
    
    /**
     * This method is used to print fibonacci series
     * @param n is total number of elements
     */
    private static void fibonacci(int n){
        for(int i = 0 ; i < n; i ++){
            System.out.print(fib(i)+", ");
        }
    }
    /**
     * This method is used recursively to find fibonacci
     * element at nth index. 
     * @param n is index
     * @return element
     */
    private static int fib(int n){
        if(n < 2)
            return n;
        return fib(n-1) + fib(n-2);
    }
}

Output : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377 

Tuesday, 9 June 2015

Sorting Algorithm : Bubble Sort

Why it is called bubble sort ?

Bubble Sort is nothing but a comparison algorithm where - 
- At the end of first iteration, largest element in the array get placed at last index
- At the end of second iteration, second largest element in the array get placed at second last index and so on...
This way large elements are moving towards the last indexes and hence small elements are moving towards the starting indexes which is also termed as smaller elements "bubble" to the top of the list that is why it is called bubble sort.

Step-by-step example

Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to greatest number using bubble sort. In each step, elements written in bold are being compared. Three passes will be required.
First Pass:
5 1 4 2 8 ) \to ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) \to ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) \to ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) \to ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
1 4 2 5 8 ) \to ( 1 4 2 5 8 )
( 1 4 2 5 8 ) \to ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
Now, the array is already sorted, but the algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )

Algorithm In Java


package com.test.algorithm.sort;
/*
 *Bubble Sort is nothing but a comparison algorithm where - 
 *- At the end of first iteration, largest element in the array get placed at last index
 *- At the end of second iteration, second largest element in the array get placed at second last index and so on...
 *This way large elements are moving towards the last indexes and hence small elements are moving towards the starting indexes 
 *which is also termed as smaller elements "bubble" to the top of the list that is why it is called bubble sort.
 */

public class BubbleSort {

    public static void main(String[] args){
        int[] array = new int[]{5, 1, 12, -5, 16};
        BubbleSort.sort(array);
    }
    
    private static void sort(int[] array){
        int count = 0;
        for(int i = array.length ; i > 0 ; i --, count++){
            for(int j = 0 ; j < array.length-1 ; j++, count++){
                if(array[j] > array[j+1]){
                    swapNumbers(j, j+1, array);
                }
            }
        }
        printNumbers(array, count);
    }
    
    private static void swapNumbers(int i, int j, int[] array) {
        int temp;
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    
    private static void printNumbers(int[] array, int count) {
        System.out.print("Sorted Array : {");
        for(int i : array){
            System.out.print(i + " ");
        }
        System.out.print("}, n : " + array.length + ", comparisons : " + count);
    }
}

Output : Sorted Array : {-5 1 5 12 16 }, n : 5, comparisons : 25

Time Complexity for worst case is O(n2). Algorithm can be further improved :

private static void sort(int[] array){
        int count = 0;
        for(int i = array.length ; i > 0 ; i --, count++){
            for(int j = 0 ; j < i-1 ; j++, count++){
                if(array[j] > array[j+1]){
                    swapNumbers(j, j+1, array);
                }
            }
        }
        printNumbers(array, count);
    }

Output :Sorted Array : {-5 1 5 12 16 }, n : 5, comparisons : 15

Friday, 1 May 2015

Stack Implementation Using Priority Queue

Stacks may be modeled as particular kinds of priority queues. In a stack, the priority of each inserted element is monotonically increasing; thus, the last element inserted is always the first retrieved.
Stack Implementation : 

import java.util.NoSuchElementException;
import java.util.PriorityQueue;


public class StackImplementationUsingPQ {

    private PriorityQueue pq = new PriorityQueue();
    private int counter = 0;
    
    public void push(String s){
        Element e = new Element(s, counter++);
        pq.add(e);
    }
    
    public String pop(){
        Element e = null;
        try{
            e = pq.remove();
            counter--;
        }catch(NoSuchElementException ex){
            return "'Stack is Empty'";
        }
        return e.toString();
    }
    
    public static void main(String[] args){
        StackImplementationUsingPQ stack = new StackImplementationUsingPQ();
        stack.push("Banana");
        stack.push("Mango");
        stack.push("Apple");
        System.out.println(stack.pop());
        stack.push("Orange");
        stack.push("Pinapple");
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }
    
}
class Element implements Comparable{
    
    private Integer priority;
    private String value;
    
    Element(String value, Integer priority){
        this.value = value;
        this.priority = priority;
    }
    
    
    public Integer getPriority() {
        return priority;
    }
    public void setPriority(Integer priority) {
        this.priority = priority;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public int compareTo(Element o) {
        return o.getPriority().compareTo(this.getPriority());
    }
    
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("value : ");
        sb.append(getValue());
        sb.append(", ");
        sb.append("priority : ");
        sb.append(getPriority());
        return sb.toString();
    }

Output:

value : Apple, priority : 2
value : Pinapple, priority : 3
value : Orange, priority : 2
value : Mango, priority : 1
value : Banana, priority : 0
'Stack is Empty'