Aug 23, 2013

How to make thread safe servlet ?

I was asked this question once in an interview Is servlet thread safe ? Luckily they did not drilled much why and how ? I have documented here for the same.

Say loudly two times !! Servlet is not thread safe unless we make it. It is developer responsibility to make servlet thread safe. What does mean thread safe servlet ?
Each servlet request is served by one instance of servlet (Generally speaking) so separate thread is created by container for entertaining each request and servlet container may send concurrent requests through the service method of the servlet. So in order to handle the requests concurrently, if the Servlet Developer make adequate provisions for concurrent processing with multiple threads in the service method then that servlet is called thread safe servlet.
Now question arise how we can make it thread safe?There are few solutions available we will see one by one.

Using ServletThreadModel interface implementation : It is simplest approach but not recommended since it has been deprecated. when we implement this interface servlet container gives guarantee that only one request thread will be present in service method.
What servlet container does then ? Servlet container may either
  • Instantiate multiple instances of the servlet (maintaining a pool of servlet instances). It will be used in a distributed environment where each jvm will be having a servlet instance for serving concurrent request.
  • Serialize requests to a particular instance.  In this case one instance will cater cater multiple request serially
    Reference : SingleThreadModel
By synchronizing service method :  Service method may be appended with synchronized keyword so that only one thread request will be under service method at a time. But in this way performance will be very poor.So it is also not recommended.Then what we need to do ?
A simple rule which need to be followed to make Servlet shared among all active thread in thread safe manner is:
"just do not assign request or session scoped data as servlet instance variables, only as method local variables."
Lets see using an example :
public class SimpleServlet extends HttpServlet {
  private Object NotThreadSafe;
  protected void doGet(HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException, IOException {
    Object ThreadSafe;
    NotThreadSafe = request.getParameter("foo");  
                 //Its Bad Design, Shared among all requests!
    ThreadSafe = request.getParameter("foo"); 
                // OK, this is thread safe.
    } 
 }
Here NotThreadSafe is an instance variable so it is shared among all thread and it is not thread safe.But at same time ThreadSafe is local variable and is unique for all thread and it is thread safe.

=================End of the article===================
Happy learning!!.

Related post, you may like it:
1. Servlet Life Cycle

Aug 22, 2013

Textual description of firstImageUrl

Display matrix elements in a spiral order.

Problem :  We have to display elements of matrix in spiral order. For the given matrix mat(4x4).
               

 In Output order of elements should be  : 1  2  3  11  12  13  9  8  7  4   5  6
 Note : solution proposed is valid for matrix of any order  (mxn) 


Solution :  First we traverse row wise  in right direction and then column wise in bottom direction,then again row wise in left direction and again column wise  in  upward direction, this way we have completed one complete cycle of matrix.We repeat same process until we have row and column elements left.

Algorithm :
     Initialize row=0 and col = 0, row and column order is mxn  
       Loop until row < m & col < n (row elements and column elements exist)  
       First : Iterate row-wise first   
           for i=col to n  
             print arr(row,i)  
           Increment row.  
       second : Iterate Coulumn in bottom direction from top right  
                      for i = row to m   
                       print arr(i,n)  
                decrement n.   
            third : Iterate row in left direction from rith to left  
                      for i=n-1 to col  
                        print arr(m-1,i)  
                      decrement m.  
            four : Iterate column from bottom to top  
                      for i=m-1 to row  
                       print arr(i,col)   
                       increment col.  
            repeat from step first.  

Now we will write sample code in java for desired result. Sample running program is as follows :
 public class SpiralPatternGeneration {  
   public SpiralPatternGeneration() {  
     super();  
   }  
   public static void spiralPatternGeneration(int[][] mat, int m, int n) {  
     int col = 0, row = 0;  
     int i;  
     while (row < m && col < n) {  
       for (i = col; i < n; i++) {  
         System.out.print(mat[row][i] + " ");  
       }  
       row++;  
       for (i = row; i < m; i++) {  
         System.out.print(mat[i][n - 1]+ " ");  
       }  
       n--;  
       if (row < m) {  
         for (i = n - 1; i >= col; i--) {  
           System.out.print(mat[m - 1][i] + " ");  
         }  
         m--;  
       }  
       if (col < n) {  
         for (i = m - 1; i >= row; i--) {  
           System.out.print(mat[i][col] + " ");  
         }  
         col++;  
       }  
       System.out.println(" ");  
     }  
   }  
   public static void main(String[] args) {  
     SpiralPatternGeneration spiralPattern = new SpiralPatternGeneration();  
     int[][] m = { { 1, 2, 3,11 }, { 4, 5, 6,12 }, { 7, 8, 9 ,13} };  
     spiralPatternGeneration(m, 3, 4);  
   }  
 }  

Sample output  when we execute the above program comes as :
1 2 3 11 12 13 9 8 7 4
5 6
First line(1 to 4 )  is outcome of one round of spiral movement
second line(5-6)  is outcome of second iteration.
-------------------------------------------------------------------------

Aug 19, 2013

Textual description of firstImageUrl

Reverse a string in java via Iterative and recursive approach.

This is very common interview question asked to warm up the interview session specially recursive approach. This problem can be solved in many ways , we will discuss iterative way first followed by recursive approach.
Iterative approach :   
1.  Using normal looping and outcome string holder : It is simplest approach for string reversal .
         Algorithm :     Convert Input string into char array
                               loop char array in opposite direction (from last to first index)
                                    store each character in temporary string holder(outcome string holder.
Sample code and inline comments for above mentioned approach :
   public StringBuffer reverseString(String str) {  
char[] strCharArry = str.toCharArray(); //Convert input string to char array
StringBuffer sbf = new StringBuffer(); // temp string holder to store result
for (int i = strCharArry.length - 1; i >= 0; i--) {
sbf = sbf.append(str.charAt(i));
}
return sbf;
}
we have used StringBuffer(A mutable sister of String) for storing the reversed string.

2. In-place reversal without using extra string holder : In this approach we will stick to normal looping but we will not use any extra string holder. Instead we use some temporary variable to store char and indexes wile iterating.
Algorithm :  Loop input string using two index start and end , until start is less than end
                   Swap start index char and end index
                      change the index's position and repeat
Sample code for the above mentioned approach :
   public String reverseInplace(StringBuffer str) {  
char temp;
for (int i = 0, j = str.length() - 1; i < j; i++, j--) {
temp = str.charAt(i);
str.setCharAt(i, str.charAt(j));
str.setCharAt(j, temp);
}
return str.toString();
}
For swapping of char we are using stringBuffer's method to set the char value at specified index.

3. Using XOR operation : It is really tricky one, I admit it. Before going into delve it is worth to  understand the basic concept behind it XOR swapping algorithm.Now using XOR swap algorithm we will solve this problem.
Algorithm :  Loop input string with two index start and end, until start is less than end.
                   for each char pointing start and end (X = char at start index and Y = char at end index)
                   do this and swap it
                        X = X XOR Y
                        Y = X XOR Y
                        X = X XOR Y
Now we will write sample code which uses input string as StringBuffer and its method charAt(index) and  in each iteration get char from start and end index and swap it. Sample code is as follows :
   public StringBuffer reverseByXOROperation(StringBuffer str) {   
int inputLenght = str.length();
for (int i = 0, j = inputLenght - 1; i < j; i++, j--) {
str.setCharAt(i, (char)(str.charAt(i) ^ str.charAt(j)));
str.setCharAt(j, (char)(str.charAt(i) ^ str.charAt(j)));
str.setCharAt(i, (char)(str.charAt(i) ^ str.charAt(j)));
}
return str;
}

Recursive approach:
4.Using recursion:  It is most commonly asked approach in an interview.
   Algorithm :  Iterate input string fetching one char at a time
                     repeatedly call recursive method for remaining of the char and append the preprocessed char
  Best way to visualize the recursive approach via sample code , so we will see first the sample code :
   public String reverseByRecursion(String str) {  
if (null == str || str.length() == 1) {
return str;
} else {
String reverse = reverseByRecursion(str.substring(1))
+ str.charAt(0);
return reverse;
}
}

How it is working ? : lets take input string as "java"
When first time control comes inside loop , since "java" is not null so if  block is not executed. so it comes in else block, under else  String reverse = reverseByRecursion(str.substring(1)) + str.charAt(0);  changes to String reverse = reverseByRecursion("ava") + j, Diagrammatically have shown below the  recursive call and how it concludes in upward direction.

............................................................................................................................................................
Finally reverse is returned to caller of this method as "avaj" and this concludes various string reversal approaches.
                                 

Happy learning!!
Nikhil

Aug 17, 2013

Textual description of firstImageUrl

Binary tree traversal in Java - Preorder,Inorder,Postorder.

Tree traversal:- In order to process binary tree, the mechanism(different ways) of visiting nodes of tree is termed as tree traversal. Since tree is a non-linear data structure so there are different possible ways to traverse node of trees, as contrast to sequential data structure(stacks, linked list and queues) - nodes are visited in sequential order.

Traversal classification:-
 Tree traversal may be classified in following category:-
  • Based on current nodes data processing - D represents data of current node, L left child and R right child
    1. Preorder (DLR) - First data of current node is processed followed by left and right child
    2. Inorder (LDR) - First left node is processed followed by current node and then right child
    3. Postorder (LRD) - First left and right child is processed and after that current node is processed.
  • Based on hierarchy of tree nodes -
    1. Level order traversal
    2. Zig-zag traversal and many more...  
In following post, we will see recursive version of preorder, inorder and postorder traversal.Consider following binary tree for further discussion :-
Definition of Preorder traversal:- In preorder traversal, each node is processed before either of its sub-tree(left and right). Once current node is processed, left sub-tree is processed and control return back to current node and then right sub-tree is processed, so in recursive call stack maintains references of left and right children. It can be summarize as :-
1. Visit the root and process data
2. Traverse to left subtree
3. Traverse to right subtree.
In preorder traversal of above tree, nodes would be visited in following order:- 12 , 23 , 11, 43, 18, 12
/* preOrder traversal - Recursive version */
public void preorderTraversal(Node root, StringBuffer sbr) {
 if (root == null)
  return;
 /* Append node data in string buffer */
 sbr.append(root.getData() + " ");
 preorderTraversal(root.getLeftChild(), sbr);
 preorderTraversal(root.getRightChild(), sbr);
}
Definition of Inorder traversal:- In inorder traversal, left sub-tree is pocessed first and control return back to current node and finally right subtree is processed. In recursive call stack (LIFO) maintains references of left and right children and helps in processing nodes in particular order.It can be summarized as:
1. Traverse to left subtree
2. Visit the root and process data
3. Traverse to right subtree.
In preOrder traversal of above tree, nodes would be visited in following order:- 11 23 43 12 12 18
/* inOrder traversal - Recursive version */
public void inorderTraversal(Node root, StringBuffer sbr) {
 if (root == null)
  return;
 inorderTraversal(root.getLeftChild(), sbr);
 /* Append node data in string buffer */
 sbr.append(root.getData() + " ");
 inorderTraversal(root.getRightChild(), sbr);
}
Definition of Postorder traversal:- In postorder traversal, first left subtree is processed followed by right subtree and then control returns back to current node. In recursive call stack (LIFO) maintains references of left and right children and helps in processing nodes in particular order.It can be summarize as :-
1. Traverse to left subtree
2. Traverse to right subtree.
3.Visit the root and process data
In postOrder traversal for above tree, nodes would be visited in following order:- 11 43 23 12 18 12
/* postOrder traversal - Recursive version */
public void postorderTraversal(Node root, StringBuffer sbr) {
 if (root == null)
  return;
 postorderTraversal(root.getLeftChild(), sbr);
 postorderTraversal(root.getRightChild(), sbr);
 /* Append node data in string buffer */
 sbr.append(root.getData() + " ");
}
Complete sample program - Preorder,Inorder,Postorder
package com.devinline.trees;

public class BinaryTree {
 Node root;

 public BinaryTree() {
  root = null;
 }

 public Node createTree() {
  if (root == null) {
   root = new Node(12);
  }
  root.setLeftChild(new Node(23));
  root.setRightChild(new Node(18));
  root.getLeftChild().setLeftChild(new Node(11));
  root.getLeftChild().setRightChild(new Node(43));
  root.getRightChild().setLeftChild(new Node(12));

  return root;
 }

 /* preOrder traversal - Recursive version */
 public void preorderTraversal(Node root, StringBuffer sbr) {
  if (root == null)
   return;
  /* Append node data in string buffer */
  sbr.append(root.getData() + " ");
  preorderTraversal(root.getLeftChild(), sbr);
  preorderTraversal(root.getRightChild(), sbr);
 }

 /* inOrder traversal - Recursive version */
 public void inorderTraversal(Node root, StringBuffer sbr) {
  if (root == null)
   return;
  inorderTraversal(root.getLeftChild(), sbr);
  /* Append node data in string buffer */
  sbr.append(root.getData() + " ");
  inorderTraversal(root.getRightChild(), sbr);
 }

 /* postOrder traversal - Recursive version */
 public void postorderTraversal(Node root, StringBuffer sbr) {
  if (root == null)
   return;
  postorderTraversal(root.getLeftChild(), sbr);
  postorderTraversal(root.getRightChild(), sbr);
  /* Append node data in string buffer */
  sbr.append(root.getData() + " ");
 }

 /* Level order traversal - Recursive version */
 public void levelorderTraversal(Node root, StringBuffer sbr) {
  if (root == null)
   return;
  postorderTraversal(root.getLeftChild(), sbr);
  postorderTraversal(root.getRightChild(), sbr);
  /* Append node data in string buffer */
  sbr.append(root.getData() + " ");
 }

 public static void main(String[] args) {
  BinaryTree bt = new BinaryTree();
  Node root = bt.createTree();
  StringBuffer sbr = new StringBuffer();
  bt.preorderTraversal(root, sbr);
  System.out.println("Pre order traversal:\t" + sbr.toString());
  sbr = new StringBuffer();
  bt.inorderTraversal(root, sbr);
  System.out.println("In order traversal: \t" + sbr.toString());
  sbr = new StringBuffer();
  bt.postorderTraversal(root, sbr);
  System.out.println("Post order traversal:\t" + sbr.toString());
 }
}

class Node {

 private int data;
 private Node leftChild;
 private Node rightChild;

 public Node(int data) {
  this.data = data;
  leftChild = null;
  rightChild = null;
 }

 public int getData() {
  return data;
 }

 public void setData(int data) {
  this.data = data;
 }

 public Node getLeftChild() {
  return leftChild;
 }

 public void setLeftChild(Node leftChild) {
  this.leftChild = leftChild;
 }

 public Node getRightChild() {
  return rightChild;
 }

 public void setRightChild(Node rightChild) {
  this.rightChild = rightChild;
 }

}
========Sample output==========
Pre order traversal:  12 23 11 43 18 12
In order traversal:  11 23 43 12 12 18
Post order traversal: 11 43 23 12 18 12
============================

Aug 15, 2013

Textual description of firstImageUrl

Servlet life cycle

If you are all set to attend an interview related to J2EE/Java Web application development then, it is recommended to brush up this important concept.I witnessed this question in telephonic round interview. Today I am documenting it for future reference and for others.
What is Servlet ?:  A Servlet is a Java program that runs within a servlet container. Servlets receive and respond to requests from Web clients. Servlets could in principle communicate over any client–server protocol, but they are most often used with the HTTP protocol. Thus "servlet" is often used as shorthand for "HTTP servlet". As every object is having a life-cycle so as of servlet instance.
The life-cycle of a servlet is controlled by the container in which the servlet has been deployed. Life cycle of servlet can be broadly divided into three stages :
1. Initialization stage -  init() -   Executed only once
2. Service stage -            service() -     For each request
3. Destroy stage. -          destroy() -     Executed only once
 We can represent all three method executing in servlet container as follows :
 
                                             Diagram taken from : http://www3.ntu.edu.sg/

1. Initialization phase : In this stage web-container initializes the servlet instance by calling the init() method and ONE instance per JVM for each servlet is created. It is important to note that init() method can be invoked in either of two ways :
1. On demand basis  - On arrival of first HTTP request for the given servlet .
2. On Servlet container start: When servlet container start,it reads the web.xml ,finds the declared servlets in the classpath and if <load-on-startup> is configured with an  integer value 0 or more then for the given servlet one instance of that servlet will be created and are stored in memory and reused every time the request arrives. (Always remember REUSED !!).Sample code for servlet config of  load-on-startup:
     <servlet>
           <servlet-name>controlServlet</servlet-name>
          //Mapping details .....
          <load-on-startup> 1 </load-on-startup>
    </servlet>
Note : load-on-startup can specify an (optional) integer value. If the value is greater than 0, it indicates an order for servlets to be loaded, servlets with higher numbers get loaded after servlets with lower numbers.
Please note, init(ServletConfig) is being called by the servlet container to indicate a servlet that the servlet is being placed into service.We can override this init() method see this for reference. 
  public void init(ServletConfig config) throws ServletException 
  { 
       //some initialization - like getting database connection,
       // resource management etc.
   } 
Here is a visual explanation of Instantiation phase, in layman terminology.
Notes : 
  • init() is not the entry point of a servlet. servlet constructor is executed before execution of init() but it is not  recommended to use constructor for any Servlet. why? Find here
  • The container would decide how many instances of servlet would be instantiated upfront to cater the requests.This is container implementation..(Confused !! But it's fact)
2. Service phase : In this stage for every new request a new thread is created or allocated from a pool to invoke that servlet instance which was created in earlier stage . The HttpRequest and HttpResponse objects will be new for each new request.
One commonly asked question in interview : How HTTP request coming from web client is served by servlet ? 
On request arrival web container(servlet container) calls service() method of servlet and the service() method determines the kind of request and calls the appropriate method (doGet() or doPost() for handling the request and sends response to the client using response object. Lets consider following code blocks:
 public class SimpleHttpServlet extends HttpServlet {
  protected void doGet( HttpServletRequest request,
                        HttpServletResponse response)
        throws ServletException, IOException {
      response.getWriter().write("<html><body>GET response</body></html>");
  }
  protected void doPost( HttpServletRequest request,
                         HttpServletResponse response)
      throws ServletException, IOException {
      response.getWriter().write("GET/POST response");
  }
}
HttpServlet(javax.servlet.http.HttpServle) class reads the HTTP request(coming from client), and determines if the request is an HTTP GET, POST, PUT, DELETE, HEAD etc. and calls one the corresponding method.
Notes :
  • It is important to note that each request is served by a new thread if and only if our servlet is not implementing SingleThreadModel interface. It is not recommended to use SingleThreadModel interface. 
  • Is servlet threadsafe ? Answer is : No, but we can make by it thread-safe by following some standard so that it can serve multiple request in thread safe manner. How we can make servlet thread safe?
3. Destroy phase : When a servlet is unloaded by the servlet container, its destroy() method is called. It is executed only once in servlet life cycle. A servlet is unloaded by the container if the container shuts down, or if the container reloads the whole web application at run-time.

Refer J2EE developer interview questions

======================End of article=====================

Aug 11, 2013

Run time complexity- Analysis of loops

Its' the very first thing one should understand before studying algorithm - what is running time complexity of block of code/How to find running time complexity ?
For beginner it's very important to understand running complexity for simple loops since it is commonly asked question in preliminary interview rounds. I came across such stuff in my interviews so documented for my reference and others too :)

We will proceed with some sample code , associated complexity and  small analysis notes.
  • O(1) or Constant time complexity : Constant time complexity means - Time taken to execute a particular set of code is independent of size of input.In other words, We can represent a constant upper bound to how long the program will take to run which isn't affected by any of the input parameters. "Time complexity of a function (or set of statements) is considered as O(1): if it doesn't contain loop, recursion and call to any other non-constant time function. Please note that a loop or recursion that runs constant number of times is also considered as running time of complexity O(1)". lets consider following snippet code
     for (int i = 1; i <= c; i++) { 
    //some operation of constant complexity i.e : Swap operation.
    }
    Analysis :  Since loop is running constant number of times, so complexity of this for loop is O(1). Please note that swap operation is having complexity of O(1). It is also good question to confuse somebody specially in interview.
  • Order of O(n) complexity or linear time complexity : linear time complexity means - Time taken to complete the execution of the block of code is "order of size of input". Time Complexity of a running loop is considered as O(n) if the loop variables is incremented / decremented by a constant amount. lets consider following code :
     for (int i = 1; i <= n; i += c) { 
    // some O(1) expressions
    }
    //Here n is input size and c is constant
    //which is incremented each time.
    Analysis: Since loop is running in order of n times and it is incremented each time by a constant , so running time of this loop is O(n). Please note instead of increment operation with constant, if we decrements with same constant and then also running time will be o(n) itself. After modifying for loop will look like this :
      for (int i = n; i > 0; i - = c) {  // i is decremented by c
       // some O(1) expressions
      }
  • Order of O(n^2) time complexity/Nested looping complexity:Time complexity of nested loops is equal to the number of times the innermost statement is executed. Lets consider :
     for (int i = 1; i <=n; i += c) {
    for (int j = 1; j <=n; j += c) {
    //innermost statement with respect to outer loop
    // some O(1) expressions
    }
    }
    Analysis : Here innermost loop is running n + n-1+n-2 ..............+1 times and sum-up values comes out as n(n+1)/2 so it is order of O(n2). Selection sort and Insertion Sort have O(n2) time complexity.
    Please note : In above snippet code, we have increment operation by constant value. It matters lets see below how ?
  • Order of O(Logn) time complexity : Now we will change the increment section in for loop from a constant to a variable. we see that run time complexity of loop has improved from O(n) to O(Logn). Lets consider:
     for (int i = 1; i <=n; i *= c) {
    // some O(1) expressions
    }
    Analysis : In for loop increment operator is multiplied by a constant so running time leads to   O(Logn). So how it happened ? Lets take a simple example and see how it happened. lets assume c = 2 for simplicity. The size of the input cut down by some constant factor on each iteration. The algorithm must terminate after O(log n) iterations, because after doing O(log n) divisions by a constant, the algorithm must shrink the problem size down to 0 or 1.If n = 16 ,  How many times can you divide n by two before you get a number less than or equal to one ? Its 4 .If n = 128 , How many times can you divide n by two before you get a number less than or equal to one ? Its 7 .
    S
    o what is happening..For 16 , log2 16 = 4.For 128 , log2 128 = 7 and so on.......we can conclude that on diving by 2 each time we are reducing size by 2 so instead of taking n iteration it will take only O(log n) iterations.
    Reference links :  Algorithm to have o(log n) complexity
  • Order of O(log log n) time complexity: Now we will add some more twist in loops. What will happen : Instead of multiplying or dividing by constant we take a square root of loop variable or take square of it or loop variable is incremented exponentially. Lets consider this code:
     for (int i = 2; i <=n; i = pow(i, c)) { 
    // some O(1) expressions
    }

    Analysis : Run time complexity will be O(log log n). Below mentioned link best explains how it happens, An algorithm to have O(log log n) complexity

Reference :  geeksforgeeks

Thanks and happy learning!!
Nikhil  

Aug 10, 2013

Java puzzle -Set 1

Disclaimer : I do not claim that contents available here are my own , it's compiled by me after reading various pages on internet to make others life easy. :) Happy learning!!

Question 1:   Static block trap!! What will be the output of this program ?
public class Test {  
   static {  
     main(new String[]{"[Static call]"});  
   }  
   public static void main(String[] args) {  
     System.out.println(args.length > 0 ? args[0] : 
                                        "[From main]");  
   }  
 }
Solution : Here two time main method will be called one originated from static block (Since on loading a class by class loader static block elements are scanned from top to bottom and executed one by one) So in this case static block code will be executed and main method will be executed. Later since execution of program is starts from main(Its golden rule in java) so second time again main method will be executed.Sample output is :
 Static call
 From main
Question 2: Give a try with ternary operator!! What will be the output of this program ?
public class TernaryOperation{  
   public static void main(String[] args) {  
     char x = 'X';  
     int i = 0;  
     System.out.print(true ? x : 0);  
     System.out.print(false ? i : x);   
   }  
 }  
Solution: At first look it appears easy and output flashes in mind ,match your output with sample output below. We will go into delve of problem and concept behind it , from first SOP it is clear that conditional expression is true so value of x will be printed (i.e : X) but what happened to second SOP ?  it did not printed 'X' again , instead printed ASCII value of 'X'. As per JLS(Java language specification) automatic conversion of type comes into picture in ternary operator if type is integer or double is there.please refer this and this for detail.
Some general rules to workout such problem :
1. If any operand is double final result will be of double type.
2. If operand is of reference type the unboxing will happen there.
3. If one operand char and other is variable of type int then final result will be of type int. Sample output is:
  X 88
Question 3 : Do you recognize me ">>" and ">>>" ? Verify your output with sample outcome.
 public class ShiftOperators {  
   public static void main(String[] args) {    
      System.out.println("I(>>) maintain sign so (-4 >> 2) is : 
                                                      "+ -4>>2);  
      System.out.println("I(>>) maintain sign so (4 >> 2) is :
                                                       "+ 4>>2);
      System.out.println("I do not (>>>) maintain sign so  
                               (-4 >>> 2) is :" + -4>>>2);
      System.out.println("I do not (>>>) maintain sign so 
                                (4 >>> 2) is :" + 4>>>2);
   } 
}
Solution:  Java supports following two right shift operators : signed right shift operator >> and
Unsigned right shift operator >>>.
The operator ‘>>’ uses the sign bit (left most bit) to fill the trailing positions after shift. If the number is negative, then 1 is used as a filler and if the number is positive, then 0 is used as a filler.
On the other hand, the operator ‘>>>’ is unsigned right shift operator. It always fills 0 irrespective of the sign of the number. Before going to our problem, we should understand how internally negative numbers are stored: Negative numbers are stored in 32 bit 2's complement form. For example, Binary representation of -1 is all 1s (111..1) 32 times ,left most bit of this is 1, it indicates that it is negative number. How do we find 2's complement of a number?
Now come back to our problem, in case of first SOP statement with signed shift operator:
2's complement representation of -4 =  1111...100 and after doing shift operation (-4>>2) it shift number by 2 and outcome becomes 111...001(1 at 3rd position from right is shifted 2 position right) and sign is maintained as stated earlier with left most bit as 1, So final outcome is -1(111...001).
Similarly, for second SOP, (4>>2), the outcome is 1 (left most bit is 0, since it is positive number).
Now we will look for third SOP statement, binary representation of -4 is 111...100. After performing right shift unsigned operation(-4>>>2) outcome becomes : 011....001, here leftmost bit is 0 because this operator (>>>) does not retain sign and It always fills 0 irrespective of the sign of the number.
So it prints 1073741823.
For fourth SOP statement it prints 1. It is similar to second one because it is positive number and sign bit is 0.Sample output is:
 -1
 1
 1073741823
 1
Question 4 : Predict the outcome. (Hint: Program start from main method, Opps!! We have two main method here)
class MainBuster{
    public static void main(){
         System.out.println("Hello!! I will execute too.");
    }
    public static void main(String[] args) {
         System.out.println("Do not worry!! I will execute.");
         MainBuster.main();
    }
}
Solution:What is your sample output ? Compile time error because of two main method or something else.This program compiles with ease. We can have multiple main method in a class with once exception ONLY one main method signature can have String array as method argument.
so it works as usual.Sample output is :
 Do not worry!! I will execute.
 Hello!! I will execute too.
Question 5: What is outcome of following snippet, when doThis() is being called?

class TryFinally{  
  public static int doThis() {
        try {
            System.out.println("Hello try");
            return 12;
        } finally {
            System.out.println("Hello finally");
            return 13;
        }
  }
   public static void main(String[] arg) {
        System.out.println(TryFinally.doThis());
   }
}
Solution: finally block is always executed except in system failure( or System.exit()).So, finally block will be always executed and 13 will be returned instead of 12. So , what will happen to statement "return 12" ? Answer of this question lies in when finally gets executed? Answer : finally is always executed just before any return statement in try block, As it can be verified from following snippet :
public static int tryFinallyTest()
 {
   try {  
    return 1;  
   }  
   finally {  
     System.out.println("finally block is run before 
                            method returns.");
   }
 }
 public static void main(String args[]) 
 { 
   // call the prtryFinallyTest method and print the return value
   System.out.println(tryFinallyTest()); 
 }
Outcome of the above snippet is :
finally block is run before method returns
1
Now it's evident that, finally block is executed just before return statement of try block if available. Now we apply the same logic in our main problem and we can conclude that return value in the finally block (“13″) will override the return value in the try block (“12″) and ultimately 13 will be returned to calling method.Sample output is
 Hello try
 Hello finally
 13
                   ================End of article ===============

Happy learning!!!
Nikhil


Aug 9, 2013

Textual description of firstImageUrl

Create a matrix with alternating rectangles of O and X .

Problem :  User will inputs two numbers m and n and creates a matrix of size m x n (m rows and n columns) in which every elements is either X or 0.
         

                
Solution :  Here outermost layer having X then O then again inner one is X and so on,It reminds me to apply  similar concept which is discussed here(Spiral movement of matrix) .
Instead of printing the elements we will fill matrix with X or O and after each iteration we will change next character to be considered from X to O and vice versa.
 Sample code in java which will display our pattern as needed.

 import java.util.Scanner;  
 public class MatrixPatternXandO {  
   public MatrixPatternXandO() {  
     super();  
   }  
   public static void generatePatternXandOMatrix(int m, int n) {  
     int r = m, c = n;  
     int col = 0, row = 0;  
     int i;  
     char ch = 'X';  
     // A 2D array to store the output to be printed  
      char mat[][] = new char[m][n];  
     while (row < m && col < n) {  
       for (i = col; i < n; i++) {  
         mat[row][i] = ch;  
       }  
       row++;  
       for (i = row; i < m; i++) {  
         mat[i][n - 1] = ch;  
       }  
       n--;  
       if (row < m) {  
         for (i = n - 1; i >= col; i--) {  
           mat[m - 1][i] = ch;  
         }  
         m--;  
       }  
       if (col < n) {  
         for (i = m - 1; i >= row; i--) {  
           mat[i][col] = ch;  
         }  
         col++;  
       }  
       ch = (ch == 'X') ? 'O' : 'X';  
     }  
     for (int j = 0; j < r; j++) {  
       for (int k = 0; k < c; k++) {  
         System.out.print(mat[j][k] + " ");  
       }  
       System.out.println();  
     }  
   }  
   public static void main(String[] args) {  
     MatrixPatternXandO matrixPatternXandO = new MatrixPatternXandO();  
     Scanner scanner = new Scanner(System.in);  
     System.out.println("Enter number of row for pattern :");  
     int row = scanner.nextInt();  
     System.out.println("Enter number of row for pattern :");  
     int column = scanner.nextInt();  
     matrixPatternXandO.generatePatternXandOMatrix(row, column);  
   }  
 }  
Sample output :
Enter number of row for pattern : 5
Enter number of row for pattern : 5

X X X X X
X O O O X
X O X O X
X O O O X
X X X X X

Aug 1, 2013

Java puzzle - Set 0

In java puzzle series,I am discussing interesting and intriguing concept of java. It will include some interview questions and MCQ.
Disclaimer : I do not claim that contents available here are my own , it's compiled by me after reading various pages on internet to make others life easy. :) Happy learning!!

Class and object initialization's are the most fundamental concept in java  and every java developer must have a clear understanding of that.Here we will discuss these concepts based on questions. Please read this article for better understanding of class and object initialization.
Question 1 : what will be the output of the following sample code? 
class ClassInitSample
{
   static boolean b;
   static char c;
   static char ca = '\u0000';
   public static void main (String [] args)
   {
      System.out.println ("b = " + b);
      System.out.println ("c = " + c);
      System.out.println ("c = " + (c == ca));
   }
} 
Answer : Sample output is as follows, if you arrive at this then you can next question.
 false
  
 true
First "false" is obvious as it is default value for boolean type. Why empty place for second SOP(System.out.println()) statement ? Reason : In java  char is represented by 16 bit unicode and default value of char is '/u0000' and the most important thing is that JVM interprets '\u0000' as the nondisplayable null value that's why, SOP executes but display nothing.Third SOP will be obviously true as (c=='\u0000').
Question 2: Do you think it will give compile time error ? (Hint:ClassName tells the story)
class ForwardRefNotAllowed
{
   static int one = two + 2;
   static int two = 2;
   public static void main (String [] args)
   {
      System.out.println ("first = " + one);
   }
}
Solution: If your answer is Yes, then your are on right track.But, what makes compilation failure ? In java forward reference is not allowed. Compiler reports error( illegal forward reference) because compiler cannot decide whether default value of two (which is 0) should be used or assigned value 2 should be used.
Question 3: Do you know what is class block initializer and object block initializer. Then try this question and predict the output?
class ClassBlockInitialization
{ 
  public ClassBlockInitialization(){
  System.out.println("Creating a new instance of 
                              ClassBlockInitialization");
  }
  //I am an class block initializer
  static
   {
     System.out.println ("Loading JDBC driver.....");
   }
  //I am an object block initializer 
   {
     System.out.println("I will be available for each object");
   }
  public static void main (String [] args){
      ClassBlockInitialization t1 = new ClassBlockInitialization();
      ClassBlockInitialization t2 = new ClassBlockInitialization();   
  }
}
Solution: If you have observed carefully, comments in sample code tells whole story.Here is the sample output, check it Did you arrived at this ?
 Loading JDBC driver.....
 I will be available for each object
 Creating a new instance of ClassBlockInitialization
 I will be available for each object
 Creating a new instance of ClassBlockInitialization
The fundamental difference between class block initializer and object block initializer is that :
class block initializer is executed only once right after class is loaded in JVM or just before main() method execution if it is an "initial class".
object block initializer is executed for each object creation, before executing constructor of the class.
Now come back to our question, on class loading class block got executed and display "Loading JDBC driver....." and when first object referenced by t1 is created, first object block got executed and then its's constructor is being called, so first "I will be available for each object" displayed followed by "Creating a new instance of ClassBlockInitialization". Similarly for second object creation it;s got repeated.
Question 4: How does class initialization work in the context of a class hierarchy? Try this and predict the output. (Hint: Always show respect to your parents - parent first always)
class ParentClass
{
   static int a = 1;
   static
   {
      System.out.println ("Parent initializer and " + "a = " + a);
   }
}
class ChildClass extends ParentClass
{
   static int b = 2 + a;
   static
   {
      System.out.println ("Child initializer and" + "b = " + b);
   }
   public static void main (String [] args)
   {
   }
}
Solution: Here is the sample output, is it what you predicted.
 Parent initializer a = 1
 Child initializer b = 3
As hint in the question states parents first: when a class hierarchy is involved then at runtime, the JVM loads all hierarchy classes from top to bottom(parenet class first- it will be propagated to the parent's of all class : Object class) and execute class field /class block initializer in same fashion(First parent class field and class block initializer then child's) and it will boil down to the class where main() method is available. In this question , first ParentClass is loaded and its field and class block got initialized, after that child class field and class block is executed.(Did you notice one thing b = 2+ a,  a= 1 is available since a is part of parent class which got initialized before).Now we can reach at the sample outcome as stated at top.
Question 5: Do you understand visibility of fields in class(Declaration and initialization) and its accessibility. What will the output of this program ?
public class VisiblityOfFields {
  int localVariable;
  static double PI;
  static
  {
     PI = 3.14159;
  }
  {
     int localVariable = 1;
     System.out.println("localVariable is "+ localVariable);
     System.out.println("Class field initialized, PI is "+ PI);
  }
  public VisiblityOfFields() {
     System.out.println("Initializing object, localVariable is "+ 
                                                 localVariable);
     System.out.println("Class field initialized, PI is "+ PI);
  }
  public static void main (String [] args){
          VisiblityOfFields vof = new VisiblityOfFields ();
  }
}
Solution: Here is the sample output:
 localVariable is 1
 Class field initialized, PI is 3.14159
 Initializing object, localVariable is 0
 Class field initialized, PI is 3.14159
Here we have to recall two fundamental's of class and object initialization discussed earlier :
First, Once class is loaded by class loader in JVM, before main() method execution class block gets executed and PI is initialized with 3.14159.
Second, for each object, the object block initializer executes before the constructor.Now once new object is created control reaches to object block section where localVariable is declared and initialized with value 1 (Please pay attention: declared and initialized not just initialized) and its SOP's displays as expected. Now, when constructor of VisiblityOfFields class is executed object field "localVariable" is initialized with default value  of 0(default value for int is 0) while PI remains unaffected (It is class fields), that's why in constructor SOP's we get 0 for localVariable and 3.14159 for PI.
One important take away from this question is : Any variable that you declare in a class block/object block initializer is local to that block.
This is all about fundamental of class and object initialization and hope after reading got insight of the same.
                        ==============End of article============

Happy learning,
Nikhil