What are the main classes which are used in struts application?


  1. ActionServlet : Its is back-bond of web application. Its a controller class responsible entire request.
  2. Action : Using Action classes all the business logic is developed us call model of the application also.
  3. ActionForm : Action Form class is Java Bean. its mapping between form data to Action.Form's data objects to be auto wiring client form data to server side.
  4. ActionMapping : Its mapping object and Action.
  5. ActionForward : This is getting result and controller to forward destination.

What is interceptor?

  1. Interceptors are an objects that dynamically intercept Action invocation.
  2.  It is invoked at the preprocessing and postprocessing of a request.
  3.  Interceptors provide a developer way to encapsulate common functionality in a re-usable that from one or more Action.
  4.  It is perform validations, exception handling, logger, intermediate results etc.

What is abstraction?

Abstraction is a process of hiding implementation and showing only functionally to the user. 

What is the relation between ValueStack and OGNL ?

ValueStack is a place where all the data related to action and action itself store. OGNL is a mean which the data in ValueStack is manipulated.

Different Modes of autowiring


There are five type of auto wiring in Spring:
  • no : no autowire
  • byName : Autowiring by property name, means bean matching property name is autowired.
  • byType : Bean having type as that of property type is autowired.
  • constructor : Similar to byType just that the property is in constructor.
  • autodetect :  Spring is allowed to select autowiring from byType and constructor

Spring Autowiring

  • By Autowiring , Spring injects dependencies without having to specify those explicitly.
  • Spring inspects bean factory contents and establishes relationships amongst collaborating beans. To implement it,just add autowire property in xml configuration.

What are the important Spring beans life cycle methods?


There are two important beans life cycle methods.
  1. setup
  2. teardown
setup - It is called when bean is load into the container.
teardown - It is called when bean is unloaded from the container.

What is Classloader in Java?

  • The classloader is a subsystem of JVM that is used to load classes and interfaces.
  •  There are many types of classloders.
  • e.g. Bootstrap classloader, Extenstion classloader, System classloader, Plugin classloader etc.

Difference between Thread class and Runnable interface

  1. Thread is a block of code which can execute concurrently with other threads in the JVM. You can create and run a thread in either ways; Extending Thread class, Implementing Runnable interface.
  2. Both approaches do the same job but there have been some differences. Almost everyone have this question in their minds: which one is best to use? We will see the answer at the end of this post.
The most common difference is
  • When you extends Thread class, after that you can’t extend any other class which you required. (As you know, Java does not allow inheriting more than one class).
  • When you implements Runnable, you can save a space for your class to extend any other class in future or now.
However, the significant difference is.
  • When you extends Thread class, each of your thread creates unique object and associate with it.
  • When you implements Runnable, it shares the same object to multiple threads.
 class ImplementsRunnable implements Runnable {  
      private int counter = 0;  
      public void run() {  
           counter++;  
           System.out.println("ImplementsRunnable : Counter : " + counter);  
      }  
 }  
 class ExtendsThread extends Thread {  
      private int counter = 0;  
      public void run() {  
           counter++;  
           System.out.println("ExtendsThread : Counter : " + counter);  
      }  
 }  
 public class ThreadVsRunnable {  
      public static void main(String args[]) throws Exception {  
           //Multiple threads share the same object.  
           ImplementsRunnable rc = new ImplementsRunnable();  
           Thread t1 = new Thread(rc);  
           t1.start();  
           Thread.sleep(1000); // Waiting for 1 second before starting next thread  
           Thread t2 = new Thread(rc);  
           t2.start();  
           Thread.sleep(1000); // Waiting for 1 second before starting next thread  
           Thread t3 = new Thread(rc);  
           t3.start();  
           //Creating new instance for every thread access.  
           ExtendsThread tc1 = new ExtendsThread();  
           tc1.start();  
           Thread.sleep(1000); // Waiting for 1 second before starting next thread  
           ExtendsThread tc2 = new ExtendsThread();  
           tc2.start();  
           Thread.sleep(1000); // Waiting for 1 second before starting next thread  
           ExtendsThread tc3 = new ExtendsThread();  
           tc3.start();  
      }  
 }  

Output of the above program.
ImplementsRunnable : Counter : 1
ImplementsRunnable : Counter : 2
ImplementsRunnable : Counter : 3
ExtendsThread : Counter : 1
ExtendsThread : Counter : 1
ExtendsThread : Counter : 1

Struts2 work flow

  1. ActionContextCleanUp Filter : The ActionContextCleanUp filter is optional and it is useful when integration has to be done with other technologies like SiteMash Plugin.
  2. FilterDispatcher : Next the FilterDispatch is called, which int turn uses the ActionMapper to determine weather to invoke an Action. If the action is requires to be invoked, the FilterDispathcer delegates the control to ActionProxy.
     
  3. ActionProxy : The ActionProxy takes the help from Configuration Files manager, which is initialized from the struts.xml. Then the ActionProxy creates an ActionInvocation, which implements the command pattern. The ActionInvocation process invokes the Interceptors (if configured) and then invokes the Action. The ActionInvocation looks for proper result. Then the result is executed, which involves the rendering of JSP or templates.

    Then the Interceptors are executed again in reverse order. Finally the response returns through the filters configured in web.xml file. If the ActionContextCleanUp filter is configured, the FilterDispatcher does not clean the ThreadLocal ActionContext. If the ActionContextCleanUp filter is not present then the FilterDispatcher will cleanup all the ThreadLocals present.

  4. Struts2 work flow

JDBC vs Hibernate



  1. JDBC:
    1. JDBC stands for Java Database Connectivity allows developers to connect, query and update a database using the Structured Query Language(SQL).
    2.  JDBC API standard provides Java developers to interact with different RDBMS and access table data through Java application without learning RDBMS details and using Database Specific JDBC Drivers.
  2. Hibernate:
    1. Hibernate is an Object-Relational Mapping (ORM) solution for java. It is a powerful, high performance object/relational persistence and query service.
    2. It allows us to develop persistent classes following object-oriented idiom – including association, inheritance and polymorphism.
Difference beetween JDBC and Hibernate.

JDBC 
Hibernate 
With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema.  
Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this. 
With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code.  
Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS.  
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task.  
Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.  
Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. 
Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.  
With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually.  
Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.  
With JDBC, caching is maintained by hand-coding.  
Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.  
In JDBC there is no check that always every user has updated data. This check has to be added by the developer.  
Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.       

Object states in hibernate

This summary is not available. Please click here to view the post.

Why do use lazy="false"?


It decides whether the child object is loading to the parent or not.
  1. We have to set it in the mapping file of the parent class.If lazy="true" (means not to load child)
  2.  By default the lazy loading is true.
  3.  But some cases we need to load the child object when the parent is loaded.
  4.  So in that case we'll have to write lazy="false".

What is preinitialization of a java servlet?

In the java servlet life cycle, the first phase is called ‘Creation and intialization’.

The java servlet container first creates the servlet instance and then executes the init() method. This initialization can be done in three ways. The default way is that, the java servlet is initialized when the servlet is called for the first time. This type of servlet initialization is called lazy loading.

The other way is through the <load-on-startup>non-zero-integer</load-on-startup> tag using the deployment descriptor web.xml. This makes the java servlet to be loaded and initialized when the server starts. This process of loading a java servlet before receiving any request is called preloading or preinitialization of a servlet.

Servlet are loaded in the order of number(non-zero-integer) specified. That is, lower(example: 1) the load-on-startup value is loaded first and then servlet with higher values are loaded.

Example usage:
<servlet>
       <servlet-name>Servlet-URL</servlet-name>
       <servlet-class>com.javapapers.Servlet-Class</servlet-class>
       <load-on-startup>2</load-on-startup>
</servlet>

Can we make hashMap synchronized?

Yes, we can make HashMap to be synchronized.
Map hashMap = new HashMap();
Map m = Collections.synchronizedMap(hashMap);

Types of Inner Class / Nested Class in Java

 There are four type of inner classes in java. There briefly,
  1. Static inner class
  2. Non static inner class
  3. Local inner class
  4. Anonymous inner class
The class which is declared with inside class is called nested class / inner class. This is classified to two types. There are, Static Nested Class & Non Static Nested Class / Inner Class.
1. Static Nested Class:
  • Nested class which is declared static is static nested class.
  • Its methods & members associates with outer class.
  • It can be used through object reference.
  •  Example:
    OuterClass.StaticNestedClass innerStatic = new OuterClass.StaticNestedClass();  
               innerStatic.display(); 
Example for Static Nested Class
 class OuterClass{  
      // Declare static nested inner classs  
      static class StaticNestedClass{  
           //static inner class method  
           void display(){  
                System.out.println("Inside Static Nested Class");  
           }  
      }  
      //outer class method  
      void display(){  
           System.out.println("Outer Class");  
      }  
 }  
 class MainClass  
 {  
      public static void main(String[] arg)  
      {  
           //how to access static nested class method  
           //1st create object for outer class object  
           OuterClass outer = new OuterClass();  
           outer.display();  
           //Now calling static nested class   
           OuterClass.StaticNestedClass innerStatic = new OuterClass.StaticNestedClass();  
           innerStatic.display();  
      }  
 }  

2. Non Static Nested Class / Inner Class:
  • It has access to the other members of the outer class, even they are private.
  • As the static declaration are not allowed inside inner class, we can't run inner class directly console.
  • We can access inner class code through outer class object only.
  • Instance of inner class valid within the enclosed class & has direct access to the methods & members of the enclosed instance.
  • For example,  
    OuterClassNonStat.NonStaticNestedClass inner = outer.new NonStaticNestedClass();
 Example for Inner Class:
 class OuterClassNonStat{  
      // Declare static nested inner classs  
      class NonStaticNestedClass{  
           //non static inner class method  
           void display(){  
                System.out.println("Inside Non Static Nested Class");  
           }  
      }  
      //outer class method  
      void display(){  
           System.out.println("Outer Class");  
      }  
 }  
 class MainClassNonStatic  
 {  
      public static void main(String[] arg)  
      {  
           //how to access non static nested class method  
           //1st create object for outer class object  
           OuterClassNonStat outer = new OuterClassNonStat();  
           outer.display();  
           //Now calling non static nested class   
           OuterClassNonStat.NonStaticNestedClass inner = outer.new NonStaticNestedClass();  
           inner.display();  
      }  
 }  

 3. Local Inner Class:
  • Local inner class is class declared in the body of method. Such class is know within contains method only. It is called Local Inner Class.
  • If we are declaring local inner class inside method, we can access both instance and static variables of outer class directly from the inner class.
  • From local inner class we are not allowed to access the local variables of the method unless it is marked as final.
  • Its not a member of enclosing class, hence doesn't have a access specifiers.
  • These inner class are very rarely used classes in real time. Because, these inner classes can be accessed with in the method only. Outside the method, your not allowed to access, violation leads to CTE.
Example for local inner class:
 class OuterClass {  
   static int x=10;  
   void m1()  
   {  
           int y=20;  
           class LocalInnerClass  
           {  
                void show()  
                {  
                     System.out.println(x); // 10  
                     System.out.println(y); // Compile time error ( If y is final no error)  
                }  
           }  
           LocalInnerClass inner=new LocalInnerClass();  
           inner.show();  
   }  
 }  
 public class MainLocalInnerClass {  
      public static void main(String args[]) {  
           OuterClass outer = new OuterClass();  
     outer.m1();  
      }  
 }  

4. Anonymous Inner Class:
  • We can declare anonymous inner class either in static or non static methods.
  • If we declare anonymous inner class in the static method the static variables of outer class can be accessed directly from inner class.
  • If we are declaring anonymous inner class inside instance method, we can access both instance and static variables of outer class directly from the inner class.
  • From anonymous inner class we are not allowed to access the local variables of the method unless it is marked as final.
  • It is accessible only at the point of its declaration.
 Example for anonymous inner class:
 interface Inter {  
      void display();  
 }  
 class AnonymousInnerClass  
 {  
      public static void main(String arg[]){  
           //Create thread using anonymous class  
           int x = 10;  
           Runnable r=new Runnable(){  
                public void run(){  
                     System.out.println("run"+x);//compile error.  
                               //local variable x accessed from inner class (if x is final then no error)  
                }  
           };  
           Thread t=new Thread(r);  
           t.start();  
           //implement interface  
           Inter inter = new Inter(){  
                public void display(){  
                     System.out.println("Display method");  
                }  
           };  
           inter.display();  
      }  
 }  

Live Trend: Earthquake in Chennai, Thiruvallur Today Apr 11-4-...

Live Trend: Earthquake in Chennai, Thiruvallur Today Apr 11-4-...: - Mild Earthquake in some parts of Chennai at around 2.15 pm IST today April 11 2012 (Wednesday) - Tremor was also felt at Tiruvallur - Pe...

Difference between a Vector and an Array in Java


  1. Vector is a dynamic array, whose size can be increased, where as an array size can not be changed.
  2. Reserve space can be given to Vector, where as array can not.
  3. Vector is a Class, where as array is not.
  4. Vector can be stored any type of objects, where as an array can stored only homogeneous values.
  5. Vector implements List interface, where as an array is primitive data type.
  6. Vector is synchronized, where as array is not.

Difference between class variable and instance variable in java


Consider the following class:
public class IdentifyMyParts {
    public static int x = 7;
    public int y = 3;
} 
  1. Question: What are the class variables?
    Answer: x
  2. Question: What are the instance variables?
    Answer: y
  3. Question: What is the output from the following code:
    IdentifyMyParts a = new IdentifyMyParts(); 
    IdentifyMyParts b = new IdentifyMyParts(); 
    a.y = 5; 
    b.y = 6; 
    a.x = 1; 
    b.x = 2; 
    System.out.println("a.y = " + a.y); 
    System.out.println("b.y = " + b.y); 
    System.out.println("a.x = " + a.x); 
    System.out.println("b.x = " + b.x); 
    System.out.println("IdentifyMyParts.x = " + IdentifyMyParts.x);
    
    Answer: Here is the output:
     a.y = 5 
     b.y = 6 
     a.x = 2 
     b.x = 2
     IdentifyMyParts.x = 2
    
    Becausexis defined as apublic static intin the classIdentifyMyParts, every reference toxwill have the value that was last assigned becausexis a static variable (and therefore a class variable) shared across all instances of the class. That is, there is only onex: when the value ofxchanges in any instance it affects the value ofxfor all instances ofIdentifyMyParts

JSP useBean and Scope Types

The beans can be declared in JSP as following: Scope parameter indicates the context in which the bean should be made available. There are four different possible kinds of useBean scope, “page” scope being the default one.
  1. page: Availability: The bean is only available on the current page Storage:The bean is stored in the PageContext of the current page.
  2. request: Availability: The bean is only available for the current client request Storage: The bean is stored in the ServletRequest object. 
  3. session: Availability:The object is available to all pages during the life of the current HttpSession. Storage: The bean is stored in HttpSession object. 
  4. application: Availability: The bean available to all pages that share the same context. Storage: The bean is stored in ServletContext object

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()");  
      }  
 }