Tuesday, February 17, 2009

Java Questions - 2


  • What is a thread?
  • A thread is most fundamental unit of a computer program which is under execution independent of other parts.A thread and a task are similar and often confused.An operating system executes a program by allocating it certain resources like memory,CPU cycles and when there are many a programs doing several things corresponding to several users requests.In such a scenario each program is viewed as a 'task' by OS for which it identifies an allocate resources. An OS treats each application e.g. Word Processor,spreadsheet,email client etc as a separate task , if a certain program initiates some parallel activity e.g. doing some IO operations,printing then a 'thread' will be created fro doing this job.

  • What is the difference between process and threads?
  • A thread is part of a process; a process may contain several different threads. Two threads of the same process share a good deal of state and are not protected against one another, whereas two different processes share no state and are protected against one another. Two threads of the same process have different values of the program counter; different stacks (local variables); and different registers.The program counter, stack pointer, and registers are therefore saved in the thread table. Two threads share open files and memory allocation; therefore, file information and memory information (e.g. base/limit register or page table) is stored in the process table.

  • What are two types of multitasking?
  • Co-operative
    In case of co-operative multitasking applications consume resources i.e. memory and CPU cycle and once it is completed with its execution of set of instructions, it returns control back to the OS. The scheme depends on the application co-operating and so is known as co-operative multitasking. In cases where the application entered an endless loop and never reached the code which handed control back to the operating system, the whole machine became locked up. An example is Windows 3.1Pre -emptive
    In this technique the operating system allocates resources to an application. This will enable it to execute. Rather than wait for the application to give the resources up, the operating system is
    activated at certain time intervals and may take the resources back from the executing application and allocate them to another application that is waiting.Example: Unix, Windows NT, and 32 bit programs running under Windows '95

  • What are two ways of creating threads in Java and why so?
  • Threads can be created in the following ways :

    -Instantiating a class extending java.lang.Thread class and calling start() method

    -Creating a java.lang.Thread and passing a reference of a class implementing Runnable interface.Then calling start() method on this object.
    As mentioned,Java supports these two mechanisms for Thread creations but second option is preferred as in first case there is a possibility of single inheritance making a thread object less flexible in its behaviour while in second case a thread object can be clubbed with multiple features.

  • How does multithreading take place on a computer with a single CPU?
  • It is the responsibility of scheduler to organise multiple tasks by allocating execution time to each task, in such a way that it seems to be executed in a sequential fashion to rest of the world.

  • How a Java object be locked for exclusive use by a given thread?
  • A Java object can be locked for an exclusive use of a thread by making it available via a 'synchronized' block or method.Only a particular thread at given time which will be possessing the lock on the object will be able to do execution of code available in synchronized block or method, once this thread with lock is through with its executions then it releases the lock on the object and it is made available to the next thread in wait state.

  • What is Synchronization?
  • In Java, JVM takes care of thread synchronization. Java support multithreading and data is shared along multiple threads.
    Inside the Java virtual machine, each thread is awarded a Java stack, which contains data no other thread can access, including the local variables, parameters, and return values of each method the thread has invoked. The data on the stack is limited to primitive types and object references. In the JVM, it is not possible to place the image of an actual object on the stack. All objects reside on the heap.
    There is only one heap inside the JVM, and all threads share it. The heap contains nothing but objects. There is no way to place a solitary primitive type or object reference on the heap -- these things must be part of an object. Arrays reside on the heap, including arrays of primitive types, but in Java, arrays are objects too.
    Besides the Java stack and the heap, the other place data may reside in the JVM is the method area, which contains all the class (or static) variables used by the program. The method area is similar to the stack in that it contains only primitive types and object references. Unlike the stack, however, the class variables in the method area are shared by all threads.
    Object and class locks
    As described above, two memory areas in the Java virtual machine contain data shared by all threads. These are:
    The heap, which contains all objects
    The method area, which contains all class variables
    If multiple threads need to use the same objects or class variables concurrently, their access to the data must be properly managed. Otherwise, the program will have unpredictable behavior.
    To coordinate shared data access among multiple threads, the Java virtual machine associates a lock with each object and class. A lock is like a privilege that only one thread can "possess" at any one time. If a thread wants to lock a particular object or class, it asks the JVM. At some point after the thread asks the JVM for a lock -- maybe very soon, maybe later, possibly never -- the JVM gives the lock to the thread. When the thread no longer needs the lock, it returns it to the JVM. If another thread has requested the same lock, the JVM passes the lock to that thread.
    Class locks are actually implemented as object locks. When the JVM loads a class file, it creates an instance of class java.lang.Class. When you lock a class, you are actually locking that class's Class object.
    Threads need not obtain a lock to access instance or class variables. If a thread does obtain a lock, however, no other thread can access the locked data until the thread that owns the lock releases it.
    Monitors The JVM uses locks in conjunction with monitors. A monitor is basically a guardian in that it watches over a sequence of code, making sure only one thread at a time executes the code.
    Each monitor is associated with an object reference. When a thread arrives at the first instruction in a block of code that is under the watchful eye of a monitor, the thread must obtain a lock on the referenced object. The thread is not allowed to execute the code until it obtains the lock. Once it has obtained the lock, the thread enters the block of protected code.
    When the thread leaves the block, no matter how it leaves the block, it releases the lock on the associated object.

  • Explain wait(),notify(), and notifyAll() methods?
  • These methods are used for thread intercommunication and usually called within synchronised block or methods.A thread with lock on the object when calls wait() then it goes into wait state till some other thread with lock on this object invokes notify() method or the notifyAll() method.

  • What is a Daemon thread?
  • A ''daemon'' thread is one that is supposed to provide a general service in the background as long as the program is running, but is not part of the essence of the program. Thus, when all of the non
    daemon threads complete the program is terminated. Conversely, if there are any non-daemon threads still running the program doesn' t terminate.

  • How a dead thread can be started?
  • It is not possible to start a dead thread.

  • What is the difference between String and StringBuffer?
  • String objects are immutable. It means any method like concat, substring, replace called upon an existing String object will return a new String object i.e. updations of an existing String object will not be reflected in the same object rather a new String object will be created.

    A StringBuffer implements a mutable sequence of characters, which can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer. The append method always adds these characters at the end of the buffer; the insert method adds the characters at a specified point

  • How is '==' different from .equals() method in case of String objects?
  • In case of String objects:
    '==': does reference check
    .equals() method: checks the contents of the two String objects.
    The following example will illustrate the difference between the two:

  • Explain StreamTokenizer?
  • The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time. The parsing process is controlled by a table and a number of flags that can be set to various states. The stream tokenizer can recognize identifiers, numbers, quoted strings, and various comment styles.
    Each byte read from the input stream is regarded as a character in the range '\u0000' through '\u00FF'. The character value is used to look up five possible attributes of the character: white space, alphabetic, numeric, string quote, and comment character. Each character can have zero or more of these attributes.
    In addition, an instance has four flags. These flags indicate:
    Whether line terminators are to be returned as tokens or treated as white space that merely separates tokens.
    Whether C-style comments are to be recognized and skipped.
    Whether C++-style comments are to be recognized and skipped.
    Whether the characters of identifiers are converted to lowercase.
    A typical application first constructs an instance of this class, sets up the syntax tables, and then repeatedly loops calling the nextToken method in each iteration of the loop until it returns the value TT_EOF.

  • What is Collection?
  • A collection object(technically speaking data-structures) represents a container for objects,which generally expands itself to accommodate these objects.One has not be bothered about how many objects a collection object can contain.The collection classes like Vector,Hashtable(both are in Java 1.1) and ArrayList,HashMap(both are in Java2)are sophisticated way of holding objects.One can pick any of the collection objects as per need and sometimes on choice.

  • Explain List,Set and Map.
  • The three most significant types of Collections framework are:
    -List
    -Set
    -Map

    First,look into the hierarchy of collection interfaces:

    java.util.Collection <---------java.util.List
    java.util.Collection <--------- java.util.Set
    java.util.Collection <--------- java.util.SortedSet
    Collection interface is the root interface of collection hierarchy.List interface is most commonly used collection type.LinkedList and ArrayList are its well known implementing classes.Lists can store objects only and not primitive types like int but one can create Integer objects.All objects in List are indexed from 0 to (size of list-1)

    Set is very much like list but with added constraint of not storing duplicate values.Sets do not impose a 0..size-1 indexing of the elements (that's what Lists do), so List methods like get(int index) are not available for sets.

    HashSet is mostly used set which only works with elements, like String and Integer, which have a hashCode() defined. The TreeSet is an alternative which has performance issues, but keeps the set in sorted order, so iteration will yield the values in sorted order.

    java.util.Collection <-----------java.util.Map

    A Map is altogether different from List and Set.It stores key-value pairs and any value can quickly be searched on the basis of a key.A map cannot contain duplicate keys; each key can map to at most one value.'Map' is a basic interface being implemented by classes HashMap and TreeMap.HashMap is most commonly used which can store objects in unordered fashion while TreeMap can store in ordered fashion.Some implementations of Map prohibit null keys and values and some have restrictions on type of their keys.You may get NullPointerException or ClassCastException when trying to insert or retrieve invalid keys or values.
    Read More on Collection Framework...

  • What is the serialization?
  • Serialization is a process of converting an object into byte stream which can be stored in persistent storage area like file system or database and can occur over a network.This persisted object can be converted back,called a process of deserialization, to restore original object. A java.io.Serailizable interface provides syntactical approach to do serialization.This interface does not contain any method,also known as marker interface.
    Object serialization is necessary for:
    -Java RMI, while sending messages to a remote object,it is necessary to transport arguments to remote object and return values.
    -Java Beans, state information of object is stored and later recovered when needed.

  • What is the difference between Serializable and Externalizable interface?
  • java.io.Serializable interface is an empty interface with no methods and attributes.It is implemented by objects which are needed to be serialized and serves only to identify the semantics of being serializable.
    When process of serializing an object is to be controlled then Externalizable interface is used.The Externizable interface extends Serializable and adds two methods,writeExternal() and readExternal() which are automatically called during serialization and deserialization.
    Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:
    private void writeObject(java.io.ObjectOutputStream out) throws IOException

    private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;

  • What is memory leak?
  • A memory leak occurs when all references (pointers) to a piece of allocated memory are overwritten, cleared, or pass out of scope. The result is that the program simply "forgets" about that particular piece of memory.Unfortunately , the operating environment (usually an OS) is not aware of the application's amnesia. That memory is treated by the outside world as though it still belongs to the application. The memory is therefore completely unavailable;it has "leaked". (In the worst case, the memory can become unavailable to all applications in the system, even if the application that created the leak is terminated. The memory can only be reclaimed by rebooting the system.)

  • Difference between ArrayList and Vector class?
  • From an API perspective, the two classes are very similar.

    Vectors are synchronized. Any method that touches the Vector's contents is thread safe. ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization will incur a performance hit. So if you don't need a thread-safe collection, use the ArrayList.

    Internally, both the ArrayList and Vector hold onto their contents using an Array. You need to keep this fact in mind while using either in your programs. When you insert an element into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Depending on how you use these classes, you could end up taking a large performance hit while adding new elements. It's always best to set the object's initial capacity to the largest capacity that your program will need. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later. If you don't know how much data you'll have, but you do know the rate at which it grows, Vector does possess a slight advantage since you can set the increment value.

  • What is the difference between Hashtable and HashMap?
  • Both Hashtable and HashMap store key-value pairs but they have following distinctive features:
    -Hashtable is synchronized while HashMap is not.In such a case Hashtable has performance overhead and should only be used when data is to be accessed in thread safe manner.
    -In Hashtable any non-null object can be used as a key or as a value but HashMap allows null keys and values.

  • What is JFC?
  • Java Foundation Classes(JFC) offers lightweight Java language specific GUI controls.JFC consists of group of classes for building graphical user interfaces (GUIs) and adding rich graphics functionality and interactivity to Java applications.
    JFC supoorts:
    -Swing GUI Components
    -Pluggable Look-and-Feel Support
    -Accessibility API
    -Java 2D API
    -Internationalization

  • What is the difference between JFC Swing and AWT?
  • AWT has following characteristics:
    -It has native C specific code
    -Rendering of AWT controls is dependent upon underlying OS.
    While JFC Swing is :
    -Pure Java based
    -Lightweight components
    -Pluggable look and feel features
    -Appearance of GUI developed using JFC Swing will be consistent across various OS.
    -Swing uses a more efficient event model than AWT; therefore, Swing components can run more quickly than their AWT counterparts

  • What is the base class for all swing components?
  • JFC Swing components (like textfields,buttons,checkboxes,lists etc. ) are direct replacements of corresponding AWT components and it replaces just some section of AWT GUI components,other aspects of AWT like layout managers remains unchanged.All these Swing components are extended from the javax.swing.JComponent, which has following hierarchy:
    java.lang.Object
    - java.awt.Component
    - java.awt.Container
    - javax.swing.JComponent

  • What are lightweight and heavyweight components ?
  • In AWT, all GUI controls are referred as heavyweight components as they are dependent on underlying OS(e.g. Windows,Solaris etc.) to provide it(paint it and redraw it).An AWT button control in MacOS is actually a MacOS button.
    All Swing components are lightweight components(except for the top-level ones: JWindow, JFrame, JDialog, and JApplet) as they do not require underlying OS to provide them.JVM renders Swing components and hence they are platform independent but they have performance related issues as compared to heavyweight components which are faster to be rendered due to hardware acceleration.
    The lightweight components have transparent pixels unlike heavyweights which have opaque pixels.Mouse events on a lightweight component fall through to its parent; while on a heavyweight component it does not.It is generally not recommended to mix heavyweight components with lightweight components while building the GUI.

  • How can a GUI component handle its own events?
  • A GUI component handles its events by implementing the required event listener interface.It adds its own event listener in order to keep a track of all events associated with it.AWT has Java1.0 and Java1.1 of Event handling in different manners:
    In Java1.0:Event handling is based on inheritance.A program catches and processes GUI events by subclassing GUI components and override either action() or handleEvent() methods.There are two possibilities in this scenario:
    a)Each component is subclassed to specifically handle its target events. The results in too many classes.
    b)All events or a subset for an entire hierarchy for handling a particular container; results in container's overridden action() or handleEvent() method and complex conditional statement for events processing.
    The event handling in Java 1.0 had issues like cumbersome to handle by developers,flitering of events was not too efficient as it was done in a single method handleEvent().
    In Java 1.1 these issues are resolved through delegation based event model.The GUI code can be seprated from event handling code which is cleaner,flexible,easier to maintanin and robust.In delegation event model,java.util.EventObject is the root class for event handling.An event is propagated from "Source" object(responsible for firing the event) to "Listener" object by invoking a method on the listener and passing in the instance of the event subclass which defines the event type generated.
    A listener is commonly an "adapter" object which implements the appropriate listener/(s) for an application to handl of events. The listener object could also be another AWT component which implements one or more listener interfaces for the purpose of hooking GUI objects up to each other.
    There can be following types of events:
    A low-level event represents a low-level input or window-system occurrence on a visual component on the screen.
    The semantic events are defined at a higher-level to encapsulate the semantics of a UI component's model.
    The low event class hierarchy:

    -java.util.EventObject

    -java.awt.AWTEvent

    -java.awt.event.ComponentEvent (component resized, moved, etc.)
    -java.awt.event.FocusEvent (component got focus, lost focus)

    -java.awt.event.InputEvent


    -java.awt.event.KeyEvent (component got key-press, key-release, etc.)

    -java.awt.event.MouseEvent (component got mouse-down, mouse-move, etc.)
    -java.awt.event.ContainerEvent

    -java.awt.event.WindowEvent

    The semantics event class hierarchy:

    -java.util.EventObject

    -java.awt.AWTEvent
    -java.awt.event.ActionEvent ("do a command")

    -java.awt.event.AdjustmentEvent ("value was adjusted")

    -java.awt.event.ItemEvent ("item state has changed")

    -java.awt.event.TextEvent ("the value of the text object changed")

    The low-level listener interfaces in AWT are as follows:
    java.util.EventListener - java.awt.event.ComponentListener

    - java.awt.event.ContainerListener

    - java.awt.event.FocusListener

    - java.awt.event.KeyListener

    - java.awt.event.MouseListener

    - java.awt.event.MouseMotionListener

    - java.awt.event.WindowListener

    The semantic listener interfaces in AWT are as follows:
    java.util.EventListener

    -java.awt.event.ActionListener

    -java.awt.event.AdjustmentListener

    -java.awt.event.ItemListener

    -java.awt.event.TextListener

    There are following Adapter classes in AWT :
    java.awt.event.ComponentAdapter

    java.awt.event.ContainerAdapter

    java.awt.event.FocusAdapter

    java.awt.event.KeyAdapter

    java.awt.event.MouseAdapter

    java.awt.event.MouseMotionAdapter

    java.awt.event.WindowAdapter

  • What is a Layout Manager and what are its different types and their advantages?
  • In Java,a GUI component does not decide about its geometry(location and size) on its own.A layout manager is an object which is responsible for managing or arranging the size and location of a GUI component.In AWT there are following layout managers which are supported:
    -Flow
    -Border
    -GridBag
    -Card
    -GridBag
    These layout managers organizes components consistently across all windowing platforms. Irrespective of underlying windowing OS,layouts behave in a regular fashion and show GUI components.A layout manager also represents an instance of a class which implements LayoutManager interface.The layout manager is set by setLayout(LayoutManager layoutManager) method.

  • How are the elements of a GridBagLayout organized?
  • A GridBagLayout organizes/arranges all GUI controls to a grid. However, these controls are of different sizes and may occupy more than one row or column of the grid. These rows and columns may have different sizes as well.It is by far most powerful layout manager and requires good practice and understanding to use.It can combine the features of Border,Flow and Card layouts and capable of much more.
    GridBag layout divides its container into an array of cells, different cell rows can have different heights, and different cell columns can have different widths. A component can occupy part or all of a region.While a region is spanned over a single cell or a rectangle made up of multiple cells.A helper class called GridBagConstraints is used to hold all the layout position information.The add(Component, Object) version of the add() method is used for adding a control, passing an instance of GridBagConstraints as the Object parameter.

  • What are the problems faced by Java programmers in absence of layout managers?
  • If relevant layout managers are not used while designing a GUI then GUI controls will have haphazard/inconsistent display across multiple windowing systems.These GUI controls will neglect their common sizing and positioning that ideally should be same across various windowing systems.
    In order to counter this issue, an appropriate layout which is applicable for container object, must be chosen.

  • Where the CardLayout is used?
  • A CardLayout object is a layout manager for a container. It treats each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards. The first component added to a CardLayout object is the visible component when the container is first displayed.The ordering of cards is determined by the container's own internal ordering of its component objects. CardLayout defines a set of methods that allow an application to flip through these cards sequentially, or to show a specified card. The addLayoutComponent(java.awt.Component,java.lang.Object) method can be used to associate a string identifier with a given card for fast random access

  • What is the difference between GridLayout and GridBagLayout?
  • GridLayout class lays all components in a rectangular grid like structure of container. The container is divided into an equal sized rectangles and each component is placed inside a rectangle.
    The GridBagLayout class is a flexible layout manager that aligns components vertically and horizontally, without requiring that the components be of the same size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells, with each component occupying one or more cells, called its display area.

    Each component managed by a GridBagLayout is associated with an instance of GridBagConstraints. The constraints object specifies where a component's display area should be located on the grid and how the component should be positioned within its display area. In addition to its constraints object, the GridBagLayout also considers each component's minimum and preferred sizes in order to determine a component's size.

  • How will you add a panel to a frame?
  • Here goes the snippet:
    import javax.swing.*;
    public class XYZ extends JFrame{
    public XYZ(){
    JPanel panel =new JPanel();
    this.getContentPane().add(panel);
    }
    public static void main (String args[]){
    XYZ obj=new XYZ();
    obj.setVisible(true);
    }
    }

  • What is the difference between Application and Applet?
  • An applet runs in client side web browser. A class extending java.awt.Applet class which has methods like init(), start(), stop(), destroy(),paint() overridden.An applet has restriction of accessing client side resources like network connections, it cannot open socket connections and cannot write to client side files i.e. hard disk.
    An application runs standalone with a support of virtual machine. An application does not have nay restrictions as Applets have over network and file related activities.They are free to open sockets over a network read and write to a file.

  • Explain Lifecycle of the Applet and what is the order of method invocation in an applet?
  • An applet is built up of four methods:init,start,stop and destroy.First of all an instance of applet subclass will be created and then applet will be initialized.Swing provides a special subclass of Applet, called javax.swing.JApplet, which should be used for all applets that use Swing components to construct their GUIs.
    Here is a sequence of method calls in an applet :

    -init():An applet can initialize itself and does whatever initializations are required to do for an applet.
    -start(): This method is automatically called when applet is initialized.When a user comes back to a page with an applet this method is invoked then too.
    -stop(): This method is called when user moves away from the webpage containing applet
    -destroy:It is responsible for clean up and is called when browser is shut down normally.
    An applet can be initialized and destroyed only once in its lifetime but it can be started and stopped several times.

  • What is the difference between Java class and bean?
  • What differentiates Beans from typical Java classes is introspection. The tools that recognize predefined patterns in method signatures and class definitions can "look inside" a Bean to determine its properties and behavior. A Bean's state can be manipulated at the time it is being assembled as a part within a larger application. The application assembly is referred to as design time in contrast to run time. In order for this scheme to work, method signatures within Beans must follow a certain pattern in order for introspection tools to recognize how Beans can be manipulated, both at design time, and run time.

  • What is difference between trusted and untrusted applet?
  • A trusted applet is one which signed by a trusted authority. The trusted applet is installed on the local hard disk, in a directory on the CLASSPATH used by the program that you are using to run the applet. Usually, this is a Java-enabled browser, but it could be the appletviewer, or other Java programs that know how to load applets.

    The applet is signed by an identity marked as trusted in your identity database.By default all applets downloaded in client browser are untrusted.
    -They cannot read or write files to clients' local file system at all.
    -They cannot start a program at client's machine.
    -They cannot do network operations i.e. cannot do Socket programming.
    -They cannot load libraries and use native codes.

  • How do you set Java Library path programmatically?
  • Java library path can be set by choosing an option as:-

    -Djava.library.path=your_path
    While setting the java.library.path property to "." instructs the Java virtual machine to search for native libraries in the current directory.

    And you execute your code as :
      java -Djava.library.path=. HelloWorld
    
    The "-D" command-line option sets a Java platform system property. But these values are 'read only' like many of the system properties, the value in java.library.path is just FYI and changing it doesn't actually change the behaviour of the JVM.
    If you want to load a library from a specific location, you can use System.load() instead with the full path to the library.

  • Explain the usage of java.util.Date and more classes and APIs for date handling in Java?
  • The class java.util.Date
    -Represents a point in time.
    -Corresponds to the number of milliseconds since the start of the Unix epoch on January 1, 1970, 00:00:00 GMT.
    -This class depends on System.currentTimeMillis() to obtain the current point in time,which actually returns a long value and its accuracy and precision is determined by the implementation of System and underlying OS.
    Apart from this class there are several other classes like GregorianCalendar,SimpleTimeZone,SimpleDateFormat,DateFormatSymbols,java.sql.Date,java.sql.Time ,java.sql.Timestamp which are used for handling date and time related problems.In the table shown below a very brief purposes of these classes have been summarized:



  • JDBC

  • What is JDBC ?
  • JDBC is Java Database Connectivity, a collection of APIs for connecting a Java application to a database. It is an abstraction over ODBC so as to provide Java clients an interface to connect to the database end.The latest update of the JDBC API is JDBC3.0. It contains many features, including scrollable result sets and the SQL:1999 data types.
    The first version of JDBC(JDBC1.22 with JDK1.1.x release) had only one pacakge named java.sql.* but in JDBC2.0(released with Java2) there had been introduced several new features in two pacakges namely,java.sql.* and javax.sql.*

  • What are four drivers available in JDBC?
  • Type 1: JDBC-ODBC bridge.It is for databases that support ODBC.It Uses a bridging technology to access the database (e.g., Sun's JDBC-ODBC Bridge driver)

    Type 2: JDBC to a database vendor DLL.It uses native API drivers.It requires software on the client machine. Uses native API drivers; requires software on the client machine Supplied by the vendor or by third parties.

    Type 3: JDBC to middleware software to the database.It translates JDBC calls into a database-independent network protocol, which a server then translates into a database protocol

    Type 4: Pure Java to a network protocol.It uses the network protocols built into the database engine

    Type1 and Type2 database drivers are not suitable for Internet based connection to the databases as these types of database drivers are to be installed on client machine.

  • How do you establish database connection using JDBC?
  • The database connection using JDBC involves two steps:
    - Loading database driver class
    - Making the connection to database
    Here is code snippet for connection to the database:
    String driverClassName="sun.jdbc.odbc.JdbcOdbcDriver";
    String url="jdbc:odbc:dsnname";
    String usrname="hello";
    String passwd="india";
    String qry="select username from users";
    try{
    Class.forName(driverClassName);//loading the database driver
    Connection con=DriverManager.getConnection(url,usrname,passwd);
    Statement stmt=con.createStatement();
    ResultSet rs =stmt.executeQuery(qry);
    while(rs.next()){

    }
    } catch(Exception exc){
    exc.printStackTrace();
    }

  • How do you connect to a MySql Database using JDBC?
  • Recently some newbie asked me a simple question of connecting to MySql database using JDBC.Here is a code snippet for that.The important thing here is to ensure that you have added MySql database driver classes(mysql.jar) in your classpath. Here goes the code snippet:
    import java.sql.*;
    
    public class MySqlConnect {
    
    
      public static void main (String[] args)
      {
          Connection connection = null;
    
          try
          {
              String userName = "root";
              String password = "bunty";
              String url = "jdbc:mysql://localhost:3306/systdb";
           
              Class.forName ("com.mysql.jdbc.Driver").newInstance ();
           
              connection = DriverManager.getConnection (url, userName, password);
              System.out.println ("Database connection established");
          }
          catch (Exception e)
          {
              System.err.println ("Connection to database server cannot be establish");
          }
          finally
          {
              if (connection != null)
              {
                  try
                  {
                      connection.close ();
                      System.out.println ("Database connection terminated");
                  }
                  catch (Exception e) { System.out.println ("These connection errors can be ignored."); }
              }
          }
      }
    } 

  • What are the different types of Statements?
  • There are several statements supported in JDBC and mainly they are as given below:
    -Regular statement (use createStatement method),
    -Prepared statement (use prepareStatement method)
    -Callable statement (use prepareCall)

  • What is PreparedStatement and how is different from Statement?
  • A PreparedStatement, in contrast to a Statement, is used for SQL statements that are executed multiple times with different values. For instance, you might want to insert several values into a table, one after another. The advantage of the PreparedStatement is that it is pre-compiled, reducing the overhead of parsing SQL statements on every execution.
    In such cases DBMS will execute the query directly without worrying about compiling the statement again.

  • What is the difference between executeQuery () and execute() ?
  • The return type of execute() method is boolean , if true that means a ResultSet object is returned, if false no result is returned.The ResultSet is obtained on Statement object in such case through getResultSet method.In case of executeQuery() method once executed returns ResultSet object.

  • What is the difference between executeQuery () and executeUpdate()?
  • The difference between executeQuery and executeUpdate is that executeUpdate is for executing statements that change data in the database. For example, use executeUpdate to execute a CREATE an INSERT or an UPDATE statement. executeUpdate returns an int, and the value of that int corresponds to the number of records that were modified. While executeQuery() method is used for executing SQL statements and it returns ResultSet object.

  • How do you call a stored procedure in Java?
  • Through a CallableStatement: Callable statements are implemented by the CallableStatement object. A CallableStatement is a way to execute stored procedures in a JDBC-compatible database.

  • What are new features from JDBC2.0 onwards?
  • New Features in JDBC 2.0:
    -Scrollable resultset
    -No more updations on tables through queries required,one can use methods provided like updateRow(),insertRow() and deleteRow() etc.
    -Send multiple SQLs to database as a unit/batch(addbatch(),executeBatch() )
    -Use new SQL3 datatypes as column values like Blob,Clob etc

  • How can a cursor move in scrollable result sets?
  • JDBC result sets are created with three properties: type, concurrency and holdability.
    The type can be one of
    -TYPE_FORWARD_ONLY
    -TYPE_SCROLL_INSENSITIVE
    -TYPE_SCROLL_SENSITIVE.

    The concurrency can be one of
    -CONCUR_READ_ONLY
    -CONCUR_UPDATABLE.

    The holdability can be one of
    -HOLD_CURSORS_OVER_COMMIT
    -CLOSE_CURSORS_AT_COMMIT.

    JDBC allows the full cross product of these. Some database like SQL 2003 prohibits the combination {TYPE_SCROLL_INSENSITIVE, CONCUR_UPDATABLE}, but this combination is supported by some vendors, notably Oracle.

    The movable cursors,moving forward and backward on a resultset is one of the new features in the JDBC 2.0 API. There are also methods that let you move the cursor to a particular row and check the position of the cursor.
    Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
    
    ResultSet resultSet =  stmt.executeQuery("SELECT FNAME, LNAME FROM EMPLOYEE");
    
    while (resultSet.next()) {
    
    . . . // iterates forward through resultSet
    
    }
    
    . . .
    
    resultSet.absolute(5); // moves cursor to the fifth row
    
    . . .
    
    resultSet.relative(-2); // moves cursor to the third row
    
    . . .
    
    resultSet.relative(4); // moves cursor to the seventh row
    
    . . .
    
    resultSet.previous(); // moves cursor to sixth row
    
    . . .
    
    int rowNumber = resultSet.getRow(); // rowNumber should be 6
    
    resultSet.moveAfterLast(); // moves cursor to position // after last row
    
    while (previous()) {
    
    . . . // iterates backward through resultSet
    
    }
    
    When a resultset type is defined then it is also significant to define whether it is readonly or updatable and type and concurrency should be in the same order as shown in the code above.If you change the order then compiler can not distinguish it.If you specify the constant TYPE_FORWARD_ONLY, it creates a nonscrollable result set, in which the cursor moves forward only. The default value of ResultSet object type is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.

  • Differentiate TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE?
  • TYPE_SCROLL_INSENSITIVE specifies that a resultset is scrollable in either direction but is insensitive to changes committed by other transactions or other statements in the same transaction.
    TYPE_SCROLL_SENSITIVE specifies that a resultset is scrollable in either direction and is affected by changes committed by other transactions or statements within the same transaction.
    This needs a small coding effort to verify this differntiation.Any volunteers? Please write in your comments to put your understanding about this concept.

  • How will you differentiate the following two ways of loading a database driver?
  • (1)DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    (2)Class.forName("oracle.jdbc.driver.OracleDriver");

    In case one, to load the driver, one needs an appropriate class to load, make a driver instance and register it with the JDBC driver manager. Class.forName() will cause the class to create an instance, and call the current class loader's DriverManager.registerDriver() method to announce its presence.While DriverManager.registerDriver registers an instance of the with driver manager

  • How can you display a particular web page from an applet?
  • The following code snippet shows you how to achieve that using showPage method is capable of displaying any URL passed to it.
    import java.net.*;
    import java.awt.*;
    import java.applet.*;
    
    public class TestApplet extends Applet
    {
    // Applet code goes here
    
    // Show a page
    public void showPage ( String showPage)
    {
        URL url = null;
    
        // Create a URL object
        try
        {
            url = new URL ( showPage );
        }
        catch (MalformedURLException e)
        {
            // Invalid URL
        }
       
        // Show URL
        if (url != null)
        {
            getAppletContext().showDocument (url);
        }
    
    }
    }

  • How can you get the hostname on the basis of IP addres ?
  • The following snippet of code helps you in finding hostname on the basis of IP address:-
    
    InetAddress inetAddress = InetAddress.getByName("67.83.45.98");
    System.out.println ("Host Name: " + inetAddress.getHostName());

  • How can you get an IP address of a machine from its hostname?
  • In case of TCP protocol i.e. ServerSocket:

    Each Socket connection accepted corresponds to who is connecting to your server, that means relevant method calls on ServerSocket will fetch IP address and port of the same.

    Socket socket = serverSocket.accept();
    
    // Print IP address and  port
    System.out.println ("Connecting from : " +
    socket.getInetAddress().getHostAddress() + ':' + socket.getPort());
    

    In case of UDP i.e. DatagramSocket

    The DatagramPacket received contains all the necessary information:
    DatagramPacket datagramPacket = null;
    
    // Receive next packet
    datagramSocket.receive ( datagramPacket );
    
    // Print address + port
    System.out.println ("Packet received from : " +
    datagramPacket.getAddress().getHostAddress() + ':' + datagramPacket.getPort());

  • How do you know who is accessing your server?
  • In case of TCP protocol i.e. ServerSocket:

    Each Socket connection accepted corresponds to who is connecting to your server, that means relevant method calls on ServerSocket will fetch IP address and port of the same.

    Socket socket = serverSocket.accept();
    
    // Print IP address and  port
    System.out.println ("Connecting from : " +
    socket.getInetAddress().getHostAddress() + ':' + socket.getPort());
    

    In case of UDP i.e. DatagramSocket

    The DatagramPacket received contains all the necessary information:
    DatagramPacket datagramPacket = null;
    
    // Receive next packet
    datagramSocket.receive ( datagramPacket );
    
    // Print address + port
    System.out.println ("Packet received from : " +
    datagramPacket.getAddress().getHostAddress() + ':' + datagramPacket.getPort());

  • What are different socket options?
  • The different Socket options are :

    SO_TIMEOUT
    SO_LINGER
    TCP_NODELAY
    SO_RCVBUF
    SO_SNDBUF.

    They may be specified in various scenarios e.g. one might like to specify a timeout for read operations, to control the amount of time a connection will linger for before a reset is sent, whether Nagle's algorithm is enabled/disabled, or the send and receive buffers for datagram sockets.


  • What should I use a ServerSocket or DatagramSocket in my applications?
  • DatagramSocket accepts only UDP packets, whereas ServerSocket allows TCP connections in an application. It depends on the protocol one implements. Here are few things which one should keep in mind while implementing a new protocol:

    -UDP is not a reliable protocol as you may loose data packets over the network so while coding you will have to handle missing packets in your client/server.

    -ServerSockets use TCP connections for communication.TCP is safe and reliable protocol and guarantees delivery, all you need is InputStream to read and OutputStream to write over TCP.

No comments: