Monday, 28 July 2014

Why hashmap key must be immutable?

HashMap is a data-structure where data is organized as key and values pairs. i.e. for every value there must be a  key to be produced to be stored into the hashmap.

Keys are normally generated using hashcode() method.

Key’s hash code is used primarily in conjunction to its equals() method, for putting a key in map and then searching it back from map. So if hash code of key object changes after we have put a key-value pair in map, then its almost impossible to fetch the value object back from map. It is a case of memory leak. To avoid this, map keys should be immutable.

I have already posted how to make objects immutable in one of my previous posts. 

Java Static Import

 Static import is a feature introduced in the Java programming language that allows members (fields and methods) defined in a class as public static to be used in Java code without specifying the class in which the field is defined. This feature was introduced into the language in version 5.0.

The feature provides a typesafe mechanism to include constants into code without having to reference the class that originally defined the field. It also helps to deprecate the practice of creating a constant interface: An interface that only defines constants then writing a class implementing that interface, which is considered an inappropriate use of interfaces.

The mechanism can be used to reference individual members of a class:

import static java.lang.Math.PI;
import static java.lang.Math.pow;

or all the static members of a class -

import static java.lang.Math.*; 

For example, the class:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
        System.out.println("Considering a circle with a diameter of 5 cm, it has:");
        System.out.println("A circumference of " + (Math.PI * 5) + " cm");
        System.out.println("And an area of " + (Math.PI * Math.pow(2.5,2)) + " sq. cm");
    }
}
Can instead be written as:

import static java.lang.Math.*;
import static java.lang.System.out;
public class HelloWorld {
    public static void main(String[] args) {
        out.println("Hello World!");
        out.println("Considering a circle with a diameter of 5 cm, it has:");
        out.println("A circumference of " + (PI * 5) + " cm");
        out.println("And an area of " + (PI * pow(2.5,2)) + " sq. cm");
    }
}


 

Sunday, 27 July 2014

What is JSESSIONID in J2EE Web application - JSP Servlet?

What is JSESSIONID in J2EE Web application - JSP Servlet? 

JSESSIONID is a cookie generated by Servlet container like Tomcat or Jetty and used for session management in J2EE web application for http protocol. Since HTTP is a stateless protocol there is no way for Web Server to relate two separate requests coming from same client and Session management is the process to track user session using different session management techniques like Cookies and URL Rewriting. If Web server is using cookie for session management it creates and sends JSESSIONID cookie to the client and than client sends it back to server in subsequent http requests.

When JSESSIONID created in Web application?


  • In Java J2EE application container is responsible for Session management and by default uses Cookie.
  • If user request is served by Servlet than session is created by calling request.getSession(true) method. it accepts a boolean parameter which instruct to create session if its not already existed. if you call    request.getSession(false) then it will either return null if no session is associated with this user or return the associated HttpSession object.
  • If HttpRequest is for JSP page than Container automatically creates a new Session with JSESSIONID if this feature is not disabled explicitly by using page directive %@ page session="false" %>.
  • Once Session is created Container sends JSESSIONID cookie into response to the client. In case of HTML access, no user session is created. If  client has disabled cookie than Container uses URL rewriting for managing session on which jsessionid is appended into URL as shown below:           
  •  Ex. - https://localhost:8443/supermart/login.htm;jsessionid=1A530637289A03B07199A44E8D531427
  • When HTTP session is invalidated(), mostly when user logged off, old JSESSIONID destroyed and a new JSESSIONID is created when user further login.

ConcurrentAcessModification Exception Java

 

ConcurrentAcessModification Exception Java


This exception does not normally have anything to do with synchronization - it is normally thrown if a Collection is modified while an Iterator is iterating through it. AddAll methods may use an iterator - and its worth noting that the posh foreach loop iterates over instances of Iterator too.

Example - 

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class Test{
   
    public static void main(String[] args) {
        HashMap map = new HashMap();
        map.put(1,"1");
        map.put(2,"2");
        map.put(3,"3");
        map.put(4,"4");
        map.put(5,"5");
        map.put(6,"6");
        Set keyset = map.keySet();
        Iterator iterator = keyset.iterator();
        while(iterator.hasNext()){
          System.out.println(map.get((Integer)iterator.next()));

          // Here you will get java.lang.ConcurrentAccessModification Exception.
            map.put(6,"6");
            map.put(7,"7");
          
        }
    }

}

 

Why we cant make class as private and protected

Why we cant make class as private and protected?

Private - 
What are other benefits you will get , if class declare as private ?
         Can we able to create object for private class from other class ? : No
         We cannot access the any of member (fields, methods ) of private class , then what is use of it ?



Protected-
If declared the class as protected - only via inheritance can access the fields and member , any other class who is not belong to protected class ( i.e . class is not inherited ) : it cont access any of fields and methods . 


Monday, 21 July 2014

Immutable objects - Java

Immutable Class - 

An immutable class is one whose state can not be changed once created


Rules/Guidelines to make a class immutable in java 


  •  Donot provide / remove all the setter methods of the member variables in the class
  •  Make the class as final . If we donot make it final child class can have setter implementation. 
  •  Make all the fields final and private 

import java.util.Date;

public final class ImmutableClass
{
 private final Integer test1;

 private ImmutableClass(Integer test1)
 {      this.test1 = test1;
 }
     public static ImmutableClass createNewInstance(Integer fld1, String fld2, Date date)
 {
  return new ImmutableClass(fld1, fld2, date);
 }

 //Provide no setter methods

 public Integer getTest1() {
  return test1;
 }


Tuesday, 15 July 2014

How to use implicit objects in JSP


Example of how to use implicit objects in JSP


<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%@ page import="java.util.Date" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Index JSP Page</title>
</head>
<body>
<%-- out object example --%>
<h4>Hi There</h4>
<strong>Current Time is</strong>: <% out.print(new Date()); %><br><br>
 
<%-- request object example --%>
<strong>Request User-Agent</strong>: <%=request.getHeader("User-Agent") %><br><br>
 
<%-- response object example --%>
<%response.addCookie(new Cookie("Test","Value")); %>
 
<%-- config object example --%>
<strong>User init param value</strong>:<%=config.getInitParameter("User") %><br><br>
 
<%-- application object example --%>
<strong>User context param value</strong>:<%=application.getInitParameter("User") %><br><br>
 
<%-- session object example --%>
<strong>User Session ID</strong>:<%=session.getId() %><br><br>
 
<%-- pageContext object example --%>
<% pageContext.setAttribute("Test", "Test Value"); %>
<strong>PageContext attribute</strong>: {Name="Test",Value="<%=pageContext.getAttribute("Test") %>"}<br><br>
 
<%-- page object example --%>
<strong>Generated Servlet Name</strong>:<%=page.getClass().getName() %>
 
</body>
</html>