Thursday 22 August 2013

How to traverse HashMap and HashTable with iterator in Java Collection framework?



Traversing Map interface is bit differ from traversing the collection interface because we have key, Value pair is stored in map and we have to traverse them as a set. We use some properties of Map interface to do the work like Map.Entry, Map.entryset(), which are used to tackle key, value pair as set. We can get the value of key and value with getKey() and getValue() methods from object of Map.Entry type. Please see the program below to understand it more clearly.
In below examples, we traversed both HashMap and Hashtable. There is no difference between traversing of them, the only difference is the output of both program.  The HashMap produce a sorted output but Hashtable  produce a unsorted output (As per their properties).

1 - Traverse HashMap with Iterator Example:
import java.util.*;
public class demoTraverseHashMap
{
 public static void main(String s[])
        {
            Map mp = new HashMap();
            mp.put(1,"First");
            mp.put(2,"Second");
            mp.put(3,"Third");
            mp.put(4,"Fourth");
            System.out.println("Print MAP contents without traversing");
            System.out.println(mp);


           System.out.println("Print MAP contents with Iterator traversing");
           Iterator it = mp.entrySet().iterator();
           while(it.hasNext())
           {
               Map.Entry pairs = (Map.Entry) it.next();
               System.out.println("Key : "+pairs.getKey()+", Value : "+pairs.getValue());
           }
        }
}

OutPut:
Print MAP contents without traversing
{1=First, 2=Second, 3=Third, 4=Fourth}
Print MAP contents with Iterator traversing
Key : 1, Value : First
Key : 2, Value : Second
Key : 3, Value : Third
Key : 4, Value : Fourth


2 - Traverse HashTable with Iterator Example:
 import java.util.*;
public class demoTraverseHashMap
{
 public static void main(String s[])
        {
            Map mp = new Hashtable();
            mp.put(1,"First");
            mp.put(2,"Second");
            mp.put(3,"Third");
            mp.put(4,"Fourth");
            System.out.println("Print MAP contents without traversing");
            System.out.println(mp);


           System.out.println("Print MAP contents with Iterator traversing");
           Iterator it = mp.entrySet().iterator();
           while(it.hasNext())
           {
               Map.Entry pairs = (Map.Entry) it.next();
               System.out.println("Key : "+pairs.getKey()+", Value : "+pairs.getValue());
           }
        }
}

OutPut:
Print MAP contents without traversing
{4=Fourth, 3=Third, 2=Second, 1=First}
Print MAP contents with Iterator traversing
Key : 4, Value : Fourth
Key : 3, Value : Third
Key : 2, Value : Second
Key : 1, Value : First

Wednesday 21 August 2013

Can we call init method in service method of servlet?

This is a very tricky question asked in an interview. The servlet lifecycle is a very important question in any java interview. The goal behind asking this question is to check the knowledge of servlet lifecycle of the candidate. This question can be modified in many ways like can we call destroy method in service method etc. (Read the link --http://javaitblog.blogspot.in/2013/04/what-happens-if-you-call-destroy-from.html). 
For the question “can we call init method in service method”, the direct answer is “Yes”. We can call init method in service method for any number of times. The init method initializes the ServletConfig parameter or initializes the servlet instance. The init method will be called by the container only once when it is started. So there is no use of calling it again in the service method but if we want, we can call it in the service method. To understand it more clearly, please see the below example.
Example Code:
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/demoCalInitMethod")
public class demoCalInitMethod extends HttpServlet {
                private static final long serialVersionUID = 1L;
                ServletConfig config;
                int count=0;
                  
    public demoCalInitMethod() {
        super();
    }

                public void init(ServletConfig config) throws ServletException {
                                this.config = config;
                                ++count;
                }
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
               
                                System.out.println("The value of count variable before calling init methods in service method :- "+count);
                                init(config);
                                init(config);
                                init(config);
                                init(config);
                                init(config);
                                System.out.println("The value of count variable before calling init methods in service method :- "+count);
                }

                protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                                }

                protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                }

}

Output :-

The value of count variable before calling init methods in service method :- 1
The value of count variable before calling init methods in service method :- 6

In the above example, the init method is called in service method for five times. In init method, we incremented an integer type variable “count” with one so whenever this method is called it will increment the value of “count” variable by one. We printed the value of count variable in service method before and after calling the init method explicitly. As the output showing above, it printed the value of count 1 before calling the init methods explicitly (Because container calls it once automatically when it loads the servlet) and 6 after calling  the init methods explicitly because  we called the init method for five times in service method.
So init will initiate the servlet n times if call the init method n times with same ServletConfig object.

Tuesday 6 August 2013

How can we perform Exception Handling in JSP?

Exception handling can be performed in JSP with three ways
  1. Using page directive (isErrorPage=”True” and errorPage=”error.jsp”).
  2. Using simple Try/catch  
  3. Using JSTL

  1.  Page Directive Exception Handling: - This is the most common way of JSP exception handling. In this approach, we use the errorPage and isErrorPage methods of page directive. As in the below example, we used two JSP pages.
·         generateException.jsp
·         error.jsp
The generateException page used the errorPage method of page directive for describing the name of the page which will handle the exceptions occurred in the page (As error.jsp in below example). Now when any exception will occur in the generateException page, it will go to the error.jsp page.
              In error.jsp page we used the isErrorPage method of the page directive to tell the container that this page is for exception handling and then container will give an implicit object “Exception” for handling the exceptions. This can be easily understood with the below example.
generateException.jsp
<%@ page errorPage="error.jsp" %>
<%
  int count=0;
  count=100/count;

%>

error.jsp
<html>
<body>
<%@ page isErrorPage="true" %>
<%="Sorry, Exception occured"%>
</br>
<%="Here is your Exception:- "+exception%>
</body>
</html>


2.  Try/Catch Block exception handling: - This is very much similar to the core java exception handling. We put the code under the try block and catch the exception in exception block.
This can be easily understood with the example below.

generateException.jsp
<%
 try
  {
     int count=0;
     count=100/count;
  }
catch(Exception e)
  {
                out.println("Try/Catch block Exception Handling "+e);
  }

%>

3.       JSTL Exception: - JSTL (Java standard tag library) is used for making coding easy. JSTL gives some standard tags to perform some specific tasks so JSTL also provide tags to perform exception handling. Please refer the below example for JSTL exception handling.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
 <body>
    <c:catch var="ExceptionVar">
    <% int count=0;
     count=100/count; %>
    </c:catch>
    Test :
                <c:if test = "${ExceptionVar != null}">
                out.println("Try/Catch block Exception Handling ");
                ${ExceptionVar}
    </c:if>
    </body>
</html>