Java interview Questions

What are the differences between SAX and DOM parser.




Both SAX and DOM are used to parse the XML document. Both has advantages and disadvantages and can be used in our programming depending on the situation.

Parses node by node

Stores the entire XML document into memory before processing

Doesn’t store the XML in memory

Occupies more memory

We cant insert or delete a node

We can insert or delete nodes

Top to bottom traversing

Traverse in any direction.

SAX is an event based parser

DOM is a tree model parser

SAX is a Simple API for XML

Document Object Model (DOM) API

import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

import javax.xml.parsers.*;
import org.w3c.dom.*;

doesn’t preserve comments

preserves comments

SAX generally runs a little faster than DOM

SAX generally runs a little faster than DOM

If we need to find a node and doesn’t need to insert or delete we can go with SAX itself otherwise DOM provided we have more memory.



Checked Vs unchecked exceptions

Checked exceptions:

·         represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)

·         are subclasses of Exception

·         methods are obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow)

Unchecked exceptions:

·         represent defects in the program (often invalid arguments passed to a non-private method)

·         are subclasses of RuntimeException, and are usually implemented usingIllegalArgumentException, NullPointerException, or IllegalStateException

·         methods are not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they almost always do not do so)

It is somewhat confusing, but note as well that RuntimeException (unchecked) is itself a subclass of Exception (checked). 

What is the difference between Struts 1.0 and Struts 1.1? 

The new features added to Struts 1.1 are
1. RequestProcessor class
2. Method perform() replaced by execute() in Struts base Action Class
3. Changes to web.xml and struts-config.xml
4.Declarative exception handling
5.Dynamic ActionForms
7.Multiple Application Modules
8.Nested Tags
9.The Struts Validator
10.Change to the ORO package
11.Change to Commons logging
12.Removal of Admin actions
13. Deprecation of the GenericDataSource.

What is the difference between ActionErrors and ActionMessages?

There is no differnece between these two classes.All the behavior of ActionErrors was copied into ActionMessages and vice versa. This was done in the attempt to clearly signal that these classes can be used to pass any kind of messages from the controller to the view — where as errors being only one kind of message.

The difference between saveErrors(…) and saveMessages(…) is simply the attribute name under which the ActionMessages object is stored, providing two convenient default locations for storing controller messages for use by the view. If you look more closely at the html:errors and html:messages tags, you can actually use them to get an ActionMessages object from any arbitrary attribute name in any scope. 

What is the difference between ActionForm and DynaActionForm

# The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger.

# The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.

# ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.

# ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.getParameter( .. ).

# DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.

# Time savings from DynaActionForm is insignificant. It doesn t take long for today s IDEs to generate getters and setters for the ActionForm attributes. (Let us say that you made a silly typo in accessing the DynaActionForm properties in the Action instance. It takes less time to generate the getters and setters in the IDE than fixing your Action code and redeploying your web application).

Difference between final, finally and finalize() 

·         final – constant declaration.

·         finally – The finally block always executes when the try block exits, except System.exit(0) call. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

·         finalize() – method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method. 

Forward Vs Redirect

A Controller servlet may perform either a forward or a redirect operation at the end of processing a request.


·         forward is performed internally by the servlet

·         the browser is completely unaware that it has taken place, so its original URL remains intact

·         any browser reload will simple repeat the original request, with the original URL


·         redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original

·         a browser reload of the second URL will not repeat the original request, but will rather fetch the second URL

·         redirect is always slower than a forward, since it requires a second browser request

·         beans placed in the original request scope are not available to the second request

Forward should be used if the operation can be safely repeated upon reload; otherwise, redirect must be used. Typically, if the operation performs an edit on the datastore, then a redirect, not a forward, is required. 

Difference between ArrayList and Vector?  

·          Internally, both the ArrayList and Vector hold onto their contents using an Array. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

·         ArrayList doesn’t have a constructor for specifying the incremental capacity, where as Vector has a constructor to specify the initial capacity and incremental capacity.

·         Vector is synchronized where as ArrayList is not synchronized 

Difference between error and an exception? 

An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.). 

Difference between a constructor and a method 

constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
 A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

Difference between getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface  

The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a “/” it is interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must start with a “/” and are interpreted as relative to current context root. 

Difference between throw and throws 

The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as argument. The exception will be caught by an immediately encompassing try-catch construction or propagated further up the calling hierarchy.
 The throws keyword is a modifier of a method that designates that exceptions may come out of the method, either by virtue of the method throwing the exception itself or because it fails to catch such exceptions that a method it calls may throw.

Difference between throw and throws 

throw keyword is used to throw an exception manually from a method where throws is used to tell the compiler that we haven’t handled the exception, ask the caller to handle the exception.

Overloadnig Vs Overriding 

The rules for overriding a method are as follows:

Theargument list must exactly matchthat of the overridden method.
■Thereturn type must exactly matchthat of the overridden method.
■Theaccess level can be less restrictivethan that of the overridden method.
■The overriding methodmust not throw new or broader checked exceptionsthan those declared by the overridden method. 
■The overriding methodcan throw narrower or fewer exceptions. Just becausean overridden method “takes risks” doesn’t mean that the overriding subclass’exception takes the same risks. Bottom line: An overriding method doesn’thave to declare any exceptions that it will never throw, regardless of whatthe overridden method declares.
■Youcannot override a method markedfinal.
■If a method can’t be inherited, you cannot override it. 

The rules for Overloaded method are as follows:

■Overloaded methodsmustchange the argument list.
■Overloaded methodscanchange the return type.
■Overloaded methodscanchange the access modifier.
■Overloaded methodscandeclare new or broader checked exceptions.
■A methodcanbe overloaded in the same class or in a subclass. 

 What is difference between perform() used in strut…

The actual difference is

public ActionForward perform(ActionMapping mapping,
ActionForm form,
                             javax.servlet.http.HttpServletRequest request,
                             javax.servlet.http.HttpServletResponse response)
                      throws java.io.IOException,


public ActionForward exceute(ActionMapping mapping,
ActionForm form,
                             javax.servlet.http.HttpServletRequest request,
                             javax.servlet.http.HttpServletResponse response)

                             throws Exception

so in case of perform() method u can’t throw exceptions other than IOException,ServletException.

In case of excute() method, u can throw any exception,because its prototype is ‘throws Exception.’

 What is the difference between Abstract class and Interface

When should you use an abstract class, when an interface, when both?
What is similarities/difference between an Abstract class and Interface?
What is the difference between interface and an abstract class?

1. Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. An abstract class can contain no abstract methods also i.e. abstract class may contain concrete methods. A Java Interface can contain only method declarations and public static final constants and doesn’t contain their implementation. The classes which implement the Interface must provide the method definition for all the methods present.

2. Abstract class definition begins with the keyword “abstract” keyword followed by Class definition. An Interface definition begins with the keyword “interface”.

3. Abstract classes are useful in a situation when some general methods should be implemented and specialization behavior should be implemented by subclasses. Interfaces are useful in a situation when all its properties need to be implemented by subclasses

4. All variables in an Interface are by default – public static final while an abstract class can have instance variables.

5. An interface is also used in situations when a class needs to extend an other class apart from the abstract class. In such situations its not possible to have multiple inheritance of classes. An interface on the other hand can be used when it is required to implement one or more interfaces. Abstract class does not support Multiple Inheritance whereas an Interface supports multiple Inheritance.

6. An Interface can only have public members whereas an abstract class can contain private as well as protected members.

7. A class implementing an interface must implement all of the methods defined in the interface, while a class extending an abstract class need not implement any of the methods defined in the abstract class.

8. The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass

9. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast

10.Interfaces are often used to describe the peripheral abilities of a class, and not its central identity, E.g. an Automobile class might
implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.

Note: There is no difference between a fully abstract class (all methods declared as abstract and all fields are public static final) and an interface.

Note: If the various objects are all of-a-kind, and share a common state and behavior, then tend towards a common base class. If all they 
share is a set of method signatures, then tend towards an interface.

Neither Abstract classes nor Interface can be instantiated.

What is the difference between Hashmap and Hashtable? 

All the Mehods in HashTable are synchronized whereas HashMap is not thread-safe.
Another big difference is that HashMap allows null key and null values whereas HashTable does not permit null key and null values.
Submitted by Bikramjit Bardhan (

1–HashMap is a New Java Class , where as HashTable is Old.
2?HashMap is not Synchronized where as hashTable is.
3?HashMap allows null as both key and value, where as HashTable does?nt allow null.
4?HashMap retrieval is not in order (random). HashTable provide ordered retrieval.