Interface Java Interview Questions | Eklavya Online

Interface Java Interview Questions

Yes,an inner class may be built an Interface.

public interface xyz


static int p=0;

void m();

class c



int q;

public static void main(String c[])

System.out.println(“inside “);



In order to assign a superclass object in a variable to a subclass,one needs to do explicit casting.

For example:Person person=null;

Man man = (Man)person;

An automatic casting takes place when we typecast a object in subclass as parent class object.

Define Externalizable.

Externalizable is coined as an Interface

It extends the Serializable Interface.

It also sends data into the Streams.

Externalizable sends data in a Compressed Format.

Externalizable is having two methods,for e.g. writeExternal(ObjectOuput out) & readExternal(ObjectInput in)

JDBC is a set of Java API for executing SQL statements. This API consists of a set of classes and interfaces to enable programs to write pure Java Database applications.

JDBC technology drivers fit into one of four categories:

  • A JDBC-ODBC bridgeprovides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun, see “” JDBC-ODBC Bridge Driver.
  • A native-API partly Java technology-enabled driverconverts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.
  • A net-protocol fully Java technology-enabled drivertranslates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to their existing database middleware products.
  • A native-protocol fully Java technology-enabled driverconverts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress.

a) JDBC-ODBC Bridge driver

b) Native API Partly-Java driver

c) JDBC-Net Pure Java driver

d) Native-Protocol Pure Java driver

Here is the sample code that makes use of the default compareTo( ) provided in the String class as it implements the Comparable interface and the Collections utility class that provides a sorting method, which internally uses the efficient “merge sort” algorithm.

import java.util.Arrays;

import java.util.Collections;

import java.util.List;


public class Sort1 {

public static void main(String[] args) {

List<string> values = Arrays.asList(“JEE”, “Java”, “Servlets”, “JMS”, “JNDI”, “JDBC”, “JSP”, “EJB”);

Collections.sort(values); // uses the default compareTo(String anotherString)  in the String class





[EJB, JDBC, JEE, JMS, JNDI, JSP, Java, Servlets]

// Sort


// Sort case-insensitive

Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

// SortReverse-order

Collections.sort(list, Collections.reverseOrder ());

// Reverse-order sort case-insensitive

Define local, member and a class variable.

Within a method variables declared are called “local” variables.

Variables declared in the class i.e not in any methods are “member” variables (global variables).

Variables declared in the class i.e not in any methods and are called as “static” are class variables.

Name the different identifier states of a Thread.

Different types of identifiers of a Thread are:

R – Running or runnable thread

S – Suspended thread

CW – Thread waiting on a condition variable

MW – Thread waiting on a monitor lock

MS – Thread suspended waiting on a monitor lock

Define Vector class? Differentiate the Vector and ArrayList.

Vector canbe said a legacy class which has been introduced to implement the List interface since Java 2 platform v1.2

Vector is always synchronized but ArrayList is not.

When Vector class is synchronized, if we will run in multithreading environment we’ve to use ArrayList with Collections.

Vector has a default size i.e 10 while arrayList has no default size.

ArraayList is not having any method returning Enumerations where as vector list is having.

Differentiate between Enumeration and Iterator interface

In java.util package the Enumeration and Iterator are available.

The Enumeration interface is replicated by the Iterator interface.

In preference to Enumeration new implementations should consider using Iterator .


The difference of Iterators from enumerations are:

  • Enumeration has 2 methods namely hasMoreElements() & nextElement() where the Iterator contained three methods namely hasNext(), next(),remove().
  • An optional remove operation is added in Iterator,and has shorter method names. We Use remove() to delete the objects but the Enumeration interface does not support this feature.
  • The legacy classes use Enumeration interface .Vector.elements() & Hashtable.elements() method results Enumeration.
  • All Java Collections Framework classes returns iterator. java.util.Collection.iterator() method returning an instance of Iterator.

Collections.sort(list, String.CASE_INSENSITIVE_ORDER);


java.util.Comparator and java.lang.Comparable

java.util.Comparator compares some other class’s instances,

while java.lang.Comparable compares itself with another object.

Remote method invocation is called RMI.

One can work with remote object using RMI.

It gives a impression that you are working with a object that resides within your own JVM though it is somewhere.

The protocol used by RMI is RMI-IIOP

Define a Collection API.

The set of classes and interfaces supporting the operation on collections of objects is the Collection API.

Than the vectors, arrays, and hashtables if effectively replaces,these classes and interfaces are more flexible, more powerful, and more regular

class examples: HashSet, TreeMap, ArrayList, LinkedList,HashMap and TreeMap.

interface examples: Set,List ,Collection and Map.

How many forms of Polymorphism are there?

polymorphism exists in three different forms in Java:

  • Method overloading
  • Method overriding through inheritance
  • Method overriding through the Java interface

Define the wrapper classes in Java and name a few.

Wrapper class is wraps around the primitive data type. List of the primitive types and the corresponding wrapper classes:

Primitive Wrapper

boolean java.lang.Boolean

byte java.lang.Byte

char java.lang.Character

double java.lang.Double

float java.lang.Float

int java.lang.Integer

long java.lang.Long

short java.lang.Short

void java.lang.Void

Differentiate between JDK ,JRE & JVM

JDK stands for Java Development Kit. It is the most widely used Java Software Development Kit.

JRE stands for Java Runtime Environment. It is an implementation of the Java Virtual Machine which executes Java programs

JVM stands for Java Virtual Machine. It is an interpreter.

An interface may be declared as public or abstract

A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface

Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

JSP is a dynamic scripting capability for web pages that allows Java as well as a few special tags to be embedded into a web file (HTML/XML, etc). The suffix traditionally ends with .jsp to indicate to the web server that the file is a JSP files. JSP is a server side technology – you can’t do any client side validation with it. The advantages are: a) The JSP assists in making the HTML more functional. Servlets on the other hand allow outputting of HTML but it is a tedious process. b) It is easy to make a change and then let the JSP capability of the web server you are using deal with compiling it into a servlet and running it.

JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web applications in a portable, secure and well-defined way. The JSP Technology allows us to use HTML, Java, JavaScript and XML in a single file to create high quality and fully functionaly User Interface components for Web Applications.

A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

  1. a) OBDC is for Microsoft and JDBC is for Java applications. b) ODBC can’t be directly used with Java because it uses a C interface. c) ODBC makes use of pointers which have been removed totally from Java. d) ODBC mixes simple and advanced features together and has complex options for simple queries. But JDBC is designed to keep things simple while allowing advanced capabilities when required. e) ODBC requires manual installation of the ODBC driver manager and driver on all client machines. JDBC drivers are written in Java and JDBC code is automatically installable, secure, and portable on all platforms. f) JDBC API is a natural Java interface and is built on ODBC. JDBC retains some of the basic features of ODBC.

An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act listener by extending one of the adapter classes and implementing only those events in which you are interested. For example, the MouseMotionAdapter class has two methods, mouseDragged()and mouseMoved(). The signatures of these empty are exactly as defined in the MouseMotionListener interface. If you are interested in only mouse drag events, then you could simply extend MouseMotionAdapter and implement mouseDragged()

?– A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management

Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse. Inheritance is the process by which one object acquires the properties of another object. Polymorphism is the feature that allows one interface to be used for general class actions.

java.util.Comparator compares some other class’s instances.

java.lang.Comparable compares another object with itself.

Differentiate between final, finally and finalize.

The keyword is final. It is used for declaring a constant It prevents a class from producing subclasses.

finally is a code.It always executes when the try block is finished, Unless System.exit() has been called.finalize() is a method, Before discarding by the garbage collector it is invoked.

Differentiate JAR and WAR files

JAR files:

  • JAR files is the acronym stands for Java ARchive fles.
  • JAR files allow aggregating many files into one,
  • JAR is usually used to hold Java classes in a library.

WAR files:

  • WAR files is the acronym stands for Web ARchive fles.
  • WAR stores XML, java classes, and JavaServer pages
  • WAR is mainly used for Web Application purposes.

In a Java , how can you send program messages on the system console, but error messages, to a file?

The class System has a variable out that denotes the standard output.

The standard error device represents the variable err .

Naturally, they both point at the system console.


In this way, the standard output can be sent to the file:

Stream x = new Stream(new FileOutputStream(“error.txt”));



The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.

  1. a) All the methods declared inside an interface are abstract whereas abstract class must have at least one abstract method and others may be concrete or abstract. b) In abstract class, key word abstract must be used for the methods whereas interface we need not use that keyword for the methods. c) Abstract class must have subclasses whereas interface can’t have subclasses.

A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces.

Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces

The Collection interface provides support for the implementation of a mathematical bag – an unordered collection of objects that may contain duplicates.

The EventObject class and the EventListener interface support event processing.

The sizeof operator is not a keyword.

Thread class and Runnable interface can be used to create threads and using Runnable interface is the most advantageous method to create threads because we need not extend thread class here.

All tasks must implement the run() method, whether they are a subclass of Thread or implement theRunnable interface.

All AWT event listeners extend the java.util.EventListener interface.

There are two packages in servlets and they are javax. servlet and

Interface is similar to a class which may contain method’s signature only but not bodies and it is a formal set of method and constant declarations that must be defined by the class that implements it. Interfaces are useful for: a)Declaring methods that one or more classes are expected to implement b)Capturing similarities between unrelated classes without forcing a class relationship. c)Determining an object’s programming interface without revealing the actual body of the class.

There are six interfaces and come under two different inheritance group one which comes under the collection interface root and the other in the map interface root.



It’s the base of all collection classes. It provides a unified way to manipulate collection objects. Collection has group of object called as elements. These elements can be accessed and manipulated using Iterator. List

In List interface the elements are arranged sequentially. Elements can be inserted in to any location and you can also insert duplicate elements. In order to access the elements you need to use the “ListIterator”. Using “ListIterator” you can move back and forth which makes it unique as compared to other iterators.



It represents a collection but no duplicates are allowed in this case.



It extends the Set interface and sorts the set in ascending order.



Map stores association between keys and value pairs. So given a key you can easily find the value. One thing important to note is they do not implement iterable interface. But yes you can obtain a collection view of the map which allows you loop using for loop.



It extends Map so that the keys are maintained in ascending order.

The left operand is an object reference or null value and the right operand is a class, interface, or arraytype.

The Iterator interface is used to step through the elements of a Collection.

The Iterator is an interface, used to traverse through the elements of a Collection. It is not advisable to modify the collection itself while traversing an Iterator.

The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model, components are required to handle their own events. If they do not handle a particular event, the event is inherited by (or bubbled up to) the component’s container. The container then either handles the event or it is bubbled up to its container and so on, until the highest-level container has been tried.

In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces. The event-delegation model is more efficient than the event-inheritance model because it eliminates the processing required to support the bubbling of unhandled events

A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package

The Collections API is a set of classes and interfaces that support operations on collections of objects.

The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program..

  1. a) Servlets are to servers what applets are to browsers. b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.

JDBC is a set of Java API for executing SQL statements. This API consists of a set of classes and interfaces to enable programs to write pure Java Database applications.

Vector : The Vector class provides the capability to implement a growable array of objects. Hashtable : The Hashtable class implements a Hashtable data structure. A Hashtable indexes and stores objects in a dictionary using hash codes as the object’s keys. Hash codes are integer values that identify objects. LinkedList: Removing or inserting elements in the middle of an array can be done using LinkedList. A LinkedList stores each object in a separate link whereas an array stores object references in consecutive locations. Enumeration: An object that implements the Enumeration interface generates a series of elements, one at a time. It has two methods, namely hasMoreElements() and nextElement(). HasMoreElemnts() tests if this enumeration has more elements and nextElement method returns successive elements of the series.

An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event.

An event adapter provides a default implementation of an event-listener interface

It must provide all of the methods in the interface and identify the interface in its implements clause.

a)Application must be run on local machine whereas applet needs no explicit installation on local machine. b)Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser. d)Application starts execution with its main method whereas applet starts execution with its init method. e)Application can run with or without graphical user interface whereas applet must run within a graphical user interface.

If one or more methods of the class are abstract. If class inherits one or more

abstract methods from the parent abstract class and no implementation is provided for

that method If class implements an interface and provides no implementation for

those methods

A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

The marker interface is a design pattern, used with languages that provide run-time type information about objects. It provides a way to associate metadata with a class where the language does not have explicit support for such metadata. To use this pattern, a class implements a marker interface, and code that interact with instances of that class test for the existence of the interface. Whereas a typical interface specifies methods that an implementing class must support, a marker interface does not do so. The mere presence of such an interface indicates specific behavior on the part of the implementing class. There can be some hybrid interfaces, which both act as markers and specify required methods, are possible but may prove confusing if improperly used. Java utilizes this pattern very well and the example interfaces are:

  • io.Serializable – Serializability of a class is enabled by the class implementing the interface. The Java Classes that do not implement Serializable interface will not be able to serialize or deserializ their state. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.
  • rmi.Remote – The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object must directly or indirectly implement this interface. Only those methods specified in a “remote interface”, an interface that extends java.rmi.Remote are available remotely.
  • lang.Cloneable – A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class. Invoking Object’s clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.
  • servlet.SingleThreadModel – Ensures that servlets handle only one request at a time. This interface has no methods.
  • util.EvenListener – A tagging interface that all event listener interfaces must extend.
  • The “instanceof” keyword in java can be used to test if an object is of a specified type. So this keyword in combination with Marker interface can be used to take different actions based on type of interface an object implements.

Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon.

There are two types of polymorphism:-

  • Method Polymorphism through overloading.
  • Object polymorphism by inheritance / interfaces.

An anonymous class may implement an interface or extend a superclass, but may not be declared to do both

The List interface provides support for ordered collections of objects.

Remote Method Invocation (RMI) allows java object that executes on one machine and to invoke the method of a Java object to execute on another machine. The steps involved in developing an RMI object are: a) Define the interfaces b) Implementing these interfaces c) Compile the interfaces and their implementations with the java compiler d) Compile the server implementation with RMI compiler e) Run the RMI registry f) Run the application

within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined A Java source code file takes the name of a public class or interface that is defined within a source code file, then the source code file must take the name of the public class or interface.

If no public class or interface is defined within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension.

An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.

An object reference be cast to an interface reference when the object implements the referenced interface.

?– It is not having any method because it is a TAGGED or MARKER interface.

There are two types of casting, casting between primitive numeric types and casting between object references.

Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values.

Casting between object references is used to refer to an object by a compatible class, interface, or arraytype reference.

Packages group related classes and interfaces together and thus avoiding any name conflicts. From OOP’s point of view packages are useful for grouping related classes together. Classes are group together in a package using “package” keyword.

In Java, if the super class of a class is implementing Serializable interface, it means that it is already serializable. Since, an interface cannot be unimplemented, it is not possible to make a class non-serializable. However, the serialization of a new class can be avoided. For this, writeObject () and readObject() methods should be implemented in your class so that a Not Serializable Exception can be thrown by these methods. And, this can be done by customizing the Java Serialization process. Below the code that demonstrates it

class MySubClass extends SomeSerializableSuperClass {

private void writeObject( out)

throws IOException {

throw new NotSerializableException(“Can not serialize this class”);


private void readObject( in)

throws IOException, ClassNotFoundException {

throw new NotSerializableException(“Can not serialize this class”);


private void readObjectNoData()

throws ObjectStreamException; {

throw new NotSerializableException(“Can not serialize this class”);



Serialization is required for a variety of reasons. It is required to send across the state of an object over a network by means of a socket. One can also store an object’s state in a file. Additionally, manipulation of the state of an object as streams of bytes is required. The core of Java Serialization is the Serializable interface. When Serializable interface is implemented by your class it provides an indication to the compiler that java Serialization mechanism needs to be used to serialize the object.

when the internal array fills up. The arrayList has to create a new array and copy all the elements there. The ArrayList has a growth algorithm of (n*3)/2+1, meaning that each time the buffer is too small it will create a new one of size (n*3)/2+1 where n is the number of elements of the current buffer. Hence if we can guess the number of elements that we are going to have, then it java.util.ArrayList and java.util.LinkedList are two Collections classes used for storing lists of object references Here are some key differences:

  • ArrayList uses primitive object array for storing objects whereas LinkedList is made up of a chain of nodes. Each node stores an element and the pointer to the next node. A singly linked list only has pointers to next. A doubly linked list has a pointer to the next and the previous element. This makes walking the list backward easier.
  • ArrayList implements the RandomAccess interface, and LinkedList does not. The commonly used ArrayList implementation uses primitive Object array for internal storage. Therefore an ArrayList is much faster than a LinkedList for random access, that is, when accessing arbitrary list elements using the get method. Note that the get method is implemented for LinkedLists, but it requires a sequential scan from the front or back of the list. This scan is very slow. For a LinkedList, there’s no fast way to access the Nth element of the list.
  • Adding and deleting at the start and middle of the ArrayList is slow, because all the later elements have to be copied forward or backward. (Using System.arrayCopy()) Whereas Linked lists are faster for inserts and deletes anywhere in the list, since all you do is update a few next and previous pointers of a node.
  • Each element of a linked list (especially a doubly linked list) uses a bit more memory than its equivalent in array list, due to the need for next and previous pointers.
  • ArrayList may also have a performance issue makes sense to create a arraylist with that capacity during object creation (using construtor new ArrayList(capacity)). Whereas LinkedLists should not have such capacity issues.

Map is Interface which is part of Java collections framework. This is to store Key Value pair, and Hashmap is class that implements that using hashing technique.

Map is Interface and Hashmap is class that implements that

Best practices relating to Java Collection framework are as follow:

  • Choose the right type of data structure based on usage patterns like fixed size or required to grow, duplicates allowed or not, ordering is required to be maintained or not, traversal is forward only or bi-directional, inserts at the end only or any arbitrary position, more inserts or more reads, concurrently accessed or not, modification is allowed or not, homogeneous or heterogeneous collection, etc. Also, keep multi-threading, atomicity, memory usage and performance considerations discussed earlier in mind.
  • Don’t assume that your collection is always going to be small as it can potentially grow bigger with time. So your collection should scale well.
  • Program in terms of interface not implementation: For example, you might decide a LinkedList is the best choice for some application, but then later decide ArrayList might be a better choice for performance reason.
    • Bad:
      • ArrayList list = new ArrayList(100);
    • Good:

// program to interface so that the implementation can change

  • List list = new ArrayList(100);
  • List list2 = new LinkedList(100);
  • Return zero length collections or arrays as opposed to returning a null in the context of the fetched list is actually empty. Returning a null instead of a zero length collection is more error prone, since the programmer writing the calling method might forget to handle a return value of null.
    • List emptyList = Collections.emptyList( );
    • Set emptySet = Collections.emptySet( );
  • Use generics for type safety, readability, and robustness.
  • Encapsulate collections: In general, collections are not immutable objects. So care should be taken not to unintentionally expose the collection fields to the caller. The caller may not perform any necessary validation.

Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession( ) method.

public class HibernateUtil {

public static final ThreadLocal local = new ThreadLocal();

public static Session currentSession() throws HibernateException {

Session session = (Session) local.get();

//open a new session if this thread has no session

if(session == null) {

session = sessionFactory.openSession();



return session;



It is also vital that you close your session after your unit of work completes. Note: Keep your Hibernate Session API handy. Quite often, hibernate is used with Spring framework, using the HibernateTemplate.

Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. A servlet is a Java class implementing the javax.servlet.Servlet interface that runs within a Web or application server’s servlet engine, servicing client requests forwarded to it through the server. A Java Server Page is a slightly more complicated beast. JSP pages contain a mixture of HTML, Java scripts (not to be confused with JavaScript), JSP elements, and JSP directives. The elements in a Java Server Page will generally be compiled by the JSP engine into a servlet, but the JSP specification only requires that the JSP page execution entity follow the Servlet Protocol.

The advantage of Java Server Pages is that they are document-centric. Servlets, on the other hand, look and act like programs. A Java Server Page can contain Java program fragments that instantiate and execute Java classes, but these occur inside an HTML template file and are primarily used to generate dynamic content. Some of the JSP functionality can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides a framework for Web application development. Rather than choosing between servlets and Java Server Pages, you will find that most non-trivial applications will want to use a combination of JSP and servlets. In fact, the JSP 1.1 and Servlet 2.2 specifications are based around the concept of the Web application, combining the two APIs into a unified framework.

: Casting from Old types to Newtypes

Compile time rules :

– When both Oldtypes and Newtypes are classes, one should be subclass of the other

– When both Oldtype ad Newtype are arrays, both arrays must contain reference types

(not primitive), and it must be legal to cast an element of Oldtype to an element of


– You can always cast between an interface and a non-final object

Runtime rules :

– If Newtype is a class. The class of the expression being converted must be Newtype

or must inherit from Newtype

– If NewType is an interface, the class of the expression being converted must

implement Newtype

JDBC API has 2 Metadata interfaces DatabaseMetaData & ResultSetMetaData. The DatabaseMetaData provides Comprehensive information about the database as a whole. This interface is implemented by driver vendors to let users know the capabilities of a Database Management System (DBMS) in combination with the driver based on JDBC technology (“JDBC driver”) that is used with it. Below is a sample code which demonstrates how we can use the DatabaseMetaData

DatabaseMetaData md = conn.getMetaData();

System.out.println(“Database Name: ” + md.getDatabaseProductName());

System.out.println(“Database Version: ” + md.getDatabaseProductVersion());

System.out.println(“Driver Name: ” + md.getDriverName());

System.out.println(“Driver Version: ” + md.getDriverVersion());


The ResultSetMetaData is an object that can be used to get information about the types and properties of the columns in a ResultSet object. Use DatabaseMetaData to find information about your database, such as its capabilities and structure. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns. Below a sample code which demonstrates how we can use the ResultSetMetaData

ResultSet rs = stmt.executeQuery(“SELECT a, b, c FROM TABLE2”);

ResultSetMetaData rsmd = rs.getMetaData();

int numberOfColumns = rsmd.getColumnCount();

boolean b = rsmd.isSearchable(1);

Below is a snippet from SUN’s site. The Java SDK contains 2 implementations of the List interface – ArrayList and LinkedList. If you frequently add elements to the beginning of the List or iterate over the List to delete elements from its interior, you should consider using LinkedList. These operations require constant-time in a LinkedList and linear-time in an ArrayList. But you pay a big price in performance. Positional access requires linear-time in a LinkedList and constant-time in an ArrayList

Vector & ArrayList both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. ArrayList and Vector class both implement the List interface. Both the classes are member of Java collection framework, therefore from an API perspective, these two classes are very similar. However, there are still some major differences between the two. Below are some key differences

  • Vector is a legacy class which has been retrofitted to implement the List interface since Java 2 platform v1.2

Vector is synchronized whereas ArrayList is not. Even though Vector class is synchronized, still when you want programs to run in multithreading There are multiple aspects to this decision:

  • The basic difference between a Hashtable and an HashMap is that, Hashtable is synchronized while HashMap is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Hashtable. While if not multiple threads are going to access the same instance then use HashMap. Non synchronized data structure will give better performance than the synchronized one.
  • If there is a possibility in future that – there can be a scenario when you may require to retain the order of objects in the Collection with key-value pair then HashMap can be a good choice. As one of HashMap’s subclasses is LinkedHashMap, so in the event that you’d want predictable iteration order (which is insertion order by default), you can easily swap out the HashMap for a LinkedHashMap. This wouldn’t be as easy if you were using Hashtable. Also if you have multiple thread accessing you HashMap then Collections.synchronizedMap() method can be leveraged. Overall HashMap gives you more flexibility in termsenvironment using ArrayList with Collections.synchronizedList() is recommended over Vector.
  • ArrayList has no default size while vector has a default size of 10.
  • The Enumerations returned by Vector’s elements method are not fail-fast. Whereas ArraayList does not have any method returning Enumerations.

Java Collections Framework provides a set of interfaces and classes that support operations on a collections of objects.

This is one of a difficult and tricky questions and answering this correctly would mean you are an expert in Java Serialization concept. In an already serialized object, the most challenging task is to change the structure of a class when a new field is added or removed. As per the specifications of Java Serialization, addition of any method or field is considered to be a compatible change whereas changing of class hierarchy or non-implementation of Serializable interface is considered to be a non-compatible change. You can go through the Java serialization specification for the extensive list of compatible and non-compatible changes. If a serialized object need to be compatible with an older version, it is necessary that the newer version follows some rules for compatible and incompatible changes. A compatible change to the implementing class is one that can be applied to a new version of the class, which still keeps the object stream compatible with older version of same class. Some Simple Examples of compatible changes are:

  • Addition of a new field or class will not affect serialization, since any new data in the stream is simply ignored by older versions. the newly added field will be set to its default values when the object of an older version of the class is un marshaled.
  • The access modifiers change (like private, public, protected or default) is compatible since they are not reflected in the serialized object stream.
  • Changing a transient field to a non-transient field is compatible change since it is similar to adding a field.
  • Changing a static field to a non-static field is compatible change since it is also similar to adding a field.
  • Some Simple Examples of incompatible changes are:
  • Changing implementation from Serializable to Externalizable interface can not be done since this will result in the creation of an incompatible object stream.
  • Deleting a existing Serializable fields will cause a problem.
  • Changing a non-transient field to a transient field is incompatible change since it is similar to deleting a field.
  • Changing a non-static field to a static field is incompatible change since it is also similar to deleting a field.
  • Changing the type of a attribute within a class would be incompatible, since this would cause a failure when attempting to read and convert the original field into the new field.
  • Changing the package of class is incompatible. Since the fully-qualified class name is written as part of the object byte stream.

Java serialization is one of the most commonly misunderstood areas. Many developers still think its only used for saving objects on the file system

  • ServletConfig a ServletConfig object is used to obtain configuration data when it is loaded.
  • There can be multiple ServletConfig objects in a single web application.
  • This object defines how a servlet is to be configured is passed to a servlet in its init method.
  • Most servlet containers provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters.
  • The container, in turn, passes these parameters to the servlet via the ServetConfig.



















ServletConfig config = getServletConfig();

String driverClassName = config.getInitParameter(“driverclassname”);

String dbURL = config.getInitParameter(“dburl”);


dbConnection = DriverManager.getConnection(dbURL,username,password);


This is one of top serialization questions that is asked in many big companies to test your in-depth understanding of serialization. Serializable is a marker interface therefore you are not forced to implement any methods, however Externalizable contains two methods readExternal() and writeExternal() which must be implemented. Serializable interface provides a inbuilt serialization mechanism to you which can be in-efficient at times. However Externilizable interface is designed to give you greater control over the serialization mechanism. The two methods provide you immense opportunity to enhance the performance of specific object serialization based on application needs. Serializable interface provides a default serialization mechanism, on the other hand, Externalizable interface instead of relying on default Java Serialization provides flexibility to control this mechanism. One can drastically improve the application performance by implementing the Externalizable interface correctly. However there is also a chance that you may not write the best implementation, so if you are not really sure about the best way to serialize, I would suggest your stick to the default implementation using Serializable interface.

The Observer pattern is a behavioral design pattern that  allows an object (an Observer) to watch another object (a Subject). The subject and observer to have a publish/subscribe relationship. Observers can register to receive events from the Subject.

Some of the practical uses of observer pattern are:

  • When a change to one object requires changing of others, and you don’t know how many objects need to be changed.
  • When an object should be able to notify other objects without making assumptions about who these objects are and not tightly coupling them.
  • When a report is received or an event occurs, a message needs to be sent to the subscribed handlers.


  • Programming Swing based GUI applications where the listeners register them with events like button click, property change, etc.
  • Programming a stock market application to know when the price of a stock changes.
  • Programming a order placement or trading application to know the status changes like pending, filled, shipped, rejected, etc.

So, whenever you want to have the state change or other information, instead of polling every few second, register the observers with a subject.


Here is some pseudo code of this third scenario

STEP 1: Define the Subject and Observer interfaces

This is the subject interface

package com;


public interface ReportExecutor {

public void addHandler(ReportHandler rh);

public void removeHandler(ReportHandler rh);

public void processReport(String message);


This is the observer interface

package com;


public interface ReportHandler {

//handles report

public void handleMessage(String message);


STEP 2: Define the concrete subject and observers

The concrete subject

package com;


import java.util.ArrayList;

import java.util.List;


public class SalesReportExecutor implements ReportExecutor {


//list of observers that register their interest in SalesReport

private List<reporthandler> reportHandlers = new ArrayList<reporthandler>();


public void addHandler(ReportHandler rh) {




public void processReport(String message) {

for (ReportHandler reportHandler : reportHandlers) {





public void removeHandler(ReportHandler rh) {




The concrete observers

package com;


public class LoggingReportHandler implements ReportHandler {



public void handleMessage(String message) {

//handles report by formatting and printing

System.out.println(“Logging report  ” + message);




package com;


public class EmailReportHandler implements ReportHandler {



public void handleMessage(String message) {

//handles the report by formatting it differently and emailing.

System.out.println(“Emailing report ” + message);

//logic to email report.




STEP 3: Finally, the JMS listener class that uses the subject. The JMS Listener class listens on a queue for presence of a report.

package com.mgl.mts.fix;


import javax.jms.Message;

import javax.jms.TextMessage;


public class MyAppListener {


public void onMessage(Message message) {

if (message instanceof TextMessage) {


ReportExecutor executor = new SalesReportExecutor();

executor.addHandler(new LoggingReportHandler());

executor.addHandler(new EmailReportHandler());



} else {

throw new IllegalArgumentException(“Message must be of type TextMessage”);




RowSet is a interface that adds support to the JDBC API for the JavaBeans component model. A rowset, which can be used as a JavaBeans component in a visual Bean development environment, can be created and configured at design time and executed at run time. The RowSet interface provides a set of JavaBeans properties that allow a RowSet instance to be configured to connect to a JDBC data source and read some data from the data source. A group of setter methods (setInt, setBytes, setString, and so on) provide a way to pass input parameters to a rowset’s command property. This command is the SQL query the rowset uses when it gets its data from a relational database, which is generally the case. Rowsets are easy to use since the RowSet interface extends the standard java.sql.ResultSet interface so it has all the methods of ResultSet. There are two clear advantages of using RowSet over ResultSet

  • RowSet makes it possible to use the ResultSet object as a JavaBeans component. As a consequence, a result set can, for example, be a component in a Swing application.
  • RowSet be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a RowSet object implementation (e.g. JdbcRowSet) with the data of a ResultSet object and then operate on the RowSet object as if it were the ResultSet object.

TreeSet – It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.

  • Servlet is server side component, a servlet is small pluggable extension to the server.
  • Servlets are used to extend the functionality of the java-enabled server.
  • Servlets will be loaded in theAddress space of web server.
  • Servlet can be loaded in 3 ways
    • When the web sever starts.
    • You can set this in the configuration file.
    • Through an administration interface.

It creates new hibernate sessions by referencing immutable and thread safe objects. Application using hibernate are usually allowed and desgined to implement single instance of the class using this interface. Only single instance of a class can be used which is using this interface.

Enumeration and Iterator are the interface available in java.util package. The functionality of Enumeration interface is duplicated by the Iterator interface. New implementations should consider using Iterator in preference to Enumeration. Iterators differ from enumerations in following ways:

  • Enumeration contains 2 methods namely hasMoreElements() & nextElement() whereas Iterator contains three methods namely hasNext(), next(),remove().
  • Iterator adds an optional remove operation, and has shorter method names. Using remove() we can delete the objects but Enumeration interface does not support this feature.
  • Enumeration interface is used by legacy classes. Vector.elements() & Hashtable.elements() method returns Enumeration. Iterator is returned by all Java Collections Framework classes. java.util.Collection.iterator() method returns an instance of Iterator.

Most of the times when you want to do a selective attribute serialization you can use Serializable interface with transient modifier for variables not to be serialized. However, use of Externalizable interface can be really effective in cases when you have to serialize only some dynamically selected attributes of a large object. Lets take an example, Some times when you have a big Java object with hundreds of attributes and you want to serialize only a dozen dynamically selected attributes to keep the state of the object you should use Externalizable interface writeObject method to selectively serialize the chosen attributes. In case you have small objects and you know that most or all attributes are required to be serialized then you should be fine with using Serializable interface and use of transient variable as appropriate.

  • ServletContextInterface defines methods that a servlet can use to communicate to the Container.
  • ServletContext Parameters are specified for entire application and are available for all servlets.
  • ServletContext is also calledapplication object.
  • ServletContext is used to obtain information about environment on which a servlet is running.
  • There is one instance object of the ServletContext interface associated with each Web application deployed into a container.
  • In cases where the container is distributed over many virtual machines, a Web application will have an instance of the ServletContext for each JVM.
  • Servlet Context is a grouping under which related servlets run. They can share data, URL namespace, and other resources. There can be multiple contexts in a single servlet container.
  • The Java Message Service (JMS) models the observer pattern, with its guaranteed delivery, non-local distribution, and persistence, to name a few of its benefits. The JMS publish-subscribe messaging model allows any number of subscribers to listen to topics of interest. When a message for the published topic is produced, all the associated subscribers are notified.
  • The Java Foundation Classes (JFC) like JList, JTree and the JTable components manipulate data through their respective data models. The components act as observers of their data models.
  • In the java.util package, we have the Observerinterface and the Observable class.
  • In an MVC (Model-View-Controller) architecture, the view gets its own data from the model or in some cases the controller may issue a general instruction to the view to render itself. In others, the view acts as an observer and is automatically notified by the model of changes in state that require a screen update.

Session tracking in Servlets is done by using Interface HttpSession. It helps to identify a client throughout many page requests or visiting a website and to store details about that client.

One of the recommended approaches is HTTP session. A request is being identified by the session which is originated from similar browser during the conversation time period. Same session could be shared by all servlets. The JSESSIONID gets generated by server and is passed via cookies to the client, Built in SSL mechanism or URL rewriting (if cookies get off). For minimizing the object’s size stored in session, care shall be taken.

To obtain the session in Java servlet proceed as following:

HttpSession session = request.getSession();

  • If user already has a session  the existing session is returned.
  • If no session exists a new one is created and returned.
  • If you want to know if this is a new session:

call the Session isNew() method.

because JComponent is a subclass of Container, and can contain other components and jcomponents. How can I implement a thread-safe JSP page? – You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe=”false” % > within your JSP page


An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open: in the case of a “hash collision”, a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent.


This implementation provides constant-time [ Big O Notation is O(1) ] performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the “capacity” of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it’s very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.


The TreeMap implementation provides guaranteed log(n) [ Big O Notation is O(log N) ] time cost for the containsKey, get, put and remove operations.


A linked hash map has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashMap. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashMap, as iteration times for this class are unaffected by capacity.

This represents hibernate session which perform the manipulation on the database entities. Some of the activities performed by session interface are as follows they are managing the persistence state, fetching persisted ones and management of the transaction demarcation.

Java has implementation of BlockingQueue available since Java 1.5. Blocking Queue interface extends collection interface, which provides you power of collections inside a queue. Blocking Queue is a type of Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element. A typical usage example would be based on a producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers. An ArrayBlockingQueue is a implementation of blocking queue with an array used to store the queued objects. The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. ArrayBlockingQueue requires you to specify the capacity of queue at the object construction time itself. Once created, the capacity cannot be increased. This is a classic “bounded buffer” (fixed size buffer), in which a fixed-sized array holds elements inserted by producers and extracted by consumers. Attempts to put an element to a full queue will result in the put operation blocking; attempts to retrieve an element from an empty queue will be blocked.

JSP is mostly used to develop the user interface, It plays are role of View in the MVC Model.

You should use ArrayList over Vector because you should default to non-synchronized access. Vector synchronizes each individual method. That’s almost never what you want to do. Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time) but also slower (why take out a lock repeatedly when once will be enough)? Of course, it also has the overhead of locking even when you don’t need to. It’s a very flawed approach to have synchronized access as default. You can always decorate a collection using Collections.synchronizedList – the fact that Vector combines both the “resized array” collection implementation with the “synchronize every operation” bit is another example of poor design; the decoration approach gives cleaner separation of concerns. Vector also has a few legacy methods around enumeration and element retrieval which are different than the List interface, and developers (especially those who learned Java before 1.2) can tend to use them if they are in the code. Although Enumerations are faster, they don’t check if the collection was modified during iteration, which can cause issues, and given that Vector might be chosen for its syncronization – with the attendant access from multiple threads, this makes it a particularly pernicious problem. Usage of these methods also couples a lot of code to Vector, such that it won’t be easy to replace it with a different List implementation. Despite all above reasons Sun may never officially deprecate Vector class.

Java Collections framework API is a unified architecture for representing and manipulating collections. The API contains Interfaces, Implementations & Algorithm to help java programmer in everyday programming. In nutshell, this API does 6 things at high level

  • Reduces programming efforts. – Increases program speed and quality.
  • Allows interoperability among unrelated APIs.
  • Reduces effort to learn and to use new APIs.
  • Reduces effort to design new APIs.
  • Encourages & Fosters software reuse.

To be specific, There are six collection java interfaces. The most basic interface is Collection. Three interfaces extend Collection: Set, List, and SortedSet. The other two collection interfaces, Map and SortedMap, do not extend Collection, as they represent mappings rather than true collections.

The default Java Serialization mechanism is really useful, however it can have a really bad performance based on your application and business requirements. The serialization process performance heavily depends on the number and size of attributes you are going to serialize for an object. Below are some tips you can use for speeding up the marshaling and un-marshaling of objects during Java serialization process.

  • Mark the unwanted or non Serializable attributes as transient. This is a straight forward benefit since your attributes for serialization are clearly marked and can be easily achieved using Serialzable interface itself.
  • Save only the state of the object, not the derived attributes. Some times we keep the derived attributes as part of the object however serializing them can be costly. Therefore consider calcualting them during de-serialization process.
  • Serialize attributes only with NON-default values. For examples, serializing a int variable with value zero is just going to take extra space however, choosing not to serialize it would save you a lot of performance. This approach can avoid some types of attributes taking unwanted space. This will require use of Externalizable interface since attribute serialization is determined at runtime based on the value of each attribute.
  • Use Externalizable interface and implement the readObject and writeObject methods to dynamically identify the attributes to be serialized. Some times there can be a custom logic used for serialization of various attributes.


  • Loose coupling between Subject and Observer: The subject knows only a list of observers, that implementthe Observer interface, it does no know the concrete implementation of the Observer.
  • Broadcast communication: An eventnotification is broadcast to observers irrespective of the number of Observers


  • If not used carefullythe observer pattern can add unnecessary complexity.
  • The order of Observer notifications is undependable. Simply registering the observers in a particular order will not enforce their order ofnotification. You don’t necessarily know if the first registered listener is notified first or last. If you need to have cascading notifications, where object X must be notified first, followed by object Y, you must introduce an intermediary object to enforce the ordering.
  • The possibility of a memory leak: A reference tothe Observer is maintained by the Subject. Until the Subject releases the reference, the Observer cannot be removed by the garbage collector.

The JdbcRowSet implementation is a wrapper around a ResultSet object that has following advantages over ResultSet

  • This implementation makes it possible to use the ResultSet object as a JavaBeans component. A JdbcRowSet can be used as a JavaBeans component in a visual Bean development environment, can be created and configured at design time and executed at run time.
  • It can be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a JdbcRowSet object with the data of a ResultSet object and then operate on the JdbcRowSet object as if it were the ResultSet object.

CallableStatement Example in Java

The JDBC CallableStatement interface extends PreparedStatement and provides support for output and input/output parameters. The CallableStatement interface also has support for input parameters that is provided by the PreparedStatement interface.

The CallableStatement interface allows the use of SQL statements to call stored procedures. Stored procedures are programs that have a database interface. These programs possess the following:

  • They can have input and output parameters, or parameters that are both input and output.
  • They can have a return value.
  • They have the ability to return multiple ResultSets.

CREATE PROCEDURE GetImmediateManager

@employeeID INT,




SELECT @managerID = ManagerID

FROM HumanResources.Employee

WHERE EmployeeID = @employeeID


Conceptually in JDBC, a stored procedure call is a single call to the database, but the program associated with the stored procedure may process hundreds of database requests. The stored procedure program may also perform a number of other programmatic tasks not typically done with SQL statements.

public static void executeStoredProcedure(

Connection con) {

try {

CallableStatement cstmt = con.prepareCall(“{call dbo.GetImmediateManager(?, ?)}”);

cstmt.setInt(1, 5);

cstmt.registerOutParameter(2, java.sql.Types.INTEGER);


System.out.println(“MANAGER ID: ” + cstmt.getInt(2));


catch (Exception e) {




Get CLOB Object Using JDBC

package com.Javastuff.jdbc;

import java.sql.*;

import java.util.*;


public class GetEmployeeDetails {

public static void main(String s[]) throws Exception {

Driver d= (Driver) ( Class.forName(


Properties p=new Properties ();



Connection con=d.connect(


Statement st=con.createStatement();

ResultSet rs=st.executeQuery( “select profile from empprofiles where empno=”+s[0]);

while ( {

Reader r=rs.getCharacterStream(1);

FileWriter fw=new FileWriter(“ProfileOf”+s[0]+”.doc”);


while (i!=-1){




System.out.println(“Profile retrived”);




How to convert blob to byte array in java

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] buf = new byte[1024];

InputStream in = blob.getBinaryStream();

int n = 0;

while ((>=0)


baos.write(buf, 0, n);



byte[] bytes = baos.toByteArray();

BatchUpdate in JDBC

The JDBC drivers that support JDBC 2.0 and above support batch updates. Batch updates is a option given by the JDBC in which application developers can submit a set of SQL update statements as batch to the database.

The following methods used for creating, executing, and removing a batch of SQL updates:

  • addBatch
  • executeBatch
  • clearBatch

package com.javstuff.jdbc;


import java.sql.*;

import java.util.*;


public class BatchUpdateExample {

public static void main(String s[]) throws Exception {

Driver d= (Driver) ( Class.forName(


Properties p=new Properties ();



Connection con=d.connect(“jdbc:oracle:thin:@mysys:1521:javastuff”,p);

Statement st=con.createStatement();


st.addBatch(“insert into emp(empno,sal,deptno) values(“+s[0]+”,1000,10)”);


st.addBatch(“update emp set sal=2000 where empno=”+s[0]);


st.addBatch(“insert into emp(empno,sal,deptno) values(202,1000,10)”);


st.addBatch(“insert into emp(empno,sal,deptno) values(203,1000,10)”);

try {

int[] counts=st.executeBatch();

System.out.println(“Batch Executed Successfully”);

for (int i=0;i<counts.length;i++){

System.out.println(“Number of records effected by statement”+(i+1)+”: “+counts[i]);



catch(BatchUpdateException e){

System.out.println(“Batch terminated with an abnormal condition”);

int[] counts=e.getUpdateCounts();

System.out.println(“Batch terminated at statement”+ (counts.length+1));

for (int i=0;i<counts.length;i++) {

System.out.println(“Number of records effected by the statement”+ (i+1)+”: “+counts[i]);






Arrays in JDBC

Array, one of the SQL 99 datatypes. offers you the facility to include an ordered list of values within the column. The java.sql.Array interface to store the values of the array types. To store the Array first we need to create a User-Defined-Type Array. this can be done by creating a UDT as array in database.

package com.Javastuff.jdbc;


import java.sql.*;

import java.util.*;

import oracle.sql.*;


public class InsertEmpPassportDetails {

public static void main(String s[]) throws Exception {

Driver d= (Driver) ( Class.forName(


Properties p=new Properties ();



Connection con=d.connect(


PreparedStatement ps=con.prepareStatement(“insert into emppassportDetails values(?,?,?)”);



String s1[]={“v1″,”v2″,”v3″,”v4″,”v5”};

ArrayDescriptor ad=ArrayDescriptor.createDescriptor(“VISA_NOS”,con);

ARRAY a=new ARRAY(ad,con,s1);


int i=ps.executeUpdate();

System.out.println(“Row Inserted, count : “+i);




DatabaseMetaData in JDBC

The DatabaseMetaData class is used to determine the capabilities of a JDBC driver and it database during runtime. If a given method of this interface is not supported by the JDBC driver, the method will either throw an SQLException, or in the case of a method that returns a result set, it may return null. Some of the methods take search patterns as its arguments. The pattern values used can be the SQL wildcard characters % and _. Other search arguments accept an empty set (“”) when the argument is not applicable, or null to drop the argument from the search criteria.

This interface is implemented by driver vendors to let users know the capabilities of a Database Management System (DBMS) in combination with the driver based on JDBC driver that is used with it. Different relational DBMSs often support different features, implement features in different ways, and use different data types. In addition, a driver may implement a feature on top of what the DBMS offers. Information returned by methods in this interface applies to the capabilities of a particular driver and a particular DBMS working together.

The JDBC API enables you to uncover metadata about a database using the DatabaseMetaData interfaces. The DatabaseMetaData interface enables you to obtain information about your database’s attributes and make runtime decisions based around that information.

package com.javastuff.jdbc;

import java.sql.*;

import java.util.*;


public class DataBaseMetaDataExample {

public static void main(String s[]) throws Exception {


Connection con =

DriverManager.getConnection(“jdbc:odbc:javastuff”, “scott”,”tiger”);

DatabaseMetaData db= con.getMetaData();

System.out.println(“Database name : “+db.getDatabaseProductName());

System.out.println(“Database version : “+db.getDatabaseProductVersion());

System.out.println(“\nDriver Name : “+ db.getDriverName());

System.out.println(“Driver Version : “+ db.getDriverVersion());





The HashSet class offers constant-time [ Big O Notation is O(1) ] performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance’s size (the number of elements) plus the “capacity” of the backing HashMap instance (the number of buckets). Thus, it’s very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.


The TreeSet implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).


A linked hash set has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashSet. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashSet, as iteration times for this class are unaffected by capacity.

Though the Map interface is part of collections framework, it does not extend collection interface. This is by design, and the answer to this questions is best described in Sun’s FAQ Page: This was by design. We feel that mappings are not collections and collections are not mappings. Thus, it makes little sense for Map to extend the Collection interface (or vice versa). If a Map is a Collection, what are the elements? The only reasonable answer is “Key-value pairs”, but this provides a very limited (and not particularly useful) Map abstraction. You can’t ask what value a given key maps to, nor can you delete the entry for a given key without knowing what value it maps to. Collection could be made to extend Map, but this raises the question: what are the keys? There’s no really satisfactory answer, and forcing one leads to an unnatural interface. Maps can be viewed as Collections (of keys, values, or pairs), and this fact is reflected in the three “Collection view operations” on Maps (keySet, entrySet, and values). While it is, in principle, possible to view a List as a Map mapping indices to elements, this has the nasty property that deleting an element from the List changes the Key associated with every element before the deleted element. That’s why we don’t have a map view operation on Lists.

Toggle Content

The Logical division of data is called Input Split and physical division of data is called HDFS Block

We use panels in bootstrap from the boxing of DOM components.

The TaskTracker periodically sends heartbeat messages to the JobTracker to assure that it is alive. This messages also inform the JobTracker about the number of available slots. This return message updates JobTracker to know about where to schedule task.

Heartbeat is a signal which is used between a data node and name node, and between task tracker and job tracker. If the name node or job tracker doesn’t respond to the signal then it is considered that there is some issue with data node or task tracker.

In Hadoop, SequenceFileInputFormat is used to read files in sequence. It is a specific compressed binary file format which passes data between the output of one MapReduce job to the input of some other MapReduce job.

Following are the network requirement for using Hadoop:

  • Password-less SSH connection.
  • Secure Shell (SSH) for launching server processes

Hadoop is a distributed computing platform. It is written in Java. It consists of the features like Google File System and MapReduce.

These are the main tasks of JobTracker:

  • To accept jobs from the client.
  • To communicate with the NameNode to determine the location of the data.
  • To locate TaskTracker Nodes with available slots.
  • To submit the work to the chosen TaskTracker node and monitors the progress of each task.

TaskTracker is a node in the cluster that accepts tasks like MapReduce and Shuffle operations from a JobTracker.

HDFS data blocks are distributed across local drives of all machines in a cluster whereas, NAS data is stored on dedicated hardware.

Button groups are used for the placement of more than one buttons in the same line.

An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.

Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

Vector & ArrayList both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. ArrayList and Vector class both implement the List interface.

  • Synchronization – ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.
  • Data growth – Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

All standard implementations of collections List, Set and Map interface already implement All the commonly used collection classes like java.util.ArrayList, java.util.Vector, java.util.Hashmap, java.util.Hashtable, java.util.HashSet, java.util.TreeSet do implement Serializable. This means you do not really need to write anything specific to serialize collection objects. However you should keep following things in mind before you serialize a collection object – Make sure all the objects added in collection are Serializable. – Serializing the collection can be costly therefore make sure you serialize only required data isntead of serializing the whole collection. – In case you are using a custom implementation of Collection interface then you may need to implement serialization for it.

the JDBC API has 3 Interfaces, (1. Statement, 2. PreparedStatement, 3. CallableStatement ). The key features of these are as follows: Statement

  • This interface is used for executing a static SQL statement and returning the results it produces.
  • The object of Statement class can be created using Connection.createStatement() method.
  • PreparedStatement
  • A SQL statement is pre-compiled and stored in a PreparedStatement object.
  • This object can then be used to efficiently execute this statement multiple times.
  • The object of PreparedStatement class can be created using Connection.prepareStatement() method. This extends Statement interface.
  • CallableStatement
  • This interface is used to execute SQL stored procedures.
  • This extends PreparedStatement interface.
  • The object of CallableStatement class can be created using Connection.prepareCall() method.

Statement: to be used createStatement() method for executing single SQL statement

PreparedStatement: To be used preparedStatement() method for executing same SQL statement over and over.

CallableStatement: To be used prepareCall() method for multiple SQL statements over and over.

The configuration files hibernate.cfg.xml (or and mapping files *.hbm.xml are used by the Configuration class to create (i.e. configure and bootstraphibernate) the SessionFactory, which in turn creates the Session instances. Session instances are the primary interface for the persistence service.hibernate.cfg.xml (alternatively can use These two files are used to configure the hibernate sevice (connection driver class, connection URL,connection username, connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml file overrides the settings found in the file.Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best practice to store each object in an individual mapping file (i.e mapping file per class) because storing large number of persistent classes into one mapping file can be difficult to manage and maintain. The naming convention is to use the same name as the persistent (POJO) class name.

For example Account.class will have a mapping file named Account.hbm.xml. Alternatively, hibernate annotations can be used as part of your persistent class code instead of the *.hbm.xml files.

Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below:

  • request :It represents the request made by the client. The request implicit object is generally used to get request parameters, request attributes, header information and query string values.
  • response :The JSP implicit response object is an instance of a java class that implements the javax.servlet.http.HttpServletResponse interface. It represents the response to be given to the client. The response implicit object is generally used to set the response content type, add cookie and redirect the response.
  • pageContext : This is used to access page attributes and also to access all the namespaces associated with a JSP page. The lass or the interface name of the object PageContext is jsp.pageContext. The object PageContext is written: Javax.servlet.jsp.pagecontext The PageContext object has a page scope. It is an instance of the javax.servlet.jsp.PageContext class.
  • session :The session object has a scope of an entire HttpSession. It is an instance of the javax.servlet.http.HttpSession class. It represents the session created for the requesting client, and stores objects between client’s requests. The session object views and manipulates session information, such as the session identifier, creation time, and last accessed time. It also binds objects to a session, so that the user information may persist across multiple user connections.
  • application :The application object has an application scope. It is an instance of the javax.servlet.ServletContext class. It represents the context within which the JSP is executing. It defines a set of methods that a servlet uses to communicate with its servlet container.
  • out :The JSP implicit out object is an instance of the javax.servlet.jsp.JspWriter class. It represents the output content to be sent to the client. The out implicit object is used to write the output content.
  • config :The JSP implicit config object is an instance of the java class that implements javax.servlet.ServletConfig interface. It gives facility for a JSP page to obtain the initialization parameters available.
  • page :The Page object denotes the JSP page, used for calling any instance of a Page’s servlet. The class or the interface name of the Page object is jsp.HttpJspPage. The Page object is written: Java.lang.Object.
  • exception :The JSP implicit exception object is an instance of the java.lang.Throwable class. It is available in JSP error pages only. It represents the occured exception that caused the control to pass to the JSP error page.

Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. This Map permits null value

The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn’t. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects. So Enumeration is used when ever we want to make Collection objects as Read-only.

import java.util.ArrayList;

import java.util.LinkedHashSet;

import java.util.List;


public class CollectionFunction {

    public <e> List<e> function (List <e> list) {

          return new ArrayList<e>(new LinkedHashSet<e>(list));



The above code removes duplicates from a supplied list by passing it through an implementation of a Set interface. In this case, a LinkedHashSet is used to honor the ordering by implementing a SortedSet interface. If ordering is not required, the LinkedHashSet can be replaced with a HashSet.

Serialization is a mechanism by which you can save or transfer the state of an object by converting it to a byte stream. This can be done in java by implementing Serialiazable interface. Serializable is defined as a marker interface which needs to be implemented for transferring an object over a network or persistence of its state to a file. Since its a marker interface, it does not contain any methods. Implementation of this interface enables the conversion of object into byte stream and thus can be transferred. The object conversion is done by the JVM using its default serialization mechanism.

Servlets are not thread safe. If you want to make it Servlet as Thread safe, you can implement SingleThreadInterface.

There are two different ways of making a servlet thread safe namely

  • By implementing SingleThreadModel:
    • By implementing a SingleThreadModel it will be possible to create a Thread safe servlet.There can only be one user at a given point of time.
  • Synchornize the part of sensitive code:

We can allow a single user at a given point of time by making that part of the code which is sensitive as synchronized


Performance of get and remove methods is linear time [ Big O Notation is O(n) ] – Performance of add and Iterator.remove methods is constant-time [ Big O Notation is O(1) ]


The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. [ Big O Notation is O(1) ] – The add operation runs in amortized constant time [ Big O Notation is O(1) ] , but in worst case (since the array must be resized and copied) adding n elements requires linear time [ Big O Notation is O(n) ] – Performance of remove method is linear time [ Big O Notation is O(n) ] – All of the other operations run in linear time [ Big O Notation is O(n) ]. The constant factor is low compared to that for the LinkedList implementation.

Vector, ArrayList, LinkedList

ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to make room for the new element.

The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.

An interface type can only be converted to an interface type or to object. If the

new type is an interface, it must be a superinterface of the old type.

A class type can be converted to a class type or to an interface type. If converting to a

class type the new type should be superclass of the old type. If converting to an

interface type new type the old class must implement the interface.

An array maybe converted to class object, to the interface cloneable, or to an array.

Only an array of object references types may be converted to an array, and the old

element type must be convertible to the new element

  • Request parameters are the result of submitting an HTTP request with a query string that specifies the name/value pairs, or of submitting an HTML form that specifies the name/value pairs. The name and the values are always strings. For example, when you do a post from html, data can be automatically retrieved by using getParameter(). Parameters are Strings, and generally can be retrieved, but not set.
  • Let’s take a real example, you have one html page named htmland JSP page named Register.jsp. The RegisterForm.html contains a form with few parameters for user registration on web application and those parameters you want to store in database.



<form name=”regform” method=”post” action=”../Register.jsp”>

<table ID=”Table1″>



First Name : <input type=”text” name=”FIRSTNAME” size=”25″ value=””>





<input type=”Submit” NAME=”Submit” value=”Submit” >







When user will enter first name in the text filed and press submit button, it will callRegister.jsp page. Now you want the value entered in text field by user in jsp/servlet so there you use request.getParameter() method.


String lFirstName = request.getParameter(“FIRSTNAME”);



On the server side, the request.getParameter() will retrieve a value that the client has submitted in the First Name text field. Using this method you can retrive only one value. This method i.e. getParameter method is in ServletRequest interface which is part of javax.servlet package.

Request attributes (more correctly called “request-scoped variables”) are objects of any type that are explicitly placed on the request object via a call to the setAttribute() method. They are retrieved in Java code via the getAttribute() method and in JSP pages with Expression Language references. Always use request.getAttribute() to get an object added to the request scope on the serverside i.e. using request.setAttribute().

Attributes are objects, and can be placed in the request, session, or context objects. Because they can be any object, not just a String, they are much more flexible. You can also set attributes programaticly and retrieve them later. This is very useful in the MVC pattern. For example, you want to take values from database in one jsp/servlet and display them in another jsp. Now you have resultset filled with data ready in servlet then you use setAttributemethod and send this resultset to another jsp where it can be extracted by using getAttributemethod.

Once a servlet gets a request, it can add additional attributes, then forward the request off to another servlet for processing. Attributes allow servlets to communicate with one another.

The Runnable interface is preferred, as it does not require your object to inherit a thread because when you need multiple inheritance, only interfaces can help you. In the above example we had to extend the Base class so implementing Runnable interface is an obvious choice.

Also note how the threads are started in each of the different cases as shown inthe code sample. In an OO approach you should only extend a class when you want to make it different from it’s superclass, and change it’s behavior.

By implementing a Runnable interface instead of extending the Thread class, you are telling to the user that the class Counter is an object of type Base and will run as a thread.

There are three types of dependency injection:

  • Constructor Injection(e.g. Spring): Dependencies are provided as constructor parameters.
  • Setter Injection(e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
  • Interface Injection(e.g. Avalon): Injection is done through an interface.

There are a number of high level conceptual architectures as discussed below. These individual architectures can be mixed and matched to produce hybrid architectures.

Model-View-Controller Architecture

Most web and stand-alone GUI applications follow this pattern. For example, Struts and Spring MVC frameworks and Swing GUI.


  • The model represents the core business logic and state.
  • The view renders the content of the model state by adding display logic.
  • The controller translates the interaction with the view into action to be performed by the model.

The actions performed by a model include executing the business logic  and changing the state of the model.Based on the user interactions, the controller selects an appropriate view to render.The controller decouples the model from the view.

Service Oriented Architecture (SOA)

The business logic and application state are exposed as reusable services.

An Enterprise Service Bus (ESB) is used as an orchestration and mediation layer to decouple the applications from the services.


The above architecture has 5 tiers. The application tier could be using a typical MVC architecture.

  • The service orchestration tier could be using ESB products like OracleService Bus, TIBCO, etc and BPM products like Lombardi BPM, Pega BPM, etc.
  • In the abovediagram, the ESB integrates with the BPM via messaging queues.
  • The service tier consists of individual services that can be accessed through SOAP or RESTful web services.
  • The SOA implementation requires change agents to drive adoption of new approaches.
  • The BPM,application integration, and real-time information all contribute to dynamically changing how business users do their jobs.

So, it needs full support from the business, requiring  restructuring and also it can take some time to realize the benefits of SOA. Cloud computing is at the leading edge of its hype and as a concept compliments SOA as an architectural style. Cloud computing is expected to provide a computing capability that can scale up (to massive proportions) or scale down dynamically based on demand. This implies a very large pool of computing resources either be within the enterprise intranet or on the Internet (i.e on the cloud).

User Interface (UI) Component Architecture

This architecture is driven by a user interface that is made up of a number of discrete components.Each component calls a service that encapsulates business logic and hides lower level details. Components can be combined to form new composite components allowing richer functionality. These components can also be shared across a number ofapplications.

For example, JavaScript widgets, Java Server Faces (JSF) components, etc.


RESTful data composition Architecture

The user interface can be built by calling a number of underlying services that are each responsible for building part of a page.


The user interface translates and combine the data in different formats like XML(translate to HTML using XSLT), JSON (Java Script Object Notation), ATOM (feed for mail messages and calendar applications), RSS (for generating RSS feeds), etc.

HTML composition Architecture

In this architecture, multiple applications output fragments of HTML that are combined to generate the final user interface.


For example, Java portlets used inside a portal application server to aggregate individual content..

Plug-in Architecture

In this architecture, a core application defines an interface, and the functionality will be implemented as a set of plug-ins that conform to that interface.


For example, the the Eclipse RCP framework, Maven build tool, etc use this architecture.

Event Driven Architecture (EDA)

The EDA pattern decouples the interactions between the event publishers and the event consumers. Many to many communications are achieved via a topic, where one specific event can be consumed by many subscribers. The EDA also supports asynchronous operations and acknowledgments through event messaging.

This architecture requires effective monitoring in place to track queue depth, exceptions, and other possible problems. The traceability, isolation, and debugging of an event can be difficult in some cases. This architecture is useful in scenarios where the business process is inherently asynchronous, multiple consumers are interested in an event(e.g. order status has changed to partially-filled ), no immediate acknowledgment is required (e.g. an email is sent with the booking details and itinerary), and real-time request/response is not required (e.g. a long running report can be generated asynchronously and made available later via online or via email).




Most conceptual architectures use a hybrid approach using a combination of different architectures based on the benefits of each approach and its pertinence to your situation. Here is a sample hybrid approach depicting an online trading system.




FIX is a Financial Information eXchange protocol. You could also notice a number of synchronous calls using XML/HTTP or SOAP/HTTP and asynchronous calls using JMS. The above diagram also depicts that an enterprise architecture can be complex with a number of moving parts. So, it is imperative that all these moving parts are properly monitored and tested for any potential performance issues. Most of these services will be running as a cluster or a load balanced service with either active/active or active.passive configuration for high availability and scalability.

Earlier versions of Java had no mechanism to handle/detect deadlock. Since JDK 1.5 there are some powerful methods added in the package to diagnose and detect deadlocks. The interface is management interface for the thread system of the Java virtual machine. It has two methods which can leveraged to detect deadlock in a Java application.

  • findMonitorDeadlockedThreads() – This method can be used to detect cycles of threads that are in deadlock waiting to acquire object monitors. It returns an array of thread IDs that are deadlocked waiting on monitor.
  • findDeadlockedThreads() – It returns an array of thread IDs that are deadlocked waiting on monitor or ownable synchronizers.

The traditional middle-wares tightly couple connections to the applications and it can break if you make any modification to your application. Tightly coupled applications are hard to maintain and less reusable. Generally do not support heterogeneity. Do not work across Internet. Can be more expensive and hard to use.

Web Services support loosely coupled connections. The interface of the Web service provides a layer of abstraction between the client and the server. The loosely coupled applications reduce the cost of maintenance and increases re-usability. Web Services present a new form of middle-ware based on XML and Web. Web services are language andplatform independent. You can develop a Web service using any language and deploy it on to any platform, from small device to the largest supercomputer. Web service uses language neutral protocols such as HTTP and communicates between disparate applications by passing XML messages to each other via a Web API. Do work across internet, less expensive and easier to use.

A Java thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is more advantageous, when you are going for multiple inheritance.

Dependency Inversion Principle (DIP) is a design principle which is in some ways related to the Dependency Injection (DI) pattern. The idea of DIP is that higher layers of your application should not directly depend on lower layers. Dependency Inversion Principle does not imply Dependency Injection. This principle doesn’t say anything about how higher la yers know what lower layer to use. This could be done as shown below by coding to interface using a factory pattern or through Dependency Injection by using an IoC container like Spring framework, Pico container, Guice, or Apache HiveMind.


The Dependency Inversion Principle (DIP) states that High level modules should not depend upon low level modules. Both should depend upon abstractions.Abstractions should not depend upon details. Details should depend upon abstractions.When this principle is applied, the higher level classes will not be working directly with the lower level classes, but with anabstract layer. This gives us the flexibility at the cost of increased effort.Here are some code snippets for DIP.

Firstly define the abstraction layer.

package principle_dip2;


public interface AnimalHandler {

public abstract void handle( );


package principle_dip2;


public interface AnimalHelper {

public abstract void help( );


Now the implementation that depends on the abstraction as opposed to the implementation.

package principle_dip2;


public class CircusService {

AnimalHandler handler;

public void setHandler(AnimalHandler handler) {

this.handler = handler;



public void showStarts( ) {

//code omitted for brevity

handler.handle( );



package principle_dip2;

public class TigerHandler implements AnimalHandler{

AnimalHelper helper;

public void setHelper(AnimalHelper helper) {

this.helper = helper;



public void handle( ){

//… );




package principle_dip2;

public class TigerHelper implements AnimalHelper{


public void help( ){




Dependency Injection (DI) is a pattern of injecting a class’s dependencies into it at runtime. This is achieved by defining the dependencies as interfaces, and then injecting in a concrete class implementing that interface to the constructor. This allows you to swap in different implementations without having to modify the main class. The Dependency Injection pattern also promotes high cohesion by promoting the  Single Responsibility Principle (SRP), since your dependencies are individual objects which perform discrete specialized tasks like data access (via DAOs) and business services (via Service and Delegate classes).

The Inversion of Control Container (IoC) is a container that supports Dependency Injection. In this you use a central container  like Spring framework, Guice, or HiveMind, which defines what concrete classes should be used for what dependencies throughout your application. This brings in an added flexibility through looser coupling, and it makes it much easier to change what dependencies are used on the fly. The basic concept of the Inversion of Control pattern is that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up. Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

The real power of DI and IoC is realized  in its ability to replace the compile time binding of the relationships between classes with  binding those relationships at runtime. For example, in Seam framework, you can have a real and mock implementation of an interface, and at runtime decide which one to use based on a property, presence of another file, or some precedence values. This is incredibly useful if you think you may need to modify the way your application behaves in different scenarios. Another real benefit of DI and IoC is that it makes your code easier to unit test. There are other benefits like promoting looser coupling without any proliferation of factory and singleton design patterns, follows a consistent approach for lesser experienced developers to follow, etc. These benefits can come in at the cost of the added complexity to your application and has to be carefully manged by using them only at the right places where the real benefits are realized, and not just using them because many others are using them.

Note: The CDI (Contexts and Dependency Injection)  is an attempt at describing a true standard on Dependency Injection. CDI is a part of the Java EE 6 stack, meaning an application running in a Java EE 6 compatible container can leverage CDI out-of-the-box. Weld is the reference implementation of CDI.

Spring has a layered architecture with over 20 modules to choose from. This means, use what you need and leave what you don’t need now. Spring simplifies JEE through POJO programming. There is no behind the scene magic in Spring as in JEE programming. POJO programming enables continuous integration and testability.


Spring framework’s core functionality is dependency injection (DI). Dependency injection promotes easy unit testing and more maintainable and flexible code. DI code is much easier to test. The functionality expressed by the object can be tested in a black box by building ‘mock’ objects implementing the interfaces expected by yourapplication logic. DI code is much easier to reuse as the ‘depended’ functionality is extrapolated into well defined interfaces, allowing separate objects whose configuration is handled by a suitable application platform to be plugged into other objects at will. DI code is more flexible. It is innately loosely coupled code to an extreme. This allows the programmer to pick and choose how objects are connected based exclusively on their required interfaces on one end and their expressed interfaces on the other.

Spring supports Aspect Oriented Programming (AOP), which enables cohesive development by separatingapplication business logic from system services. Supporting functionalities like auditing, gathering performance and memory metrics, etc can be enabled through AOP.

Spring also provides a lot of templates which act as base classes to make using the JEE standard technologies a breeze to work with. For example, the JdbcTemplate works well with JDBC, the JpaTemplate does good things with JPA, JmsTemplate makes JMS pretty straightforward. The RestTemplate is simply awesome in it’s simplicity. Simplicity means more readable and maintainable code.When writing software these days, it is important to try and decouple as much middleware code from your business logic as possible. The best approach when using remoting is to use Spring Remoting which can then use any messaging or remoting technology under the covers. Apache Camel is a powerful open source integration framework based on known Enterprise Integration Patterns with powerful Bean Integration. Apache Camel is designed to work nicely with the Spring Framework in a number of ways.

It also provides declarative transactions, job scheduling, authentication, a fully-fledged MVC webframework, and integration to other frameworks likeHibernate,iBatis,JasperReports,JSF,Struts,Tapestry,Seam, Quartz job scheduler, etc.

Spring beans can be shared between different JVMs using Terracotta. This allows you to take existing beans and spread them across a cluster, turn Spring application context events into distributed events, export clustered beans via Spring JMX, and make your Spring applications highly available and clustered. Spring also integrate well with other clustering solutions like Oracle’s Coherance.Spring favors unchecked exceptions and eliminates unsightly try, catch, and finally (and some times try/catch within finally itself) blocks. The Spring templates like JpaTemplate takes care of closing or releasing a database connection. This prevents any potential resource leaks and promotes more readable code.It prevents the proliferation of factory and singleton pattern classes that need to be created to promote loose coupling if not for using a DI framework like Spring or Guice.

Threads can be used by either:

  • Extending the Thread class.
  • Implementing the Runnable interface.

Using the Executor framework (this creates a thread pool)


By extends:

class Counter extends Thread {


//method where the thread execution will start

public void run(){

//logic to execute in a thread



//let’s see how to start the threads

public static void main(String[] args){

Thread t1 = new Counter();

Thread t2 = new Counter();

t1.start();  //start the first thread. This calls the run() method.

t2.start(); //this starts the 2nd thread. This calls the run() method.



By implements:

class Counter extends Base implements Runnable{


//method where the thread execution will start

public void run(){

//logic to execute in a thread



//let us see how to start the threads

public static void main(String[] args){

Thread t1 = new Thread(new Counter());

Thread t2 = new Thread(new Counter());

t1.start();  //start the first thread. This calls the run() method.

t2.start();  //this starts the 2nd thread. This calls the run() method.



The thread pool is more efficient and  learn why and how to create pool of  threads using the executor framework.

We need run() & start() method both because JVM needs to create a separate thread which can not be differentiated from a normal method call. So this job is done by start method native implementation which has to be explicitly called. Another advantage of having these two methods is we can have any object run as a thread if it implements Runnable interface. This is to avoid Java’s multiple inheritance problems which will make it difficult to inherit another class with Thread.

The core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.

  • Session interface
  • SessionFactory interface
  • Transaction interface
  • Query and Criteria interfaces