JDBC Interview Questions & Answers

JDBC Interview Questions

Java database connectivity (JDBC) is an API that enables Java programs to execute SQL statements. If you are attending an interview related to JDBC, you need to gain knowledge on different aspects of the subject. Every job seeker is unsure about the JDBC interview questions and answers he/ she is going to encounter during the interview process. Gaining some information on the same would make getting placed an easy job for the job seeker. Let wisdomjobs.com help you in this regard. Reach the portal to know various job interview questions and answers that you are going to encounter during the process and give a thorough preparation in this regard to win the competitions. A well-researched set of questions framed here will give you the exposure to the skill set the interviewer is looking for to hire you for the job.


JDBC Interview Questions And Answers

JDBC Interview Questions
    1. Question 1. What Is The Jdbc?

      Answer :

      Java Database Connectivity (JDBC) is a standard Java API to interact with relational databases form Java. JDBC has set of classes and interfaces which can use from Java application and talk to database without learning RDBMS details and using Database Specific JDBC Drivers.

    2. Question 2. What Are The New Features Added To Jdbc 4.0?

      Answer :

      The major features added in JDBC 4.0 include :

      • Auto-loading of JDBC driver class
      • Connection management enhancements
      • Support for RowId SQL type
      • DataSet implementation of SQL using Annotations
      • SQL exception handling enhancements
      • SQL XML support

    3. Question 3. Explain Basic Steps In Writing A Java Program Using Jdbc?

      Answer :

      JDBC makes the interaction with RDBMS simple and intuitive. When a Java application needs to access database :

      • Load the RDBMS specific JDBC driver because this driver actually communicates with the database (Incase of JDBC 4.0 this is automatically loaded).
      • Open the connection to database which is then used to send SQL statements and get results back.
      • Create JDBC Statement object. This object contains SQL query.
      • Execute statement which returns resultset(s). ResultSet contains the tuples of database table as a result of SQL query.
      • Process the result set.
      • Close the connection.

    4. Question 4. What Are The Main Components Of Jdbc ?

      Answer :

      The life cycle of a servlet consists of the following phases:

      • DriverManager: Manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.
      • Driver: The database communications link, handling all communication with the database. Normally, once the driver is loaded, the developer need not call it explicitly.
      • Connection : Interface with all methods for contacting a database.The connection object represents communication context, i.e., all communication with database is through connection object only.
      • Statement : Encapsulates an SQL statement which is passed to the database to be parsed, compiled, planned and executed.
      • ResultSet: The ResultSet represents set of rows retrieved due to query execution.

    5. Question 5. What Is Jdbc Driver Interface?

      Answer :

      The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendor driver must provide implementations of the java.sql.Connection, Statement, Prepared Statement,  CallableStatement, ResultSet and Driver.

    6. Question 6. What Does The Connection Object Represents?

      Answer :

      The connection object represents communication context, i.e., all communication with database is through connection object only.

    7. Question 7. What Is Statement ?

      Answer :

      • Statement acts like a vehicle through which SQL commands can be sent. Through the connection object we create statement kind of objects.
      • Through the connection object we create statement kind of objects.
      • Statement stmt = conn.createStatement();
      • This method returns object which implements statement interface.

    8. Question 8. What Is Preparedstatement?

      Answer :

      A prepared statement is an SQL statement that is precompiled by the database. Through precompilation, prepared statements improve the performance of SQL commands that are executed multiple times (given that the database supports prepared statements). Once compiled, prepared statements can be customized prior to each execution by altering predefined SQL parameters.

      PreparedStatement pstmt = conn.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?");
      pstmt.setBigDecimal(1, 153833.00);
      pstmt.setInt(2, 110592);

      Here: conn is an instance of the Connection class and "?" represents parameters.These parameters must be specified before execution.

    9. Question 9. What Are Callable Statements ?

      Answer :

      Callable statements are used from JDBC application to invoke stored procedures and functions.

    10. Question 10. How To Call A Stored Procedure From Jdbc ?

      Answer :

      PL/SQL stored procedures are called from within JDBC programs by means of the prepareCall() method of the Connection object created. A call to this method takes variable bind parameters as input parameters as well as output variables and creates an object instance of the CallableStatement class. The following line of code illustrates this:

      CallableStatement stproc_stmt = conn.prepareCall("{call procname(?,?,?)}");

      Here conn is an instance of the Connection class.


    11. Question 11. What Are Types Of Jdbc Drivers?

      Answer :

      There are four types of drivers defined by JDBC as follows:

      • Type 1: JDBC/ODBC—These require an ODBC (Open Database Connectivity) driver for the database to be installed. This type of driver works by translating the submitted queries into equivalent ODBC queries and forwards them via native API calls directly to the ODBC driver. It provides no host redirection capability.
      • Type2: Native API (partly-Java driver)—This type of driver uses a vendor-specific driver or database API to interact with the database. An example of such an API is Oracle OCI (Oracle Call Interface). It also provides no host redirection.
      • Type 3: Open Protocol-Net—This is not vendor specific and works by forwarding database requests to a remote database source using a net server component. How the net server component accesses the database is transparent to the client. The client driver communicates with the net server using a database-independent protocol and the net server translates this protocol into database calls. This type of driver can access any database.
      • Type 4: Proprietary Protocol-Net(pure Java driver)—This has a same configuration as a type 3 driver but uses a wire protocol specific to a particular vendor and hence can access only that vendor's database. Again this is all transparent to the client.


    12. Question 12. Which Type Of Jdbc Driver Is The Fastest One?

      Answer :

      JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the JDBC calls into vendor specific protocol calls and it directly interacts with the database.

    13. Question 13. Does The Jdbc-odbc Bridge Support Multiple Concurrent Open Statements Per Connection?

      Answer :

      No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.

    14. Question 14. Which Is The Right Type Of Driver To Use And When?

      Answer :

      • Type I driver is handy for prototyping.
      • Type III driver adds security, caching, and connection control.
      • Type III and Type IV drivers need no pre-installation.

    15. Question 15. What Are The Standard Isolation Levels Defined By Jdbc?

      Answer :

      The values are defined in the class java.sql.Connection and are:


      Any given database may not support all of these levels.

    16. Question 16. What Is Resultset ?

      Answer :

      The ResultSet represents set of rows retrieved due to query execution.

      ResultSet rs = stmt.executeQuery(sqlQuery);

    17. Question 17. What Is Rowset?

      Answer :

      A RowSet is an object that encapsulates a set of rows from either Java Database Connectivity (JDBC) result sets or tabular data sources like a file or spreadsheet. RowSets support component-based development models like JavaBeans, with a standard set of properties and an event notification .

    18. Question 18. What Are The Different Types Of Rowset ?

      Answer :

      There are two types of RowSet are there. They are:

      • Connected - A connected RowSet object connects to the database once and remains connected until the application terminates.
      • Disconnected - A disconnected RowSet object connects to the database, executes a query to retrieve the data from the database and then closes the connection. A program may change the data in a disconnected RowSet while it is disconnected. Modified data can be updated in the database after a disconnected RowSet reestablishes the connection with the database.

    19. Question 19. What Is The Need Of Batchupdates?

      Answer :

      The BatchUpdates feature allows us to group SQL statements together and send to database server in one single trip.

    20. Question 20. What Is A Datasource?

      Answer :

      A DataSource object is the representation of a data source in the Java programming language. In basic terms,

      • A DataSource is a facility for storing data.
      • DataSource can be referenced by JNDI.
      • Data Source may point to RDBMS, file System , any DBMS etc..

    21. Question 21. What Is Connection Pooling? What Is The Main Advantage Of Using Connection Pooling?

      Answer :

      A connection pool is a mechanism to reuse connections created. Connection pooling can increase performance dramatically by reusing connections rather than creating a new physical connection each time a connection is requested.

    22. Question 22. What's The Jdbc 3.0 Api?

      Answer :

      The JDBC 3.0 API is the latest update of the JDBC API. It contains many features, including scrollable result sets and the SQL:1999 data types.

      JDBC (Java Database Connectivity) is the standard for communication between a Java application and a relational database. The JDBC API is released in two versions; JDBC version 1.22 (released with JDK 1.1.X in package java.sql) and version 2.0 (released with Java platform 2 in packages java.sql and javax.sql). It is a simple and powerful largely database-independent way of extracting and inserting data to or from any database.

    23. Question 23. Does The Jdbc-odbc Bridge Support The New Features In The Jdbc 3.0 Api?

      Answer :

      The JDBC-ODBC Bridge provides a limited subset of the JDBC 3.0 API.

    24. Question 24. Can The Jdbc-odbc Bridge Be Used With Applets?

      Answer :

      Use of the JDBC-ODBC bridge from an untrusted applet running in a browser, such as Netscape Navigator, isn't allowed. The JDBC-ODBC bridge doesn't allow untrusted code to call it for security reasons. This is good because it means that an untrusted applet that is downloaded by the browser can't circumvent Java security by calling ODBC. Remember that ODBC is native code, so once ODBC is called the Java programming language can't guarantee that a security violation won't occur. On the other hand, Pure Java JDBC drivers work well with applets. They are fully downloadable and do not require any client-side configuration.

      Finally, we would like to note that it is possible to use the JDBC-ODBC bridge with applets that will be run in appletviewer since appletviewer assumes that applets are trusted. In general, it is dangerous to turn applet security off, but it may be appropriate in certain controlled situations, such as for applets that will only be used in a secure intranet environment. Remember to exercise caution if you choose this option, and use an all-Java JDBC driver whenever possible to avoid security problems.

    25. Question 25. How Do I Start Debugging Problems Related To The Jdbc Api?

      Answer :

      A good way to find out what JDBC calls are doing is to enable JDBC tracing. The JDBC trace contains a detailed listing of the activity occurring in the system that is related to JDBC operations.

      If you use the DriverManager facility to establish your database connection, you use the DriverManager. setLogWriter method to enable tracing of JDBC operations. If you use a DataSource object to get a connection, you use the DataSource.setLogWriter method to enable tracing. (For pooled connections, you use the ConnectionPoolDataSource.setLogWriter method, and for connections that can participate in distributed transactions, you use the XADataSource.setLogWriter method.)

    26. Question 26. What Is New In Jdbc 2.0?

      Answer :

      With the JDBC 2.0 API, you will be able to do the following:
      Scroll forward and backward in a result set or move to a specific row (TYPE_SCROLL_ SENSITIVE, previous(), last(), absolute(), relative(), etc.) Make updates to database tables using methods in the Java programming language instead of using SQL commands.(updateRow(), insertRow(), deleteRow(), etc.) Send multiple SQL statements to the database as a unit, or batch (addBatch(), executeBatch()) Use the new SQL3 datatypes as column values like Blob, Clob, Array, Struct, Ref.

    27. Question 27. How Many Types Of Jdbc Drivers Are Present And What Are They?

      Answer :

      There are 4 types of JDBC Drivers

      • JDBC-ODBC Bridge Driver
      • Native API Partly Java Driver
      • Network protocol Driver
      • JDBC Net pure Java Driver

    28. Question 28. Can We Implement An Interface In A Jsp?

      Answer :


    29. Question 29. What Is The Difference Between Servletcontext And Pagecontext?

      Answer :

      ServletContext: Gives the information about the container.
      PageContext: Gives the information about the Request.

    30. Question 30. How To Pass Information From Jsp To Included Jsp?

      Answer :

      Using <%jsp:param> tag.

    31. Question 31. What Is The Difference Between Directive Include And Jsp Include?

      Answer :

      <%@ include>: Used to include static resources during translation time.

      JSP include: Used to include dynamic content or static content during runtime.

    32. Question 32. What Is The Difference Between Requestdispatcher And Sendredirect?

      Answer :

      RequestDispatcher: server-side redirect with request and response objects.

      sendRedirect : Client-side redirect with new request and response objects.

    33. Question 33. How Does Jsp Handle Runtime Exceptions?

      Answer :

      Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP.

    34. Question 34. How Do You Delete A Cookie Within A Jsp?

      Answer :

      Cookie mycook = new Cookie("name","value");
      Cookie killmycook = new Cookie("mycook","value");

    35. Question 35. How Do I Mix Jsp And Ssi #include?

      Answer :

      If you’re just including raw HTML, use the #include directive as usual inside your .jsp file.

    36. Question 36. I Made My Class Cloneable But I Still Get Can't Access Protected Method Clone. Why?

      Answer :

      Some of the Java books imply that all you have to do in order to have your class support clone() is implement the Cloneable interface. Not so. Perhaps that was the intent at some point, but that’s not the way it works currently. As it stands, you have to implement your own public clone() method, even if it doesn’t do anything special and just calls super.clone().

    37. Question 37. Why Is Xml Such An Important Development?

      Answer :

      It removes two constraints which were holding back Web developments: dependence on a single, inflexible document type (HTML) which was being much abused for tasks it was never designed for; the complexity of full SGML, whose syntax allows many powerful but hard-to-program options. XML allows the flexible development of user-defined document types. It provides a robust, non-proprietary, persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web; and it removes the more complex options of SGML, making it easier to program for.

    38. Question 38. What Is The Fastest Type Of Jdbc Driver?

      Answer :

      JDBC driver performance will depend on a number of issues:

      • the quality of the driver code,
      • the size of the driver code,
      • the database server and its load,
      • network topology,
      • the number of times your request is translated to a different API.

      In general, all things being equal, you can assume that the more your request and response change hands, the slower it will be. This means that Type 1 and Type 3 drivers will be slower than Type 2 drivers (the database calls are make at least three translations versus two), and Type 4 drivers are the fastest (only one translation).

    39. Question 39. How Do I Find Whether A Parameter Exists In The Request Object?

      Answer :

      boolean hasFoo = !(request.getParameter("foo") == null
      || request.getParameter("foo").equals(""));
      boolean hasParameter =
      request.getParameterMap().contains(theParameter); //(which works in Servlet 2.3+)

    40. Question 40. How Can I Send User Authentication Information While Makingurlconnection?

      Answer :

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

    41. Question 41. How Do I Create A Database Connection?

      Answer :

      The database connection is created in 3 steps:

      1. Find a proper database URL.
      2. Load the database driver.
      3. Ask the Java DriverManager class to open a connection to your database.

      In java code, the steps are realized in code as follows:

      • Create a properly formatted JDBR URL for your database.  A JDBC URL has the form jdbc:someSubProtocol://myDatabaseServer/theDatabaseName
      • try {
      catch(Exception ex)
      System.err.println("Could not load database driver: " + ex);
      • Connection conn = DriverManager.getConnection("a.JDBC.URL", "databaseLogin", "databasePassword");

    42. Question 42. What Is Metadata And Why Should I Use It?

      Answer :

      Metadata ('data about data') is information about one of two things:

      1. Database information (java.sql.DatabaseMetaData), or
      2. Information about a specific ResultSet (java.sql. ResultSet MetaData).

      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.

    43. Question 43. How Does The Java Database Connectivity (jdbc) Work?

      Answer :

      The JDBC is used whenever a Java application should communicate with a relational database for which a JDBC driver exists. JDBC is part of the Java platform standard; all visible classes used in the Java/database communication are placed in package java.sql.

      Main JDBC classes:

      • DriverManager: Manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. The first driver that recognizes a certain subprotocol under jdbc (such as odbc or dbAnywhere/dbaw) will be used to establish a database Connection.
      • Driver: The database communications link, handling all communication with the database. Normally, once the driver is loaded, the developer need not call it explicitly.
      • Connection: Interface with all methods for contacting a database.
      • Statement: Encapsulates an SQL statement which is passed to the database to be parsed, compiled, planned and executed.
      • ResultSet: The answer/result from a statement. A ResultSet is a fancy 2D list which encapsulates all outgoing results from a given SQL query.

    44. Question 44. What Is The Advantage Of Using A Preparedstatement?

      Answer :

      For SQL statements that are executed repeatedly, using a PreparedStatement object would almost always be faster than using a Statement object. This is because creating a PreparedStatement object by explicitly giving the SQL statement causes the statement to be precompiled within the database immediately. Thus, when the PreparedStatement is later executed, the DBMS does not have to recompile the SQL statement and prepared an execution plan - it simply runs the statement.

      Typically, PreparedStatement objects are used for SQL statements that take parameters. However, they can also be used with repeatedly executed SQL statements that do not accept parameters.

    45. Question 45. How Do I Extract The Sql Statements Required To Move All Tables And Views From An Existing Database To Another Database?

      Answer :

      The operation is performed in 9 steps:

      1. Open a connection to the source database. Use the DriverManager class.
      2. Find the entire physical layout of the current database. Use the DatabaseMetaData interface.
      3. Create DDL SQL statements for re-creating the current database structure. Use the DatabaseMetaData interface.
      4. Build a dependency tree, to determine the order in which tables must be setup. Use the DatabaseMetaData interface.
      5. Open a connection to the target database. Use the DriverManager class.
      6. Execute all DDL SQL statements from (3) in the order given by (4) in the target database to setup the table and view structure. Use the PreparedStatement interface.
      7. If (6) threw exceptions, abort the entire process.
      8. Loop over all tables in the physical structure to generate DML SQL statements for re-creating the data inside the table. Use the ResultSetMetaData interface.
      9. Execute all DML SQL statements from (8) in the target database.

    46. Question 46. What Does Resultset Actually Contain? Is It The Actual Data Of The Result Or Some Links To Databases? If It Is The Actual Data Then Why Can't We Access It After Connection Is Closed?

      Answer :

      A ResultSet is an interface. Its implementation depends on the driver and hence ,what it "contains" depends partially on the driver and what the query returns. For example with the Odbc bridge what the underlying implementation layer contains is an ODBC result set. A Type 4 driver executing a stored procedure that returns a cursor - on an oracle database it actually returns a cursor in the databse. The oracle cursor can however be processed like a ResultSet would be from the client. Closing a connection closes all interaction with the database and releases any locks that might have been obtained in the process.

    47. Question 47. Can I Use The Jdbc-odbc Bridge Driver In An Applet?

      Answer :


    48. Question 48. How Can I Connect From An Applet To A Database On The Server?

      Answer :

      There are two ways of connecting to a database on the server side.

      1. The hard way. Untrusted applets cannot touch the hard disk of a computer. Thus, your applet cannot use native or other local files (such as JDBC database drivers) on your hard drive. The first alternative solution is to create a digitally signed applet which may use locally installed JDBC drivers, able to connect directly to the database on the server side.
      2. The easy way. Untrusted applets may only open a network connection to the server from which they were downloaded. Thus, you must place a database listener (either the database itself, or a middleware server) on the server node from which the applet was downloaded. The applet would open a socket connection to the middleware server, located on the same computer node as the webserver from which the applet was downloaded. The middleware server is used as a mediator, connecting to and extract data from the database.

    49. Question 49. How Do I Insert An Image File (or Other Raw Data) Into A Database?

      Answer :

      All raw data types (including binary documents or images) should be read and uploaded to the database as an array of bytes, byte[]. Originating from a binary file,

      1. Read all data from the file using a FileInputStream.
      2. Create a byte array from the read data.
      3. Use method setBytes(int index, byte[] data); of java.sql.PreparedStatement to upload the data.

    50. Question 50. How Can Resultset Records Be Restricted To Certain Rows?

      Answer :

      The easy answer is "Use a JDBC 2.0 compliant driver". With a 2.0 driver, you can use the setFetchSize() method within a Statement or a ResultSet object.
      For example,

      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery("select * from customers");

      will change the default fetch size to 400.
      You can also control the direction in which the rows are processed. For instance:
      will process the rows from bottom up.
      The driver manager usually defaults to the most efficient fetch size...so you may try experimenting with different value for optimal performance.

    51. Question 51. What Is The Difference Between Client And Server Database Cursors?

      Answer :

      What you see on the client side is the current row of the cursor which called a Result (ODBC) or ResultSet (JDBC). The cursor is a server-side entity only and remains on the server side.

    52. Question 52. How Can I Convert A Java Array To A Java.sql.array?

      Answer :

      A Java array is a first class object and all of the references basically use PreparedStatement.setObject() or ResultSet.updateObject() methods for putting the array to an ARRAY in the database. Here's a basic example:

      String[] as = { "One", "Two", "Three" };
      PreparedStatement ps = con.prepareStatement(
      "UPDATE MYTABLE SET ArrayNums = ? WHERE MyKey = ?" );
      ps.setObject( 1, as );

    53. Question 53. How Can I Insert Multiple Rows Into A Database In A Single Transaction?

      Answer :

      //turn off the implicit commit 
      //..your insert/update/delete goes here

      a new transaction is implicitly started. JDBC 2.0 provides a set of methods for executing a batch of database commands. Specifically, the java. sql. Statement interface provides three methods: addBatch(), clearBatch() and executeBatch(). Their documentation is pretty straight forward. The implementation of these methods is optional, so be sure that your driver supports these.


    54. Question 54. How Can I Connect To An Oracle Database Not On The Web Server From An Untrusted Applet?

      Answer :

      You can use the thin ORACLE JDBC driver in an applet (with some extra parameters on the JDBC URL). Then, if you have NET8, you can use the connection manager of NET8 on the web server to proxy the connection request to the database server.

    55. Question 55. How Do I Get Runtime Information About The Jdbc Driver?

      Answer :

      Use the following DatabaseMetaData methods:


    56. Question 56. How Can I Determine Whether A Statement And Its Resultset Will Be Closed On A Commit Or Rollback?

      Answer :

      Use the DatabaseMetaData methods supportsOpen StatementsAcrossCommit() and supports Open Statements Across Rollback().

    57. Question 57. Is There A Practical Limit For The Number Of Sql Statements That Can Be Added To An Instance Of A Statement Object

      Answer :

      While the specification makes no mention of any size limitation for Statement.addBatch(), this seems to be dependent, as usual, on the driver. Among other things, it depends on the type of container/collection used. I know of at least one driver that uses a Vector and grows as needed. I've seen questions about another driver that appears to peak somewhere between 500 and 1000 statements. Unfortunately, there doesn't appear to be any metadata information regarding possible limits. Of course, in a production quality driver, one would expect an exception from an addBatch() invocation that went beyond the command list's limits.

    58. Question 58. What Does Setfetchsize() Really Do?

      Answer :

      The API documentation explains it pretty well, but a number of programmers seem to have a misconception of its functionality. The first thing to note is that it may do nothing at all; it is only a hint, even to a JDBC Compliant driver. setFetchSize() is really a request for a certain sized blocking factor, that is, how much data to send at a time.

      Because trips to the server are expensive, sending a larger number of rows can be more efficient. It may be more efficient on the server side as well, depending on the particular SQL statement and the DB engine. That would be true if the data could be read straight off an index and the DB engine paid attention to the fetch size. In that case, the DB engine could return only enough data per request to match the fetch size. Don't count on that behavior. In general, the fetch size will be transparent to your program and only determines how often requests are sent to the server as you traverse the data. Also, both Statement and ResultSet have setFetchSize methods. If used with a Statement, all ResultSets returned by that Statement will have the same fetch size. The method can be used at any time to change the fetch size for a given ResultSet. To determine the current or default size, use the getFetchSize methods.

    59. Question 59. What Scalar Functions Can I Expect To Be Supported By Jdbc?

      Answer :

      JDBC supports numeric, string, time, date, system, and conversion functions on scalar values. For a list of those supported and additional information, see section A.1.4 Support Scalar Functions in the JDBC Data Access API For Driver Writers. Note that drivers are only expected to support those scalar functions that are supported by the underlying DB engine.

    60. Question 60. What Does Normalization Mean For Java.sql.date And Java.sql.time?

      Answer :

      These classes are thin wrappers extending java.util.Date, which has both date and time components. java.sql.Date should carry only date information and a normalized instance has the time information set to zeros. java.sql.Time should carry only time information and a normalized instance has the date set to the Java epoch ( January 1, 1970 ) and the milliseconds portion set to zero.

    61. Question 61. What Jdbc Objects Generate Sqlwarnings?

      Answer :

      Connections, Statements and ResultSets all have a getWarnings method that allows retrieval. Keep in mind that prior ResultSet warnings are cleared on each new read and prior Statement warnings are cleared with each new execution. getWarnings() itself does not clear existing warnings, but each object has a clearWarnings method.

    62. Question 62. How Can I Investigate The Physical Structure Of A Database?

      Answer :

      The JDBC view of a database internal structure can be seen in the image below.

      • Several database objects (tables, views, procedures etc.) are contained within a Schema.
      • Several schema (user namespaces) are contained within a catalog.
      • Several catalogs (database partitions; databases) are contained within a DB server (such as Oracle, MS SQL.

      The DatabaseMetaData interface has methods for discovering all the Catalogs, Schemas, Tables and Stored Procedures in the database server. The methods are pretty intuitive, returning a ResultSet with a single String column; use them as indicated in the code below:

      public static void main(String[] args) throws Exception
      // Load the database driver - in this case, we
      // use the Jdbc/Odbc bridge driver.
      // Open a connection to the database
      Connection conn = DriverManager.getConnection("[jdbcURL]", "[login]", "[passwd]");
      // Get DatabaseMetaData
      DatabaseMetaData dbmd = conn.getMetaData();
      // Get all Catalogs
      System.out.println("nCatalogs are called '" + dbmd.getCatalogTerm()
      + "' in this RDBMS.");
      processResultSet(dbmd.getCatalogTerm(), dbmd.getCatalogs());
      // Get all Schemas
      System.out.println("nSchemas are called '" + dbmd.getSchemaTerm()
      + "' in this RDBMS.");
      processResultSet(dbmd.getSchemaTerm(), dbmd.getSchemas());
      // Get all Table-like types
      System.out.println("nAll table types supported in this RDBMS:");
      processResultSet("Table type", dbmd.getTableTypes());
      // Close the Connection
      public static void processResultSet(String preamble, ResultSet rs)
      throws SQLException
      // Printout table data
      // Printout
      System.out.println(preamble + ": " + rs.getString(1));
      // Close database resources

    63. Question 63. How Do I Find All Database Stored Procedures In A Database?

      Answer :

      Use the getProcedures method of interface java.sql.DatabaseMetaData to probe the database for stored procedures. The exact usage is described in the code below.

      public static void main(String[] args) throws Exception
      // Load the database driver - in this case, we
      // use the Jdbc/Odbc bridge driver.
      // Open a connection to the database
      Connection conn = DriverManager.getConnection("[jdbcURL]", "[login]", "[passwd]");
      // Get DatabaseMetaData
      DatabaseMetaData dbmd = conn.getMetaData();
      // Get all procedures.
      System.out.println("Procedures are called '" + dbmd.getProcedureTerm() +"' in the DBMS.");
      ResultSet rs = dbmd.getProcedures(null, null, "%");
      // Printout table data
      // Get procedure metadata
      String dbProcedureCatalog = rs.getString(1);
      String dbProcedureSchema = rs.getString(2);
      String dbProcedureName = rs.getString(3);
      String dbProcedureRemarks = rs.getString(7);
      short dbProcedureType = rs.getShort(8);
      // Make result readable for humans
      String procReturn = (dbProcedureType == DatabaseMetaData.procedureNoResult ? "No Result" : "Result");
      // Printout
      System.out.println("Procedure: " + dbProcedureName + ", returns: " + procReturn);
      System.out.println(" [Catalog | Schema]: [" + dbProcedureCatalog + " | " + dbProcedureSchema + "]");
      System.out.println(" Comments: " + dbProcedureRemarks);
      // Close database resources

    64. Question 64. How Do I Check What Table Types Exist In A Database?

      Answer :

      Use the getTableTypes method of interface java.sql.DatabaseMetaData to probe the database for table types. The exact usage is described in the code below.

      public static void main(String[] args) throws Exception
      // Load the database driver - in this case, we
      // use the Jdbc/Odbc bridge driver.
      // Open a connection to the database
      Connection conn = DriverManager.getConnection("[jdbcURL]", "[login]", "[passwd]");
      // Get DatabaseMetaData
      DatabaseMetaData dbmd = conn.getMetaData();
      // Get all table types.
      ResultSet rs = dbmd.getTableTypes();
      // Printout table data
      // Printout
      System.out.println("Type: " + rs.getString(1));
      // Close database resources

    65. Question 65. How Do I Extract A Blob From A Database?

      Answer :

      A BLOB (Binary Large OBject) is essentially an array of bytes (byte[]), stored in the database. You extract the data in two steps:

      1. Call the getBlob method of the Statement class to retrieve a java.sql.Blob object.
      2. Call either getBinaryStream or getBytes in the extracted Blob object to retrieve the java byte[] which is the Blob object.

      Note that a Blob is essentially a pointer to a byte array (called LOCATOR in database-talk), so the java.sql.Blob object essentially wraps a byte pointer. Thus, you must extract all data from the database blob before calling commit or

      <div align="center">
      private void runGetBLOB()
      { // Prepare a Statement:
      PreparedStatement stmnt = conn.prepareStatement("select aBlob from BlobTable");
      // Execute
      ResultSet rs = stmnt.executeQuery();
      // Get as a BLOB
      Blob aBlob = rs.getBlob(1);
      byte[] allBytesInBlob = aBlob.getBytes(1, (int) aBlob.length());
      catch(Exception ex)
      // The driver could not handle this as a BLOB...
      // Fallback to default (and slower) byte[] handling
      byte[] bytes = rs.getBytes(1);
      // Close resources rs.close();
      catch(Exception ex)
      this.log("Error when trying to read BLOB: " + ex);

    66. Question 66. Which Is The Preferred Collection Class To Use For Storing Database Result Sets?

      Answer :

      When retrieving database results, the best collection implementation to use is the LinkedList. The benefits include:

      • Retains the original retrieval order
      • Has quick insertion at the head/tail
      • Doesn't have an internal size limitation like a Vector where when the size is exceeded a new internal structure is created (or you have to find out size beforehand to size properly)
      • Permits user-controlled synchronization unlike the pre-Collections Vector which is always synchronized.
      ResultSet result = stmt.executeQuery("...");
      List list = new LinkedList();
      while(result.next()) {

      If there are multiple columns in the result set, you'll have to combine them into their own data structure for each row. Arrays work well for that as you know the size, though a custom class might be best so you can convert the contents to the proper type when extracting from databse, instead of later.

    67. Question 67. How Can I Get Data From Multiple Resultsets?

      Answer :

      With certain database systems, a stored procedure can return multiple result sets, multiple update counts, or some combination of both. Also, if you are providing a user with the ability to enter any SQL statement, you don't know if you are going to get a ResultSet or an update count back from each statement, without analyzing the contents. The Statement.execute() method helps in these cases.

      Method Statement.execute() returns a boolean to tell you the type of response:

      • true indicates next result is a ResultSet

      Use Statement.getResultSet to get the ResultSet

      • false indicates next result is an update count

      Use Statement.getUpdateCount to get the update count

      • false also indicates no more results

      Update count is -1 when no more results (usually 0 or positive)

      After processing each response, you use Statement.getMoreResults to check for more results, again returning a boolean. The following demonstrates the processing of multiple result sets:

      boolean result = stmt.execute(" ... ");
      int updateCount = stmt.getUpdateCount();
      while (result || (updateCount != -1)) {
      if(result) {
      ResultSet r = stmt.getResultSet();
      // process result set
      } else if(updateCount != -1) {
      // process update count
      result = stmt.getMoreResults();
      updateCount = stmt.getUpdateCount();

    68. Question 68. What Are The Components Of The Jdbc Url For Oracle's "thin" Driver And How Do I Use Them?

      Answer :

      Briefly: jdbc:oracle:thin:@hostname:port:oracle-sid

      1. in green the Oracle sub-protocol (can be oracle:oci7:@, oracle:oci8:@, racle:thin:@, etc...) is related on the driver you are unsign and the protocol to communicate with server.
      2. in red the network machine name, or its ip address, to locate the server where oracle is running.
      3. in blue the port (it is complementary to the address to select the specific oracle service)
      4. in magenta the sid, select on which database you want to connect.
      Here's an example:
      where user=scott and pass=tiger.

    69. Question 69. I Need To Have Result Set On A Page Where The User Can Sort On The Column Headers. Any Ideas?

      Answer :

      One possibility: Have an optional field in your form or GET url called (appropriately) ORDER with a default value of either "no order" or whatever you want your default ordering to be (i.e. timestamp, username, whatever). When you get your request, see what the value of the ORDER element is. If it's null or blank, use the default. Use that value to build your SQL query, and display the results to the page. If you're caching data in your servlet, you can use the Collection framework to sort your data (see java.util.Collections) if you can get it into a List format. Then, you can create a Collator which can impose a total ordering on your results.

    70. Question 70. What's The Best Way, In Terms Of Performance, To Do Multiple Insert/update Statements, A Preparedstatement Or Batch Updates?

      Answer :

      Because PreparedStatement objects are precompiled, their execution can be faster than that of Statement objects. Consequently, an SQL statement that is executed many times is often created as a PreparedStatement object to increase efficiency. A CallableStatement object provides a way to call stored procedures in a standard manner for all DBMSes. Their execution can be faster than that of PreparedStatement object. Batch updates are used when you want to execute multiple statements together. Actually, there is no conflict here. While it depends on the driver/DBMS engine as to whether or not you will get an actual performance benefit from batch updates, Statement, PreparedStatement, and CallableStatement can all execute the addBatch() method.

    71. Question 71. What Is Jdo?

      Answer :

      JDO provides for the transparent persistence of data in a data store agnostic manner, supporting object, hierarchical, as well as relational stores.

    72. Question 72. What Is The Difference Between Setmaxrows(int) And Setfetchsize(int)? Can Either Reduce Processing Time?

      Answer :

      setFetchSize(int) defines the number of rows that will be read from the database when the ResultSet needs more rows. The method in the java.sql.Statement interface will set the 'default' value for all the ResultSet derived from that Statement; the method in the java.sql.ResultSet interface will override that value for a specific ResultSet. Since database fetches can be expensive in a networked environment, fetch size has an impact on performance.

      setMaxRows(int) sets the limit of the maximum nuber of rows in a ResultSet object. If this limit is exceeded, the excess rows are "silently dropped". That's all the API says, so the setMaxRows method may not help performance at all other than to decrease memory usage. A value of 0 (default) means no limit. Since we're talking about interfaces, be careful because the implementation of drivers is often different from database to database and, in some cases, may not be implemented or have a null implementation. Always refer to the driver documentation.

    73. Question 73. How Can I Tell If My Jdbc Driver Normalizes Java.sql.date And Java.sql.time Objects?

      Answer :

      To actually determine the values, the objects must be converted to a java.util.Date and examined. See What does normalization mean for java.sql.Date and java.sql.Time? for the definition of normalization. Notice that even a debugger will not show whether these objects have been normalized, since the getXXX methods in java.sql.Date for time elements and in java.sql.Time for date elements throw an exception.

      So, while a java.sql.Date may show 2001-07-26, it's normalized only if the java.util.Date value is:
      Thu Jul 26 00:00:00 EDT 2001

      and while a java.sql.Time may show 14:01:00, it's normalized only if the java.util.Date value is:
      Thu Jan 01 14:01:00 EST 1970

    74. Question 74. Can I Get Information About A Resultset's Associated Statement And Connection In A Method Without Having Or Adding Specific Arguments For The Statement And Connection?

      Answer :

      Yes. Use ResultSet.getStatement(). From the resulting Statement you can use Statement.getConnection().

    75. Question 75. What Is Pessimistic Concurrency?

      Answer :

      With a pessimistic approach, locks are used to ensure that no users, other than the one who holds the lock, can update data. It's generally explained that the term pessimistic is used because the expectation is that many users will try to update the same data, so one is pessimistic that an update will be able to complete properly. Locks may be acquired, depending on the DBMS vendor, automatically via the selected Isolation Level. Some vendors also implement 'Select... for Update', which explicitly acquires a lock.

    76. Question 76. What Is Optimistic Concurrency?

      Answer :

      An optimistic approach dispenses with locks ( except during the actual update ) and usually involves comparison of timestamps, or generations of data to ensure that data hasn't changed between access and update times. It's generally explained that the term optimistic is used because the expectation is that a clash between multiple updates to the same data will seldom occur.

    77. Question 77. When An Sql Select Statement Doesn't Return Any Rows, Is An Sqlexception Thrown?

      Answer :

      No. If you want to throw an exception, you could wrap your SQL related code in a custom class and throw something like ObjectNotFoundException when the returned ResultSet is empty.

    78. Question 78. What Is Connection Pooling?

      Answer :

      Connection pooling is a technique used for sharing server resources among requesting clients. Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. Connection pool manager maintains a pool of open database connections.

    79. Question 79. Which Java And Java.sql Data Types Map To My Specific Database Types?

      Answer :

      JDBC is, of necessity, reliant on the driver and underlying DBMS. These do not always adhere to standards as closely as we would like, including differing names for standard Java types. To deal with this, first, there are a number of tables available in the JDK JDBC documentation dealing with types.

    80. Question 80. Does The Database Server Have To Be Running Java Or Have Java Support In Order For My Remote Jdbc Client App To Access The Database?

      Answer :

      The answer should always be no. The two critical requirements are LAN/internet connectivity and an appropriate JDBC driver. Connectivity is usually via TCP/IP, but other communication protocols are possible. Unspoken, but assumed here is that the DBMS has been started to listen on a communications port. It is the JDBC driver's job to convert the SQL statements and JDBC calls to the DBMS' native protocol. From the server's point of view, it's just another data request coming into the port, the programming language used to send the data is irrelevant at that point.

    81. Question 81. What Is A Jdbc 2.0 Datasource?

      Answer :

      The DataSource class was introduced in the JDBC 2.0 Optional Package as an easier, more generic means of obtaining a Connection. The actual driver providing services is defined to the DataSource outside the application ( Of course, a production quality app can and should provide this information outside the app anyway, usually with properties files or ResourceBundles ). The documentation expresses the view that DataSource will replace the common DriverManager method.

    82. Question 82. What Types Of Datasource Objects Are Specified In The Optional Package?

      Answer :

      • Basic - Provides a standard Connection object.
      • Pooled - Provides a Connection pool and returns a Connection that is controlled by the pool.
      • Distributed - Provides a Connection that can participate in distributed transactions ( more than one DBMS is involved). It is anticipated, but not enforced, that a distributed DataSource will also provide pooling.

      However, there are no standard methods available in the DataSource class to determine if one has obtained a pooled and/or distributed Connection.

    83. Question 83. What Is The Significance Of Databasemetadata.tableindexstatistics? How To Obtain And Use It?

      Answer :

      To answer the second question first, the tableIndexStatistic constant in the TYPE column will identify one of the rows in the ResultSet returned when DatabaseMetaData.getIndexInfo() is invoked. If you analyze the wordy API, a tableIndexStatistic row will contain the number of rows in the table in the CARDINALITY column and the number of pages used for the table in the PAGES column.

    84. Question 84. What Is Dml?

      Answer :

      DML is an abbreviation for Data Manipulation Language. This portion of the SQL standard is concerned with manipulating the data in a database as opposed to the structure of a database. The core verbs for DML are SELECT, INSERT, DELETE, UPDATE, COMMIT and ROLLBACK.

    85. Question 85. Can I Use Jdbc To Execute Non-standard Features That My Dbms Provides?

      Answer :

      The answer is a qualified yes. As discussed under SQL Conformance: "One way the JDBC API deals with this problem is to allow any query string to be passed through to an underlying DBMS driver. This means that an application is free to use as much SQL functionality as desired, but it runs the risk of receiving an error on some DBMSs. In fact, an application query may be something other than SQL, or it may be a specialized derivative of SQL designed for specific DBMSs (for document or image queries, for example)."

      Clearly this means either giving up portability or checking the DBMS currently used before invoking specific operations.

    86. Question 86. How Can I Get Information About Foreign Keys Used In A Table?

      Answer :

      DatabaseMetaData.getImportedKeys() returns a ResultSet with data about foreign key columns, tables, sequence and update and delete rules.

    87. Question 87. How Can I Determine Where A Given Table Is Referenced Via Foreign Keys?

      Answer :

      DatabaseMetaData.getExportedKeys() returns a ResultSet with data similar to that returned by Database MetaData .getImported Keys(), except that the information relates to other tables that reference the given table as a foreign key container.

    88. Question 88. What Are The Considerations For Deciding On Transaction Boundaries?

      Answer :

      Transaction processing should always deal with more than one statement and a transaction is often described as a Logical Unit of Work ( LUW ). The rationale for transactions is that you want to know definitively that all or none of the LUW completed successfully. Note that this automatically gives you restart capability. Typically, there are two conditions under which you would want to use transactions:

      • Multiple statements involving a single file - An example would be inserting all of a group of rows or all price updates for a given date. You want all of these to take effect at the same time; inserting or changing some subset is not acceptable.
      • Multiple statements involving multiple files - The classic example is transferring money from one account to another or double entry accounting; you don't want the debit to succeed and the credit to fail because money or important records will be lost. Another example is a master/detail relationship, where, say, the master contains a total column. If the entire LUW, writing the detail row and updating the master row, is not completed successfully, you A) want to know that the transaction was unsuccessful and B) that a portion of the transaction was not lost or dangling.

      Therefore, determining what completes the transaction or LUW should be the deciding factor for transaction boundaries.

    89. Question 89. How Does One Get Column Names For Rows Returned In A Resultset?

      Answer :

      ResultSet rs = ...
      ResultSetMetaData rsmd = rs.getMetaData();
      int numCols = rsmd.getColumnCount();
      for (int i = 1; i <= numCols; i++)
      System.out.println("[" + i + "]" +
      rsmd.getColumnName(i) + " {" +
      rsmd.getColumnTypeName(i) + "}");

    90. Question 90. Why Can't Tomcat Find My Oracle Jdbc Drivers In Classes111.zip?

      Answer :

      TOMCAT 4.0.1 on NT4 throws the following exception when I try to connect to Oracle DB from JSP.

      javax.servlet.ServletException : oracle.jdbc.driver.OracleDriver 
      java.lang.ClassNotFoundException: oracle:jdbc:driver:OracleDriver

      But, the Oracle JDBC driver ZIP file (classes111.zip)is available in the system classpath.
      Copied the Oracle Driver class file (classes111.zip) in %TOMCAT_Home - Home%lib directory and renamed it to classess111.jar.
      Able to connect to Oracle DB from TOMCAT 4.01 via Oracle JDBC-Thin Driver.


    91. Question 91. Is There A Way To Find The Primary Key(s) For An Access Database Table? Sun's Jdbc-odbc Driver Does Not Implement The Getprimarykeys() Method For The Databasemetadata Objects?

      Answer :

      // Use meta.getIndexInfo() will 
      //get you the PK index. Once
      // you know the index, retrieve its column name
      DatabaseMetaData meta = con.getMetaData();
      String key_colname = null;
      // get the primary key information
      rset = meta.getIndexInfo(null,null, table_name, true,true);
      while( rset.next())
      String idx = rset.getString(6);
      if( idx != null)
      //Note: index "PrimaryKey" is Access DB specific
      // other db server has diff. index syntax.
      if( idx.equalsIgnoreCase("PrimaryKey"))
      key_colname = rset.getString(9);
      setPrimaryKey( key_colname );

    92. Question 92. How Do I Insert/update Records With Some Of The Columns Having Null Value?

      Answer :

      Use either of the following PreparedStatement methods:

      public void setNull(int parameterIndex, int sqlType) throws SQLException 
      public void setNull(int paramIndex, int sqlType, String typeName) throws SQLException

      These methods assume that the columns are nullable. In this case, you can also just omit the columns in an INSERT statement; they will be automatically assigned null values.


    93. Question 93. How Do I Disallow Null Values In A Table?

      Answer :

      Null capability is a column integrity constraint, normally applied at table creation time. Note that some databases won't allow the constraint to be applied after table creation. Most databases allow a default value for the column as well. The following SQL statement displays the NOT NULL constraint:

      CREATE TABLE CoffeeTable ( 
      Type VARCHAR(25) NOT NULL,
      Pounds INTEGER NOT NULL,
      Price NUMERIC(5, 2) NOT NULL

    94. Question 94. Db2 Universal Claims To Support Jdbc 2.0, But I Can Only Get Jdbc 1.0 Functionality. What Can I Do?

      Answer :

      DB2 Universal defaults to the 1.0 driver. You have to run a special program to enable the 2.0 driver and JDK support. 

    95. Question 95. Why Do I Get Unsatisfiedlinkerror When I Try To Use My Jdbc Driver?

      Answer :

      The first thing is to be sure that this does not occur when running non-JDBC apps. If so, there is a faulty JDK/JRE installation. If it happens only when using JDBC, then it's time to check the documentation that came with the driver or the driver/DBMS support. JDBC driver types 1 through 3 have some native code aspect and typically require some sort of client install. Along with the install, various environment variables and path or classpath settings must be in place. Because the requirements and installation procedures vary with the provider, there is no reasonable way to provide details here. A type 4 driver, on the other hand, is pure Java and should never exhibit this problem. The trade off is that a type 4 driver is usually slower.

    96. Question 96. How Do I Check In My Code Whether A Maximum Limit Of Database Connections Have Been Reached?

      Answer :

      Use DatabaseMetaData.getMaxConnections() and compare to the number of connections currently open. Note that a return value of zero can mean unlimited or, unfortunately, unknown. Of course, driver Manager .getConnection () will throw an exception if a Connection can not be obtained.

    97. Question 97. What Is The Jdbc Syntax For Using A Literal Or Variable In A Standard Statement?

      Answer :

      First, it should be pointed out that PreparedStatement handles many issues for the developer and normally should be preferred over a standard Statement.
      Otherwise, the JDBC syntax is really the same as SQL syntax. One problem that often affects newbies ( and others ) is that SQL, like many languages, requires quotes around character ( read "String" for Java ) values to distinguish from numerics. So the clause:
      "WHERE myCol = " + myVal
      is perfectly valid and works for numerics, but will fail when myVal is a String. Instead use:
      "WHERE myCol = '" + myVal + "'"
      if myVal equals "stringValue", the clause works out to:
      WHERE myCol = 'stringValue'
      You can still encounter problems when quotes are embedded in the value, which, again, a PreparedStatement will handle for you.

    98. Question 98. What Is An Sql Locator?

      Answer :

      A Locator is an SQL3 data type that acts as a logical pointer to data that resides on a database server. Read "logical pointer" here as an identifier the DBMS can use to locate and manipulate the data. A Locator allows some manipulation of the data on the server. While the JDBC specification does not directly address Locators, JDBC drivers typically use Locators under the covers to handle Array, Blob, and Clob data types.

    99. Question 99. Why Do I Have To Reaccess The Database For Array, Blob, And Clob Data?

      Answer :

      Most DBMS vendors have implemented these types via the SQL3 Locator type
      Some rationales for using Locators rather than directly returning the data can be seen most clearly with the Blob type. By definition, a Blob is an arbitrary set of binary data. It could be anything; the DBMS has no knowledge of what the data represents. Notice that this effectively demolishes data independence, because applications must now be aware of what the Blob data actually represents. Let's assume an employee table that includes employee images as Blobs.

      Say we have an inquiry program that presents multiple employees with department and identification information. To see all of the data for a specific employee, including the image, the summary row is selected and another screen appears. It is only at this pont that the application needs the specific image. It would be very wasteful and time consuming to bring down an entire employee page of images when only a few would ever be selected in a given run.

      Now assume a general interactive SQL application. A query is issued against the employee table. Because the image is a Blob, the application has no idea what to do with the data, so why bring it down, killing performance along the way, in a long running operation? Clearly this is not helpful in those applications that need the data everytime, but these and other considerations have made the most general sense to DBMS vendors.

    100. Question 100. What Does It Mean To "materialize" Data?

      Answer :

      This term generally refers to Array, Blob and Clob data which is referred to in the database via SQL locators "Materializing" the data means to return the actual data pointed to by the Locator.

      • For Arrays, use the various forms of getArray() and getResultSet().
      • For Blobs, use getBinaryStream() or getBytes(long pos, int length).
      • For Clobs, use getAsciiStream() or getCharacterStream().

    101. Question 101. How Can I Get Or Redirect The Log Used By Drivermanager And Jdbc Drivers?

      Answer :

      As of JDBC 2.0, use DriverManager.getLogWriter() and DriverManager.setLogWriter(PrintWriter out). Prior to JDBC 2.0, the DriverManager methods getLogStream() and setLogStream(PrintStream out) were used. These are now deprecated.

    102. Question 102. How Can I Write To The Log Used By Drivermanager And Jdbc Drivers?

      Answer :

      The simplest method is to use DriverManager.println(String message), which will write to the current log.

    103. Question 103. How Do I Receive A Resultset From A Stored Procedure?

      Answer :

      Stored procedures can return a result parameter, which can be a result set. For a discussion of standard JDBC syntax for dealing with result, IN, IN/OUT and OUT parameters, see Stored Procedures.

    104. Question 104. Connecting To A Database Through The Proxy I Want To Connect To Remote Database Using A Program That Is Running In The Local Network Behind The Proxy. Is That Possible?

      Answer :

      I assume that your proxy is set to accept http requests only on port 80. If you want to have a local class behind the proxy connect to the database for you, then you need a servlet/JSP to receive an HTTP request and use the local class to connect to the database and send the response back to the client.

      You could also use RMI where your remote computer class that connects to the database acts as a remote server that talks RMI with the clients. if you implement this, then you will need to tunnel RMI through HTTP which is not that hard.

      In summary, either have a servlet/JSP take HTTP requests, instantiate a class that handles database connections and send HTTP response back to the client or have the local class deployed as RMI server and send requests to it using RMI.

    105. Question 105. How Can I Determine The Isolation Levels Supported By My Dbms?

      Answer :

      Use DatabaseMetaData.supportsTransactionIsolationLevel(int level).

    106. Question 106. What Isolation Level Is Used By The Dbms When Inserting, Updating And Selecting Rows From A Database?

      Answer :

      The answer depends on both your code and the DBMS. If the program does not explicitly set the isolation level, the DBMS default is used. You can determine the default using Database MetaData. getDefault TransactionIsolation() and the level for the current Connection with Connection.getTransactionIsolation(). If the default is not appropriate for your transaction, change it with Connection.setTransactionIsolation(int level).

    107. Question 107. Update Fails Without Blank Padding. Although A Particular Row Is Present In The Database For A Given Key, Executeupdate() Shows 0 Rows Updated And, In Fact, The Table Is Not Updated. If I Pad The Key With Spaces For The Column Length (e.g. If The Key Column Is 20 Characters Long, And Key Is Msgid, Length 6, I Pad It With 14 Spaces), The Update Then Works!!! Is There Any Solution To This Problem Without Padding?

      Answer :

      In the SQL standard, CHAR is a fixed length data type. In many DBMSes ( but not all), that means that for a WHERE clause to match, every character must match, including size and trailing blanks. As Alessandro indicates, defining CHAR columns to be VARCHAR is the most general answer.

    108. Question 108. Is Possible To Open A Connection To A Database With Exclusive Mode With Jdbc?

      Answer :

      I think you mean "lock a table in exclusive mode". You cannot open a connection with exclusive mode. Depending on your database engine, you can lock tables or rows in exclusive mode.

      In Oracle you would create a statement st and run
      st.execute("lock table mytable in exclusive mode");

      Then when you are finished with the table, execute the commit to unlock the table. Mysql, Informix and SQLServer all have a slightly different syntax for this function, so you'll have to change it depending on your database. But they can all be done with execute().

    109. Question 109. What Driver Should I Use For Scalable Oracle Jdbc Applications?

      Answer :

      Sun recommends using the thin ( type 4 ) driver.

      • On single processor machines to avoid JNI overhead.
      • On multiple processor machines, especially running Solaris, to avoid synchronization bottlenecks.

    110. Question 110. Detecting Duplicate Keys I Have A Program That Inserts Rows In A Table. My Table Has A Column 'name' That Has A Unique Constraint. If The User Attempts To Insert A Duplicate Name Into The Table, I Want To Display An Error Message By Processing The Error Code From The Database. How Can I Capture This Error Code In A Java Program?

      Answer :

      A solution that is perfectly portable to all databases, is to execute a query for checking if that unique value is present before inserting the row. The big advantage is that you can handle your error message in a very simple way, and the obvious downside is that you are going to use more time for inserting the record, but since you're working on a PK field, performance should not be so bad.

      You can also get this information in a portable way, and potentially avoid another database access, by capturing SQLState messages. Some databases get more specific than others, but the general code portion is 23 - "Constraint Violations". UDB2, for example, gives a specific such as 23505, while others will only give 23000.

    111. Question 111. Can I Set Up A Connection Pool With Multiple User Ids? The Single Id We Are Forced To Use Causes Problems When Debugging The Dbms.

      Answer :

      Since the Connection interface ( and the underlying DBMS ) requires a specific user and password, there's not much of a way around this in a pool. While you could create a different Connection for each user, most of the rationale for a pool would then be gone. Debugging is only one of several issues that arise when using pools.
      However, for debugging, at least a couple of other methods come to mind. One is to log executed statements and times, which should allow you to backtrack to the user. Another method that also maintains a trail of modifications is to include user and timestamp as standard columns in your tables. In this last case, you would collect a separate user value in your program.

    112. Question 112. How Do I Implement A Rowsetreader? I Want To Populate A Cachedrowset Myself And The Documents Specify That A Rowsetreader Should Be Used. The Single Method Accepts A Rowsetinternal Caller And Returns Void. What Can I Do In The Readdata Method?

      Answer :

      "It can be implemented in a wide variety of ways..." and is pretty vague about what can actually be done. In general, readData() would obtain or create the data to be loaded, then use CachedRowSet methods to do the actual loading. This would usually mean inserting rows, so the code would move to the insert row, set the column data and insert rows. Then the cursor must be set to to the appropriate position.

    113. Question 113. How Does A Custom Rowsetreader Get Called From A Cachedrowset?

      Answer :

      The Reader must be registered with the CachedRowSet using Cached RowSet .setReader javax.sql. RowSet Reader reader). Once that is done, a call to Cached RowSet. execute() will, among other things, invoke the readData method.

    114. Question 114. How Can I Create A Custom Rowsetmetadata Object From Scratch?

      Answer :

      One unfortunate aspect of RowSetMetaData for custom versions is that it is an interface. This means that implementations almost have to be proprietary. The JDBC RowSet package is the most commonly available and offers the sun.jdbc.rowset .RowSetMetaDataImpl class. After instantiation, any of the RowSetMetaData setter methods may be used. The bare minimum needed for a RowSet to function is to set the Column Count for a row and the Column Types for each column in the row. For a working code example that includes a custom RowSet MetaData.

    115. Question 115. Where Can I Find Info, Frameworks And Example Source For Writing A Jdbc Driver?

      Answer :

      There a several drivers with source available, like MM.MySQL, SimpleText Database, FreeTDS, and RmiJdbc. There is at least one free framework, the jxDBCon-Open Source JDBC driver framework. Any driver writer should also review For Driver Writers.

    116. Question 116. Once I Have The Java 2 Sdk, Standard Edition, From Sun, What Else Do I Need To Connect To A Database?

      Answer :

      You still need to get and install a JDBC technology-enabled driver that supports the database that you are using. There are many drivers available from a variety of sources. You can also try using the JDBC-ODBC Bridge if you have ODBC connectivity set up already. The Bridge comes with the Java 2 SDK, Standard Edition, and Enterprise Edition, and it doesn't require any extra setup itself. The Bridge is a normal ODBC client. Note, however, that you should use the JDBC-ODBC Bridge only for experimental prototyping or when you have no other driver available.

    117. Question 117. If I Use The Jdbc Api, Do I Have To Use Odbc Underneath?

      Answer :

      No, this is just one of many possible solutions. We recommend using a pure Java JDBC technology-enabled driver, type 3 or 4, in order to get all of the benefits of the Java programming language and the JDBC API.

    118. Question 118. I Would Like To Download The Jdbc-odbc Bridge For The Java 2 Sdk, Standard Edition (formerly Jdk 1.2). I'm A Beginner With The Jdbc Api, And I Would Like To Start With The Bridge. How Do I Do It?

      Answer :

      The JDBC-ODBC Bridge is bundled with the Java 2 SDK, Standard Edition, so there is no need to download it separately.

    119. Question 119. There Is A Method Getcolumncount In The Jdbc Api. Is There A Similar Method To Find The Number Of Rows In A Result Set?

      Answer :

      No, but it is easy to find the number of rows. If you are using a scrollable result set, rs, you can call the methods rs.last and then rs.getRow to find out how many rows rs has. If the result is not scrollable, you can either count the rows by iterating through the result set or get the number of rows by submitting a query with a COUNT column in the SELECT clause.

    120. Question 120. What Is The Query Used To Display All Tables Names In Sql Server (query Analyzer)?

      Answer :

      select * from information_schema.tables.

    121. Question 121. How Can I Retrieve A String Or Other Object Type Without Creating A New Object Each Time?

      Answer :

      Creating and garbage collecting potentially large numbers of objects (millions) unnecessarily can really hurt performance. It may be better to provide a way to retrieve data like strings using the JDBC API without always allocating a new object. We are studying this issue to see if it is an area in which the JDBC API should be improved.

    122. Question 122. Why Can't I Invoke The Resultset Methods Afterlast And Beforefirst When The Method Next Works?

      Answer :

      You are probably using a driver implemented for the JDBC 1.0 API. You need to upgrade to a JDBC 2.0 driver that implements scrollable result sets. Also be sure that your code has created scrollable result sets and that the DBMS you are using supports them.

    123. Question 123. Is The Jdbc-odbc Bridge Multi-threaded?

      Answer :

      No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won't get the advantages of multi-threading. In addition, deadlocks can occur between locks held in the database and the semaphore used by the Bridge. We are thinking about removing the synchronized methods in the future. They were added originally to make things simple for folks writing Java programs that use a single-threaded ODBC driver.

    124. Question 124. 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.

    125. Question 125. How To Use Jdbc To Connect Microsoft Access?

      Answer :

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

    126. Question 126. 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

    127. Question 127. 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.

    128. Question 128. 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.

    129. Question 129. 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.


      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.


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

      uprs.deleteRow();//delete row 5

      To see the changes call refreshRow();


    130. Question 130. 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.


    131. Question 131. 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.

    132. Question 132. 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.

    133. Question 133. 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.

    134. Question 134. How Many Statements Can We Create With One Connection?

      Answer :

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

    135. Question 135. 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.

    136. Question 136. What Packages Are Being Used By Jdbc?

      Answer :

      Following packages are used in JDBC

      • java.sql
      • javax.sql

    137. Question 137. 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();

    138. Question 138. 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.

    139. Question 139. 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.

    140. Question 140. What Are The Tasks Of Jdbc?

      Answer :

      Following are the tasks of JDBC

      • Load the JDBC drivers
      • Register the drivers
      • Specify a database
      • Open a connection to database
      • Submit a query to database
      • Gets the results.

    141. Question 141. 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.

    142. Question 142. How Do You Create Jdbc Statements?

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

    143. Question 143. 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.

    144. Question 144. 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).

    145. Question 145. How Do You Establish A Connection?

      Answer :

      Loading Drivers
      Getting connection
      Connection con = DriverManager.getConnection(url, "myLogin", "myPassword");

    146. Question 146. How Do You Load The Drivers?

      Answer :

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

    147. Question 147. What Are The Components Of Jdbc

      Answer :

      JDBC Components-

      • Connection Pools,
      • Data Sources, and
      • MultiPools.

    148. Question 148. What Is Jdbc?

      Answer :

      Short for Java Database Connectivity, a Java API that enables Java programs to execute SQL statements. This allows Java programs to interact with any SQL-compliant database. Since nearly all relational database management systems (DBMSs) support SQL, and because Java itself runs on most platforms, JDBC makes it possible to write a single database application that can run on different platforms and interact with different DBMSs.

      JDBC is similar to ODBC, but is designed specifically for Java programs, whereas ODBC is language-independent.

    149. Question 149. 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);

    150. Question 150. What Is Tomcat?

      Answer :

      • Tomcat is a Java Servlet container and web server from the Jakarta project of the Apache software foundation.
      • A web server responds with web pages to requests from client browsers.
      • Web servers can provide dynamic content based on the requests sent by the user.
      • Tomcat is very good at this because it provides both Java servlet and JavaServerPages (JSP) technologies.
      • Tomcat can also be used as a web server for many applications even if free servlet and JSP engine is wanted.
      • It can be used standalone or used behind traditional web servers such as Apache httpd, with the traditional server serving static pages and Tomcat serving dynamic servlet and JSP requests.

    151. Question 151. 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.

    152. Question 152. 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.

    153. Question 153. How Do You Create Multiple Virtual Hosts?

      Answer :

      If you want tomcat to accept requests for different hosts e.g., www.myhostname.com then you must

      0. create ${catalina.home}/www/appBase , ${catalina.home}/www/deploy, and ${catalina.home} /conf /Catalina/www.myhostname.com

      1. add a host entry in the server.xml file
        <Host appBase="www/appBase" name="www.myhostname.com"/>

      2. Create the the following file under conf/Catalina/www.myhostname.com/ROOT.xml

      <?xml version="1.0"  encoding="UTF-8"?>
          reloadable="true" antiJARLocking="true">

      Add any parameters specific to this hosts webapp to this context file

      3. put your war file in ${catalina.home}/www/deploy

      When tomcat starts, it finds the host entry, then looks for any context files and will start any apps with a context.



    154. Question 154. How Will You Load Properties File?

      Answer :

      • Use a ResourceBundle. See the Java docs for the specifics of how the ResourceBundle class works. Using this method, the properties file must go into the WEB-INF/classes directory or in a jar file contained in the WEB-INF/lib directory.
      • Another way is to use the method getResourceAsStream() from the ServletContext class. This allows you update the file without having to reload the webapp as required by the first method. Here is an example code snippet, without any error trapping:
      // Assuming you are in a Servlet extending HttpServlet
      // This will look for a file called "/more/cowbell.properties" relative
      // to your servlet Root Context
      InputStream is = getServletContext().getResourceAsStream("/more/cowbell.properties");
      Properties p = new Properties();

    155. Question 155. Can I Set Java System Properties Differently For Each Webapp?

      Answer :

      No. If you can edit Tomcat's startup scripts, you can add "-D" options to Java. But there is no way to add such properties in web.xml or the webapp's context.

    156. Question 156. How Do I Configure Tomcat To Work With Iis And Ntlm?

      Answer :

      Follow the standard instructions for when the isapi_redirector.dll
      Configure IIS to use "integrated windows security".
      In server.xml, make sure you disable tomcat authentication.

    157. Question 157. How Do I Override The Default Home Page Loaded By Tomcat?

      Answer :

      After successfully installing Tomcat, you usually test it by loading  http://localhost:8080 . The contents of that page are compiled into the index_jsp servlet. The page even warns against modifying the index.jsp files for this reason. Luckily, it is quite easy to override that page. Inside $TOMCAT_HOME/conf/web.xml there is a section called <welcome-file-list> and it looks like this:

              <welcome-file>index.html</welcome-file>         <welcome-file>index.htm</welcome-file>

      The default servlet attempts to load the index.* files in the order listed. You may easily override the index.jsp file by creating an index.html file at $TOMCAT_HOME/webapps/ROOT. It's somewhat common for that file to contain a new static home page or a redirect to a servlet's main page. A redirect would look like:

      <meta http-equiv="refresh" content="0;URL=http://mydomain.com/some/path/to/servlet/homepage/">

      This change takes effect immediately and does not require a restart of Tomcat.


    158. Question 158. How Do I Enable Server Side Includes (ssi)?

      Answer :

      Two things have to be done for tomcat to aknowledge SSI scripts:

      1. Rename $CATALINA_BASE/server/lib/servlets-ssi.renametojar to $CATALINA_BASE/server/lib/servlets-ssi.jar.

      2. Uncomment the section of web.xml found in $CATALINA_BASE/conf/web.xml that deals with SSI. it looks like this when it is uncommented:


    159. Question 159. 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.


    160. Question 160. 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.

    161. Question 161. 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.

    162. Question 162. 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.

    163. Question 163. 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.

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

      Answer :


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

    165. Question 165. 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.

    166. Question 166. 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.

    167. Question 167. 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()

    168. Question 168. 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+)

    169. Question 169. 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.

    170. Question 170. 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.

    171. Question 171. 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.

    172. Question 172. The Code In A Finally Clause Will Never Fail To Execute, Right?

      Answer :

      Using System.exit(1); in try block will not allow finally code to execute.

    173. Question 173. 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.

    174. Question 174. 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.

    175. Question 175. 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.

    176. Question 176. 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.

    177. Question 177. 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.

    178. Question 178. Which Interface Must Be Implemented By All Servlets?

      Answer :

      Servlet interface.

    179. Question 179. 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.

    180. Question 180. 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.

    181. Question 181. Why Don't We Write A Constructor In A Servlet?

      Answer :

      Container writes a no argument constructor for our servlet.

    182. Question 182. 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().

    183. Question 183. Once The Destroy() Method Is Called By The Container, Will The Servlet Be Immediately Destroyed? What Happens To The Tasks(threads) That The Servlet Might Be Executing At That Time?

      Answer :

      Yes, but Before calling the destroy() method, the servlet container waits for the remaining threads that are executing the servlet’s service() method to finish.

    184. Question 184. What Is The Difference Between Callling A Requestdispatcher Using Servletrequest And Servletcontext?

      Answer :

      We can give relative URL when we use ServletRequest and not while using ServletContext.

    185. Question 185. Why Is It That We Can't Give Relative Url's When Using Servletcontext.getrequestdispatcher() When We Can Use The Same While Calling Servletrequest.getrequestdispatcher()?

      Answer :

      Since ServletRequest has the current request path to evaluae the relative path while ServletContext does not.

    186. Question 186. Explain The Life Cycle Methods Of A Servlet?

      Answer :

      The javax.servlet.Servlet interface defines the three methods known as life-cycle method.

      public void init(ServletConfig config) throws ServletException
      public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
      public void destroy()

      First the servlet is constructed, then initialized wih the init() method.Any request from client are handled initially by the service() method before delegating to thedoXxx() methods in the case of HttpServlet.

      The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.

    187. Question 187. What Is The Difference Between The Getrequestdispatcher(string Path) Method Of Javax.servlet.servletrequest Interface And Javax.servlet.servletcontext Interface?

      Answer :

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

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

    188. Question 188. Explain The Directory Structure Of A Web Application?

      Answer :

      The directory structure of a web application consists of two parts.

      • A private directory called WEB-INF
      • A public resource directory which contains public resource folder.

      WEB-INF folder consists of

      1. web.xml
      2. classes directory
      3. lib directory.

    189. Question 189. What Are The Common Mechanisms Used For Session Tracking?

      Answer :

      • Cookies
      • SSL sessions
      • URL- rewriting.

    190. Question 190. Explain Servletcontext?

      Answer :

      ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.

    191. Question 191. What Is Preinitialization Of A Servlet?

      Answer :

      A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

    192. Question 192. What Is The Difference Between Difference Between Doget() And Dopost()?

      Answer :

      A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation.
      doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string.

    193. Question 193. What Is The Difference Between Httpservlet And Genericservlet?

      Answer :

      A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract.

    194. Question 194. What Is The Difference Between Servletcontext And Servletconfig?

      Answer :

      ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.

      ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet.

    195. Question 195. What Are The Type Of Protocols Supported By Httpservlet?

      Answer :

      It extends the GenericServlet base class and provides an framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.

    196. Question 196. What Are The Directory Structure Of Web Application?

      Answer :

      Web component follows the standard directory structure defined in the J2EE specification.

      Directory Structure of Web Component
      / index.htm, JSP, Images etc..
            servlet classes
            jar files

    197. Question 197. What Is Servletcontext?

      Answer :

      ServletContext is an Interface that defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.)

    198. Question 198. What Do You Understand By Servlet Mapping?

      Answer :

      Servlet mapping defines an association between a URL pattern and a servlet. You can use one servlet to process a number of url pattern (request pattern). For example in case of Struts *.do url patterns are processed by Struts Controller Servlet.

    199. Question 199. What Must Be Implemented By All Servlets?

      Answer :

      The Servlet Interface must be implemented by all servlets.

    200. Question 200. What Are The Differences Between Servlet And Applet?

      Answer :

      Servlets are server side components that runs on the Servlet container. Applets are client side components and runs on the web browsers. Servlets have no GUI interface.

    201. Question 201. What Are The Uses Of Servlets?

      Answer :

      • Servlets are used to process the client request.
      • A Servlet can handle multiple request concurrently and be used to develop high performance system.
      • A Servlet can be used to load balance among serveral servers, as Servlet can easily forward request.

    202. Question 202. What Are The Objects That Are Received When A Servlets Accepts Call From Client?

      Answer :

      The objects are ServeltRequest and ServletResponse . The ServeltRequest encapsulates thecommunication from the client to the server. While ServletResponse encapsulates the communication from the Servlet back to the client.

    203. Question 203. What Is Servlets And Explain The Advantages Of Servlet Life Cycle?

      Answer :

      Servlets are modules that run within the server and receive and respond to the requests made by the client. Servlets retrieve most of the parameters using the input stream and send their responses using an output stream.

      Servlets are used to extend the server side functionality of a website. They communicate with various application on the server side and respond to the request made by the client.

    204. Question 204. What Are The General Advantages And Selling Points Of Servlets?

      Answer :

      Servlets exhibit the following characteristics:

      • Can handle multiple requests concurrently.
      • Can synchronize requests.
      • can forward requests to other servers and servlets.
      • Portable (Servlets are written in the Java programming language and follow a standard API).
      • They are Secure (Like CGI, they don’t run shell and memory overflow, etc is handled by Java).
      • Inexpensive (There are a number of free or very inexpensive Web servers that are good for development use or deployment of low- or medium-volume Web sites).

    205. Question 205. Whats The Advantages Using Servlets Over Using Cgi?

      Answer :

      CGI programs run outside the webserver. So a new process must be started to execute a CGI program. CGI programs are designed to handle a single request at a time. After that they return the result to the web server and exit.

      On the other hand servlets can handle multiple requests concurrently. They run within web servers. They generate dynamic content that is easier to write and faster to run.

    206. Question 206. What Are Different Authentication Options Available In Servlets?

      Answer :

      There are four ways of Authentication options available in servlets
      HTTP basic authentication
      In this, server uses the username and password provided by the client and these credentials are transmitted using simple base64 encoding.
      HTTP digest authentication
      This option is same the basic authentication except the password is encrypted and transmitted using SHA or MD5.
      HTTPS client authentication
      This options is based on HTTP over SSL.
      Form-based authentication
      Form-based authentication uses login page to collect username and password.

    207. Question 207. Explain Why Httpservlet Is Declared Abstract.

      Answer :

      The Constructor HttpServlet() does nothing because this is an abstract class. Default implementations in a few Java classes like HttpServlet don’t really do anything. Hence, they need to be overridden.

      Usually one of the following methods of HttpServlet must be overridden by a subclass:

      doGet, if the servlet supports HTTP GET requests
      doPost, HTTP POST requests
      doPut, HTTP PUT requests
      doDelete, HTTP DELETE requests
      init and destroy, to manage resources
      getServletInfo, to provide information

      However, there doesn’t seem to be any reason why the service method should be overridden because it eventually dispatches the task to one of the doXXX methods.

    208. Question 208. What Is The Genericservlet Class?

      Answer :

      GenericServlet makes writing servlets easier. To write a generic servlet, all you need to do is to override the abstract service method.

    209. Question 209. Is Possible To Have A Constructor For A Servlet?

      Answer :

      Yes, it is possible to have a constructor for a servlet. However, it is not practiced usually. The operations with the constructor can be performed as usual just that it cannot be called explicitly using the ‘new’ keyword. This is implicitly handled by the servlet container. Thus, the container performs initialization as well as constructor functions.

    210. Question 210. What Is The Difference Between An Applet And A Servlet?

      Answer :


      • Applets are applications designed to be transmitted over the network and executed by Java compatible web browsers.
      • An Applet is a client side java program that runs within a Web browser on the client machine.
      • An applet can use the user interface classes like AWT or Swing.
      • Applet Life Cycle Methods: init(), stop(), paint(), start(), destroy().


      • Servlets are Java based analog to CGI programs, implemented by means of servlet container associated with an HTTP server.
      • Servlet is a server side component which runs on the web server.
      • The servlet does not have a user interface.
      • Servlet Methods: doGet(), doPost() .

    211. Question 211. Define Http Tunneling?

      Answer :

      In some organizations, the intranet is blocked by a firewall to the internet. It is exposed to the outer networks only by means of webserver port that accept only Http requests. In such situations, if protocols other than http are used, then they get rejected. The solution is to have them encapsulated in http or https and sent as an HttpRequest. Thus, masking other protocols as http requests is called HTTP Tunneling.

    212. Question 212. List Out The Difference Between Servletconfig And Servletcontext?

      Answer :

      Both are interfaces in the package javax.servlet.

      • ServletConfig is a servlet configuration object. It is used by a servlet container to pass information to a servlet during initialization.
      • The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets.
      • The ServletContext object is contained within the ServletConfig object. It is provided by the web server to the servlet when the servlet is initialized.
      • ServletContext is an interface which has a set of methods like getServletName(), getServletContext(), getInitParameter(), getInitParameterNames(). The servlet uses to interact with its servlet container.
      • ServletContext is common to all servlets within the same web application. So, servlets use ServletContext to share context information.

    213. Question 213. What Is The Difference Between Using Getsession(true) And Getsession(false) Methods?

      Answer :

      getSession(true) will check whether a session already exists for the user. If yes, it will return that session object else it will create a new session object and return it.

      getSession(false) will check existence of session. If session exists, then it returns the reference of that session object, if not, this methods will return null.

    214. Question 214. List Out Difference Between A Javabean From A Servlet?

      Answer :

      Servlets are Java based analog to CGI programs, implemented by means of a servlet container associated with an HTTP server. Servlets run on the server side. Beans are reusable code components written in Java that one can use in a variety of programming environments. JavaBeans are to Java what ActiveX controls are to Microsoft. Javabeans can run on server side, client side, within an applet etc.
      So, both have nothing in common except Java.

    215. Question 215. Explain How Servlets Differ From Rmi. Explain The Advantages And Disadvantages Of Each Technology.

      Answer :

      RMI (Remote Method Invocation) are a means of client server communication. In this, the client invokes a method on the server machine and the server machine process returns the result back to the client. We need to run RMI registry to use RMI.

      Servlets are used to extend the server side functionality of a website. They communicate with various application on the server side and respond to the request made by the client. Servlets are modules that run within the server and receive and respond to the requests made by the client. Servlets retrieve most of the parameters using the input stream and send their responses using an output stream.

    216. Question 216. What Is Cdma One ?

      Answer :

      Also know as IS-95, CDMA One is a 2nd generation wireless technology. Supports speeds from 14.4Kbps to 115K bps.

    217. Question 217. What Is Project Glassfish?

      Answer :

      GlassFish is the name for the open source development project for building a Java EE 5 application server. It is based on the source code for Sun Java System Application Server PE 9 donated by Sun Microsystems and TopLink persistence code donated by Oracle. This project provides a structured process for developing a high quality application server that makes new features available faster than ever before. It is the response to Java developers who want access to the source code and the ability to contribute to the development of Sun’s next generation application server which is based on GlassFish. This project is designed to encourage communication between Sun and Oracle engineers and the community and will enable all developers to participate in the application server development process.

    218. Question 218. What Is Available On The Website?

      Answer :

      Nightly builds and the source code for the application server are available. As with other community development sites, you will also find email lists, discussion forums, news, feedback, licensing information, and extensive help resources.

    219. Question 219. How Large Is The Glassfish Community?

      Answer :

      The GlassFish development community is just getting started so it is small but rapidly growing. There are over 100 contributors already signed up. The number of Sun and Oracle engineers working on this product is comparable in size to other application server developer communities today. With the release of project GlassFish to the community, we expect to greatly increase the number of developers working on the code.

    220. Question 220. Can I As A Developer Make Any Changes I Want To The Code?

      Answer :

      Yes, developers have free access to the source code under the terms of the Common Development and Distribution License (CDDL) v1.0 and are free to change it as they see fit. To be able to claim Java Compatibility, developers of commercial distributions will need to sign the Java Developer License (JDL) and verify the code passes the compatibility test suite (CTS) before they can redistribute it. Anyone can sign a contribution agreement and work on the code to contribute changes, bug fixes, and features.

    221. Question 221. How Often Can I Get An Update Of Glassfish?

      Answer :

      Updated builds for GlassFish will be posted every night to glassfish.dev.java.net. These code pushes have gone through very basic testing to ensure they will build and execute but have not been tested as thoroughly as our production releases. Additionally, you have read access to the same CVS tree that the developers do – so you always see the latest versions of the code there. Occasionally, typically weekly or so, we will push a “promoted” build which has been more thoroughly tested and will contain many more documented features than the regular nightly builds. A supported Beta and FCS version of the Sun Java System Application Server 9.0 which is built on GlassFish.

    222. Question 222. What Version Of Java Ee Does This Apply To?

      Answer :

      GlassFish will implement the latest version of the Java EE platform, Java EE 5, and the two should become final at around the same time. At that time Sun will also release a final, supported and compatible Sun Java System Application Server PE 9.0 based on GlassFish.

    223. Question 223. What Is Being Released And When?

      Answer :

      In June of 2005, Sun published project GlassFish by making the web site available to the public. Developers can access source code, nightly builds, discussion groups, and mailing lists. This is the first time developers were able to see and participate in the Application Server development process. Over the next 6 months, Sun will gradually roll out more information and more details about the code. Initially, access will be provided to the web-tier followed by other modules as GlassFish is developed.

    224. Question 224. How Does This Impact Java Ee Licensees?

      Answer :

      Project GlassFish opens up Java EE to a larger audience that will ultimately be the customers of the Java EE licensees. GlassFish does not change any of the license terms for licensees. Under their license terms, licensees can still sell or distribute code and use the Java Compatibility brand for products which have passed the TCK. Under the license terms of the CDDL, which is granted to developers, they can use, edit, and alter the code, and distribute it or use it in production. However they do not have a license to use the CTS nor can they use the Java Compatibility brand.

    225. Question 225. What Are The Licensing Terms?

      Answer :

      The OSI-approved CDDL license is being used for project GlassFish which allows developers to view, use, edit, and alter the code, and distribute it or use it in production. Portions of this code are not yet available in source form. Because of this, a few portions are currently also under a Binary Distribution License. As time goes on, we’ll make more of the code available, with the eventual goal of making all the code available, and removing the Binary Distribution license. This isn’t some sort of evil plot – it’s hard work moving stuff out into an Open environment, we expect to have a roadmap for our timing for this published by the end of the Summer.

      People who want to redistribute a build of our application server do not have a license to use the CTS nor can they use the Java Compatibility brand. They may choose to sign a JDL commercial license and pass the CTS which would then allow them to distribute the code and use the Java Compatibility brand.

    226. Question 226. I Am A Current Scsl Licensee, And Want To Use The Cddl. Can I Do This?

      Answer :

      Yes. Current SCSL licensees can choose to use the CDDL, but they must click through the new license, and use the CDDL notification in their work.

    227. Question 227. How To Call A Stored Procedure From Jdbc?

      Answer :

      The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure.
      CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");

    228. Question 228. What Class.forname Will Do While Loading Drivers?

      Answer :

      It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.

    229. Question 229. What Is Relational Database?

      Answer :

      Either as a programmer or a user, you have probably interacted with a database before. A database is simply a program that makes it easy to store and retrieve data. The data can be numeric, string or more complex objects, such as a video database. A relational database is one implementation of a database—one that organizes data in tables.

      A table is made up of rows and columns. In relational database terminology, the table is called a file, a row is called a record and a column is called afield. One of the features of a relational database is that you can retrieve the data by its content. For example, assume you have a relational database with a table made up of two fields, one for names and another for phone numbers. To retrieve data by content means that you can simply ask the database to retrieve a phone number for a particular name. You do not have to specify an explicit row and column to get a data element.

    230. Question 230. Explain The Sql?

      Answer :

      SQL (Structured Query Language) is a high-level language that hides particular relational database's implementation. SQL provides a standard database interface. Using SQL, your program is not stuck with one particular vendor's database management system (DBMS). Ideally, you can change from one DBMS to another without changing your application. In reality, however, each vendor's interpretation of SQL is slightly different, so switching from one DBMS to another normally requires some work.

      SQL is officially pronounced "ess-cue-ell," but most people call it "sequel." You use SQL to interact with relational databases. There are three main operations that you may want to perform with a database: database manipulation, definition, and administration. We shall focus on database manipulation, that is, data retrieval and modification. The other operations database definition and administration, correspond to database creation and management, which most users are not in a position to perform.

    231. Question 231. How Applet Restrictions Affect Jdbc? Explain.

      Answer :

      As you have learned, a Java applet can only connect to the server from which the user downloaded the applet. In addition, some browser, such as Netscape, do not let an applet write or read local files. Therefore, a database applet cannot write search result to a file or insert data into a database. You must take these restrictions into consideration when you design an applet that is going to access a database.

    232. Question 232. How To Set A Parameter To Null?

      Answer :

      As you have learned within a database, the null value is a valid field value. Sometimes, depending on your database contents, you will want to set a parameter within a prepare statement to null There are two ways that you can do this. First, you can pass null as an argument to any of the setx methods. The JDBC, in turn, will set the data field to null. Second, you can call the setNull method.

    233. Question 233. What Is The Java.sql.timestamp Class?

      Answer :

      Within a Java database, you can use the TIMESTAMP type to store a time with a resolution in nanoseconds. Java's Date class, on the other hand, only measures to milliseconds. Therefore, the JDBC developers have made a java.sql.Timestamp class. This new Timestamp class extends the java.util. Date class by adding a nanosecond variable to store the time-stamp information.

    234. Question 234. How To Serialize Objects With Multiple References?

      Answer :

      When you serialize objects that your program references multiple times, you should write the object only one time. To do this, you can use a hashtable to keep track of the object that you have written. When you write an object for the first time, you add its reference to the hashtable along with a unique ID value. The ID can be any numeric value. You write the object's class name and ID value to the stream, followed by the object itself. If your program encounters the object a second time, you only write the name of the object and ID value to the stream.

    235. Question 235. How To Deserialize Objects With Multiple References?

      Answer :

      When you deserialize objects that you have referenced multiple times, you should reconstruct the objects only once. You should use a hashtable to keep track of objects that you must reconstruct. When you read an object for the first time, you add the reference to the hashtable along with the object's ID value. If you encounter the object a second time, you use the reference that is stored in the hashtable.

    236. Question 236. What Is Stored Procedure?

      Answer :

      Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters.

    237. Question 237. What Does A Thread Enter When It Terminates Its Processing?

      Answer :

      When a thread terminates its processing, it enters the dead state.

    238. Question 238. What Is Servlet Chaining?

      Answer :

      Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request. In servlet chaining, one servlet's output is piped to the next servlet's input. This process continues until the last servlet is reached. Its output is then sent back to the client.

    239. Question 239. What Is Inet Address?

      Answer :

      Every computer connected to a network has an IP address. An IP address is a number that uniquely identifies each computer on the Net. An IP address is a 32-bit number.

    240. Question 240. What Is Unicastremoteobject?

      Answer :

      All remote objects must extend UnicastRemoteObject, which provides functionality that is needed to make objects available from remote machines.

Popular Interview Questions

All Interview Questions

Jdbc Practice Test

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

JDBC Tutorial