Interface Java Interview Questions – Set 07

What is a Session? Can you share a session object between different threads

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

local.set(session);

}

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.

Difference Between Servlets And JSP

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.

What are the rules for Object reference casting

: 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

Newtype

– 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

What is Metadata and why should I use it

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);

Where will you use ArrayList and Where will you use LinkedList? Or Which one to use when (ArrayList LinkedList)

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

Difference between Vector and ArrayList? What is the Vector class

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.

Explain about Java Collections API

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

What changes are compatible and incompatible to the mechanism of java Serialization

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

Explain about ServletConfig Interface

  • 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.

<web-app>

<servlet>

<servlet-name>TestServlet</servlet-name>

<servlet-class>TestServlet</servlet-class>

<init-param>

<param-name>driverclassname</param-name>

<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>

</init-param>

<init-param>

<param-name>dburl</param-name>

<param-value>jdbc:odbc:MySQLODBC</param-value>

</init-param>

</servlet>

</web-app>

publicvoidinit()

{

ServletConfig config = getServletConfig();

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

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

Class.forName(driverClassName);

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

}

What is the Difference between Externalizable and Serializable Interfaces?

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.