Feeds:
Posts
Comments

Archive for the ‘Java Q & A’ Category

   1. What is the servlet?

      Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet may be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database.

   2. What’s the difference between servlets and applets?

      Servlets are to servers; applets are to browsers. Unlike applets, however, servlets have no graphical user interface.

   3. What’s the advantages using servlets than using CGI?

      Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. It is efficient, convenient, powerful, portable, secure and inexpensive. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with Java Servlet API, a standard Java extension.

   4. What are the uses of Servlets?

      A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.

   5. What’s the Servlet Interface?

      The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet. Servlets–>Generic Servlet–>HttpServlet–>MyServlet. The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

   6. When a servlet accepts a call from a client, it receives two objects. What are they?

      ServeltRequest: which encapsulates the communication from the client to the server.
      ServletResponse: which encapsulates the communication from the servlet back to the client.
      ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

Read Full Post »

JSP

   1. What is JSP technology?

      Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSPs are secure, platform-independent, and best of all, make use of Java as a server-side scripting language.

   2. What is JSP page?

      A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content.

   3. What are the implicit objects?

      Implicit objects are created by the web container and contain information related to a particular request, page, or application. They are request, response, pageContext, session, application, out, config, page and exception.

   4. How many JSP scripting elements and what are they?

      There are three scripting language elements: declarations, scriptlets, and expressions.

   5. Why are JSP pages the preferred API for creating a web-based client program?

      Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.

   6. Is JSP technology extensible?

      YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

Read Full Post »

JDBC

   1. What is JDBC?

      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.

   2. What are the two major components of JDBC?

      One implementation interface for database manufacturers, the other implementation interface for application and applet writers.

   3. What is JDBC Driver interface?

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

   4. What are the common tasks of JDBC?

1.Create an instance of a JDBC driver or load JDBC drivers through jdbc.drivers;
2. Register a driver;
3. Specify a database;
4. Open a database connection;
5. Submit a query;
6. Receive results.

   5. What packages are used by JDBC?

      There are 8 packages: java.sql.Driver, Connection,Statement, PreparedStatement, CallableStatement, ResultSet, ResultSetMetaData, DatabaseMetaData.

   6. What are the flow statements of JDBC?

      A URL string –>getConnection–>DriverManager–>Driver–>Connection–>Statement–>executeQuery–>ResultSet.

   7. What are the steps involved in establishing a connection?

      This involves two steps: (1) loading the driver and (2) making the connection.

   8. How can you load the drivers?

      Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:

Eg.
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

      Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ , you would load the driver with the following line of code:

E.g.
Class.forName(“jdbc.DriverXYZ”);

   9. What Class.forName will do while loading drivers?

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

  10. How can you make the connection?

      In establishing a connection is to have the appropriate driver connect to the DBMS. The following line of code illustrates the general idea:

E.g.
String url = “jdbc:odbc:Fred”;
Connection con = DriverManager.getConnection(url, “Fernanda”, “J8″);

  11. How can you create JDBC statements?

      A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate. E.g. It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object stmt :

Statement stmt = con.createStatement();

  12. How can you retrieve data from the ResultSet?

      First JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.

E.g.
ResultSet rs = stmt.executeQuery(“SELECT COF_NAME, PRICE FROM COFFEES”);

Second:
String s = rs.getString(“COF_NAME”);

      The method getString is invoked on the ResultSet object rs , so getString will retrieve (get) the value stored in the column COF_NAME in the current row of rs

  13. What are the different types of Statements?

1.Statement (use createStatement method)
2. Prepared Statement (Use prepareStatement method) and
3. Callable Statement (Use prepareCall)

  14. How can you use PreparedStatement?

      This special type of statement is derived from the more general class, Statement. If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement ‘s SQL statement without having to compile it first.

E.g.
PreparedStatement updateSales = con.prepareStatement(“UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?”);

  15. How to call a Stored Procedure from JDBC?

      The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure;

E.g.
CallableStatement cs = con.prepareCall(“{call SHOW_SUPPLIERS}”);
ResultSet rs = cs.executeQuery();

  16. How to Retrieve Warnings?

      SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object

E.g.
SQLWarning warning = stmt.getWarnings();
    if (warning != null) {

        while (warning != null) {
          System.out.println(“Message: ” + warning.getMessage());
          System.out.println(“SQLState: ” + warning.getSQLState());
          System.out.print(“Vendor error code: “);
          System.out.println(warning.getErrorCode());
          warning = warning.getNextWarning();
        }
    }

  17. How to Make Updates to Updatable Result Sets?

      Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.

E.g.
Connection con = DriverManager.getConnection(“jdbc:mySubprotocol:mySubName”);
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = (“SELECT COF_NAME, PRICE FROM COFFEES”);

Read Full Post »

   1. What is the difference between URL instance and URLConnection instance?

      A URL instance represents the location of a resource, and a URLConnection instance represents a link for accessing or communicating with the resource at the location.

   2. How do I make a connection to URL?

      You obtain a URL instance and then invoke openConnection on it. URLConnection is an abstract class, which means you can’t directly create instances of it using a constructor. We have to invoke openConnection method on a URL instance, to get the right kind of connection for your URL. Eg. URL url;

 URLConnection connection;
 try {
  url = new URL(“…”);
  connection = url.openConnection();
 } catch (MalFormedURLException e) { }

   3. What Is a Socket?      A socket is one end-point of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes–Socket and ServerSocket–which implement the client side of the connection and the server side of the connection, respectively.

   4. What information is needed to create a TCP Socket?

      The Local System?s IP Address and Port Number. And the Remote System’s IPAddress and Port Number.

   5. What are the two important TCP Socket classes?

      Socket and ServerSocket. ServerSocket is used for normal two-way socket communication. Socket class allows us to read and write through the sockets. getInputStream() and getOutputStream() are the two methods available in Socket class.

   6. When MalformedURLException and UnknownHostException throws?

      When the specified URL is not connected then the URL throw MalformedURLException and If InetAddress? methods getByName and getLocalHost are unable to resolve the host name they throw an UnknownHostException.

   7. What does RMI stand for?

      It stands for Remote Method Invocation.

   8. What is RMI?

      RMI is a set of APIs that allows to build distributed applications. RMI uses interfaces to define remote objects to turn local method invocations into remote method invocations.

Read Full Post »

  81. What is the purpose of the enableEvents() method?

      The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.

  82. What is the difference between the File and RandomAccessFile classes?

      The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

  83. What interface must an object implement before it can be written to a stream as an object?

      An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

  84. What is the ResourceBundle class?

      The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.

  85. What is the difference between a Scrollbar and a ScrollPane?

      A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.

  86. What is a Java package and how is it used?

      A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.

  87. What are the Object and Class classes used for?

      The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.

  88. What is Serialization and deserialization?

      Serialization is the process of writing the state of an object to a byte stream.
      Deserialization is the process of restoring these objects.

  90. How you restrict a user to cut and paste from the html page ?

      Using javascript to lock keyboard keys. It is one of solutions.

  91. Is Java a super set of JavaScript ?

      No. They are completely different. Some syntax may be similar.

Read Full Post »

  52. Which package has light weight components?

      javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.

  53. What are peerless components?

      The peerless components are called light weight components.

  54. What is the difference between the Font and FontMetrics classes?

      The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.

  55. What happens when a thread cannot acquire a lock on an object?

      If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object’s lock, it enters the waiting state until the lock becomes available.

  56. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

      The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.

  57. What classes of exceptions may be caught by a catch clause?

      A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.

  58. If a class is declared without any access modifiers, where may the class be accessed?

      A class that is declared without any access modifiers is said to have package or friendly access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

  59. What is the Map interface?

      The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.

  60. Does a class inherit the constructors of its superclass?

      A class does not inherit constructors from any of its superclasses.

  61. Name primitive Java types.

      The primitive types are byte, char, short, int, long, float, double, and boolean.

  62. Which class should you use to obtain design information about an object?

      The Class class is used to obtain information about an object’s design.

  63. How can a GUI component handle its own events?

      A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

  64. How are the elements of a GridBagLayout organized?

      The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

  65. What advantage do Java’s layout managers provide over traditional windowing systems?

      Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.

  66. What are the problems faced by Java programmers who don’t use layout managers?

      Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.

  67. What is the difference between static and non-static variables?

      A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

  68. What is the difference between the paint() and repaint() methods?

      The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

  69. What is the purpose of the File class?

      The File class is used to create objects that provide access to the files and directories of a local file system.

  70. How does multithreading take place on a computer with a single CPU?

      The operating system’s task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.

  71. What restrictions are placed on method overloading?

      Two methods may not have the same name and argument list but different return types.

  72. What restrictions are placed on method overriding?

      Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.

  73. What is casting?

      There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

  74. Name Container classes.

      Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

  75. What class allows you to read objects directly from a stream?

      The ObjectInputStream class supports the reading of objects from input streams.

  76. How are this() and super() used with constructors?

      this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

  77. How is it possible for two String objects with identical values not to be equal under the == operator?

      The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.

  78. What an I/O filter?

      An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

  79. What is the Set interface?

      The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.

  80. What is the List interface?

      The List interface provides support for ordered collections of objects.

Read Full Post »

  30. What is the purpose of finalization?

      The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

  31. Which class is the superclass for every class.

      Object

  32. What invokes a thread’s run() method?

      After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread’s run() method when the thread is initially executed.

  33. What is the difference between the Boolean & operator and the && operator?

      If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
      Operator & has no chance to skip both sides evaluation and && operator does. If asked why, give details as above.

  34. What is the GregorianCalendar class?

      The GregorianCalendar provides support for traditional Western calendars.

  35. What is the SimpleTimeZone class?

      The SimpleTimeZone class provides support for a Gregorian calendar.

  36. Which Container method is used to cause a container to be laid out and redisplayed?

      validate()

  37. What is the Properties class?

      The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.

  38. What is the purpose of the Runtime class?

      The purpose of the Runtime class is to provide access to the Java runtime system.

  39. What is the purpose of the System class?

      The purpose of the System class is to provide access to system resources.

  40. What is the purpose of the finally clause of a try-catch-finally statement?

      The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

  41. What is the Locale class?

      The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.

  42. What must a class do to implement an interface?

      It must provide all of the methods in the interface and identify the interface in its implements clause.

  43. What is the purpose of the wait(), notify(), and notifyAll() methods?

      The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to communicate each other.

  44. What is an abstract method?

      An abstract method is a method whose implementation is deferred to a subclass.

  45. What are the high-level thread states?

      The high-level thread states are ready, running, waiting, and dead.

  46. What is the difference between a static and a non-static inner class?

      A non-static inner class may have object instances that are associated with instances of the class’s outer class. A static inner class does not have any object instances.

  47. What is an object’s lock and which object’s have locks?

      An object’s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object’s lock. All objects and classes have locks. A class’s lock is acquired on the class’s Class object.

  48. When can an object reference be cast to an interface reference?

      An object reference be cast to an interface reference when the object implements the referenced interface.

  49. What is the difference between a Window and a Frame?

      The Frame class extends Window to define a main application window that can have a menu bar.

  50. What do heavy weight components mean?


  Heavy weight components like Abstract Window Toolkit (AWT), depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button. In this relationship, the Motif button is called the peer to the java.awt.Button. If you create two Buttons, two peers and hence two Motif Buttons are also created. The Java platform communicates with the Motif Buttons using the Java Native Interface. For each and every component added to the application, there is an additional overhead tied to the local windowing system, which is why these components are called heavyweight.

Read Full Post »

Older Posts »

Follow

Get every new post delivered to your Inbox.

Join 196 other followers