How do handling String object in JVM?

  1. Java Virtual Machine maintains an internal list of references for interned Strings (Pool of unique Strings) to avoid duplicate String objects in heap memory.
  2. Whenever the JVM load String literal from the class file and executes, it checks whether that String already exists in the internal list or not.
  3. if Already exists in the list, String object does not create a new String and it uses reference to existing String  object.
  4. JVM does this type of checking for String literal but not for String object which it creates through 'new' keyword.
  5. You explicitly force JVM to do this type of checking for String objects which are creates through 'new' keyword using String.intern() method.
  6. This forces JVM to check the internal list and use the existing String object if it is already exist.

Difference between String and StringBuffer in java

Overview of String:
  1. String is Immutable objects.
  2. Immutable objects cannot be modified once they are created.
  3. Next question that comes to our mind is "If String is immutable than how i change the contents of the object?".
  4. Well, to be precise it’s not the same String object that reflects the changes you do. Internally a new String object is created to do the changes.
Example :
      String myString = "Hello";
      Next, you want append "Guest" to the same String. What do you do?
      myString = myString + " Guest";

When you print the content of myString the output will be "Hello Guest".
Although we made use of the same object(myString), internally a new object was created in the process. 
Here "+" is act concatenation operation in String. 

Example:
      String myStr = "Hello".
      Next, you want append "Guest" to the same String using String's concat() method.
      myStr.concat(" Guest");

When you print content of the object(myStr) the output will be "Hello".
Here not call internal a new object. So, you assign explicitly another String object or same String object.

     String tempStr =  myStr.concat(" Guest");
Now, you print the content of  tempStr the output will be "Hello Guest".

Overview of StringBuffer:
  1. StringBuffer is mutable objects.
  2. Mutable objects can be modified after their creation.
The default behavior of StringBuffer:
  1. StringBuffer maintains a character array internally.
  2. When you create StringBuffer with default constructor StringBuffer() without setting initial length, then the StringBuffer is initialized with 16 characters.
  3. The default capacity of 16 characters.
  4. When the StringBuffer reaches its maximum capacity , it will be increase its size by twice the size plus  (2 * old size) + 2.
Example:
       StringBuffer strBuf = new StringBuffer();
       Next, you want append " to Java" to the same object
       strBuf.append("Welcome");

When you print the content of strBuf the output will be "Welcome to Java".


What would you use to compare two String variables the operator == or the method equals() in java?

  1. We use String compare using equels() methods. Its compare both String's contents.
  2. In case using = = then check both String object's memory address.
  3. If you know more info about, how do handling String object in JVM? More...

 class StringCompare  
 {  
      public static void main(String[] arg)  
      {  
           System.out.println("String comparition difference between == and equals()");  
           String str1 = "hello";  
           String str2 = "hello";  
           String str3 = new String("hello");  
           String str4 = new String("hello");  
           System.out.println("str1 : "+str1);  
           System.out.println("str2 : "+str2);  
           System.out.println("str3 : "+str3);  
           System.out.println("str4 : "+str4);  
           System.out.println("==");  
           System.out.print("str1 == str2 : ");  
           System.out.println(str1 == str2);  
           System.out.print("str1 == str3 : ");  
           System.out.println(str1 == str3);  
           System.out.print("str3 == str4 : ");  
           System.out.println(str3 == str4);  
           System.out.println("equals()");  
           System.out.print("str1.equals(str2) : ");  
           System.out.println(str1.equals(str2));  
           System.out.print("str1.equals(str3) : ");  
           System.out.println(str1.equals(str3));  
           System.out.print("str3.equals(str4) : ");  
           System.out.println(str3.equals(str4));  
      }  
 }  

Output:


Difference between daemon thread and non-daemon thread in java

  • Daemon term is mainly used in UNIX. 
  • In Java, this is used to indicate a special type of thread. 
  • Normally when a thread is created in Java, by default it is a non-daemon thread. 
  • Whenever a Java Program is executed, the Java Virtual Machine (JVM) will not exit until any non-daemon threads are still running. 
  • This means if the main thread of an application ends and the remaining threads left are Daemon threads, then the JVM will exit killing all the daemon threads without warning.
  • A daemon thread should be used for some background task that might provide a service to the applications. 
  • e.g. a Server thread listening on a port for the clients` requests. A thread for which an exit method is not provided or which does not have an exit mechanism can be marked as a daemon thread.
 /*  
 Daemon term is mainly used in UNIX. In Java, this is used to indicate a special type of thread.   
 Normally when a thread is created in Java, by default it is a non-daemon thread.   
 Whenever a Java Program is executed, the Java Virtual Machine (JVM) will not exit until any non-daemon threads are still running.   
 This means if the main thread of an application ends and the remaining threads left are Daemon threads,   
 then the JVM will exit killing all the daemon threads without warning.  
 A daemon thread should be used for some background task that might provide a service to the applications.   
 e.g. a Server thread listening on a port for the clients` requests.   
 A thread for which an exit method is not provided or which does not have an exit mechanism can be marked as a daemon thread.   
 */  
 public class DaemonThread implements Runnable   
 {  
      public void run()   
      {  
           System.out.println("Entering run()");  
           try   
           {  
                System.out.println("Inside run(): currentThread() is :: "+ Thread.currentThread());  
                while (true) {  
                     try{  
                      Thread.sleep(500);  
                     }   
                     catch (InterruptedException x) {  
                     }  
                     System.out.println("Inside run(): Wake up Again");  
                }  
           }  
           finally {  
            System.out.println("Leaving run()");  
           }  
      }  
      public static void main(String[] args) {  
           System.out.println("Enter to Main()");  
           Thread t = new Thread(new DaemonThread());  
           //Not contain setDaemon(true) is called non-daemon thread.  
           //See this program output.  
           //After uncomment following line. then see the program's output.  
           //You easy to understand, what is different between daemon thread and non-daemon thread.  
           //t.setDaemon(true);  
           t.start();  
           try {  
            Thread.sleep(3000);  
           } catch (InterruptedException x) {  
           }  
           System.out.println("Leaving Main()");  
      }  
 }  

Java toString Method

Implementing toString method in java is done by overriding the Object’s toString method. The java toString() method is used when we need a string representation of an object. It is defined in Object class. This method can be overridden to customize the String representation of the Object. Below is a program showing the use of the Object’s Default toString java method.
 class PointCoordnate {  
      private int a, b;  
      public PointCoordnate(int a, int b) {  
           this.a = a;  
           this.b = b;  
      }  
      public int geta() {  
           return a;  
      }  
      public int getb() {  
           return b;  
      }  
 }  
 public class JavaToString {  
      public static void main(String args[]) {  
           PointCoordnate point = new PointCoordnate(20, 20);  
           // using the Default Object.toString() Method  
           System.out.println("Object toString() method : " + point);  
           // implicitly call toString() on object as part of string concatenation  
           String s1 = point + " TEST";  
           System.out.println(s1);  
      }  
 }  

When you run the JavaToString program,
the output is:
Object toString() method : PointCoordnate@119c082
PointCoordnate@119c082 TESTING

In the above example when we try printing PointCoordinate object, it internally calls the Object’s toString() method as we have not overridden the java toString() method. Since out example has no toString method, the default one in Object is used. The format of the default toString method of the Object is as shown below.
Class Name, “@”, and the hex version of the object’s hashcode concatenated into a string. The default hashCode method in Object is typically implemented by converting the memory address of the object into an integer.

getClass().getName() + '@' + Integer.toHexString(hashCode());
Below is an example shown of the same program by Overriding the default Object toString() method. The toString() method must be descriptive and should generally cover all the contents of the object.
 class PointCoordnate {  
      private int a, b;  
      public PointCoordnate(int a, int b) {  
           this.a = a;  
           this.b = b;  
      }  
      public int geta() {  
           return a;  
      }  
      public int getb() {  
           return b;  
      }  
      public String toString() {  
           return "a=" + a + " " + "b=" + b;  
      }  
 }  
 public class JavaToString {  
      public static void main(String args[]) {  
           PointCoordnate point = new PointCoordnate(20, 20);  
           System.out.println("Object toString() method : " + point);            
           String s1 = point + " TESTING";  
           System.out.println(s1);  
      }  
 }  
When you run the JavaToString program,
the output is: a=20 b=20 a=20 b=20 TESTING

Number validation using javascript

 <html>  
 <head>  
 <script>  
 function floatValidation(e,control)  
 {  
   if (e.keyCode==46)  
   {     
     var patt1=new RegExp("\\.");  
     var ch =patt1.exec(control.value);  
     if(ch==".")  
     {  
       e.keyCode=0;  
     }  
   }  
   else if( (e.keyCode>=48 && e.keyCode<=57) || e.keyCode==8)//Numbers or BackSpace  
   {     
     if (control.value.indexOf('.') != -1)//. Exist in TextBox  
     {  
       var pointIndex=control.value.indexOf('.');  
       var beforePoint = control.value.substring(0,pointIndex);  
       var afterPoint = control.value.substring(pointIndex+1);  
       var iCaretPos = 0;  
       if (document.selection)  
       {  
         if (control.type == 'text') // textbox  
         {  
           var selectionRange = document.selection.createRange();  
           selectionRange.moveStart ('character', -control.value.length);  
           iCaretPos = selectionRange.text.length;  
         }  
       }  
       if(iCaretPos > pointIndex && afterPoint.length >= 2)  
       {  
         e.keyCode=0;  
        alert('You enter two digit only after decimal point');  
       }  
       else if(iCaretPos <= pointIndex && beforePoint.length >= 7)  
       {  
         e.keyCode=0;  
       }  
     }  
     else//. Not Exisist in TextBox  
     {  
       if(control.value.length >= 7)  
       {  
         e.keyCode=0;  
         alert('You enter 7 digit only before decimal point');  
       }  
     }  
   }  
   else  
   {  
     e.keyCode=0;  
   }  
 }  
 </script>  
 </head>  
 <body>  
      <input id="amt" type="text" name="Amount" onkeypress="return floatValidation(event,this)" onfocus="setCaretPosition(this,0);"/>  
 </body>  
 </html>  

Why do we need wrapper classes in java?

It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.

Configuring Tomcat 6 For https (SSL) Page for Windows

Prerequisites:-
1. JDK
2. Tomcat

For any https (SSL) page a certificate is very necessary. First we will learn generating a keystore, which will contain a certificate chain. We will use the keytool command from JDK.

1. Goto the command prompt.

2. Type keytool -genkey -alias tomcat -keyalg RSA (if your path is not set to the java bin directory, please go there and type the command).

3. Now you will prompted for a keystore password give it as changeit (you can give it different but you will have to make some changes later).

4. Enter the details needed.

5. Now alias password will be aksed. It must be same as keystore password.

6. After the end of it a keystore will be generated in "drive":\Documents and Settings\"username"\.keystore
Now configure "tomcat_home"\conf\server.xml, add the following code:-

  You are done with your configuration. Save the server.xml file. Restart your tomcat. Now type https://localhost:8443

This should show you the same tomcat homepage but in secured format.

Create ireport using struts2, hibernate, spring

Simple iReport generate using struts2.

Download Source: IreportSourceCode

Download JAR file: JARs

Load dependent combo using AJAX, JSP & Servlet


1.index,jsp
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <!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=ISO-8859-1">  
 <title>Insert title here</title>  
 <script type="text/javascript" src="script.js">  
 </script>  
 </head>  
 <body>  
 <div align="center">  
      <form name="CountryDetails" >  
           <table>  
                <tr>  
                     <td>State </td>  
                     <td>  
                          <select name="state" id="state" onchange="changeState()">  
                               <option>-- Select State --</option>  
                               <option value="1">Kerala</option>  
                               <option value="3">Tamilnadu</option>  
                          </select>  
                     </td>  
                </tr>  
                <tr>  
                     <td>District Name</td>  
                     <td>       
                          <span id="loadDistrict">  
                               <select name="district" id="district">  
                                    <option>--Select District--</option>  
                               </select>  
                          </span>  
                     </td>  
                </tr>  
           </table>  
      </form>  
 </div>  
 </body>  
 </html>  

2.script.js
 function AjaxFunction()  
 {  
      var xmlrequest=false;  
      try  
      {  
           xmlrequest=new ActiveXObject("Msxml2.XMLHTTP");   
      }  
      catch(e1)  
      {  
           try  
           {  
                xmlrequest=new ActiveXObject("Microsoft.XMLHTTP");   
           }  
           catch(e2)  
           {     
                xmlrequest=false;  
           }  
      }  
      if (!xmlrequest && typeof XMLHttpRequest != 'undefined')   
      {  
           xmlrequest=new XMLHttpRequest();  
      }  
      return xmlrequest;  
 }   
 function changeState()  
 {  
      var state=document.getElementById("state").value;  
      var url="StateDetails?command=statechange&id="+state;  
      var xmlrequest= AjaxFunction();  
      xmlrequest.open("GET",url,true);   
      xmlrequest.onreadystatechange=function()  
      {  
           if(xmlrequest.readyState==4)  
           {  
                if(xmlrequest.status==200)  
                {  
                     //alert(xmlrequest.responseText);  
                     document.getElementById("loadDistrict").innerHTML=xmlrequest.responseText;  
                }  
           }  
      };    
      xmlrequest.send(null);  
 }  

3.StateDetails.java(Servlet)
 import java.io.IOException;  
 import java.io.PrintWriter;  
 import java.sql.Connection;  
 import java.sql.DriverManager;  
 import java.sql.ResultSet;  
 import javax.servlet.ServletException;  
 import javax.servlet.http.HttpServlet;  
 import javax.servlet.http.HttpServletRequest;  
 import javax.servlet.http.HttpServletResponse;  
 import com.mysql.jdbc.Statement;  
 /**  
  * Servlet implementation class StateDetails  
  */  
 public class StateDetails extends HttpServlet {  
      private static final long serialVersionUID = 1L;  
      private static final String CONTENT_TYPE = "text/xml; charset=windows-1252";  
      /**  
       * Default constructor.   
       */  
      public StateDetails() {  
           // TODO Auto-generated constructor stub  
      }  
      /**  
       * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)  
       */  
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
           // TODO Auto-generated method stub  
           response.setContentType(CONTENT_TYPE);  
           int stateID=Integer.parseInt(request.getParameter("id").toString());  
           PrintWriter out=response.getWriter();  
           String xml="";  
           int id[]={1,2,3,4,5};  
           String name[]={"Erode","Karur","Trichy","Chennai","Madurai"};  
           try{  
                Connection con=null;  
                Class.forName("com.mysql.jdbc.Driver");  
                con=DriverManager.getConnection("jdbc:mysql://localhost:3036/country","root","");  
                System.out.println("111111111111111");  
                java.sql.Statement statement=con.createStatement();  
                ResultSet rs = statement.executeQuery("SELECT id,district FROM district where stateId="+stateID);  
                xml="<select name=\"district\" id=\"district\">";  
                xml+="<option>--Select District--</option>";  
                while (rs.next()) {  
                     xml+="<option id=\""+rs.getInt(1)+"\">"+rs.getString(2)+"</option>";  
                }  
                xml+="</select>";  
           }  
           catch(Exception e){  
                System.out.println(e.getMessage());  
           }  
           /*xml="<select name=\"district\" id=\"district\">";  
           xml+="<option>--Select District--</option>";  
           for(int i=0;i<5;i++)  
           {  
                xml+="<option id=\""+id[i]+"\">"+name[i]+"</option>";  
           }  
           xml+="</select>";*/  
           out.write(xml);  
      }  
      /**  
       * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)  
       */  
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
           // TODO Auto-generated method stub  
      }  
 }  

Download Source: AJAXExample