Interface Java Interview Questions – Set 08

What is an observer design pattern

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.

Examples:

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

@Override

public void addHandler(ReportHandler rh) {

reportHandlers.add(rh);

}

@Override

public void processReport(String message) {

for (ReportHandler reportHandler : reportHandlers) {

reportHandler.handleMessage(message);

}

}

@Override

public void removeHandler(ReportHandler rh) {

reportHandlers.remove(rh);

}

}

The concrete observers

package com;

public class LoggingReportHandler implements ReportHandler {

@Override

public void handleMessage(String message) {

//handles report by formatting and printing

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

}

}

package com;

public class EmailReportHandler implements ReportHandler {

@Override

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

executor.processReport(message.toString());

} else {

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

}

}

}

What is RowSet? or What is the difference between RowSet and ResultSet? or Why do we need RowSet? or What are the advantages of using RowSet over ResultSet

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.

What is TreeSet

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.

What is a servlet

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

Brief about the Session factory 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.

What is the Difference between Enumeration and Iterator 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.

When will you use Serializable or Externalizable interface? and why

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.

What is ServletContext

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

Can you list some Java interfaces that use the observerdesign pattern

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

What is HTTP session in servlets

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.