Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

51.

When We Don't Write Any Constructor For The Servlet, How Does Container Create An Instance Of Servlet?

Answer»

CONTAINER CREATES instance of SERVLET by CALLING Class.forName(CLASSNAME).newInstance().

Container creates instance of servlet by calling Class.forName(className).newInstance().

52.

Why Don't We Write A Constructor In A Servlet?

Answer»

CONTAINER WRITES a no ARGUMENT CONSTRUCTOR for our SERVLET.

Container writes a no argument constructor for our servlet.

53.

When Is The Servlet Instance Created In The Life Cycle Of Servlet? What Is The Importance Of Configuring A Servlet?

Answer»

An instance of servlet is created when the servlet is LOADED for the first TIME in the container. Init() method is USED to configure this servlet instance. This method is called only once in the life time of a servlet, hence it makes sense to write all those configuration DETAILS about a servlet which are required for the whole life of a servlet in this method.

An instance of servlet is created when the servlet is loaded for the first time in the container. Init() method is used to configure this servlet instance. This method is called only once in the life time of a servlet, hence it makes sense to write all those configuration details about a servlet which are required for the whole life of a servlet in this method.

54.

Explain The Life Cycle Of Servlet?

Answer»

Loaded(by the CONTAINER for first request or on start up if config FILE suggests load-on-startup), INITIALIZED( using init()), SERVICE(service() or doGet() or DOPOST()..), destroy(destroy()) and unloaded.

Loaded(by the container for first request or on start up if config file suggests load-on-startup), initialized( using init()), service(service() or doGet() or doPost()..), destroy(destroy()) and unloaded.

55.

Which Interface Must Be Implemented By All Servlets?

Answer»

SERVLET INTERFACE.

Servlet interface.

56.

What Is Servlet Context ?

Answer»

The servlet context is an object that contains a servlet's view of the Web APPLICATION WITHIN which the servlet is running. Using the context, a servlet can LOG events, obtain URL REFERENCES to resources, and set and store attributes that other servlets in the context can use.

The servlet context is an object that contains a servlet's view of the Web application within which the servlet is running. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use.

57.

What Is Servlet Mapping?

Answer»

The servlet mapping DEFINES an association between a URL pattern and a servlet. The mapping is used to MAP requests to servlets.

The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets.

58.

What Is Session?

Answer»

The SESSION is an object used by a servlet to track a user's INTERACTION with a Web application ACROSS MULTIPLE HTTP REQUESTS.

The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests.

59.

Difference Between Get And Post ?

Answer»

In GET your entire form submission can be encapsulated in ONE URL, LIKE a hyperlink. QUERY length is limited to 260 characters, not secure, faster, quick and easy.

In POST Your name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size LIMITATIONS on the form's output. It is used to send a chunk of data to the server to be processed, more versatile, most secure.

In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 260 characters, not secure, faster, quick and easy.

In POST Your name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the form's output. It is used to send a chunk of data to the server to be processed, more versatile, most secure.

60.

What Mechanisms Are Used By A Servlet Container To Maintain Session Information?

Answer»

COOKIES, URL rewriting, and HTTPS protocol information are USED to maintain session information.

Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information.

61.

How Can A Servlet Refresh Automatically If Some New Data Has Entered The Database?

Answer»

You can USE a client-side REFRESH or SERVER PUSH.

You can use a client-side Refresh or Server Push.

62.

Can We Use The Constructor, Instead Of Init(), To Initialize Servlet?

Answer»

Yes , of course you can use the CONSTRUCTOR instead of init(). There's nothing to stop you. But you shouldn't. The original reason for init() was that ancient versions of JAVA couldn't dynamically invoke CONSTRUCTORS with arguments, so there was no way to give the constructur a ServletConfig. That no LONGER applies, but servlet containers still will only call your no-arg constructor. So you won't have access to a ServletConfig or Servlet CONTEXT.

Yes , of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't. The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won't have access to a ServletConfig or Servlet Context.

63.

How Can I Send User Authentication Information While Making Url Connection?

Answer»

You'll want to USE HttpURLConnection.setRequestProperty and SET all the APPROPRIATE headers to HTTP AUTHORIZATION.

You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.

64.

Request Parameter How To Find Whether A Parameter Exists In The Request Object?

Answer»
  1. boolean hasFoo = !(request.getParameter("FOO") == NULL || request.getParameter("foo").EQUALS(""));
  2. boolean hasParameter = request.getParameterMap().contains(theParameter); (which WORKS in Servlet 2.3+)

65.

What Is New In Servletrequest Interface ? (servlet 2.4)

Answer»

The following METHODS have been ADDED to SERVLETREQUEST 2.4 VERSION:

public INT getRemotePort()
public java.lang.String getLocalName()
public java.lang.String getLocalAddr()
public int getLocalPort()

The following methods have been added to ServletRequest 2.4 version:

66.

When Using Servlets To Build The Html, You Build A Doctype Line, Why Do You Do That?

Answer»

I know all major browsers ignore it EVEN though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE LINE tells HTML VALIDATORS which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you CATCH HTML syntax errors.

I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE line tells HTML validators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors.

67.

What Is Filter? Can Filter Be Used As Request Or Response?

Answer»

A FILTER is a reusable piece of code that can transform the content of HTTP requests,responses, and header information. Filters do not generally create a RESPONSE or respond to a request as servlets do, RATHER they MODIFY or adapt the requests for a resource, and modify or adapt responses from a resource.

A filter is a reusable piece of code that can transform the content of HTTP requests,responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource.

68.

Given The Request Path Below, Which Are Context Path, Servlet Path And Path Info?

Answer»

/bookstore/EDUCATION/index.html

context path: /bookstore
SERVLET path: /education
path INFO: /index.html

/bookstore/education/index.html

context path: /bookstore
servlet path: /education
path info: /index.html

69.

If A Servlet Is Not Properly Initialized, What Exception May Be Thrown?

Answer»

During initialization or SERVICE of a REQUEST, the servlet INSTANCE can throw an UnavailableException or a ServletException.

During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException.

70.

When A Client Request Is Sent To The Servlet Container, How Does The Container Choose Which Servlet To Invoke?

Answer»

The SERVLET container determines which servlet to invoke BASED on the CONFIGURATION of its servlets, and CALLS it with objects REPRESENTING the request and response.

The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response.

71.

What Is Servlet Container?

Answer»

The servlet CONTAINER is a part of a Web server or application server that provides the network services over which requests and RESPONSES are sent, DECODES MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages SERVLETS through their lifecycle.

The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle.

72.

Why Is Servlet So Popular?

Answer»

Because SERVLETS are platform-independent Java CLASSES that are COMPILED to platform-neutral byte code that can be loaded DYNAMICALLY into and RUN by a Java technology-enabled Web server.

Because servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.

73.

What Is Servlet?

Answer»

A servlet is a JAVA technology-based Web component, MANAGED by a container called servlet container or servlet engine, that GENERATES DYNAMIC content and interacts with web CLIENTS via a request\/response paradigm.

 

A servlet is a Java technology-based Web component, managed by a container called servlet container or servlet engine, that generates dynamic content and interacts with web clients via a request\/response paradigm.

 

74.

Explain The Concepts Of Tomcat Servlet Container?

Answer»
  • A servlet container is a specialized web server that supports servlet EXECUTION.
  • It combines the basic functionality of a web server with certain Java/servlet specific optimizations and extensions (such as an integrated Java runtime environment, and the ability to automatically translate specific URLs into servlet REQUESTS).
  • Individual servlets are registered with a servlet container, PROVIDING the container with information such as the functionality, the URL used for IDENTIFICATION.
  • The servlet container then initializes the servlet as necessary and delivers requests to the servlet as they arrive.
  • Many containers can dynamically add and remove servlets from the system, allowing new servlets to quickly be deployed or removed without affecting other servlets running from the same container.
  • Servlet containers are also referred to as web containers or web engines.

75.

What Is Jasper?

Answer»
  • JASPER is TOMCAT's JSP Engine. Tomcat 5.x uses Jasper 2, which is an implementation of the Sun Microsystems's JavaServer Pages 2.0 SPECIFICATION.
  • Jasper parses JSP files to compile them into Java code as servlets (that can be handled by Catalina).
  • At RUNTIME, Jasper is able to automatically detect JSP file changes and recompile them.

76.

What's The Difference Between Type_scroll_insensitive , And Type_scroll_sensitive

Answer»

You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the TWO has to do with WHETHER a result SET reflects changes that are made to it while it is OPEN and whether CERTAIN methods can be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopened:

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet .CONCUR_ READ_ ONLY);
ResultSet srs = stmt.executeQuery("SELECT NAME, SALARY FROM PERSON"); srs.afterLast();
while (srs.previous())
{
String name = srs.getString("NAME");
float salary = srs.getFloat("SALARY");
System.out.println(name + " " + salary);
}

You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopened:

77.

What Are The Components Of Jdbc

Answer»

JDBC COMPONENTS-

JDBC Components-

78.

How Do You Load The Drivers?

Answer»

Class.forName() method is USED in JDBC to load the JDBC DRIVERS DYNAMICALLY.

Class.forName() method is used in JDBC to load the JDBC drivers dynamically.

79.

How Do You Establish A Connection?

Answer»

Answer : LOADING Drivers
Class.forName("DRIVER");
Getting connection
Connection CON = DriverManager.getConnection(URL, "myLogin", "myPassword");

80.

What Are Different Types Of Statements In Jdbc?

Answer»

java.sql.Statement - Top most interface which provides basic methods useful for executing SELECT, INSERT, UPDATE and DELETE SQL STATEMENTS.

java.sql.PreparedStatement - An ENHANCED verion of java.sql.Statement which allows precompiled queries with parameters. It is more efficient to use java.sql.PreparedStatement if you have to specify parameters to your SQL queries.

java.sql.CallableStatement - Allows you to execute stored procedures within a RDBMS which supports stored procedures (MySQL doesn't support stored procedures at the MOMENT).

java.sql.Statement - Top most interface which provides basic methods useful for executing SELECT, INSERT, UPDATE and DELETE SQL statements.

java.sql.PreparedStatement - An enhanced verion of java.sql.Statement which allows precompiled queries with parameters. It is more efficient to use java.sql.PreparedStatement if you have to specify parameters to your SQL queries.

java.sql.CallableStatement - Allows you to execute stored procedures within a RDBMS which supports stored procedures (MySQL doesn't support stored procedures at the moment).

81.

When Do We Used Prepared Statements?

Answer»

If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead.

The main feature of a PreparedStatement object is that, unlike a Statement object, it is GIVEN an SQL statement when it is created. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object CONTAINS not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just RUN the PreparedStatement 's SQL statement WITHOUT having to compile it first.

Although PreparedStatement objects can be used for SQL statements with no parameters, you will probably use them most often for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it. You will see an example of this in the following sections.

If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead.

The main feature of a PreparedStatement object is that, unlike a Statement object, it is given an SQL statement when it is created. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's SQL statement without having to compile it first.

Although PreparedStatement objects can be used for SQL statements with no parameters, you will probably use them most often for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it. You will see an example of this in the following sections.

82.

How Do You Create Jdbc Statements?

Answer»

Answer : Connection CON = null;
STATEMENT st = null;
// OBTAIN connection here
st = con.createStatement();
ResultSet rs = null;
rs = st.executeQuery("SELECT * FROM USERS");
int recordsUpdated;
recordsUpdated = st.executeUpdate("DELETE FROM users WHERE user_id = 1");

83.

What Is A Stored Procedure?

Answer»

A stored procedure is a group of SQL statements that form a LOGICAL UNIT and perform a particular task. Stored procedures are used to encapsulate a set of OPERATIONS or queries to execute on a database server. For example, operations on an employee database (hire, fire, promote, lookup) could be coded as stored procedures executed by application code. Stored procedures can be COMPILED and executed with different parameters and RESULTS, and they may have any combination of input, output, and input/output parameters.

A stored procedure is a group of SQL statements that form a logical unit and perform a particular task. Stored procedures are used to encapsulate a set of operations or queries to execute on a database server. For example, operations on an employee database (hire, fire, promote, lookup) could be coded as stored procedures executed by application code. Stored procedures can be compiled and executed with different parameters and results, and they may have any combination of input, output, and input/output parameters.

84.

What Are The Tasks Of Jdbc?

Answer»

Following are the TASKS of JDBC

Following are the tasks of JDBC

85.

What Do You Mean By Batch Updates?

Answer»

If you want to EXECUTE a SET of statements, i.e. SQL statements at a TIME then we USE batch update statement.
resultset=pst.batchUpdate();

If you want to execute a set of statements, i.e. SQL statements at a time then we use batch update statement.
resultset=pst.batchUpdate();

86.

Why Do We Need Batch Updates?

Answer»

Let's say there are 100 RECORDS need to be insert. If we execute normal statemets the no of transactions will be 100 (in TERMS of connection making to DB). USING batch updates we can add 100 rec to batch and the no of transactions will be only one in this CASE. This will reduce the burdon on db, which is very costly in terms of RESOURCES.

Let's say there are 100 records need to be insert. If we execute normal statemets the no of transactions will be 100 (in terms of connection making to DB). using batch updates we can add 100 rec to batch and the no of transactions will be only one in this case. This will reduce the burdon on db, which is very costly in terms of resources.

87.

How Do You Call A Stored Procedure From Java?

Answer»

You can call a STORED PROCEDURE USING Callable statements CALLABLESTATEMENT cs = con.prepareCall("{call StoredProc}"); RESULTSET rs = cs.executeQuery();

You can call a stored procedure using Callable statements CallableStatement cs = con.prepareCall("{call StoredProc}"); ResultSet rs = cs.executeQuery();

88.

What Packages Are Being Used By Jdbc?

Answer»

FOLLOWING PACKAGES are USED in JDBC

  • java.sql
  • javax.sql

Following packages are used in JDBC

89.

What Do We Use Setautocommit() For?

Answer»

The DML OPERATIONS by DEFAULT are committed. If we wish to avoid the commit by default, setAutoCommit(false) has to be CALLED on the Connection object.

Once the STATEMENTS are executed, commit() has to be called on the Connection object explicitly.

The DML operations by default are committed. If we wish to avoid the commit by default, setAutoCommit(false) has to be called on the Connection object.

Once the statements are executed, commit() has to be called on the Connection object explicitly.

90.

How Many Statements Can We Create With One Connection?

Answer»

There is no such LIMIT on NUMBER of STATEMENTS to be CREATED.

There is no such limit on number of statements to be created.

91.

How Do You Insert Images In Database Using Jdbc?

Answer»

We can store IMAGES in the databse using the BLOB DATATYPE where in the image is STORED as a byte stream.

We can store images in the databse using the BLOB datatype where in the image is stored as a byte stream.

92.

What Is Metadata

Answer»

It is information about one of two THINGS: DATABASE information (java.sql.DatabaseMetaData), or Information about a SPECIFIC RESULTSET (java.sql.ResultSetMetaData). 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.

It is information about one of two things: Database information (java.sql.DatabaseMetaData), or Information about a specific ResultSet (java.sql.ResultSetMetaData). 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.

93.

What Is A Data Source

Answer»

A DataSource class BRINGS another level of abstraction than directly USING a connection object. Data source can be referenced by JNDI. Data Source may point to RDBMS, FILE System , any DBMS ETC.

A DataSource class brings another level of abstraction than directly using a connection object. Data source can be referenced by JNDI. Data Source may point to RDBMS, file System , any DBMS etc.

94.

How Can I Know When I Reach The Last Record In A Table, Since Jdbc Doesn't Provide An Eof Method?

Answer»
  • You can use last() method of java.SQL.ResultSet, if you make it scrollable.
  • You can also use isLast() as you are reading the ResultSet.
  • One thing to keep in mind, though, is that both methods TELL you that you have REACHED the end of the current ResultSet, not NECESSARILY the end of the table. SQL and RDBMSes make no guarantees about the order of rows, even from sequential SELECTs, unless you SPECIFICALLY use ORDER BY. Even then, that doesn't necessarily tell you the order of data in the table.

 

 

95.

How To Insert And Delete A Row Programmatically? (new Feature In Jdbc 2.0)

Answer»

Make sure the resultset is updatable.
1. MOVE the cursor to the SPECIFIC position.

uprs.moveToCurrentRow();

2. set VALUE for each column.

uprs.moveToInsertRow();//to set up for insert
uprs.updateString("col1" "strvalue");
uprs.updateInt("col2", 5);
...

3. call inserRow() method to finish the row insert process.

uprs.insertRow();

To DELETE a row: move to the specific position and call deleteRow() method:

uprs.absolute(5);
uprs.deleteRow();//delete row 5

To SEE the changes call refreshRow();

uprs.refreshRow();

Make sure the resultset is updatable.
1. move the cursor to the specific position.

2. set value for each column.

3. call inserRow() method to finish the row insert process.

To delete a row: move to the specific position and call deleteRow() method:

To see the changes call refreshRow();

96.

How Can I Use The Jdbc Api To Access A Desktop Database Like Microsoft Access Over The Network?

Answer»

Most desktop databases currently require a JDBC solution that USES ODBC UNDERNEATH. This is because the vendors of these database products haven't implemented all-Java JDBC drivers.

The BEST approach is to use a commercial JDBC driver that supports ODBC and the database you WANT to use. See the JDBC drivers page for a list of available JDBC drivers. The JDBC-ODBC bridge from Sun's Java Software does not provide network access to desktop databases by itself.

The JDBC-ODBC bridge loads ODBC as a local DLL, and typical ODBC drivers for desktop databases like Access aren't networked. The JDBC-ODBC bridge can be used together with the RMI-JDBC bridge, however, to access a desktop database like Access over the net. This RMI-JDBC-ODBC solution is FREE.

Most desktop databases currently require a JDBC solution that uses ODBC underneath. This is because the vendors of these database products haven't implemented all-Java JDBC drivers.

The best approach is to use a commercial JDBC driver that supports ODBC and the database you want to use. See the JDBC drivers page for a list of available JDBC drivers. The JDBC-ODBC bridge from Sun's Java Software does not provide network access to desktop databases by itself.

The JDBC-ODBC bridge loads ODBC as a local DLL, and typical ODBC drivers for desktop databases like Access aren't networked. The JDBC-ODBC bridge can be used together with the RMI-JDBC bridge, however, to access a desktop database like Access over the net. This RMI-JDBC-ODBC solution is free.

97.

How Do I Retrieve A Whole Row Of Data At Once, Instead Of Calling An Individual Resultset.getxxx Method For Each Column?

Answer»

The ResultSet.getXXX methods are the only way to retrieve data from a ResultSet object, which MEANS that you have to make a method call for each column of a ROW. It is unlikely that this is the cause of a performance problem, however, because it is difficult to see how a column could be fetched without at least the COST of a FUNCTION call in any scenario. We welcome input from developers on this issue.

The ResultSet.getXXX methods are the only way to retrieve data from a ResultSet object, which means that you have to make a method call for each column of a row. It is unlikely that this is the cause of a performance problem, however, because it is difficult to see how a column could be fetched without at least the cost of a function call in any scenario. We welcome input from developers on this issue.

98.

What Are The Common Tasks Of Jdbc?

Answer»

Create an instance of a JDBC DRIVER or load JDBC drivers through jdbc.drivers

  • Register a driver
  • Specify a database
  • OPEN a database CONNECTION
  • Submit a query
  • RECEIVE results
  • Process results

Create an instance of a JDBC driver or load JDBC drivers through jdbc.drivers

99.

How To Use Jdbc To Connect Microsoft Access?

Answer»

There is a SPECIFIC TUTORIAL at javacamp.org. CHECK it out.

There is a specific tutorial at javacamp.org. Check it out.

100.

Are All The Required Jdbc Drivers To Establish Connectivity To My Database Part Of The Jdk?

Answer»

No. There aren't any JDBC technology-enabled drivers BUNDLED with the JDK 1.1.x or Java 2 PLATFORM releases other than the JDBC-ODBC Bridge. So, developers need to get a driver and install it before they can connect to a database. We are considering BUNDLING JDBC technology- enabled drivers in the future.

No. There aren't any JDBC technology-enabled drivers bundled with the JDK 1.1.x or Java 2 Platform releases other than the JDBC-ODBC Bridge. So, developers need to get a driver and install it before they can connect to a database. We are considering bundling JDBC technology- enabled drivers in the future.