Sunday, April 28, 2013

Java Database Connectivity

What is JDBC?
JDBC may stand for Java Database Connectivity. It is also a trade mark. JDBC is a layer of abstraction that allows users to choose between databases. It allows you to change to a different database engine and to write to a single API. JDBC allows you to write database applications in Java without having to concern yourself with the underlying details of a particular database.
xxxxxxxxxxxxxxxxxxxx
What's the JDBC 3.0 API?
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.
xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Can the JDBC-ODBC Bridge be used with applets?
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.
xxxxxxxxxxxxxxxxx
Can the JDBC-ODBC Bridge be used with applets?
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.
xxxxxxxxxxxxxxxxxxxxxxxxxx
What is new in JDBC 2.0?
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.
xxxxxxxxxxxxxxxxxxxxxxxxxx
How to move the cursor in scrollable resultsets?(new feature in JDBC 2.0)
a. create a scrollable ResultSet object.
Statement stmt = con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,
         ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery("SELECT COLUMN_1,
         COLUMN_2 FROM TABLE_NAME");
b. use a built in methods like afterLast(), previous(), beforeFirst(), etc. to scroll the resultset.
    srs.afterLast();
    while (srs.previous()) {
        String name = srs.getString("COLUMN_1");
        float salary = srs.getFloat("COLUMN_2");
        //...
c. to find a specific row, use absolute(), relative() methods.
    srs.absolute(4); // cursor is on the fourth row
    int rowNum = srs.getRow(); // rowNum should be 4
    srs.relative(-3);
    int rowNum = srs.getRow(); // rowNum should be 1
    srs.relative(2);
    int rowNum = srs.getRow(); // rowNum should be 3
d. use isFirst(), isLast(), isBeforeFirst(), isAfterLast() methods to check boundary status.
xxxxxxxxxxxxxxxx
How to update a resultset programmatically? (new feature in JDBC 2.0)
a. create a scrollable and updatable ResultSet object.
Statement stmt = con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery("SELECT COLUMN_1,
COLUMN_2 FROM TABLE_NAME");
b. move the cursor to the specific position and use related method to update data and then, call updateRow() method.
uprs.last();
uprs.updateFloat("COLUMN_2", 25.55);//update last row's data
uprs.updateRow();//don't miss this method, otherwise,
// the data will be lost.
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
How can I use the JDBC API to access a desktop database like Microsoft Access over the network?
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 fre
xxxxxxxxxxxxxxxxxx
Are there any ODBC drivers that do not work with the JDBC-ODBC Bridge?
Most ODBC 2.0 drivers should work with the Bridge. Since there is some variation in functionality between ODBC drivers, the functionality of the bridge may be affected. The bridge works with popular PC databases, such as Microsoft Access and FoxPro
xxxxxxxxxxxxxxxxxxx
What causes the "No suitable driver" error?
"No suitable driver" is an error that usually occurs during a call to the DriverManager.getConnection method. The cause can be failing to load the appropriate JDBC drivers before calling the getConnection method, or it can be specifying an invalid JDBC URL--one that isn't recognized by your JDBC driver. Your best bet is to check the documentation for your JDBC driver or contact your JDBC driver vendor if you suspect that the URL you are specifying is not being recognized by your JDBC driver.
In addition, when you are using the JDBC-ODBC Bridge, this error can occur if one or more the the shared libraries needed by the Bridge cannot be loaded. If you think this is the cause, check your configuration to be sure that the shared libraries are accessible to the Bridge.
xxxxxxxxxxxxxxxxxxxxxxx
Why isn't the java.sql.DriverManager class being found?
This problem can be caused by running a JDBC applet in a browser that supports the JDK 1.0.2, such as Netscape Navigator 3.0. The JDK 1.0.2 does not contain the JDBC API, so the DriverManager class typically isn't found by the Java virtual machine running in the browser.
Here's a solution that doesn't require any additional configuration of your web clients. Remember that classes in the java.* packages cannot be downloaded by most browsers for security reasons. Because of this, many vendors of all-Java JDBC drivers supply versions of the java.sql.* classes that have been renamed to jdbc.sql.*, along with a version of their driver that uses these modified classes. If you import jdbc.sql.* in your applet code instead of java.sql.*, and add the jdbc.sql.* classes provided by your JDBC driver vendor to your applet's codebase, then all of the JDBC classes needed by the applet can be downloaded by the browser at run time, including the DriverManager class.
This solution will allow your applet to work in any client browser that supports the JDK 1.0.2. Your applet will also work in browsers that support the JDK 1.1, although you may want to switch to the JDK 1.1 classes for performance reasons. Also, keep in mind that the solution outlined here is just an example and that other solutions are possible.

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
How to insert and delete a row programmatically? (new feature in JDBC 2.0)
Make sure the resultset is updatable.

1. move the cursor to the specific position.

   uprs.moveToCurrentRow();

2. set value for each column.

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

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

   uprs.insertRow();

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

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

To see the changes call refreshRow();

   uprs.refreshRow();
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
What are the two major components of JDBC?
One implementation interface for database manufacturers, the other implementation interface for application and applet writers.
xxxxxxxxxxxxxxxxxxxxxxxxxx
How do I retrieve a whole row of data at once, instead of calling an individual ResultSet.getXXX method for each column?
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.
xxxxxxxxxxxxxxxxxxxx
What are the common tasks of JDBC?
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
XXXXXXXXXXXXXXXXXxxxx
Why does the ODBC driver manager return 'Data source name not found and no default driver specified Vendor: 0'
This type of error occurs during an attempt to connect to a database with the bridge. First, note that the error is coming from the ODBC driver manager. This indicates that the bridge-which is a normal ODBC client-has successfully called ODBC, so the problem isn't due to native libraries not being present. In this case, it appears that the error is due to the fact that an ODBC DSN (data source name) needs to be configured on the client machine. Developers often forget to do this, thinking that the bridge will magically find the DSN they configured on their remote server machine
xxxxxxxxxxxxxxxxxx
What are four types of JDBC driver?
Type 1 Drivers

Bridge drivers such as the jdbc-odbc bridge. They rely on an intermediary such as ODBC to transfer the SQL calls to the database and also often rely on native code. It is not a serious solution for an application
Type 2 Drivers

Use the existing database API to communicate with the database on the client. Faster than Type 1, but need native code and require additional permissions to work in an applet. Client machine requires software to run.
Type 3 Drivers

JDBC-Net pure Java driver. It translates JDBC calls to a DBMS-independent network protocol, which is then translated to a DBMS protocol by a server. Flexible. Pure Java and no native code.
Type 4 Drivers

Native-protocol pure Java driver. It converts JDBC calls directly into the network protocol used by DBMSs. This allows a direct call from the client machine to the DBMS server. It doesn't need any special native code on the client machine.
Recommended by Sun's tutorial, driver type 1 and 2 are interim solutions where direct pure Java drivers are not yet available. Driver type 3 and 4 are the preferred way to access databases using the JDBC API, because they offer all the advantages of Java technology, including automatic installation. For more info, visit Sun JDBC

xxxxxxxxxxxxxxxxx
Which type of JDBC driver is the fastest one?
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.
xxxxxxxx
Are all the required JDBC drivers to establish connectivity to my database part of the JDK?
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
xxxxxxxxxxxxxxxx
Is the JDBC-ODBC Bridge multi-threaded?
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.
xxxxxxxxxxxxxx
Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?
No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.
xxxxxxxxxxxxxxxxxxxx
What is the query used to display all tables names in SQL Server (Query analyzer)?
select * from information_schema.tables
xxxxxxxxxxxxxxxxxxxxxx
Why can't I invoke the ResultSet methods afterLast and beforeFirst when the method next works?
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
xxxxxxxxxxxxxxxxxxxxxxxx
How can I retrieve a String or other object type without creating a new object each time?
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. Stay tuned, and please send us any comments you have on this question
xxxxxxxxxxx
How many types of JDBC Drivers are present and what are they?
There are 4 types of JDBC Drivers
Type 1: JDBC-ODBC Bridge Driver
Type 2: Native API Partly Java Driver
Type 3: Network protocol Driver
Type 4: JDBC Net pure Java Driver
xxxxxxxxxxxxxxxxxxx
What is the fastest type of JDBC driver?
JDBC driver performance will depend on a number of issues:
(a) the quality of the driver code,
(b) the size of the driver code,
(c) the database server and its load,
(d) network topology,
(e) 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).
xxxxxxxxxxxxxxxxxxxxxx
There is a method getColumnCount in the JDBC API. Is there a similar method to find the number of rows in a result set?
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
xxxxxxxxxxxxxxxxxxxxx
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?
The JDBC-ODBC Bridge is bundled with the Java 2 SDK, Standard Edition, so there is no need to download it separately.
xxxxxx
If I use the JDBC API, do I have to use ODBC underneath?
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.
xxxxxxxxxxxx
Once I have the Java 2 SDK, Standard Edition, from Sun, what else do I need to connect to a database?
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.
xxxxxxxxxxxxxxxxxxx
How do I insert a .jpg into a mySQL data base?
How do I insert a .jpg into a mySQL data base?
I have tried inserting the file as byte[],
but I recieve an error message stating
that the syntax is incorrect.


Binary data is stored and retrieved from
the database using streams in connection
with prepared statements and resultsets.
This minimal application stores an image
file in the database, then it retrieves
the binary data from the database and converts
it back to an image.

import java.sql.*;
import java.io.*;
import java.awt.*;
import java.awt.Image;

/**
 * Storing and retrieving images from
 *a MySQL database
 */
public class StoreBinary {
private static String driverName =
"sun.jdbc.odbc.JdbcOdbcDriver";
  private Statement stmt = null;
  private Connection conn = null;

  public StoreBinary() {}
  /**
   * Strips path prefix from filenames
   * @param fileName
   * @return the base filename
   */
public static String getBaseName(String fileName) {
    int ix=fileName.lastIndexOf("\\");
    if (ix < 0) return fileName;
    return fileName.substring(ix+1);
  }
  /**
* Store a binary (image) file in the database using a
   * prepared statement.
   * @param fileName
   * @return true if the operation succeeds
   * @throws Exception
   */
public boolean storeImageFile
(String fileName) throws Exception {
    if (!connect("test", "root", "")) {
      return false;
    }

FileInputStream in = new FileInputStream(fileName);
    int len=in.available();
String baseName=StoreBinary.getBaseName(fileName);
PreparedStatement pStmt = conn.prepareStatement
("insert into image_tab values (?,?,?)");
    pStmt.setString(1, baseName);
    pStmt.setInt(2,len);
    pStmt.setBinaryStream(3, in, len);
    pStmt.executeUpdate();
    in.close();
System.out.println("Stored: "+baseName+", length: "+len);
    return true;
  }
  /**
   * Retrieve the biary file data from
   * the DB and convert it to an image
   * @param fileName
   * @return
   * @throws Exception
   */
public Image getImageFile(String fileName)
throws Exception {
String baseName=StoreBinary.getBaseName(fileName);
   
ResultSet rs=stmt.executeQuery("select * from image_tab
    where image_name='"+baseName+"'");
   
    if (!rs.next()) {
System.out.println("Image:"+baseName+" not found");
      return null;
    }
    int len=rs.getInt(2);

    byte [] b=new byte[len];
    InputStream in = rs.getBinaryStream(3);
    int n=in.read(b);
    System.out.println("n: "+n);
    in.close();
    Image img=Toolkit.getDefaultToolkit().createImage(b);
System.out.println("Image: "+baseName+"
retrieved ok, size: "+len);
    return img;
  }
  /**
   * Establish database connection
   * @param dbName
   * @param dbUser
   * @param dbPassword
   * @return true if the operation succeeds
   */
public boolean connect(String dbName,
String dbUser, String dbPassword) {
    try {
      Class.forName(driverName);
    }
    catch (ClassNotFoundException ex) {
      ex.printStackTrace();
      return false;
    }
    try {
conn = DriverManager.getConnection("jdbc:odbc:" + dbName,
                                     dbUser,
                                     dbPassword);
      stmt = conn.createStatement();
    }
    catch (SQLException ex1) {
      ex1.printStackTrace();
      return false;
    }
    return true;
  }

  /******************************************
   * MAIN stub driver for testing the class.
   */
  public static void main(String[] args) {
    String fileName="c:\\tmp\\f128.jpg";
    StoreBinary sb = new StoreBinary();
    try {
      if (sb.storeImageFile(fileName)) {
        // stored ok, now get it back again
        Image img=sb.getImageFile(fileName);
      }
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}
xxxxxxxxxxxxxxxxxx
Whan happens when I close a Connection application obtained from a connection Pool? How does a connection pool maintain the Connections that I had closed through the application?
Answer1
It is the magic of polymorphism, and of Java interface vs. implementation types. Two objects can both be "instanceof" the same interface type, even though they are not of the same implementation type.
When you call "getConnection()" on a pooled connection cache manager object, you get a "logical" connection, something which implements the java.sql.Connection interface.
But it is not the same implementation type as you would get for your Connection, if you directly called getConnection() from a (non-pooled/non-cached) datasource.
So the "close()" that you invoke on the "logical" Connection is not the same "close()" method as the one on the actual underlying "physical" connection hidden by the pool cache manager.
The close() method of the "logical" connection object, while it satisfies the method signature of close() in the java.sql.Connection interface, does not actually close the underlying physical connection.

Answer2
Typically a connection pool keeps the active/in-use connections in a hashtable or other Collection mechanism. I've seen some that use one stack for ready-for-use, one stack for in-use.
When close() is called, whatever the mechanism for indicating inuse/ready-for-use, that connection is either returned to the pool for ready-for-use or else physically closed. Connections pools should have a minimum number of connections open. Any that are closing where the minimum are already available should be physically closed.
Some connection pools periodically test their connections to see if queries work on the ready-for-use connections or they may test that on the close() method before returning to the ready-for-use pool.
xxxxxxxxxxxxxxx
How can I know when I reach the last record in a table, since JDBC doesn't provide an EOF method?
Answer1
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.

Answer2
Assuming you mean ResultSet instead of Table, the usual idiom for iterating over a forward only resultset is:
ResultSet rs=statement.executeQuery(...);
while (rs.next()) {
// Manipulate row here
}
xxxxxxxxxxxxxxxxxx
Where can I find info, frameworks and example source for writing a JDBC driver?
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.
xxxxxxxxxxxx
How can I create a custom RowSetMetaData object from scratch?
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 RowSetMetaData,
xxxxxxxxxxxxxxx
How does a custom RowSetReader get called from a CachedRowSet?
The Reader must be registered with the CachedRowSet using CachedRowSet.setReader(javax.sql.RowSetReader reader). Once that is done, a call to CachedRowSet.execute() will, among other things, invoke the readData method.
xxxxxxxxxxxxx
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?
"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.
xxxxxxxxxxxxxxxxxxxxx
How can I instantiate and load a new CachedRowSet object from a non-JDBC source?
The basics are:
* Create an object that implements javax.sql.RowSetReader, which loads the data.
* Instantiate a CachedRowset object.
* Set the CachedRowset's reader to the reader object previously created.
* Invoke CachedRowset.execute().

Note that a RowSetMetaData object must be created, set up with a description of the data, and attached to the CachedRowset before loading the actual data.
The following code works with the Early Access JDBC RowSet download available from the Java Developer Connection and is an expansion of one of the examples:
// Independent data source CachedRowSet Example
import java.sql.*;
import javax.sql.*;
import sun.jdbc.rowset.*;


public class RowSetEx1 implements RowSetReader
{
  CachedRowSet crs;
  int iCol2;
  RowSetMetaDataImpl rsmdi;
  String sCol1,
         sCol3;

     
  public RowSetEx1()
  {
    try
    {
      crs = new CachedRowSet();
      crs.setReader(this);
      crs.execute();  // load from reader

      System.out.println(
        "Fetching from RowSet...");
      while(crs.next())
      {
        showTheData();
      } // end while next
           
      if(crs.isAfterLast() == true)
      {
        System.out.println(
          "We have reached the end");
        System.out.println("crs row: " +
                            crs.getRow());
      }
           
      System.out.println(
        "And now backwards...");
           
      while(crs.previous())
      {
        showTheData();
      }  // end while previous
           
      if(crs.isBeforeFirst() == true)
      { System.out.println(
          "We have reached the start");
      }
           
      crs.first();
      if(crs.isFirst() == true)
      { System.out.println(
          "We have moved to first");
      }

      System.out.println("crs row: " +
                          crs.getRow());

      if(crs.isBeforeFirst() == false)
      { System.out.println(
          "We aren't before the first row."); }

      crs.last();
      if(crs.isLast() == true)
      { System.out.println(
          "...and now we have moved to the last");
      }

      System.out.println("crs row: " +
                          crs.getRow());

      if(crs.isAfterLast() == false)
      {
        System.out.println(
          "we aren't after the last.");
      }

    } // end try
    catch (SQLException ex)
    {
      System.err.println("SQLException: " +
         ex.getMessage());
    }
                 
  }  // end constructor



  public void showTheData() throws SQLException
  {
    sCol1 = crs.getString(1);
    if(crs.wasNull() == false)
    { System.out.println("sCol1: " + sCol1); }
    else { System.out.println("sCol1 is null"); }
               
    iCol2 = crs.getInt(2);
    if (crs.wasNull() == false)
    { System.out.println("iCol2: " + iCol2); }
    else { System.out.println("iCol2 is null"); }   

    sCol3 = crs.getString(3);
    if (crs.wasNull() == false)
    {
      System.out.println("sCol3: " +
                          sCol3    + "\n" );
    }
    else
    { System.out.println("sCol3 is null\n"); }

  }  // end showTheData



  // RowSetReader implementation
  public void readData(RowSetInternal caller)
                 throws SQLException
  {
      rsmdi = new RowSetMetaDataImpl();
      rsmdi.setColumnCount(3);
      rsmdi.setColumnType(1, Types.VARCHAR);
      rsmdi.setColumnType(2, Types.INTEGER);
      rsmdi.setColumnType(3, Types.VARCHAR);
      crs.setMetaData( rsmdi );
          
      crs.moveToInsertRow();
     
      crs.updateString( 1, "StringCol11" );
      crs.updateInt( 2, 1 );
      crs.updateString( 3, "StringCol31" );
      crs.insertRow();

      crs.updateString( 1, "StringCol12" );
      crs.updateInt( 2, 2 );
      crs.updateString( 3, "StringCol32" );
      crs.insertRow();

      crs.moveToCurrentRow();
      crs.beforeFirst();

  } // end readData
   


  public static void main(String args[])
  {
    new RowSetEx1();
  }

} // end class RowSetEx1
xxxxxxxxxxxxxx
Can I set up a conection pool with multiple user IDs? The single ID we are forced to use causes probelems when debugging the DBMS.
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.
xxxxxxxxxxxxxxxxxxxxxxxxxxx
How can I protect my database password ? I'm writing a client-side java application that will access a database over the internet. I have concerns about the security of the database passwords. The client will have access in one way or another to the class files, where the connection string to the database, including user and password, is stored in as plain text. What can I do to protect my passwords?
This is a very common question.
Conclusion: JAD decompiles things easily and obfuscation would not help you. But you'd have the same problem with C/C++ because the connect string would still be visible in the executable.
SSL JDBC network drivers fix the password sniffing problem (in MySQL 4.0), but not the decompile problem. If you have a servlet container on the web server, I would go that route (see other discussion above) then you could at least keep people from reading/destroying your mysql database.
Make sure you use database security to limit that app user to the minimum tables that they need, then at least hackers will not be able to reconfigure your DBMS engine.
Aside from encryption issues over the internet, it seems to me that it is bad practise to embed user ID and password into program code. One could generally see the text even without decompilation in almost any language. This would be appropriate only to a read-only database meant to be open to the world. Normally one would either force the user to enter the information or keep it in a properties file.
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Detecting Duplicate Keys I have a program that inserts rows in a table ...
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?

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.
xxxxxxxxxxxxxxxxxxxxxxxx
What driver should I use for scalable Oracle JDBC applications?
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.
xxxxxxxxxxxxxxxxx
Can you scroll a result set returned from a stored procedure?...
Can you scroll a result set returned from a stored procedure? I am returning a result set from a stored procedure with type SQLRPGLE but once I reach the end of the result set it does not allow repositioning. Is it possible to scroll this result set?

A CallableStatement is no different than other Statements in regard to whether related ResultSets are scrollable. You should create the CallableStatement using Connection.prepareCall(String sql, int resultSetType, int resultSetConcurrency)
xxxxxxxxxxxxxxxxx
How do I write Greek ( or other non-ASCII/8859-1 ) characters to a database?
From the standard JDBC perspective, there is no difference between ASCII/8859-1 characters and those above 255 ( hex FF ). The reason for that is that all Java characters are in Unicode ( unless you perform/request special encoding ). Implicit in that statement is the presumption that the datastore can handle characters outside the hex FF range or interprets different character sets appropriately. That means either:

* The OS, application and database use the same code page and character set. For example, a Greek version of NT with the DBMS set to the default OS encoding.
* The DBMS has I18N support for Greek ( or other language ), regardless of OS encoding. This has been the most common for production quality databases, although support varies. Particular DBMSes may allow setting the encoding/code page/CCSID at the database, table or even column level. There is no particular standard for provided support or methods of setting the encoding. You have to check the DBMS documentation and set up the table properly.
* The DBMS has I18N support in the form of Unicode capability. This would handle any Unicode characters and therefore any language defined in the Unicode standard. Again, set up is proprietary.
xxxxxxxxxxxxxxxxxxxx
What are the standard isolation levels defined by JDBC?
The values are defined in the class java.sql.Connection and are:
* TRANSACTION_NONE
* TRANSACTION_READ_COMMITTED
* TRANSACTION_READ_UNCOMMITTED
* TRANSACTION_REPEATABLE_READ
* TRANSACTION_SERIALIZABLE
xxxxxxxxxxxxxxxxxxxxxxxxx
What is Metadata and why should I use it?
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.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.
xxxxxxxxxxxxxxxxxxxxxxxxxxx
How does the Java Database Connectivity (JDBC) work?
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
xxxxxxxxxxxxxxxxxxxxxxx
How can I investigate the physical structure of a database?
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.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// 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
conn.close();
}
public static void processResultSet(String preamble, ResultSet rs)
throws SQLException
{
// Printout table data
while(rs.next())
{
// Printout
System.out.println(preamble + ": " + rs.getString(1));
}

// Close database resources
rs.close();
}
xxxxxxxxxxxxxxxxxxxxxxxxx
How do I find all database stored procedures in a database?
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.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// 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
while(rs.next())
{
// 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
rs.close();
conn.close();
}
xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
What is the advantage of using a PreparedStatement?
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.
xxxxxxxxxxxxxxxxxxxxx
How do I create a database connection?
The database connection is created in 3 steps:
1. Find a proper database URL (see FAQ on JDBC 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:
1. Create a properly formatted JDBR URL for your database. (See FAQ on JDBC URL for more information). A JDBC URL has the form jdbc:someSubProtocol://myDatabaseServer/theDatabaseName
2.
try {
Class.forName("my.database.driver");
}
catch(Exception ex)
{
System.err.println("Could not load database driver: " + ex);
}

3. Connection conn = DriverManager.getConnection("a.JDBC.URL", "databaseLogin", "databasePassword");
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
How do I extract the SQL statements required to move all tables and views from an existing database to another database?
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.
xxxxxxxxxxxxxxxxxxxxxxxx
How do I extract a BLOB from a database?
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()
{
try
{ // Prepare a Statement:
PreparedStatement stmnt = conn.prepareStatement("select aBlob from BlobTable");

// Execute
ResultSet rs = stmnt.executeQuery();

while(rs.next())
{
try
{
// 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();
stmnt.close();

}
catch(Exception ex)
{
this.log("Error when trying to read BLOB: " + ex);
}
}
xxxxxxxxxxxxxxxxxxxxxxx
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?
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.
xxxxxxxxxxxxxxxxxxxxxxx
How do I check what table-like database objects (table, view, temporary table, alias) are present in a particular database?
Use java.sql.DatabaseMetaData to probe the database for metadata. Use the getTables method to retrieve information about all database objects (i.e. tables, views, system tables, temporary global or local tables or aliases). The exact usage is described in the code below.

NOTE! Certain JDBC drivers throw IllegalCursorStateExceptions when you try to access fields in the ResultSet in the wrong order (i.e. not consecutively). Thus, you should not change the order in which you retrieve the metadata from the ResultSet.

public static void main(String[] args) throws Exception
{
// Load the database driver - in this case, we
// use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Open a connection to the database
Connection conn = DriverManager.getConnection("[jdbcURL]",
"[login]", "[passwd]");

// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();

// Get all dbObjects. Replace the last argument in the getTables
// method with objectCategories below to obtain only database
// tables. (Sending in null retrievs all dbObjects).
String[] objectCategories = {"TABLE"};
ResultSet rs = dbmd.getTables(null, null, "%", null);

// Printout table data
while(rs.next())
{
// Get dbObject metadata
String dbObjectCatalog = rs.getString(1);
String dbObjectSchema = rs.getString(2);
String dbObjectName = rs.getString(3);
String dbObjectType = rs.getString(4);

// Printout
System.out.println("" + dbObjectType + ": " + dbObjectName);
System.out.println(" Catalog: " + dbObjectCatalog);
System.out.println(" Schema: " + dbObjectSchema);
}

// Close database resources
rs.close();
conn.close();
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
How can I investigate the parameters to send into and receive from a database stored procedure?
Use the method getProcedureColumns in interface DatabaseMetaData to probe a stored procedure for metadata. The exact usage is described in the code below.

NOTE! This method can only discover parameter values. For databases where a returning ResultSet is created simply by executing a SELECT statement within a stored procedure (thus not sending the return ResultSet to the java application via a declared parameter), the real return value of the stored procedure cannot be detected. This is a weakness for the JDBC metadata mining which is especially present when handling Transact-SQL databases such as those produced by SyBase and Microsoft.

public static void main(String[] args) throws Exception
{
// Load the database driver - in this case, we
// use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")
;
// Open a connection to the database
Connection conn = DriverManager.getConnection("[jdbcURL]",
"[login]", "[passwd]");

// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();

// Get all column definitions for procedure "getFoodsEaten" in
// schema "testlogin" and catalog "dbo".
System.out.println("Procedures are called '" + dbmd.getProcedureTerm() +"' in the DBMS.");
ResultSet rs = dbmd.getProcedureColumns("test", "dbo", "getFoodsEaten", "%");

// Printout table data
while(rs.next())
{
// Get procedure metadata
String dbProcedureCatalog = rs.getString(1);
String dbProcedureSchema = rs.getString(2);
String dbProcedureName = rs.getString(3);
String dbColumnName = rs.getString(4);
short dbColumnReturn = rs.getShort(5);
String dbColumnReturnTypeName = rs.getString(7);
int dbColumnPrecision = rs.getInt(8);
int dbColumnByteLength = rs.getInt(9);
short dbColumnScale = rs.getShort(10);
short dbColumnRadix = rs.getShort(11);
String dbColumnRemarks = rs.getString(13);


// Interpret the return type (readable for humans)
String procReturn = null;

switch(dbColumnReturn)
{
case DatabaseMetaData.procedureColumnIn:
procReturn = "In";
break;
case DatabaseMetaData.procedureColumnOut:
procReturn = "Out";
break;
case DatabaseMetaData.procedureColumnInOut:
procReturn = "In/Out";
break;
case DatabaseMetaData.procedureColumnReturn:
procReturn = "return value";
break;
case DatabaseMetaData.procedureColumnResult:
procReturn = "return ResultSet";
default:
procReturn = "Unknown";
}

// Printout
System.out.println("Procedure: " + dbProcedureCatalog + "." + dbProcedureSchema
+ "." + dbProcedureName);
System.out.println(" ColumnName [ColumnType(ColumnPrecision)]: " + dbColumnName
+ " [" + dbColumnReturnTypeName + "(" + dbColumnPrecision + ")]");
System.out.println(" ColumnReturns: " + procReturn + "(" + dbColumnReturnTypeName + ")");
System.out.println(" Radix: " + dbColumnRadix + ", Scale: " + dbColumnScale);
System.out.println(" Remarks: " + dbColumnRemarks);
}

// Close database resources
rs.close();
conn.close();
}
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
How do I extract SQL table column type information?
Use the getColumns method of the java.sql.DatabaseMetaData interface to investigate the column type information of a particular table. Note that most arguments to the getColumns method (pinpointing the column in question) may be null, to broaden the search criteria. A code sample can be seen below:

public static void main(String[] args) throws Exception
{
// Load the database driver - in this case, we
// use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Open a connection to the database
Connection conn = DriverManager.getConnection("[jdbcURL]",
"[login]", "[passwd]");

// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();

// Get all column types for the table "sysforeignkeys", in schema
// "dbo" and catalog "test".
ResultSet rs = dbmd.getColumns("test", "dbo", "sysforeignkeys", "%");

// Printout table data
while(rs.next())
{
// Get dbObject metadata
String dbObjectCatalog = rs.getString(1);
String dbObjectSchema = rs.getString(2);
String dbObjectName = rs.getString(3);
String dbColumnName = rs.getString(4);
String dbColumnTypeName = rs.getString(6);
int dbColumnSize = rs.getInt(7);
int dbDecimalDigits = rs.getInt(9);
String dbColumnDefault = rs.getString(13);
int dbOrdinalPosition = rs.getInt(17);
String dbColumnIsNullable = rs.getString(18);

// Printout
System.out.println("Col(" + dbOrdinalPosition + "): " + dbColumnName
+ " (" + dbColumnTypeName +")");
System.out.println(" Nullable: " + dbColumnIsNullable +
", Size: " + dbColumnSize);
System.out.println(" Position in table: " + dbOrdinalPosition
+ ", Decimal digits: " + dbDecimalDigits);
}

// Free database resources
rs.close();
conn.close();
}
xxxxxxxxxxxxxxxxxxxx
How can I make batch updates using JDBC?
One of the more advanced features of JDBC 2.0 is the ability to submit multiple update statements to the database for processing as a single unit. This batch updating can be significantly more efficient compared to JDBC 1.0, where each update statement has to be executed separately.

Consider the following code segment demonstrating a batch update:
try {
dbCon.setAutoCommit(false);
Statement stmt= dbCon.createStatement();
stmt.addBatch("INSERT INTO bugs "+
"VALUES (1007, 'Server stack overflow', 1,2,{d '1999-01-01'})");
stmt.addBatch("INSERT INTO bugs "+
"VALUES (1008,'Cannot load DLL', 3,1,{d '1999-01-01'})");
stmt.addBatch("INSERT INTO bugs "+
"VALUES (1009,'Applet locks up',2,2,{d '1999-01-01'})");

int[] updCnt = stmt.executeBatch();
dbCon.commit();

} catch (BatchUpdateException be) {

//handle batch update exception
int[] counts = be.getUpdateCounts();
for (int i=0; I counts.length; i++) {
System.out.println("Statement["+i+"] :"+counts[i]);
}
dbCon.rollback();
}
catch (SQLException e) {

//handle SQL exception
dbCon.rollback();
}

Before carrying out a batch update, it is important to disable the auto-commit mode by calling setAutoCommit(false). This way, you will be able to rollback the batch transaction in case one of the updates fail for any reason. When the Statement object is created, it is automatically associated a "command list", which is initially empty. We then add our SQL update statements to this command list, by making successive calls to the addBatch() method. On calling executeBatch(), the entire command list is sent over to the database, and are then executed in the order they were added to the list. If all the commands in the list are executed successfully, their corresponding update counts are returned as an array of integers. Please note that you always have to clear the existing batch by calling clearBatch() before creating a new one.
If any of the updates fail to execute within the database, a BatchUpdateException is thrown in response to it. In case there is a problem in returning the update counts of each SQL statement, a SQLException will be thrown to indicate the error
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
How can I manage special characters (for example: " _ ' % ) when I execute an INSERT query? If I don't filter the quoting marks or the apostrophe, for example, the SQL string will cause an error.
In JDBC, strings containing SQL commands are just normal strings - the SQL is not parsed or interpreted by the Java compiler. So there is no special mechanism for dealing with special characters; if you need to use a quote (") within a Java string, you must escape it.
The Java programming language supports all the standard C escapes, such as \n for newline, \t for tab, etc. In this case, you would use \" to represent a quote within a string literal:

String stringWithQuote =
"\"No,\" he replied, \"I did not like that salted licorice.\"";

This only takes care of one part of the problem: letting us control the exact string that is passed on to the database. If you want tell the database to interpret characters like a single quote (') literally (and not as string delimiters, for instance), you need to use a different method. JDBC allows you to specify a separate, SQL escape character that causes the character following to be interpreted literally, rather than as a special character.

An example of this is if you want to issue the following SQL command:

SELECT * FROM BIRDS
WHERE SPECIES='Williamson's Sapsucker'

In this case, the apostrophe in "Williamson's" is going to cause a problem for the database because SQL will interpret it as a string delimiter. It is not good enough to use the C-style escape \', because that substitution would be made by the Java compiler before the string is sent to the database.
Different flavors of SQL provide different methods to deal with this situation. JDBC abstracts these methods and provides a solution that works for all databases. With JDBC you could write the SQL as follows:

Statement statement = // obtain reference to a Statement
statement.executeQuery(
"SELECT * FROM BIRDS WHERE SPECIES='Williamson/'s Sapsucker' {escape '/'}");

The clause in curly braces, namely {escape '/'}, is special syntax used to inform JDBC drivers what character the programmer has chosen as an escape character. The forward slash used as the SQL escape has no special meaning to the Java compiler; this escape sequence is interpreted by the JDBC driver and translated into database-specific SQL before the SQL command is issued to the database.
Escape characters are also important when using the SQL LIKE clause. This usage is explicitly addressed in section 11.5 of the JDBC specification:

The characters "%" and "_" have special meaning in SQL LIKE clauses (to match zero or more characters, or exactly one character, respectively). In order to interpret them literally, they can be preceded with a special escape character in strings, e.g. "\". In order to specify the escape character used to quote these characters, include the following syntax on the end of the query:
{escape 'escape-character'}
For example, the query
SELECT NAME FROM IDENTIFIERS WHERE ID LIKE '\_%' {escape '\'}
finds identifier names that begin with an underbar.
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
The java.sql package contains mostly interfaces. When and how are these interfaces implemented while connecting to database?
The implementation of these interfaces is all part of the driver. A JDBC driver is not just one class - it is a complete set of database-specific implementations for the interfaces defined by the JDBC.
These driver classes come into being through a bootstrap process. This is best shown by stepping through the process of using JDBC to connect to a database, using Oracle's type 4 JDBC driver as an example:

* First, the main driver class must be loaded into the VM:
Class.forName("oracle.jdbc.driver.OracleDriver");
The specified driver must implement the Driver interface. A class initializer (static code block) within the OracleDriver class registers the driver with the DriverManager.
* Next, we need to obtain a connection to the database:
String jdbcURL = "jdbc:oracle:thin:@www.jguru.com:1521:ORCL";
Connection connection = DriverManager.getConnection(jdbcURL);
DriverManager determines which registered driver to use by invoking the acceptsURL(String url) method of each driver, passing each the JDBC URL. The first driver to return "true" in response will be used for this connection. In this example, OracleDriver will return "true", so DriverManager then invokes the connect() method of OracleDriver to obtain an instance of OracleConnection. It is this database-specific connection instance implementing the Connection interface that is passed back from the DriverManager.getConnection() call.
* The bootstrap process continues when you create a statement:
Statement statement = connection.createStatement();
The connection reference points to an instance of OracleConnection. This database-specific implementation of Connection returns a database-specific implementation of Statement, namely OracleStatement
* Invoking the execute() method of this statement object will execute the database-specific code necessary to issue an SQL statement and retrieve the results:
ResultSet result = statement.executeQuery("SELECT * FROM TABLE");
Again, what is actually returned is an instance of OracleResultSet, which is an Oracle-specific implementation of the ResultSet interface.
So the purpose of a JDBC driver is to provide these implementations that hide all the database-specific details behind standard Java interfaces.
xxxxxxxxxxxxxxxxxxxxx
Which is the preferred collection class to use for storing database result sets?
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

Basically:
ResultSet result = stmt.executeQuery("...");
List list = new LinkedList();
while(result.next()) {
list.add(result.getString("col"));
}

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.
xxxxxxxxxxxxxxxxxxxxxx
Can I use the JDBC-ODBC bridge driver in an applet?
Short answer: No.
Longer answer: You may create a digitally signed applet using a Certicate to circumvent the security sandbox of the browser.
xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
How can I connect from an applet to a database on the server?
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.
xxxxxxxxxxxxxxxxxx
How do I insert an image file (or other raw data) into a database?
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.
xxxxxxxxxxxxxxxxxxxxxxxxxx
How can resultset records be restricted to certain rows?
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();
stmt.setFetchSize(400);
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:
stmt.setFetchDirection(ResultSet.FETCH_REVERSE)
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.
xxxxxxxxxxxxxxxxxxxxxx
How can I get data from multiple ResultSets?
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();
}
xxxxxxxxxxxxxxxxxxxxxx
How do I execute stored procedures?
Here is an example on how to execute a stored procedure with JDBC (to use this in a servlet is the same the only thing is that you create the connection and callable statement in the init() of the servlet):
package DBTest;
import java.sql.*;
public class JdbcTest {

private String msDbUrl = "jdbc:odbc:ms";
private String msJdbcClass = "sun.jdbc.odbc.JdbcOdbcDriver";
private Connection mcDbAccess;
private CallableStatement msProcedure;

public JdbcTest() {
try {
Class.forName( msDbUrl ).newInstance();
mcDbAccess = DriverManager.getConnection( msJdbcClass, "milestone", "milestone" );
msProcedure = mcDbAccess.prepareCall(
"{? = call sp_sav_Bom_Header( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) }"
);
msProcedure.registerOutParameter( 1, java.sql.Types.VARCHAR );
msProcedure.setInt( 2, -1 );
msProcedure.setInt( 3, 39 );
msProcedure.setString( 4, "format" );
long ltTest = new java.util.Date().getTime();
System.out.println( "Today: " + ltTest );
msProcedure.setTimestamp( 5, new Timestamp( ltTest ) );
msProcedure.setString( 6, "type" );
msProcedure.setString( 7, "submitter" );
msProcedure.setString( 8, "email" );
msProcedure.setString( 9, "phone" );
msProcedure.setString( 10, "comments" );
msProcedure.setString( 11, "label" );
msProcedure.setInt( 12, 52 );
msProcedure.setBoolean( 13, true );
msProcedure.setBoolean( 14, false );
msProcedure.setInt( 15, 53 );
msProcedure.setString( 16, "runtime" );
msProcedure.setString( 17, "configuration" );
msProcedure.setBoolean( 18, true );
msProcedure.setBoolean( 19, false );
msProcedure.setString( 20, "special instructions" );
msProcedure.setInt( 21, 54 );

ResultSet lrsReturn = null;
System.out.println( "Execute: " + (lrsReturn = msProcedure.executeQuery() ) );
while( lrsReturn.next() ) {
System.out.println( "Got from result set: " + lrsReturn.getInt( 1 ) );
}
System.out.println( "Got from stored procedure: " + msProcedure.getString( 1 ) );
} catch( Throwable e ) {
e.printStackTrace();
}
}

public static void main(String[] args) {
new JdbcTest();
}
}
I also tried it by using a native JDBC driver (i-net) and it also works fine. The only problem we encounter with JDBC-ODBC bridge is that a stored procedure pads spaces to the full length of a VARCHAR but the native JDBC behaves right. Therefore I suggest to use JDBC native drivers.
The above example uses the MS SQL Server.
xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
How do I create an updatable ResultSet?
Just as is required with a scrollable ResultSet, the Statement must be capable of returning an updatable ResultSet. This is accomplished by asking the Connection to return the appropriate type of Statement using Connection.createStatement(int resultSetType, int resultSetConcurrency). The resultSetConcurrency parameter must be ResultSet.CONCUR_UPDATABLE. The actual code would look like this:

Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE );

Note that the spec allows a driver to return a different type of Statement/ResultSet than that requested, depending on capabilities and circumstances, so the actual type returned should be checked with ResultSet.getConcurrency()
xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
How can I insert multiple rows into a database in a single transaction?
//turn off the implicit commit
Connection.setAutoCommit(false);
//..your insert/update/delete goes here
Connection.Commit();
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.
xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
How do I display and parse a date?
The Java I18N way is to use a DateFormat. While SimpleDateFormat, which is generally returned, creates a large number of objects, it is locale aware and will handle most of your needs. The following sample code initially creates a java.sql.Date object and formats it for the default locale. An initial actionPerformed call additionally formats/displays it for a German locale and also displays the resulting java.sql.Date in standard escape format. Other dates can be entered and parsed after the initial display.

//JDFDP.java-Display and Parse java.sql.Date

import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;

public class JDFDP extends JFrame
                implements ActionListener,
                           WindowListener
{
  // create a java.sql.Date
  java.sql.Date jsqlDate = new java.sql.Date(
     System.currentTimeMillis() );

DateFormat dfLocal = DateFormat.getDateInstance(
     DateFormat.SHORT );
DateFormat dfGermany = DateFormat.getDateInstance(
     DateFormat.SHORT, Locale.GERMANY );

  JButton    jb = new JButton( "Go" );
  JLabel     jlI = new JLabel("Input a Date:"),
             jlD = new JLabel("Display German:"),
             jlP = new JLabel("Parsed:");

  JPanel     jp = new JPanel();

  JTextField jtI = new JTextField( 10 ),
             jtD = new JTextField( 10 ),
             jtP = new JTextField( 10 );


  public JDFDP()
  {
    super( "JDFDP" );
    addWindowListener( this );

    jb.addActionListener( this );

    jp.add(jlI);
    jp.add(jtI);
    jp.add(jb);
    jp.add(jlD);
    jp.add(jtD);
    jp.add(jlP);
    jp.add(jtP);

    getContentPane().add( jp, BorderLayout.CENTER );
    pack();

    // set text by sending dummy event
    jtI.setText( dfLocal.format( jsqlDate ) );
    actionPerformed(
       new ActionEvent( this, 12, "12" ) );

    show();

  }  // end constructor


  // ActionListener Implementation
  public void actionPerformed(ActionEvent e)
  {
    jtD.setText( "" );
    jtP.setText( "" );
    try
    {
      java.util.Date d = dfLocal.parse(
         jtI.getText() );
      jtI.setText( dfLocal.format( d ) );
      jtD.setText( dfGermany.format( d ) );
      d = dfGermany.parse( jtD.getText() );
      // get new java.sql.Date
      jsqlDate = new java.sql.Date( d.getTime() );
     
      jtP.setText( jsqlDate.toString() );
    }
    catch( ParseException pe ) { jtI.setText( "" ); }

  }  // End actionPerformed


// Window Listener Implementation
  public void windowOpened(WindowEvent e) {}
  public void windowClosing(WindowEvent e)
  {
    dispose();
    System.exit(0);
  }
  public void windowClosed(WindowEvent e) {}
  public void windowIconified(WindowEvent e) {}
  public void windowDeiconified(WindowEvent e) {}
  public void windowActivated(WindowEvent e) {}
  public void windowDeactivated(WindowEvent e) {}
// End Window Listener Implementation


  public static void main(String[] args)
  {
    new JDFDP();
  }

}  // end class JDFDP
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
How can I retrieve string data from a database in Unicode format?
The data is already in Unicode when it arrives
 in your program. Conversion from and to the
 encoding/charset/CCSID in the database from/to
 Unicode in the program is part of the JDBC driver's job.

If, for some reason, you want to see the data in
'\uHHHH' format ( where 'H' is the hex value ),
the following code, while not very efficient,
 should give you some ideas:


public class UniFormat
{

  public static void main( String[] args )
  {
    char[] ac = args[0].toCharArray();
    int iValue;
    String s = null;
    StringBuffer sb = new StringBuffer();

    for( int ndx = 0; ndx < ac.length; ndx++ )
    {
      iValue = ac[ndx];

      if( iValue < 0x10 )
      {
        s = "\\u000";
      }
      else
      if( iValue < 0x100 )
      {
        s = "\\u00";
      }
      else
      if( iValue < 0x1000 )
      {
        s = "\\u0";
      }

      sb.append( s + Integer.toHexString( iValue ) );
    } // end for

    System.out.println("The Unicode format of " +
                          args[0] + " is " + sb );

  } // end main

} // end class UniFormat
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Can ResultSets be passed between methods of a class? Are there any special usage
Yes. There is no reason that a ResultSet can't be used as a method parameter just like any other object reference. You must ensure that access to the ResultSet is synchronized. This should not be a problem is the ResultSet is a method variable passed as a method parameter - the ResultSet will have method scope and multi-thread access would not be an issue.

As an example, say you have several methods that obtain a ResultSet from the same table(s) and same columns, but use different queries. If you want these ResultSets to be processed the same way, you would have another method for that. This could look something like:

public List getStudentsByLastName(String lastName) {
ResultSet rs = ... (JDBC code to retrieve students by last name);
return processResultSet(rs);
}

public List getStudentsByFirstName(String firstName) {
ResultSet rs = ... (JDBC code to retrieve students by first name);
return processResultSet(rs);
}

private List processResultSet(ResultSet rs) {
List l = ... (code that iterates through ResultSet to build a List of Student objects);
return l;
}

Since the ResultSet always has method scope - sychronization is never an issue.

1. There is only one ResultSet. Dont assume that the ResultSet is at the start (or in any good state...) just because you received it as a parameter. Previous operations involving the ResultSet will have had the side-effect of changing its state.
2. You will need to be careful about the order in which you close the ResultSet and CallableStatement/PreparedStatement/etc

From my own experience using the Oracle JDBC drivers and CallableStatements the following statements are true:

* If you close the CallableStatement the ResultSet retrieved from that CallableStatement immediately goes out-of-scope.
* If you close the ResultSet without reading it fully, you must close the CallableStatement or risk leaking a cursor on the database server.
* If you close the CallableStatement without reading it's associated ResultSet fully, you risk leaking a cursor on the database server.

No doubt, these observations are valid only for Oracle drivers. Perhaps only for some versions of Oracle drivers.

The recommended sequence seems to be:
* Open the statement
* Retrieve the ResultSet from the statement
* Read what you need from the ResultSet
* Close the ResultSet
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
How do I create a java.sql.Date object?
java.sql.Date descends from java.util.Date, but uses only the year, month and day values. There are two methods to create a Date object. The first uses a Calendar object, setting the year, month and day portions to the desired values. The hour, minute, second and millisecond values must be set to zero. At that point, Calendar.getTime().getTime() is invoked to get the java.util.Date milliseconds. That value is then passed to a java.sql.Date constructor:

Calendar cal = Calendar.getInstance();
// set Date portion to January 1, 1970
cal.set( cal.YEAR, 1970 );
cal.set( cal.MONTH, cal.JANUARY );
cal.set( cal.DATE, 1 );

cal.set( cal.HOUR_OF_DAY, 0 );
cal.set( cal.MINUTE, 0 );
cal.set( cal.SECOND, 0 );
cal.set( cal.MILLISECOND, 0 );

java.sql.Date jsqlD =
new java.sql.Date( cal.getTime().getTime() );

The second method is java.sql.Date's valueOf method. valueOf() accepts a String, which must be the date in JDBC time escape format - "yyyy-mm-dd". For example,

java.sql.Date jsqlD = java.sql.Date.valueOf( "2010-01-31" );
creates a Date object representing January 31, 2010. To use this method with a Calendar object, use:

java.sql.Date jsqlD = java.sql.Date.valueOf(
cal.get(cal.YEAR) + ":" +
cal.get(cal.MONTH) + ":" +
cal.get(cal.DATE) );

which produces a Date object with the same value as the first example.
xxxxxxxxxxxxxxxxxxxxxxxxx
What does normalization mean for java.sql.Date and java.sql.Time?
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.
xxxxxxxxxxxxxxxxxxxxxxxxxx
What scalar functions can I expect to be supported by JDBC?
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.
xxxxxxxxxxxxxxxxxxxxx


Friday, January 25, 2013

Core Java Interview Question and Answer

Core Java Interview Questions


The below is a comprehensive list of 164 Core Java Interview Questions with answers. These questions have been arranged in such a way that there is a clean flow from one question to next one so that it will be easier for you to revise. Some of the questions might look very trivial but they have been included to make sure all questions are covered. Though topics like Exception Handling, Multi-threads, etc are part of Core Java, they have not been included in Core Java Interview Questions - they are anwered in independent of Core Java Interview Questions. If you feel any Core Java question is not answered or if you have been asked a Core Java question in the interview other than the ones listed below, please email your question to me (d4dipanshu@gmail.com), I will answer the question and include it to the below list of Core Java Interview Questions with your name as the contributor.

1.What are the most important features of Java?
Java is object oriented, platform independent,secure,robust,simple,etc

2.Which one of them do you consider the best feature of Java?
Platform independence.

3.What do you mean by platform independence?
Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc).

4.What is byte code?
Byte code is a set of instructions generated by the compiler. JVM executes the byte code.

5.How does Java acheive platform independence?
A Java source file on compilation produces an intermediary .class rather than a executable file. This .class file is interpreted by the JVM. Since JVM acts as an intermediary layer.

6.What is a JVM?
JVM is Java Virtual Machine which is a run time environment for the compiled java class files.

7.Are JVM's platform independent?
JVM's are not platform independent. JVM's are platform specific run time implementation provided by the vendor. A Windows JVM cannot be installed in Linux.

8.Who provides the JVM?
Any software vendor can provide a JVM but it should comply to the Java langauge specification.

9.What is the difference between a JDK and a JVM?
JDK is Java Development Kit which is for development purpose and it includes execution environment also. But JVM is purely a run time environment and hence you will not be able to compile your source files using a JVM.

10.What is a pointer and does Java support pointers?
Pointer is a reference handle to a memory location. Improper handling of pointers leads to memory leaks and reliability issues hence Java doesn't support the usage of pointers.

11.How is an object reference different from a pointer?
Both object reference and pointer point to the memory location of the object. You can manipulate pointers but not object references.

12.Does Java support multiple inheritance?
Java doesn't support multiple inheritance.

13.Why Java doesn't support multiple inheritance?
When a class inherits from more than class, it will lead to the diamond problem - say A is the super class of B and C & D is a subclass of both B and C. D inherits properties of A from two different inheritance paths ie via both B & C. This leads to ambiguity and related problems, so multiple inheritance is not allowed in Java.

14.Is Java a pure object oriented language?
Java is a pure object oriented language. Except for the primitives everything else are objects in Java.

15.What is the difference between Path and Classpath?
Path and Classpath are operating system level environment variales. Path is used define where the system can find the executables(.exe) files and classpath is used to specify the location .class files.

16.Why does Java not support operator overloading?
Operator overloading makes the code very difficult to read and maintain. To maintain code simplicity, Java doesn't support operator overloading.

17.What are keywords?
Keywords cannot be used as identifiers.

18.What are reserved keywords? And can you name few reserved keywords?
Few of the words are reserved as keywords for future usage. Compiler forces the developer not to use a reserved keyword. const and

19.What is the overhead of introducing a new keyword?
When a new keyword is used in a new version of the JDK, there is high chances that has been used by developers as identifiers. This make tougher for the code base to migrate to new version since it requires code change, recompilation,testing and release cycle.

20.Have you come across difficulties due to introduction of a new keyword?
Yes. enum keyword was used extensively as identifier in one of our project - we had to change the code in a lot of places to migrate it to newer v ersion.

21.What are identifiers?
Identifiers are names given to a variable, method, class and interface. Identifiers must conform to the following rules:a. The identifiers can contain a to z, A to Z,0 to 9,_ and $.b. Special characters other than _ and $ cannot be used in identifiers.c. Identifiers cannot start with numbers. d. keywords cannot be used as identifiers.

22.What is meant by naming conventions? And what are the naming conventions followed in Java?
Naming conventions are part of coding standards which are prescribed for better readability and maintenance. The following are simple conventions followed in Java:1. Instance and local Variables should start with a lowercase and subsequent word should start with a capital letter. Examples: int quantity; double unitPrice; 2. Class level variables ie constants should be in capital letters and _ is used word seprator final static double PI = 3.14; final static int MAX_PRIORITY = 10;3. Method names should start with small case and subsequent word should be capital letter. public double getAvailableBalance(String accountNo) throws InvalidAccountException{}4. Classes and Interfaces should start with a capital letter and subsequent words should also be capital letters. public class HelloWorld{}

23.If you dont follow coding standards, will it result in compilation error?
No. These are standards. Each company or fot that matter each software unit might have its own coding standards. These are not enforced by the compiler.

24.How to make sure that all programmers are following the coding standards?
The best and simple way is to do peer reviews and code walkthroughs. You can use external plugins to your IDE (integrated development environment) to enforce during coding itself.

25.What are literals?
Literals are source code representation of primitive data types.

26.Name the eight data types which are available in Java?
boolean, byte, short, int, long, float, double and char.

27.Are primitive data types objects in Java?
Primitive data types are not objects.

28.What are all the number data types? And are they signed or unsigned?
Excpet boolean and char, others are number data types and they are all signed which means that they can hold both positive and negative values.

29.What are the possible values that a boolean data type can hold?
The boolean is the simplest data type which can hold true or false.

30.What are default values?
Values which are defaulted during object initialisation are called default values. Each data type has a default value.

31.What are the default values of primitive data types?
For boolean data type, it is false. For byte,short,int and long, it is 0. For float and double, it is 0.0. For char, the default value is 'u000'.

32.Are object references defaulted?
Yes. Object references are defaulted to null.

33.Are arrays defaulted?
If arrays is just declared but not initialised then the array reference will be defaulted to null. This is because arrays are objects in Java.int arr[]; // Here the arr reference is defaulted to null.If array values are not assigned, then will be defaulted to their respective default values.double priceRange[] = new double[3]; // Here all the elements in the array will be defaulted to 0.0 - the default value of double.String str[] = new String[3]; // Here all the elements will be defaulted to null - the default value for object references.

34.Can you explain keyword , identifier and literal with an example?
Consider the below statement:int i = 10;Here int is the keyword which has special meaning attached Java programming langauge ie whatever is declared is an integer value.i is the identifier or the variable name.10 is the literal or the actual value.

35.What are the 3 ways to represent an integer value?
The following are the 3 different ways to represent an integer value:int i = 123 // this is the usual decimal representation.int i = 0123 // this is octal representation. Octal values start with a zero.int i = 0XCAAD // this is hexadecimal representation. Hexadecimal values start with 0X.

36.In how many ways a char value be represented?
Char value can be represented in 3 ways. They are as follows:char ch = 'A'; // represented using single quotes.char ch = 'u0041'; // represented using unicode representation.char ch = 41; // represented using integer value.

37.How is it possible to represent char using a integer value?
char is internally represented as a unsigned 16 bit integer value ie it will accept integer values from 0 to 65536.

38.Can char be used when an integer value is expected?
Yes. A fine example is switch statement will accept char value for multiway condition checking.

39.Can char be manipulated like integers?
Yes possible. The below is an example.char ch = 'A';System.out.println(ch++); The above statement will print B. ++ is a numeral operand and since char is internally represented as integer, ++ operand can be applied on char value.

40.What is Unicode?
A universal, 16-bit, standard coded character set for the representation of all human scripts.

41.What should i have to do if i have to print my name in Spanish?
Provide code...

42.How will the below literal value be internally represented?
float f = 21.22;
It will be represented as a double value. Floating point literals are always double by default. If you want a float, you must append an F or f to the literal.

43.Give your observation on the below statement.
int i = 10/0;
The statement will result in RuntimeException (DivideByZeroException). Integer values cannot be divided by zero.

44.Give your observation on the below statement.
double d = 10.12/0;
This will compile and execute fine. The result will be Infinity

45.What is a Variable?
a variable is a facility for storing data. The current value of the variable is the data actually stored in the variable.

46.What are the 3 types of variables?
There are 3 types of variables in Java. They are :1. Local variables.2. Instance variables.3. Class variables.

47.What are Local variables?
Local varaiables are those which are declared within a block of code like methods, loops, exception blocks, etc. Local variables should be initialised before accessing them. Local variables are stored on the stack, hence they are sometimes called stack variables. They are also called as method variables or block variables.

48.When are local variables eligible for garbage collection?
As soon as the block is completed the variables are eligible for GC. Block could be a condition, a loop, a exception block or a methodConsider the below class:public class Test { public static void main (String str[]){ String name = str[0]; for (int i=0; i<=10; i++){ System.out.println(name + i); } }}In the above the class, the variable i is eligible for garbage collection immediately after the completion of for loop.name string variable and str[] argument are eligible for GC after the completion of main method.

49.What are Instance variables?
Instance variables are those which are defined at the class level. As we know, object have identity and behaviour - the identity is provided by the instance variables. These are also called as object variables. Instance variables need not be initialized before using them. Instance variables will be initialized to their default values automatically when not initialized.

50.Are arrays primitive data types?
No. Arrays are not primitives - they are objects.

51.What are different ways to declare an array?
Object obj[]; // most frequently used form of array declaration.Object []obj; // nothing wrong with this. Object[] obj; // nothing wrong with this. int i[][]; // most frequently form multi-dimensional arrayint[] i[]; // nothing wrong with this. int[] i[],j; // nothing wrong with this. Important : i is double dimensional whereas j is single dimensional.

52.What are the 3 steps in defining arrays?
declaration,initialization and assignmentint i[]; // array declaration.i[] = new int[2]; // array initialization.i[0] = 10; i[1] = 7; i[2] = 9; // element value assignment. What is the simplest way to defining an primitive array? The below statement merges declaration,initialization and assignment into a single step:int i [] = {10, 20, 30 40}; What is wrong with the below code segment?int i[] = new int[5]System.out.println(i.length()) length is an instance variable of array object - here it is given a method.

53.What is wrong with the below code segment?
int i[5] = new int[]System.out.println(i.length)
length of an array should be given when it is initialized. Here it is given during declaration. It will result in compilation error.

54.What will be the output of the below code segment?
int i[] = new int[5]System.out.println(i.length)
It will print 6. Remember array indexes start with 0.

55.What are the frequent RuntimeException's encountered because of improper coding with respect to arrays?
ArrayIndexOutOfBoundsException and NullPointerException.

56.Should a main method be compulsorily declared in all java classes?
No not required. main method should be defined only if the source class is a java application.

57.What is the return type of the main method?
Main method doesn't return anything hence declared void.

58.Why is the main method declared static?
main method is the entry point for a Java application and main method is called by the JVM even before the instantiation of the class hence it is declared as static. static methods can be called even before the creation of objects.

59.What is the argument of main method?
main method accepts an array of String objects as argument.

60.How to pass an argument to main method?
You should pass the argument as a command line argument. Command line arguments are seprated by a space. The following is an example:java Hello Tom JerryIn the above command line Hello is the class, Tom is the first argument and Jerry is the second argument.

61.What will happen if no argument is passed to the main method?
If you dont access the argument, the main method will execute without any problem. If try to access the argument, NullPointerException will be thrown.

62.Can a main method be overloaded?
Yes. You can have any number of main methods with different method signature and implementation in the class.

63.Can a main method be declared final?
Yes. Any inheriting class will not be able to have it's own default main method.

64.Does the order of public and static declaration matter in main method?
No it doesn't matter but void should always come before main().

65.Can a source file contain more than one Class declaration?
Yes. A single source file can contain any number of Class declarations but only one of the class can be declared as public.

66.If a source file has 2 class declaration in it, on compilation how many class files will be created?
2 class files will be generated by the compiler.

67.Can the first line of the source code be a comment?
Yes. Comments can appear anywhere in the code. It is just a "skip this line" instruction to the conpiler.

68.Can the source file name and the class name in the file be different?
If the class in the source is not of public access, then the name can be anything but should confirm to identifier rules.

69.Explain Inheritance?
Inheritance is a concept where the properties and behaviour of a class is reused in another class. The class which is being reused or inherited is called the super class or the parent class. The class which is inheriting is called the subclass or the child class of the inherited class.

70.Does Java support multiple inheritance?
No. Java Supports only single inheritance.

71.Why Java doesn’t support muliple inheritance?
When a class inherits from more than class, it will lead to inheritance path amibiguity (this is normally calledthe diamond problem). Say A is the super class of B and C & D is a subclass of both B and C. D inherits properties of A from two different inheritance paths ie via both B & C. This leads to ambiguity and related problems, so multiple inheritance is not allowed in Java.

72.Which keyword is used for inheriting from another class?
extends keyword is used for inheritance.

73.Can a subclass be referenced for a super class object?
No. If Vehicle is super class and Car is the subclass then the following reference would be wrong – Car c = new Vehicle();

74.Can a parent class be referenced for a subclass object?
Yes. The below is an example :Vehicle v = new Car();

75.Can an interface be referenced for any object?
Yes. We can create a object reference for an interface. The object should have provided the implementation for the object.Runnable r = new Test(); Test class should have implemented the runnable interface and overridded the run method.

76.What are constructors?
Constructors are used to initialise an object. Constructors are invoked when the new operator on the class are called.

77.What are the decalaration of a constructor?
Constructor name should be the same as class name.Constructors doesn’t return anything – not even void.

78.Does constructors throw exceptions?
Yes. Like methods constructors can also throw exceptions.

79.Can constructors be overloaded?
Yes. Constructors can be overloaded.

80.Is it compulsory to define a constructor for a class?
No. If you don’t define a constructor, the compiler will provide a default constructor.

81.What is a default constructor?
Default constructor is a no argument constructor which initialises the instance variables to their default values. This will be provided by the compiler at the time of compilation. Default constructor will be provided only when you don’t have any constructor defined.

82.Explain about “this” operator?
“this” is used to refer the currently executing object and it’s state. “this” is also used for chaining constructors and methods.

83.Explain about “super” operator?
“super” is used to refer to the parent object of the currently running object. “super” is also to invoke super class methods and classes.

84.What is the sequence of constructor invocation?
When you instantiate a subclass, the object will begin with an invocation of the constructor in the base class and initialize downwards through constructors in each subclass till it reaches the final subclass constructor. Note: This top down imagery for class inheritance, rather than a upward tree-like approach, is standard in OOP but is sometimes confusing to newcomers.

85.Can a constructor be defined for an interface?
No

86.Explain Polymorphism?
The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class. Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. Overloading and overriding are two types of polymorphism.

87.What is Overloading?
In a class, if two methods have the same name and a different signature,it is known as overloading in Object oriented concepts.

88.When to use overloading?
Overloading is a powerful feature, but you should use it only as needed. Use it when you actually do need multiple methods with different parameters, but the methods do the same thing. That is, don't use overloading if the multiple methods perform different tasks. This approach will only confuse other developers who get a peek at your code.

89.Explain Overriding?
Overriding means, to give a specific definition by the derived class for a method implemented in the base class.

90.What is a package?
Package is a collection of related classes and interfaces. package declaration should be first statement in a java class.

91.Which package is imported by default?
java.lang package is imported by default even without a package declaration.

92.Is package statement mandatory in a Java source file?
It's not mandatory.

93.What will happen if there is no package for Java source file?
The classes will packaged into a no name default package. In practice, we always put classes into a meaningful package.

94.What is the impact using a * during importing(for example import java.io.*;?
When a * is used in a import statement, it indicates that the classes used in the current source can be available in the imported package. Using slightly increases the compilation time but has no impact on the execution time.

95.Can a class declared as private be accessed outside it's package?
A class can't be declared as private. It will result in compile time error.

96.Can a class be declared as protected?
A class can't be declared as protected. only methods can be declared as protected.

97.What is the access scope of a protected method?
A protected method can be accessed by the classes within the same package or by the subclasses of the class in any package.

98.What is the impact of marking a constructor as private?
Nobody can instantiate the class from outside that class.

99.What is meant by default access?
default access means the class,method,construtor or the variable can be accessed only within the package.

100.Is default a keyword?
Yes. default is a keyword but is associated with switch statement not with access specifiers.

101.Then how to give default access to a class?
If you dont specify any access, then it means the class is of default access.

102.Can i give two access specifiers to a method at the same time?
No its not possible. It will result in compile time error.

103.What is the purpose of declaring a variable as final?
A final variable's value can't be changed. final variables should be initialized before using them.

104.Can a final variable be declared inside a method?
No. Local variables cannot be declared as final.

105.What is the impact of declaring a method as final?
A method declared as final can't be overridden. A sub-class doesn't have the independence to provide different implementation to the method.

106.I don't want my class to be inherited by any other class. What should i do?
You should declared your class as final. A class declared as final can't be inherited by any other class.

107.When will you declare a class as final?
When a class is independent and completely concrete in nature, then the class has to be marked as final.

108.Can you give few examples of final classes defined in Java API?
java.lang.String,java.lang.Math are final classes.

109.How to define a constant variable in Java?
The variable should be declared as static and final. So only one copy of the variable exists for all instances of the class and the value can't be changed also.static final int PI = 3.14; is an example for constant.

110.Can a class be declared as static?
No a class cannot be defined as static. Only a method,a variable or a block of code can be declared as static.

111.When will you define a method as static?
When a method needs to be accessed even before the creation of the object of the class then we should declare the method as static.

112.I want to print "Hello" even before main is executed. How will you acheive that?
Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main method.

113.What is the use of a static code block?
static code blocks could be used for one time initialisation activities.

114.Cant you use the constructor for initialisation rather than static block?
Constructors are used for object level initialisation whereas the static block are used for class level initialisation ie to initialise constants.

115.Will the static block be executed for each object?
No. It will be executed only once for each class ie at the time of loading a class.

116.What are the restriction imposed on a static method or a static block of code?
A static method should not refer to instance variables without creating an instance.It cannot use "this" or "super". A static method can acces only static variables or static methods.

117.When overriding a static method, can it be converted to a non-static method?
No. It should be static only.

118.What is the importance of static variable?
static variables are class level variables where all objects of the class refer to the same variable. If one object changes the value then the change gets reflected in all the objects.

119.Can we declare a static variable inside a method?
Static varaibles are class level variables and they can't be declared inside a method. If declared, the class will not compile.

120.What is an Abstract Class and what is it's purpose?
A Class which doesn't provide complete implementation is defined as an abstract class. Abstract classes enforce abstraction.

121.What is the use of a abstract variable?
Variables can't be declared as abstract. only classes and methods can be declared as abstract.

122.Can a abstract class be declared final?
Not possible. An abstract class without being inherited is of no use and a final class cannot be inherited. So if a abstract class is declared as final, it will result in compile time error.

123.What is an abstract method?
An abstract method is a method whose implementation is deferred to a subclass.

124.Can a abstract class be defined without any abstract methods?
Yes it's possible. This is basically to avoid instance creation of the class.

125.What happens if a subclass has inherited a abstract class but has not provided implementation for all the abstract methods of the super class?
Then the subclass also becomes abstract. This will be enforced by the compiler.

126.What happens if a class has implemented an interface but has not provided implementation for a method in a interface?
Its the same as the earlier answer. The class has to be marked as abstract. This will be enforced by the compiler.

127.Can you create an object of an abstract class?
Not possible. Abstract classes are not concrete and hence can't be instantiated. If you try instantiating, you will get compilation error.

128.Can I create a reference for a an abstract class?
Yes. You can create a reference for an abstract class only when the object being has provided the implementation for the abstract class - it means that the object should be of a concrete subclass of the abstract class. This applies to interfaces also. Below is an example for interface referencing an object:java.sql.Connection con = java.sql.DriverManager.getConnection("");

129.Can a class be marked as native?
No. Only methods can be marked as native.

130.What is the use of native methods?
When a java method accesses native library written in someother programming language then the method has to be marked as native.

131.What is the disadvantage of native methods?
By using native methods, the java program loses platform independence - the accessed platform might be tightly coupled with a operating system hence java program also loses OS independence.

132.What is the purpose of transient modifier?
Only variables can be marked as transient. Variables marked as transient will not be persisted during object persistence.

133.What is the purpose of volatile modifier?
Only variables can be marked as volatile. Volatile variables might be modified asynchronously.

134.What is an Interface?
Interfaces say what a class must do but does not say how a class must do it. Interfaces are 100% abstract.

135.Class C implements Interface I containing method m1 and m2 declarations. Class C has provided implementation for method m2. Can i create an object of Class C?
No not possible. Class C should provide implementation for all the methods in the Interface I. Since Class C didn't provide implementation for m1 method, it has to be declared as abstract. Abstract classes can't be instantiated.

136.Can a method inside a Interface be declared as final?
No not possible. Doing so will result in compilation error. public and abstract are the only applicable modifiers for method declaration in an interface.

137.Can an Interface implement another Interface?
Intefaces doesn't provide implementation hence a interface cannot implement another interface.

138.Can an Interface extend another Interface?
Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface.

139.Can a Class extend more than one Class?
Not possible. A Class can extend only one class but can implement any number of Interfaces.

140.Why is an Interface be able to extend more than one Interface but a Class can't extend more than one Class?
Basically Java doesn't allow multiple inheritance, so a Class is restricted to extend only one Class. But an Interface is a pure abstraction model and doesn't have inheritance hierarchy like classes(do remember that the base class of all classes is Object). So an Interface is allowed to extend more than one Interface.

141.Can an Interface be final?
Not possible. Doing so so will result in compilation error.

142.Can a class be defined inside an Interface?
Yes it's possible.

143.Can an Interface be defined inside a class?
Yes it's possible.

144.What is a Marker Interface?
An Interface which doesn't have any declaration inside but still enforces a mechanism.

145.Can we define private and protected modifiers for variables in interfaces?
No. Always all variables declared inside a interface are of public access.

146.What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.

147.When can an object reference be cast to an interface reference?
An object reference can be cast to an interface reference when the object implements the referenced interface.

148.What are Inner Classes?
Inner classes are classes which are defined inside another class.

149.What are Nested Classes?
Static Inner classes are called sometimes referred as nested classes because these classes can exist without any relationship with the containing class.

150.What is the super class of all Inner Classes?
Inner class is just a concept and can be applied to any class, hence there is no common super class for inner classes.

151.What are the disadvantages of Inner classes?
1. Inner classes are not reusable hence defeats one of the fundamental feature of Java.2. Highly confusing and difficult syntax which leads poor code maintainability.

152.Name the different types of Inner Classes?
The following are the different types of Inner classes:Regular Inner ClassMethod Local Inner ClassStatic Inner ClassAnonymous Inner Class

153.What are Regular Inner Classes?
A Regular inner class is declared inside the curly braces of another class outside any method or other code block. This is the simplest form of inner classes.

154.Can a regular inner class access a private member of the enclosing class?
Yes. Since inner classes are treated as a member of the outer class they can access private members of the outer class.

155.How will you instantiate a regular inner class from outside the enclosing class?
Outer out=new Outer();Outer.Inner in=out.new Inner();

156.What are Local Inner Classes or Method Local Inner Classes?
A method-local inner class is defined within a method of the enclosing class.

157.What are the constraints on Method Local Inner Classes?
The following are the restrictions for Method Inner Classes:Method Local Inner classes cannot acccess local variables but can access final variables.Only abstract and final modifiers can be applied to Method Local Inner classesMethod Local Inner classes can be instantiated only within the method in which it is contained that too after the class definition.

158.What are Anonymous Inner Classes? Name the various forms of Anonymous Inner Classes.
Anonymous Inner Classes have no name, and their type must be either a subclass of the named type or an implementer of the named interface. The following are the different forms of inner classes:Anonymous subclass(i.e. extends a class)Anonymous implementer (i.e. implements an interface)Argument-Defined Anonymous Inner Classes

159.How many classes can an Anonymous Inner classes inherit from?
One.

160.How many Interfaces can an Anonymous Inner classes implement?
One. Normal classes and other inner classes can implement more than one interface whereas anonymous inner classes can either implement a single interface or extend a single class.

161.What are Static Inner Classes?
Static Inner Classes are inner classes which marked with a static modifier. These classes need not have any relationship with the outer class. These can be instantiated even without the existence of the outer class object.

162.Can you instantiate the static Inner Class without the existence of the outer class object?
If Yes, Write a sample statement. Yes. It can be instantiated as follows by referencing the Outer class.Outer.Inner in = new Outer.Inner();

163.What are the constraints on Static Inner Classes?
It cannot access non-static members of the outer class.It cannot use this reference to the outer class.

164.How many class files are produced for source file having one Outer class and one Inner class?
Two class files will be produced as follows:Outer.classOuter$Inner.class