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


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'

Monday, 6 April 2015

Elevator Implementation in Java

Implementation of Elevator/ Lift has been asked in many interviews. I have tried to implement it using muti-threading and TreeSet. TreeSet is used to store incoming request. It is a good choice here as it removes the duplicate requests and implements NavigableSet which provide you methods such as floor and ceiling.

Elevator in this program implements following features -
  • If elevator is going up or down, it checks for nearest floor request to process first in that direction. 
  • If there is no request to process, it waits at last processed floor.
  • If a new request comes while elevator is processing a request. It process the new request first if it is nearest than the processing floor in same direction.




import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.TreeSet;

public class MyLift {

    public static void main(String[] args) {
        System.out.println("Welcome to MyLift");
        // RequestListenerThread to read requested floor and add to Set
        Thread requestListenerThread = new Thread(new RequestListener(),
                "RequestListenerThread");
        // RequestProcessorThread to read Set and process requested floor
        Thread requestProcessorThread = new Thread(new RequestProcessor(),
                "RequestProcessorThread");
        
        Elevator.getInstance().setRequestProcessorThread(requestProcessorThread);
        
        requestListenerThread.start();
        requestProcessorThread.start();
        
        
    }
}

class Elevator {
    
    private static Elevator elevator = null;
    
    private TreeSet requestSet = new TreeSet();
    
    private int currentFloor = 0;

    private Direction direction = Direction.UP;

    private Elevator() {};
    
    private Thread requestProcessorThread;

    /**
     * @return singleton instance
     */

    static Elevator getInstance() {
        if (elevator == null) {
            elevator = new Elevator();
        }
        return elevator;
    }

    /**
     * Add request to Set
     * 
     * @param floor
     */

    public synchronized void addFloor(int f) {
        requestSet.add(f);
        
        if(requestProcessorThread.getState() == Thread.State.WAITING){
            // Notify processor thread that a new request has come if it is waiting
            notify();
        }else{
            // Interrupt Processor thread to check if new request should be processed before current request or not. 
            requestProcessorThread.interrupt();
        }
        
    }

    /**
     * @return next request to process based on elevator current floor and direction
     */

    public synchronized int nextFloor() {

        Integer floor = null;

        if (direction == Direction.UP) {
            if (requestSet.ceiling(currentFloor) != null) {
                floor = requestSet.ceiling(currentFloor);
            } else {
                floor = requestSet.floor(currentFloor);
            }
        } else {
            if (requestSet.floor(currentFloor) != null) {
                floor = requestSet.floor(currentFloor);
            } else {
                floor = requestSet.ceiling(currentFloor);
            }
        }
        if (floor == null) {
            try {
                System.out.println("Waiting at Floor :" + getCurrentFloor());
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            // Remove the request from Set as it is the request in Progress.
            requestSet.remove(floor);
        }
        return (floor == null) ? -1 : floor;
    }

    public int getCurrentFloor() {
        return currentFloor;
    }
    
    /**
     * Set current floor and direction based on requested floor
     * 
     * @param currentFloor
     * @throws InterruptedException 
     */

    public void setCurrentFloor(int currentFloor) throws InterruptedException {
        if (this.currentFloor > currentFloor) {
            setDirection(Direction.DOWN);
        } else {
            setDirection(Direction.UP);
        }
        this.currentFloor = currentFloor;
        
        System.out.println("Floor : " + currentFloor);
        
        Thread.sleep(3000);
    }

    public Direction getDirection() {
        return direction;
    }

    public void setDirection(Direction direction) {
        this.direction = direction;
    }

    public Thread getRequestProcessorThread() {
        return requestProcessorThread;
    }

    public void setRequestProcessorThread(Thread requestProcessorThread) {
        this.requestProcessorThread = requestProcessorThread;
    }

    public TreeSet getRequestSet() {
        return requestSet;
    }

    public void setRequestSet(TreeSet requestSet) {
        this.requestSet = requestSet;
    }
    
}

class RequestProcessor implements Runnable {

    @Override
    public void run() {
        while (true) {
            Elevator elevator = Elevator.getInstance();
            int floor = elevator.nextFloor();
            int currentFloor = elevator.getCurrentFloor();
            try{
                if (floor >= 0) {
                    if (currentFloor > floor) {
                        while (currentFloor > floor) {
                            elevator.setCurrentFloor(--currentFloor);
                        }
                    } else {
                        while (currentFloor < floor) {
                            elevator.setCurrentFloor(++currentFloor);
                        }
                    }
                    System.out.println("Welcome to Floor : " + elevator.getCurrentFloor());
                }
                
            }catch(InterruptedException e){
                // If a new request has interrupted a current request processing then check -
                // -if the current request is already processed
                // -otherwise add it back in request Set
                if(elevator.getCurrentFloor() != floor){
                    elevator.getRequestSet().add(floor);
                }
            }
        }
    }
}

class RequestListener implements Runnable {

    @Override
    public void run() {

        while (true) {
            String floorNumberStr = null;
            try {
                // Read input from console
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
                floorNumberStr = bufferedReader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (isValidFloorNumber(floorNumberStr)) {
                System.out.println("User Pressed : " + floorNumberStr);
                Elevator elevator = Elevator.getInstance();
                elevator.addFloor(Integer.parseInt(floorNumberStr));
            } else {
                System.out.println("Floor Request Invalid : " + floorNumberStr);
            }
        }
    }

    /**
     * This method is used to define maximum floors this elevator can process.
     * @param s - requested floor
     * @return true if requested floor is integer and upto two digits. (max floor = 99)
     */

    private boolean isValidFloorNumber(String s) {
        return (s != null) && s.matches("\\d{1,2}");
    }

}

enum Direction {
    UP, DOWN
}

Wednesday, 5 June 2013

Check for Updates in eclipse is not working


  1. In Eclipse (go to Preferences > General > Network connections).
  2. Select "Active Provider" as "Manual".
  3. Select HTTP and click edit.
  4. Enter the host and port
  5. Select "Requires Authentication" and enter the username and password.
  6. Repeat Step 1 to 5 for Https.
  7. In "proxy bypass" section click "Add host"
In  case it does not work try to play with Active Provider - General , Manual , Native

Top CSS Interview Questions

These CSS interview questions are based on my personal interview experience. Likelihood of question being asked in the interview is from to...