Search

Useful Links

Friday, September 23, 2011

What is session facade?

A session façade is an EJB design pattern in which a session bean is works like a wrapper over entity beans. A client does not have a direct access to Entity beans but through session beans only for reducing network overhead. Usually stateless session beans are used as single access point for the clients but stateful session beans can also be used for the same purpose. A layer of session beans exposed to clients to access not only gives a clean approach towards client access to bean components but also reduce network calls so as to make the whole system of high performance.

Thursday, September 22, 2011

Difference between Abstract Factory and Factory Method design patterns?


In order to answer this question we must first understand what are Abstract Factory and Factory Method design patterns.

An Abstract Factory(AF) provides an interface for creating families of related or dependent objects without specifying their concrete classes. you usually have multiple factory implementations. Each factory implementation is responsible for creating objects that are usually in a related hierarchy.

In case of Factory Method(or simply called Factory pattern), generally a key or parameter is provided and method obtains an object of that type.The classic example can be creating a Database Connection Factory which is responsible for providing a vendor specific database connection objects(like Oracle,DB2,MS SQL Server etc.) depending upon the kind of parameter is provided.

AF is very similar to the Factory Method pattern.One difference between the two is that with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition whereas the Factory Method pattern uses inheritance and
relies on a subclass to handle the desired object instantiation.

The best example to quote of AF is EJBHome object.When a client composes the home interface and calls a create method to get the component interface. The component interface is the abstract product and the implementation is created by the container. The client composes the abstract factory (home interface) and calls a create method on the abstract factory to create the product.

In nutshell, AF is a creational pattern for the family of objects, whereas the factory method is a way to get one individual member of a family.So in a way, AF uses Factory method.

Wednesday, September 21, 2011

Adapter Design Pattern in Java


Adapter design pattern lets unrelated classes communicate and work with each other.It achieves this objective by creating new interfaces for creating compatibility amongst otherwise non communicable classes.

The adapter classes in Java API are WindowAdapter,ComponentAdapter, ContainerAdapter, FocusAdapter, KeyAdapter, MouseAdapter and MouseMotionAdapter.

In case of listener interfaces,whenever a class implements such an interface, one has to implement all of the seven methods.In case of WindowListener interface,it has seven methods.WindowAdapter class implements WindowListener interface and make seven empty implementation. When a class subclasses WindowAdapter class, one may choose the implementation of a method as per one's choice of implementation.

Adapter design pattern is also referred as Wrapper pattern when it is introduced by composition of classes.

Tuesday, September 20, 2011

Decorator Design Pattern in Java


Decorator design pattern attaches additional responsibilities or functions, dynamically or statically on an object.One can add new functionalities on an object without affecting other objects enhancing flexibility of an object.

The best example of Decorator pattern in a visual manner can be illustrated from JScrollPane object which can be used to decorate a JTextArea object or a JEditorPane object. The different borders of a window like BevelBorder, CompoundBorder, EtchedBorder TitledBorder etc. are other examples of classes working as decorators existent in Java API.

Decorator pattern can be used in a non-visual fashion. For example, BufferedInputStream, DataInputStream, and CheckedInputStream are decorating objects of FilterInputStream class. These decorators are standard Java API classes.

Monday, September 19, 2011

Different types of design patterns?


There are three kinds of design patterns:

Creational patterns:

They are related with how objects and classes are created. While class-creation patterns use inheritance effectively in the instantiation process,while object-creation patterns use delegation to get the job done.

* Abstract Factory groups object factories that have a common theme.
* Builder constructs complex objects by separating construction and representation.
* Factory Method creates objects without specifying the exact object to create.
* Prototype creates objects by cloning an existing object.
* Singleton restricts object creation for a class to only one instance.

Structural patterns:

They are related to class and object composition.This pattern uses inheritance to define new interfaces in order to compose new objects and hence new functionalities.

* Adapter allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class.
* Bridge decouples an abstraction from its implementation so that the two can vary independently.
* Composite composes one-or-more similar objects so that they can be manipulated as one object.
* Decorator dynamically adds/overrides behavior in an existing method of an object.
* Facade provides a simplified interface to a large body of code.
* Flyweight reduces the cost of creating and manipulating a large number of similar objects.
* Proxy provides a placeholder for another object to control access, reduce cost, and reduce complexity.

Behavioral patterns:

These design patterns deal with objects communication. They are specifically concerned with communication between objects.

* Chain of responsibility delegates commands to a chain of processing objects.
* Command creates objects which encapsulate actions and parameters.
* Interpreter implements a specialized language.
* Iterator accesses the elements of an object sequentially without exposing its underlying representation.
* Mediator allows loose coupling between classes by being the only class that has detailed knowledge of their methods.
* Memento provides the ability to restore an object to its previous state (undo).
* Observer is a publish/subscribe pattern which allows a number of observer objects to see an event.
* State allows an object to alter its behavior when its internal state changes.
* Strategy allows one of a family of algorithms to be selected on-the-fly at runtime.
* Template method defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior.

Explain Facade Design Pattern in Java


The objective of Facade pattern is to make a complex system simple. It is achieved by providing a unified or general interface, which is a higher layer to these subsystems.Facade pattern decouples subsystems, reduce its dependency, and improve portability,makes an entry point to your subsystems and hides clients from subsystem components and their implementation.

JDBC design is a good example of Façade pattern. A database design is complicated. JDBC is used to connect the database and manipulate data without exposing details to the clients.

A client is exposed to certain set of methods like just getting a single instance of database connection or closing it when not required.

Another possibility is designing security of a system with Façade pattern. Clients' authorization to access information may be classified. General users may be allowed to access general information, special guests may be allowed to access more information,administrators and executives may be allowed to access the most important information. These subsystems may be generalized by oneinterface. The identified users may be directed to the related
subsystems.

interface PublicMethod{
public void accessPublicMethod();
}

interface SpecialMethod extends PublicMethod{

public void accessSpecialMethod();

}

interface PrivateMethod extends PublicMethod {

public void accessPrivateInfo();

}

class PublicInfo implements PublicMethod{

public void accessPublicMethod() {

//...
}

//...
}

class SpecialInfo extends PublicInfo implements SpecialMethod {

public void accessSpecialMethod() {

//...
}

}

class PrivateInfo extends SpecialInfo implements PrivateMethod {

public void accessPrivateMethod () {

// ...

}

//...
}


The above code example illustrates that the whole system is not exposed to the clients. It depends on the user classification.

When a person is exposed to special information, that person is allowed to access public information also. When a person is exposed to private information, that person is allowed to access public and special information as well.

Sunday, September 18, 2011

What are Design Patterns and why one needs them?


A pattern based designing approach is best suited in devising solutions for problems occurring over and over again.The design patterns are language-independent strategies for solving common object-oriented design problems.

When you design, you should have advanced knowledge of such solutions in order to overcome problems that may occur in your system. GoF, Gang-Of-Four,because of the four authors who wrote, Design Patterns: Elements of Reusable Object-Oriented Software(ISBN 0-201-63361-2) is a software engineering book describing recurring solutions to common problems in software design. The book's authors are Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. It is language independent approach of designing systems on the based of patterns.

Singleton Design Pattern?


The Singleton Design Pattern is a Creational type of design pattern which assures to have only a single instance of a class, as it is necessary sometimes to have just a single instance.The examples can be print spooler,database connection or window manager where you may require only a single object.

In a Singleton design pattern,there is a public, static method which provides an access to single possible instance of the class.The constructor can either be private or protected.
public class SingletonClass {
private static SingletonClass instance = null;
protected SingletonClass() {
// can not be instantiated.
}
public static SingletonClass getInstance() {
if(instance == null) {
instance = new SingletonClass();
}
return instance;
}
}

In the code above the class instance is created through lazy initialization,unless getInstance() method is called,there is no instance created.This is to ensure that instance is created when needed.

public class SingletonInstantiator {
public SingletonInstantiator() {
SingletonClass instance = SingletonClass.getInstance();
SingletonClass anotherInstance =
new SingletonClass();
...
}
}

In snippet above anotherInstance is created which is a perfectly legal statement as both the classes exist in the same package in this case 'default', as it is not required by an instantiator class to extend SingletonClass to access the protected constructor within the same package.So to avoid even such scenario, the constructor could be made private.

Singleton Pattern

Singleton design pattern is the first design pattern I learned (many years back). In early days when someone asks me, “do you know any design pattern?” I quickly and promptly answer “I know singleton design pattern” and the question follows, “do you know anything other than singleton” and I stand stumped!

There are only two points in the definition of a singleton design pattern,
  1. there should be only one instance allowed for a class and
  2. we should allow global point of access to that single instance

Thursday, September 15, 2011

10. What is the fastest type of JDBC driver?
Type 4 (JDBC Net pure Java Driver) is the fastest JDBC driver. 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).
11. Is the JDBC-ODBC Bridge multi-threaded?
No. The JDBC-ODBC Bridge does not support multi threading. 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.
12. What is cold backup, hot backup, warm backup recovery?
Cold backup means all these files must be backed up at the same time, before the database is restarted. Hot backup (official name is ‘online backup’ ) is a backup taken of each tablespace while the database is running and is being accessed by the users
13. What is the advantage of denormalization?
Data denormalization is reverse procedure, carried out purely for reasons of improving performance. It maybe efficient for a high-throughput system to replicate data for certain data.
14. How do you handle your own transaction ?
Connection Object has a method called setAutocommit ( boolean flag) . For handling our own transaction we can set the parameter to false and begin your transaction . Finally commit the transaction by calling the commit method.

Tuesday, September 13, 2011

JDBC Interview Question - Part 3

7. What is Connection?
Connection class represents a connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.
A Connection object’s database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.
8. What does Class.forName return?
A class as loaded by the classloader.
9. What is Connection pooling?
Connection pooling is a technique used for sharing server resources among requesting clients. Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. Connection pool manager maintains a pool of open database connections.

Monday, September 12, 2011

JDBC Interview Question - Part 2

. What are the steps required to execute a query in JDBC?
First we need to create an instance of a JDBC driver or load JDBC drivers, then we need to register this driver with DriverManager class. Then we can open a connection. By using this connection , we can create a statement object and this object will help us to execute the query.
5. What is DriverManager ?
DriverManager is a class in java.sql package. It is the basic service for managing a set of JDBC drivers.
6. What is a ResultSet ?
A table of data representing a database result set, which is usually generated by executing a statement that queries the database.
A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.

Also,

Resulset could be defined in three ways.
TYPE_SCROLL_SENSITIVE (can scroll forward or backward and sensitive to the changes made in the database)
TYPE_SCROLL_INSENSITIVE ( can scroll forward and backward but insensitive to database changes; It is actually snapshot of database so once data fetched not changed)
TYPE_FORWARD_ONLY (can move only in forward direction)

Saturday, September 10, 2011

What are the different JDBC drivers available?

here are mainly four type of JDBC drivers available. They are: Type 1 : JDBC-ODBC Bridge Driver – A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun.
Type 2: Native API Partly Java Driver- A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.
Type 3: Network protocol Driver- A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to their existing database middleware products.
Type 4: JDBC Net pure Java Driver – A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress.

JDBC Interview questions - Part 1

1. What is JDBC?
JDBC technology is an API (included in both J2SE and J2EE releases) that provides cross-DBMS connectivity to a wide range of SQL databases and access to other tabular data sources, such as spreadsheets or flat files. With a JDBC technology-enabled driver, you can connect all corporate data even in a heterogeneous environment
2. What are stored procedures?
A stored procedure is a set of statements/commands which reside in the database. The stored procedure is precompiled. Each Database has it’s own stored procedure language,
3. What is JDBC Driver ?
The JDBC Driver provides vendor-specific implementations of the abstract classes provided by the JDBC API. This driver is used to connect to the database.

Sunday, July 3, 2011

Struts Interview Questions

Q:  How to get data from the velocity page in a action class?
A: We can get the values in the action classes by using data.getParameter(\"variable name defined in the velocity page\");

Q:  How you will display validation fail errors on jsp page?
A: Following tag displays all the errors:



Q: How you will make available any Message Resources Definitions file to the Struts Framework Environment?
A: T Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through tag.

Example:

.
 

What is ActionForm?

 An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side. 

Saturday, July 2, 2011

How to enable front-end validation based on the xml in validation.xml

 The tag to allow front-end validation based on the xml in validation.xml. For example the code: generates the client side java script for the form \"logonForm\" as defined in the validation.xml file. The when added in the jsp file generates the client site validation script.

Details of XML files used in Validator Framework

The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.

What is Struts Validator Framework?

Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class.

The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

What is Action Class in Struts?

 The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. In the Action Class all the database/business processing are done. It is advisable to perform all the database related stuffs in the Action Class. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object. 

What is ActionServlet?

 The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests.

What is Jakarta Struts Framework?

Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.

What is Struts?

The core of the Struts framework is a flexible control layer based on standard technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons packages. Struts encourages application architectures based on the Model 2 approach, a variation of the classic Model-View-Controller (MVC) design paradigm.

Struts provides its own Controller component and integrates with other technologies to provide the Model and the View. For the Model, Struts can interact with standard data access technologies, like JDBC and EJB, as well as most any third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts works well with JavaServer Pages, including JSTL and JSF, as well as Velocity Templates, XSLT, and other presentation systems.

The Struts framework provides the invisible underpinnings every professional web application needs to survive. Struts helps you create an extensible development environment for your application, based on published standards and proven design patterns.

Monday, May 30, 2011

JDBC - ODBC Questions

1. What's the JDBC 2.0 API?

The JDBC 2.0 API is the latest update of the JDBC API. It contains many new features, including scrollable result sets and the new SQL:1999 (formerly SQL 3) data types. There are two parts to the JDBC 2.0 API:

the JDBC 2.0 core API (the java.sql package), which is included in the JavaTM 2 SDK, Standard Edition

the JDBC 2.0 Optional Package API (the javax.sql package), which is available separately or as part of the Java 2 SDK, Enterprise Edition

2. Does the JDBC-ODBC Bridge support the new features in the JDBC 2.0 API?

No, the JDBC-ODBC Bridge that is included in the Java 2 Platform initial release does not support the new features in the JDBC 2.0 API. However, Sun and Merant are working to produce a new version of the Bridge that does support the new features. Note that we do not recommend using the Bridge except for experimental purposes or when you have no other driver available.

3. 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. It is also possible to use the JDBC-ODBC bridge with applets that are run in the HotJavaTM browser (available from Java Software), since HotJava provides an option to turn off applet security. 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.

4. How do I start debugging problems related to the JDBC API?

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

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

5. 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 free.

6. Does the JDK include the JDBC API and the JDBC-ODBC Bridge?

Yes, the JDK 1.1 and the Java 2 SDK, Standard Edition (formerly known as the JDK 1.2), contain both the JDBC API and the JDBC-ODBC Bridge. The Java 2 SDK, Standard Edition, contains the JDBC 2.0 core API, which is the latest version. It does not include the JDBC 2.0 Optional Package, which is part of the Java 2 SDK, Enterprise Edition, or which you can download separately.

Note that the version of the JDBC API and the JDBC-ODBC Bridge provided for separate download on the JDBC download page are only for use with the JDK 1.0.2.

7. What JDBC technology-enabled drivers are available?

See our web page on JDBC technology-enabled drivers for a current listing.

8. What documentation is available for the JDBC API?


See the JDBC technology home page for links to information about JDBC technology. This page links to information about features and benefits, a list of new features, a section on getting started, online tutorials, a section on driver requirements, and other information in addition to the specifications and javadoc documentation.

9. 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.

10. Does the JDBC-ODBC Bridge work with Microsoft J++?
No, J++ does not support the JDBC-ODBC bridge since it doesn't implement the Java Native Interface (JNI). Any all-Java JDBC driver should work with J++, however.

11. 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.

12. 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.

13. Why doesn't calling the method Class.forName load my JDBC driver?

There is a bug in the JDK 1.1.x that can cause the method Class.forName to fail. A workaround is to explicitly call the method DriverManager.registerDriver(new YourDriverClass()). The exact problem in the JDK is a race condition in the class loader that prevents the static section of code in the driver class from executing and registering the driver with the DriverManager.

14. Why do the java.sql and java.math packages fail to download java.* packages? Is there a workaround?

For security reasons, browsers will not download java.* packages. In order to use the JDBC API with browsers that have not been upgraded to JDK1.1 or beyond, we recommend that the java.sql and java.math packages be renamed jdbc.sql and jdbc.math. Most vendors supplying JDBC technology-enabled drivers that are written purely in the Java programming language already provide versions of these renamed packages. When JDK 1.1 support has been added to your browser, you should convert your applets back to the java.* package names.

15. Why is the precision of java.math.BigDecimal limited to 18 digits in the JDK 1.0.2 add-on version of the JDBC API?


In JDK 1.1, java.math.BigInteger is implemented in C. It supports a precision of thousands of digits. The same is true for BigDecigmal.

The version of BigInteger provided with the JDK 1.0.2 add-on version of the JDBC API is a simplified version written in the Java programming language, and it is limited to 18 digits. Because the implementation of BigDecimal is based on BigInteger, it also is limited to this precision.

In the JDBC 2.0 API, you can use a new version of the method ResultSet.getBigDecimal that does not take a scale parameter and returns a BigDecimal with full precision.

16. Can the JDBC API be added to JDK 1.0.2?

Yes. Download the JDBC 1.22 API from the JDBC download page and follow the installation instructions in the release notes.

If you are using any version of the JDK from 1.1 on, the JDBC API is already included, and you should not download the JDBC 1.22 API.

17. 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.

18. 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

19. 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.

20. 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.

21. 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.

22. Does the JDBC-ODBC Bridge developed by Merant and Sun support result sets that contain Japanese Characters (DBCS)?

Yes, but we haven't tested this ourselves. The version of the Bridge in the Java 2 SDK, Standard Edition, and Java 2 SDK, Enterprise Edition, also supports a new charSet Connection property for specifying the character encoding used by the underlying DBMS.

23. 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 supports them.

24. 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.

25. 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 in the SELECT clause.

26. 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.

27. 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.

28. 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.

Sunday, May 29, 2011

How do Applets differ from Applications?
Following are the main differences: Application: Stand Alone, doesn’t need
web-browser. Applet: Needs no explicit installation on local machine. Can be transferred through Internet on to the local machine and may run as part of web-browser. Application: Execution starts with main() method. Doesn’t work if main is not there. Applet: Execution starts with init() method. Application: May or may not be a GUI. Applet: Must run within a GUI (Using AWT). This is essential feature of applets.
---------------------------------------------------------------------------------------------------------------

Can we pass parameters to an applet from HTML page to an applet? How? 
We can pass parameters to an applet using tag in the following way:


Access those parameters inside the applet is done by calling getParameter() method inside the applet. Note that getParameter() method returns String value corresponding to the parameter name.
----------------------------------------------------------------------------------------------------------------

How do we read number information from my applet’s parameters, given that Applet’s getParameter() method returns a string?
Use the parseInt() method in the Integer Class, the Float(String) constructor or parseFloat() method in the Class Float, or the
Double(String) constructor or parseDoulbl() method in the class Double.
----------------------------------------------------------------------------------------------------------------

How can I arrange for different applets on a web page to communicate with each other?
Name your applets inside the Applet tag and invoke AppletContext’s getApplet() method in your applet code to obtain references to the other applets on the page.
----------------------------------------------------------------------------------------------------------------

How do I select a URL from my Applet and send the browser to that page?
Ask the applet for its applet context and invoke showDocument() on that context object.

URL targetURL;
String URLString
AppletContext context = getAppletContext();
try
{
targetURL = new URL(URLString);
}
catch (MalformedURLException e)
{
// Code for recover from the exception
}
context. showDocument (targetURL);
Can applets on different pages communicate with each other?
- No, Not Directly. The applets will exchange the information at one meeting place either on the local file system or at remote system.

----------------------------------------------------------------------------------------------------------------

How do I determine the width and height of my application?
Use the getSize() method, which the Applet class inherits from the Component class in the Java.awt package. The getSize() method returns the size of the applet as a Dimension object, from which you extract separate width, height fields. The following code snippet explains this:

Dimension dim = getSize();
int appletwidth = dim.width();
int appletheight = dim.height();
----------------------------------------------------------------------------------------------------------------

Which classes and interfaces does Applet class consist?
Applet class consists of a single class, the Applet class and three interfaces: AppletContext, AppletStub, and AudioClip.
----------------------------------------------------------------------------------------------------------------

What is AppletStub Interface?
The applet stub interface provides the means by which an applet and the browser communicate. Your code will not typically implement this interface.
----------------------------------------------------------------------------------------------------------------

What tags are mandatory when creating HTML to display an applet?
name, height, width
code, name
codebase, height, width
code, height, width
Correct answer is d.
----------------------------------------------------------------------------------------------------------------

What are the Applet’s information methods?
The following are the Applet’s information methods: getAppletInfo() method: Returns a string describing the applet, its author, copyright information, etc. getParameterInfo( ) method: Returns an array of string describing the applet’s parameters.
----------------------------------------------------------------------------------------------------------------

What is the difference between Web Server and Application server?

  Webserver serves pages for viewing in web browser, application server provides exposes business logic for client applications through various protocols

· Webserver exclusively handles http requests. application server serves business logic to application programs through any number of protocols.

· Webserver delegation model is fairly simple, when the request comes into the webserver, it simply passes the request to the program best able to handle it (Server side program). It may not support transactions and database connection pooling.

· Application server is more capable of dynamic behavior than webserver. We can also configure application server to work as a webserver.Simply application server is a superset of webserver.

· Web Server serves static HTML pages or gifs, jpegs, etc., and can also run code written in CGI, JSP etc. A Web server handles the HTTP protocol. Eg of some web server are IIS or apache.

· An Application Server is used to run business logic or dynamically generated presentation code. It can either be .NET based or J2EE based (BEA WebLogic Server, IBM WebSphere, JBoss).

· A J2EE application server runs servlets and JSPs (infact a part of the app server called web container is responsible for running servlets and JSPs) that are used to create HTML pages dynamically. In addition, J2EE application server can run EJBs - which are used to execute business logic.

· An Application server has a 'built-in' web server, in addition to that it supports other modules or features like e-business integration, independent management and security module etc

Wednesday, May 18, 2011

Difference between Vector and ArrayList

 The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized on

Tuesday, May 17, 2011

Size and capacity of a Vector

The size is the number of elements actually stored in the vector, while capacity is the maximum number of elements it can store at a given instance of time.

Monday, May 16, 2011

How a Vector can contains Hetrogenous items


Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object

What is an enumeration?

An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.

Locale class and SimpleTimeZone Class in Java

Q:  What is the Locale class?
A: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region .
 
Q:  What is the SimpleTimeZone class?
A:  The SimpleTimeZone class provides support for a Gregorian calendar .

What is an Iterator interface?

A: The Iterator interface is used to step through the elements of a Collection .

Q : Which java.util classes and interfaces support event handling?
A: The EventObject class and the EventListener interface support event processing.

What is the Collections API?

The Collections API is a set of classes and interfaces that support operations on collections of objects.

Find Time taken to execute a method

 Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.

To put it in code...

long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();

System.out.println ("Time taken for execution is " + (end - start));

Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing.

Tuesday, March 29, 2011

What is the purpose of garbage collection in Java, and when is it used?

The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used

Thursday, March 24, 2011

How does an exception permeate through the code?

An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.

Differenct Types of Exception Handling

Q: What is the basic difference between the 2 approaches to exception handling.
  1> try catch block and
  2> specifying the candidate exceptions in the throws clause?
When should you use which approach?

A: In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.

Interview Questions on try/catch in Java


Q:  Is it necessary that each try block must be followed by a catch block?
A: It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.


Q:  If I write return at the end of the try block, will the finally block still execute?
A: Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.


Q:  If I write System.exit (0); at the end of the try block, will the finally block still execute?
A: No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.

Saturday, March 5, 2011

What is the differences between == and .equals() ?

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

== compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.

 public class EqualsTest {

 public static void main(String[] args) {

  String s1 = “abc”;
  String s2 = s1;
  String s5 = “abc”;
  String s3 = new String(”abc”);
  String s4 = new String(”abc”);
  System.out.println(”== comparison : ” + (s1 == s5));
  System.out.println(”== comparison : ” + (s1 == s2));
  System.out.println(”Using equals method : ” + s1.equals(s2));
  System.out.println(”== comparison : ” + s3 == s4);
  System.out.println(”Using equals method : ” + s3.equals(s4));
 }
}


 

Output

== comparison : true
== comparison : true
Using equals method : true
false
Using equals method : true

Java Wrapper Classes

What are wrapper classes?
Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, Double etc


Why do we need wrapper classes?
 It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.

Tuesday, February 22, 2011

Swings and AWT

Q: Difference between Swing and Awt?
A: AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.

Q: What is the difference between a constructor and a method?
A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

Q: What is an Iterator?
A: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

Q: State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
A: public : Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.

Java Interview Questions

Q: What is the difference between an Interface and an Abstract class?
A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.



Q: What is the purpose of garbage collection in Java, and when is it used?
A: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.


Q: Describe synchronization in respect to multithreading.
A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.


Q: Explain different way of using thread?
A: The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.


Q: What are pass by reference and passby value?
A: Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.


Q: What is HashMap and Map?
A: Map is Interface and Hashmap is class that implements that.


Q:Difference between HashMap and HashTable?
A: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.