Академический Документы
Профессиональный Документы
Культура Документы
Q: What is ActionServlet?
A: 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.
Q: How you will make available any Message Resources Definitions file to the Struts Framework
Environment?
A: 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 <message-resources /> tag.
Example:
<message-resources parameter="MessageResources" />
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
Q. How you will enable front-end validation based on the xml in validation.xml?
A: The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For
example the code: <html:javascript formName="logonForm" dynamicJavascript="true"
staticJavascript="true" /> generates the client side java script for the form "logonForm" as defined in
the validation.xml file. The <html:javascript> when added in the jsp file generates the client site
validation script.
12.What is the major practical / implementers difference between Apache Struts 1.0 and Struts
1.1 ?
A: In Apache Struts 1.0 one has to have a single struts-config.xml file, and this causes a big team
working on Struts, difficult to maintain and manage this singular point / file to use, with lots of merging
happening. But in Apache Struts 1.1, we can have any different struts config file, and each file can refer
its mapping in any other file at run time, provided all these struts config files are mentioned in the
web.xml file as config parameter.
13. Can I use EJB in an application using Apache Struts ?
Ans : Yes, Struts is a MVC framework (readymade and available to use), and EJB will be in Business tier.
Action classes will call services tier and use EJB facades.
Question: Name the containers which uses Border Layout as their default layout?
Answer: Containers which uses Border Layout as their default are: window, Frame and Dialog classes.
What is J2EE? - J2EE is an environment for developing and deploying enterprise applications. The J2EE
platform consists of a set of services, application programming interfaces (APIs), and protocols that
provide the functionality for developing multitiered, web-based applications.
Is J2EE application only a web-based? - No, It depends on type of application that client wants. A J2EE
application can be web-based or non-web-based. if an application client executes on the client
machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to
handle tasks such as J2EE system or application administration. It typically has a graphical user interface
created from Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP
connection to establish communication with a servlet running in the web tier.
Are JavaBeans J2EE components? - No. JavaBeans components are not considered J2EE components
by the J2EE specification. They are written to manage the data flow between an application client or
applet and components running on the J2EE server or between server components and a database.
JavaBeans components written for the J2EE platform have instance variables and get and set methods
for accessing the data in the instance variables. JavaBeans components used in this way are typically
simple in design and implementation, but should conform to the naming and design conventions
outlined in the JavaBeans component architecture.
Is HTML page a web component? - No. Static HTML pages and applets are bundled with web
components during application assembly, but are not considered web components by the J2EE
specification. Even the server-side utility classes are not considered web components, either.
What can be considered as a web component? - J2EE Web components can be either servlets or JSP
pages. Servlets are Java programming language classes that dynamically process requests and construct
responses. JSP pages are text-based documents that execute as servlets but allow a more natural
approach to creating static content.
What is the container? - Containers are the interface between a component and the low-level platform
specific functionality that supports the component. Before a Web, enterprise bean, or application client
component can be executed, it must be assembled into a J2EE application and deployed into its
container.
What are container services? - A container is a runtime support of a system-level entity. Containers
provide components with services such as lifecycle management, security, deployment, and threading.
What is the web container? - Servlet and JSP containers are collectively referred to as Web containers.
It manages the execution of JSP page and servlet components for J2EE applications. Web components
and their container run on the J2EE server.
What is Enterprise JavaBeans (EJB) container? - It manages the execution of enterprise beans for J2EE
applications. Enterprise beans and their container run on the J2EE server.
What is Applet container? - Manages the execution of applets. Consists of a Web browser and Java
Plugin running on the client together.
How do we package J2EE components? - J2EE components are packaged separately and bundled into a
J2EE application for deployment. Each component, its related files such as GIF and HTML files or server-
side utility classes, and a deployment descriptor are assembled into a module and added to the J2EE
application. A J2EE application is composed of one or more enterprise bean, Web, or application client
component modules. The final enterprise solution can use one J2EE application or be made up of two
or more J2EE applications, depending on design requirements. A J2EE application and each of its
modules has its own deployment descriptor. A deployment descriptor is an XML document with an .xml
extension that describes a component’s deployment settings.
What is a thin client? - A thin client is a lightweight interface to the application that does not have such
operations like query databases, execute complex business rules, or connect to legacy applications.
What are types of J2EE clients? - Following are the types of J2EE clients:
1. Applets
2. Application clients
3. Java Web Start-enabled rich clients, powered by Java Web Start technology.
4. Wireless clients, based on Mobile Information Device Profile (MIDP) technology.
What is the EAR file? - An EAR file is a standard JAR file with an .ear extension, named from Enterprise
ARchive file. A J2EE application with all of its modules is delivered in EAR file.
What is JTA and JTS? - JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for
the Jave Transaction Service. JTA provides a standard interface and allows you to demarcate
transactions in a manner that is independent of the transaction manager implementation. The J2EE
SDK implements the transaction manager with JTS. But your code doesn’t call the JTS methods directly.
Instead, it invokes the JTA methods, which then call the lower-level JTS routines. Therefore, JTA is a high
level transaction interface that your application uses to control transaction. and JTS is a low level
transaction interface and ejb uses behind the scenes (client code doesn’t directly interact with JTS. It is
based on object transaction service(OTS) which is part of CORBA.
What is JAXP? - JAXP stands for Java API for XML. XML is a language for representing and describing
text-based data which can be read and handled by any program or tool that uses XML APIs. It provides
standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover
the operations available on it, and create the appropriate JavaBeans component to perform those
operations.
What is J2EE Connector? - The J2EE Connector API is used by J2EE tools vendors and system integrators
to create resource adapters that support access to enterprise information systems that can be plugged
into any J2EE product. Each type of database or EIS has a different resource adapter. Note: A resource
adapter is a software component that allows J2EE application components to access and interact with
the underlying resource manager. Because a resource adapter is specific to its resource manager, there
is typically a different resource adapter for each type of database or enterprise information system.
What is JAAP? - The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE
application to authenticate and authorize a specific user or group of users to run it. It is a standard
Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security
architecture to support user-based authorization.
What is Java Naming and Directory Service? - The JNDI provides naming and directory functionality. It
provides applications with methods for performing standard directory operations, such as associating
attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application
can store and retrieve any type of named Java object. Because JNDI is independent of any specific
implementations, applications can use JNDI to access multiple naming and directory services, including
existing naming and directory services such as LDAP, NDS, DNS, and NIS.
What is Struts? - A Web page development framework. Struts combines Java Servlets, Java Server
Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic
platform, suitable for development teams, independent developers, and everyone between.
How is the MVC design pattern used in Struts framework? - In the MVC design pattern, application
flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler.
The handlers are tied to a Model, and each handler acts as an adapter between the request and the
Model. The Model represents, or encapsulates, an application’s business logic or state. Control is
usually then forwarded back through the Controller to the appropriate View. The forwarding can be
determined by consulting a set of mappings, usually loaded from a database or configuration file. This
provides a loose coupling between the View and Model, which can make an application significantly
easier to create and maintain. Controller: Servlet controller which supplied by Struts itself; View: what
you can see on the screen, a JSP page and presentation components; Model: System state and a
business logic JavaBeans.
What is a class? A class is a blueprint, or prototype, that defines the variables and the methods
common to all objects of a certain kind.
What is a object? An object is a software bundle of variables and related methods.An instance of a
class depicting the state and behavior at that particular time in real world.
What is a method? Encapsulation of a functionality which can be called to perform specific tasks.
Is multiple inheritance allowed in Java? No, multiple inheritance is not allowed in Java.
What is interpreter and compiler? Java interpreter converts the high level language code into a
intermediate form in Java called as bytecode, and then executes it, where as a compiler converts the
high level language code to machine language making it very hardware specific
What is JVM? The Java interpreter along with the runtime environment required to run the Java
application in called as Java virtual machine(JVM)
What are the different types of modifiers? There are access modifiers and there are other identifiers.
Access modifiers are public, protected and private. Other are final and static.
What are the access modifiers in Java? There are 3 access modifiers. Public, protected and private, and
the default one if no identifier is specified is called friendly, but programmer cannot specify the friendly
identifier explicitly.
What is a wrapper class? They are classes that wrap a primitive data type so it can be used as a object
What is a static variable and static method? What’s the difference between two? The modifier static
can be used with a variable and method. When declared as static variable, there is only one variable no
matter how instances are created, this variable is initialized when the class is loaded. Static method do
not need a class to be instantiated to be called, also a non static method cannot be called from static
method.
What is meant by final class, methods and variables? This modifier can be applied to class method and
variable. When declared as final class the class cannot be extended. When declared as final variable, its
value cannot be changed if is primitive value, if it is a reference to the object it will always refer to the
same object, internal attributes of the object can be changed.
What is interface? Interface is a contact that can be implemented by a class, it has method that need
implementation.
What is method overloading? Overloading is declaring multiple method with the same name, but with
different argument list.
What is method overriding? Overriding has same method name, identical arguments used in subclass.
What is singleton class? Singleton class means that any given time only one instance of the class is
present, in one JVM.
What is the difference between an array and a vector? Number of elements in an array are fixed at the
construction time, whereas the number of elements in vector can grow dynamically.
What is a constructor? In Java, the class designer can guarantee initialization of every object by
providing a special method called a constructor. If a class has a constructor, Java automatically calls that
constructor when an object is created, before users can even get their hands on it. So initialization is
guaranteed.
What is casting? Conversion of one type of data to another when appropriate. Casting makes explicitly
converting of data.
What is the difference between final, finally and finalize? The modifier final is used on class variable
and methods to specify certain behaviour explained above. And finally is used as one of the loop in the
try catch blocks, It is used to hold code that needs to be executed whether or not the exception occurs
in the try catch block. Java provides a method called finalize( ) that can be defined in the class. When
the garbage collector is ready to release the storage ed for your object, it will first call finalize( ), and
only on the next garbage-collection pass will it reclaim the objects memory. So finalize( ), gives you the
ability to perform some important cleanup at the time of garbage collection.
What is are packages? A package is a collection of related classes and interfaces providing access
protection and namespace management.
What is a super class and how can you call a super class? When a class is extended that is derived
from another class there is a relationship is created, the parent class is referred to as the super class by
the derived class that is the child. The derived class can make a call to the super class using the keyword
super. If used in the constructor of the derived class it has to be the first statement.
What is meant by a Thread? Thread is defined as an instantiated parallel process of a given program.
What is multi-threading? Multi-threading as the name suggest is the scenario where more than one
threads are running.
What are two ways of creating a thread? Which is the best way and why? Two ways of creating
threads are, one can extend from the Java.lang.Thread and can implement the rum method or the run
method of a different class can be called which implements the interface Runnable, and the then
implement the run() method. The latter one is mostly used as first due to Java rule of only one class
inheritance, with implementing the Runnable interface that problem is sorted out.
What is deadlock? Deadlock is a situation when two threads are waiting on each other to release a
resource. Each thread waiting for a resource which is held by the other waiting thread. In Java, this
resource is usually the object lock obtained by the synchronized keyword.
What are the three types of priority? MAX_PRIORITY which is 10, MIN_PRIORITY which is 1,
NORM_PRIORITY which is 5.
What is the use of synchronizations? Every object has a lock, when a synchronized keyword is used on
a piece of code the, lock must be obtained by the thread first to execute that code, other threads will
not be allowed to execute that piece of code till this lock is released.
2) Why does JComponent have add() and remove() methods but Component does not?
Answer: because JComponent is a subclass of Container, and can contain other components and
jcomponents.
9) Why should the implementation of any Swing callback (like a listener) execute quickly?
A: Because callbacks are invoked by the event dispatch thread which will be blocked processing other
events for as long as your method takes to execute.
10) In what context should the value of Swing components be updated directly?
A: Swing components should be updated directly only in the context of callback methods invoked from
the event dispatch thread. Any other context is not thread safe?
14) Why won’t the JVM terminate when I close all the application windows?
A: The AWT event dispatcher thread is not a daemon thread. You must explicitly call System.exit to
terminate the JVM.
Q:What are mutex and semaphore? What is the difference between them?
A:A mutex is a synchronization object that allows only one process or thread to access a critical code
block. A semaphore on the other hand allows one or more processes or threads to access a critial code
block. A semaphore is a multiple mutex.
4. why a java program can not directly communicate with an ODBC driver?
Answer: Since ODBC API is written in C language and makes use of pointers which Java can not support.
5. Are servlets platform independent? If so Why? Also what is the most common application of
servlets?
Answer: Yes, Because they are written in Java. The most common application of servlet is to access
database and dynamically construct HTTP response
What are different ways in which a thread can enter the waiting state? A thread can enter the waiting
state by invoking its sleep() method, blocking on I/O, unsuccessfully attempting to acquire an object’s
lock, or invoking an object’s wait() method. It can also enter the waiting state by invoking its
(deprecated) suspend() method.
Can a lock be acquired on a class? Yes, a lock can be acquired on a class. This lock is acquired on the
class’s Class object.
What’s new with the stop(), suspend() and resume() methods in new JDK 1.2? The stop(), suspend()
and resume() methods have been deprecated in JDK 1.2.
What is the preferred size of a component? The preferred size of a component is the minimum
component size that will allow the component to display normally.
What method is used to specify a container’s layout? The setLayout() method is used to specify a
container’s layout. For example, setLayout(new FlowLayout()); will be set the layout as FlowLayout.
Which containers use a FlowLayout as their default layout? The Panel and Applet classes use the
FlowLayout as their default layout.
What state does a thread enter when it terminates its processing? When a thread terminates its
processing, it enters the dead state.
What is the Collections API? The Collections API is a set of classes and interfaces that support
operations on collections of objects. One example of class in Collections API is Vector and Set and List
are examples of interfaces in Collections API.
What is the List interface? The List interface provides support for ordered collections of objects. It may
or may not allow duplicate elements but the elements must be ordered.
How does Java handle integer overflows and underflows? It uses those low order bytes of the result
that can fit into the size of the type allowed by the operation.
What is the Vector class? The Vector class provides the capability to implement a growable array of
objects. The main visible advantage of this class is programmer needn’t to worry about the number of
elements in the Vector.
What modifiers may be used with an inner class that is a member of an outer class? A (non-local)
inner class may be declared as public, protected, private, static, final, or abstract.
If a method is declared as protected, where may the method be accessed? A protected method may
only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is
declared.
What is an Iterator interface? The Iterator interface is used to step through the elements of a
Collection.
What is the difference between yielding and sleeping? Yielding means a thread returning to a ready
state either from waiting, running or after creation, where as sleeping refers a thread going to a waiting
state from running state. With reference to Java, when a task invokes its yield() method, it returns to
the ready state and when a task invokes its sleep() method, it returns to the waiting state
What are wrapper classes? Wrapper classes are classes that allow primitive types to be accessed as
objects. For example, Integer, Double. These classes contain many methods which can be used to
manipulate basic data types
Does garbage collection guarantee that a program will not run out of memory? No, it doesn’t. It is
possible for programs to use up memory resources faster than they are garbage collected. It is also
possible for programs to create objects that are not subject to garbage collection. The main purpose of
Garbage Collector is recover the memory from the objects which are no longer required when more
memory is needed.
Name Component subclasses that support painting? The following classes support painting: Canvas,
Frame, Panel, and Applet.
What is a native method? A native method is a method that is implemented in a language other than
Java. For example, one method may be written in C and can be called in Java.
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. For example,
closing a opened file, closing a opened database Connection.
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.
What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western
calendars.
What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian
calendar.
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.
What is the purpose of the Runtime class? The purpose of the Runtime class is to provide access to the
Java runtime system.
What is the purpose of the System class? The purpose of the System class is to provide access to
system resources.
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. For
example,
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.
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.
When a servlet accepts a call from a client, it receives two objects. What are they?
ServletRequest (which encapsulates the communication from the client to the server) and
ServletResponse (which encapsulates the communication from the servlet back to the client).
ServletRequest and ServletResponse are interfaces defined inside javax.servlet package.
What are the Applet’s Life Cycle methods? Explain them? - Following are methods in the life cycle of
an Applet:
init() method - called when an applet is first loaded. This method is called only once in the
entire cycle of an applet. This method usually intialize the variables to be used in the applet.
start( ) method - called each time an applet is started.
paint() method - called when the applet is minimized or refreshed. This method is used for
drawing different strings, figures, and images on the applet window.
stop( ) method - called when the browser moves off the applet’s page.
destroy( ) method - called when the browser is finished with the applet.
What is the sequence for calling the methods by AWT for applets? - When an applet begins, the AWT
calls the following methods, in this sequence:
init()
start()
paint()
When an applet is terminated, the following sequence of method calls takes place :
stop()
destroy()
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 <param> tag in the following way:
<param name="param1″ value="value1″>
<param name="param2″ value="value2″>
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 are the steps involved in Applet development? - Following are the steps involved in Applet
development:
Create/Edit a Java source file. This file must contain a class which extends Applet class.
Compile your program using javac
Execute the appletviewer, specifying the name of your applet’s source file or html file. In case the
applet information is stored in html file then Applet can be invoked using java enabled web browser.
Which method is used to output a string to an applet? Which function is this method included in? -
drawString( ) method is used to output a string to an applet. This method is included in the paint
method of the Applet.
What is J2EE?
J2EE is an environment for developing and deploying enterprise applications. The J2EE platform
consists of a set of services, application programming interfaces (APIs), and protocols that provide the
functionality for developing multitiered, web-based applications.
What is the J2EE module?
A J2EE module consists of one or more J2EE components for the same container type and one
component deployment descriptor of that type.
What are the components of J2EE application?
A J2EE component is a self-contained functional software unit that is assembled into a J2EE application
with its related classes and files and communicates with other components. The J2EE specification
defines the following J2EE components:
Application clients and applets are client components.
Java Servlet and JavaServer PagesTM (JSPTM) technology components are web components.
Enterprise JavaBeansTM (EJBTM) components (enterprise beans) are business components.
Resource adapter components provided by EIS and tool vendors.
What are the four types of J2EE modules?
Application client module
Web module
Enterprise JavaBeans module
Resource adapter module
What does application client module contain?
The application client module contains:
class files,
an application client deployment descriptor.
Application client modules are packaged as JAR files with a .jar extension.
What does web module contain?
The web module contains:
JSP files,
class files for servlets,
GIF and HTML files, and
a Web deployment descriptor.
Web modules are packaged as JAR files with a .war (Web ARchive) extension.
What does Enterprise JavaBeans module contain?
The Enterprise JavaBeans module contains:
class files for enterprise beans
an EJB deployment descriptor.
EJB modules are packaged as JAR files with a .jar extension.
What does resource adapt module contain?
The resource adapt module contains:
all Java interfaces,
classes,
native libraries,
other documentation,
a resource adapter deployment descriptor.
Resource adapter modules are packages as JAR files with a .rar (Resource adapter ARchive) extension.
How many development roles are involved in J2EE application?
There are at least 5 roles involved:
Enterprise Bean Developer
Writes and compiles the source code
Specifies the deployment descriptor
Bundles the .class files and deployment descriptor into an EJB JAR file
Web Component Developer
Writes and compiles servlet source code
Writes JSP and HTML files
Specifies the deployment descriptor for the Web component
Bundles the .class, .jsp, .html, and deployment descriptor files in the WAR file
J2EE Application Client Developer
Writes and compiles the source code
Specifies the deployment descriptor for the client
Bundles the .class files and deployment descriptor into the JAR file
Application Assembler The application assembler is the company or person who receives application
component JAR files from component providers and assembles them into a J2EE application EAR file.
The assembler or deployer can edit the deployment descriptor directly or use tools that correctly add
XML tags according to interactive selections. A software developer performs the following tasks to
deliver an EAR file containing the J2EE application:
Assembles EJB JAR and WAR files created in the previous phases into a J2EE application (EAR) file
Specifies the deployment descriptor for the J2EE application
Verifies that the contents of the EAR file are well formed and comply with the J2EE specification
Application Deployer and Administrator
Configures and deploys the J2EE application
Resolves external dependencies
Specifies security settings & attributes
Assigns transaction attributes and sets transaction controls
Specifies connections to databases
Deploys or installs the J2EE application EAR file into the J2EE server
Administers the computing and networking infrastructure where J2EE applications run
Oversees the runtime environment
But a developer role depends on the job assignment. For a small company, one developer may take
these 5 roles altogether.
What APIs are available for developing a J2EE application?
Enterprise JavaBeans Technology(3 beans: Session Beans, Entity Beans and Message-Driven Beans)
JDBC API(application level interface and service provider interface or driver)
Java Servlet Technology(Servlet)
Java ServerPage Technology(JSP)
Java Message Service(JMS)
Java Naming and Directory Interface(JNDI)
Java Transaction API(JTA)
JavaMail API
JavaBeans Activation Framework(JAF used by JavaMail)
Java API for XML Processiong(JAXP,SAX, DOM, XSLT)
Java API for XML Registries(JAXR)
Java API for XML-Based RPC(JAX-RPC)-SOAP standard and HTTP
SOAP with Attachments API for Java(SAAJ)-- low-level API upon which JAX-RPC depends
J2EE Connector Architecture
Java Authentication and Authorization Service(JAAS)
What is difference between J2EE 1.3 and J2EE 1.4?
J2EE 1.4 is an enhancement version of J2EE 1.3. It is the most complete Web services platform ever.
J2EE 1.4 includes:
Java API for XML-Based RPC (JAX-RPC 1.1)
SOAP with Attachments API for Java (SAAJ),
Web Services for J2EE(JSR 921)
J2EE Management Model(1.0)
J2EE Deployment API(1.1)
Java Management Extensions (JMX),
Java Authorization Contract for Containers(JavaACC)
Java API for XML Registries (JAXR)
Servlet 2.4
JSP 2.0
EJB 2.1
JMS 1.1
J2EE Connector 1.5
The J2EE 1.4 features complete Web services support through the new JAX-RPC 1.1 API, which supports
service endpoints based on servlets and enterprise beans. JAX-RPC 1.1 provides interoperability with
Web services based on the WSDL and SOAP protocols.
The J2EE 1.4 platform also supports the Web Services for J2EE specification (JSR 921), which defines
deployment requirements for Web services and utilizes the JAX-RPC programming model.
In addition to numerous Web services APIs, J2EE 1.4 platform also features support for the WS-I Basic
Profile 1.0. This means that in addition to platform independence and complete Web services support,
J2EE 1.4 offers platform Web services interoperability.
The J2EE 1.4 platform also introduces the J2EE Management 1.0 API, which defines the information
model for J2EE management, including the standard Management EJB (MEJB). The J2EE Management
1.0 API uses the Java Management Extensions API (JMX).
The J2EE 1.4 platform also introduces the J2EE Deployment 1.1 API, which provides a standard API for
deployment of J2EE applications.
The J2EE 1.4 platform includes security enhancements via the introduction of the Java Authorization
Contract for Containers (JavaACC). The JavaACC API improves security by standardizing how
authentication mechanisms are integrated into J2EE containers.
The J2EE platform now makes it easier to develop web front ends with enhancements to Java Servlet
and JavaServer Pages (JSP) technologies. Servlets now support request listeners and enhanced filters.
JSP technology has simplified the page and extension development models with the introduction of a
simple expression language, tag files, and a simpler tag extension API, among other features. This
makes it easier than ever for developers to build JSP-enabled pages, especially those who are familiar
with scripting languages.
Other enhancements to the J2EE platform include the J2EE Connector Architecture, which provides
incoming resource adapter and Java Message Service (JMS) pluggability. New features in Enterprise
JavaBeans (EJB) technology include Web service endpoints, a timer service, and enhancements to EJB
QL and message-driven beans.
The J2EE 1.4 platform also includes enhancements to deployment descriptors. They are now defined
using XML Schema which can also be used by developers to validate their XML structures.
Note: The above information comes from SUN released notes.
Is J2EE application only a web-based?
NO. A J2EE application can be web-based or non-web-based. if an application client executes on the
client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users
to handle tasks such as J2EE system or application administration. It typically has a graphical user
interface created from Swing or AWT APIs, or a command-line interface. When user request, it can
open an HTTP connection to establish communication with a servlet running in the web tier.
Are JavaBeans J2EE components?
NO. JavaBeans components are not considered J2EE components by the J2EE specification. JavaBeans
components written for the J2EE platform have instance variables and get and set methods for
accessing the data in the instance variables. JavaBeans components used in this way are typically
simple in design and implementation, but should conform to the naming and design conventions
outlined in the JavaBeans component architecture.
Is HTML page a web component?
NO. Static HTML pages and applets are bundled with web components during application assembly, but
are not considered web components by the J2EE specification. Even the server-side utility classes are
not considered web components,either.
What is the container?
A container is a runtime support of a system-level entity. Containers provide components with services
such as lifecycle management, security, deployment, and threading.
What is the web container?
Servlet and JSP containers are collectively referred to as Web containers.
What is the thin client?
A thin client is a lightweight interface to the application that does not have such operations like query
databases, execute complex business rules, or connect to legacy applications.
What are types of J2EE clients?
Applets
Application clients
Java Web Start-enabled rich clients, powered by Java Web Start technology.
Wireless clients, based on Mobile Information Device Profile (MIDP) technology.
What is deployment descriptor?
A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension
that describes a component's deployment settings. A J2EE application and each of its modules has its
own deployment descriptor.
What is the EAR file?
An EAR file is a standard JAR file with an .ear extension, named from Enterprice ARchive file. A J2EE
application with all of its modules is delivered in EAR file.
What is JTA and JTS?
JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Jave Transaction
Service. JTA provides a standard interface and allows you to demarcate transactions in a manner that is
independent of the transaction manager implementation. The J2EE SDK implements the transaction
manager with JTS. But your code doesn't call the JTS methods directly. Instead, it invokes the JTA
methods, which then call the lower-level JTS routines.
Therefore, JTA is a high level transaction interface that your application uses to control transaction. and
JTS is a low level transaction interface and ejb uses behind the scenes (client code doesn't directly
interact with JTS. It is based on object transaction service(OTS) which is part of CORBA.
What is JAXP?
JAXP stands for Java API for XML. XML is a language for representing and describing text-based data
which can be read and handled by any program or tool that uses XML APIs.
What is J2EE Connector?
The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource
adapters that support access to enterprise information systems that can be plugged into any J2EE
product. Each type of database or EIS has a different resource adapter.
What is JAAP?
The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to
authenticate and authorize a specific user or group of users to run it. It is a standard Pluggable
Authentication Module (PAM) framework that extends the Java 2 platform security architecture to
support user-based authorization.
What is Model 1?
Using JSP technology alone to develop Web page. Such term is used in the earlier JSP specification.
Model 1 architecture is suitable for applications that have very simple page flow, have little need for
centralized security control or logging, and change little over time. Model 1 applications can often be
refactored to Model 2 when application requirements change.
What is Model 2?
Using JSP and Servelet together to develop Web page. Model 2 applications are easier to maintain and
extend, because views do not refer to each other directly.
What is Struts?
A Web page development framework. Struts combines Java Servlets, Java Server Pages, custom tags,
and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for
development teams, independent developers, and everyone between.
How is the MVC design pattern used in Struts framework?
In the MVC design pattern, application flow is mediated by a central Controller. The Controller
delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts
as an adapter between the request and the Model. The Model represents, or encapsulates, an
application's business logic or state. Control is usually then forwarded back through the Controller to
the appropriate View. The forwarding can be determined by consulting a set of mappings, usually
loaded from a database or configuration file. This provides a loose coupling between the View and
Model, which can make an application significantly easier to create and maintain.
Controller--Servlet controller which supplied by Struts itself; View --- what you can see on the screen, a
JSP page and presentation components; Model --- System state and a business logic JavaBeans.
Do you have to use design pattern in J2EE project?
Yes. If I do it, I will use it. Learning design pattern will boost my coding skill.
Is J2EE a super set of J2SE?
Yes
What is JavaBeans?
JavaBeans is a portable, platform-independent component model written in the Java programming
language, developed in collaboration with industry leaders. It enables developers to write reusable
components once and run them anywhere -- benefiting from the platform-independent power of Java
technology. JavaBeans acts as a Bridge between proprietary component models and provides a
seamless and powerful means for developers to build components that run in ActiveX container
applications.
What is a Bean? Why isn't a Bean an Applet?
JavaBeans components, or Beans, are reusable software components that can be manipulated visually
in a builder tool. Beans can be combined to create traditional applications, or their smaller web-
oriented brethren, applets. In addition, applets can be designed to work as reusable Beans.
Individual Beans will function quite differently, but typical unifying features that distinguish a Bean are:
Introspection: enables a builder tool to analyze how a Bean works
Customization: enables a developer to use an app builder tool to customize the appearance and
behavior of a Bean
Events: enables Beans to communicate and connect together
Properties: enable developers to customize and program with Beans
Persistence: enables developers to customize Beans in an app builder, and then retrieve those Beans,
with customized features intact, for future use
Why are component architectures useful?
Developers are turning to creating components rather than monolithic applications to free themselves
from slow, expensive application development, and to build up a portable, reusable code base. This
enables developers to quickly attack new market opportunities, new joint development opportunities,
and new ways to sell smaller packages of software.
Is JavaBeans a complete component architecture?
JavaBeans is a complete component model. It supports the standard component architecture features
of properties, events, methods, and persistence. In addition, JavaBeans provides support for
introspection (to allow automatic analysis of a JavaBeans component) and customization (to make it
easy to configure a JavaBeans component).
Why a component architecture for the Java platform?
JavaBeans brings the extraordinary power of the Java platform to component development, offering
the ideal environment for a developer who wants to extend the concept of reusable component
development beyond one platform and one architecture to embrace every platform and every
architecture in the industry.
What kind of industry support exists for JavaBeans?
A coalition of industry leaders in component development worked with JavaSoft to create the
JavaBeans specification, which was released to the Internet for public comments on September 4,
1996. The "frozen" JavaBeans specification combines the work of Apple, Borland, IBM, JustSystem,
Microsoft, Netscape, Rogue Wave, SunSoft and Symantec and many, many others... We're very pleased
to see the tools community swiftly embracing JavaBeans by announcing support for JavaBeans in their
visual application builder tools. Furthermore, you may want to take at look at the JavaBeans Directory
to view what JavaBeans-based products are available today.
Are there JavaBeans components available that I can buy today?
Yes. A large number of companies, both large and small, have announced their plans to deliver
JavaBeans-based products including Corel, EnterpriseSoft, Gemstone, IBM, JScape, K&A Software, KL
Group, Lotus Development, Novell, ProtoView Development, Rogue Wave, and Stingray Software
among many others. Contact these companies for information on product availability. Many more
companies have adopted the JavaBeans component model, take a look at the JavaBeans Directory.
What is the relationship between Sun's JFCs and JavaBeans?
The JFC (Java Foundation Classes) is based upon the AWT (Abstract Windowing Toolkit), which has been
part of the Java platform from the beginning. JFC effectively adds a richer set of visual elements for
building JavaBeans components and applications. See the JFC web site for more information.
What are the security implications for downloading Beans over the Internet?
JavaBeans does not add any security features to the Java platform. Rather, JavaBeans components have
full access to the broad range of security features that are part of the Java platform. JavaBeans
components can be used to build a range of different kinds of solutions from full-fledged Java desktop
applications to web-based Applets.
Does the 100% Pure Java program ensure compatibility and interoperability between Beans?
The 100% Pure Java Initiative is a program designed specifically for developers of Java software. Sun will
provide testing and marketing support specifically for JavaBeans components in the first half of 1998.
Will the BeanBox evolve to become a "complete" development environment?
The BeanBox, provided as part of the BDK, is provided as a test container to allow JavaBeans
developers to test and evaluate Bean behavior. Though Sun will release additional versions of the
BeanBox as a part of future BDKs, we intend to keep it true to its original mission as outlined above.
Can someone from the JavaBeans team review my book about JavaBeans?
We can not accommodate every author/publisher with a complete review of their transcript, but will
do our best to make sure your questions are answered. Please forward any such requests to java-
beans@java.sun.com.
General FAQ
What is JavaServer Pages technology?
JavaServer Pages (JSP) technology provides a simplified, fast way to create web pages that display
dynamically-generated content. The JSP specification, developed through an industry-wide initiative led
by Sun Microsystems, defines the interaction between the server and the JSP page, and describes the
format and syntax of the page.
How does the JavaServer Pages technology work?
JSP pages use XML tags and scriptlets written in the Java programming language to encapsulate the
logic that generates the content for the page. It passes any formatting (HTML or XML) tags directly back
to the response page. In this way, JSP pages separate the page logic from its design and display.
JSP technology is part of the Java technology family. JSP pages are compiled into servlets and may call
JavaBeans components (beans) or Enterprise JavaBeans components (enterprise beans) to perform
processing on the server. As such, JSP technology is a key component in a highly scalable architecture
for web-based applications.
JSP pages are not restricted to any specific platform or web server. The JSP specification represents a
broad spectrum of industry input.
What is a servlet?
A servlet is a program written in the Java programming language that runs on the server, as opposed to
the browser (applets). Detailed information can be found at http://java.sun.com/products/servlet.
Why do I need JSP technology if I already have servlets?
JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-
based applications. However, JSP technology was designed to simplify the process of creating pages by
separating web presentation from web content. In many applications, the response sent to the client is
a combination of template data and dynamically-generated data. In this situation, it is much easier to
work with JSP pages than to do everything with servlets.
Where can I get the most current version of the JSP specification?
The JavaServer Pages 2.0 specification is available for download from here.
How does the JSP specification relate to the Java 2 Platform, Enterprise Edition?
The JSP 2.0 specification is an important part of the Java 2 Platform, Enterprise Edition 1.4. Using JSP
and Enterprise JavaBeans technologies together is a great way to implement distributed enterprise
applications with web-based front ends.
Which web servers support JSP technology?
There are a number of JSP technology implementations for different web servers. The latest
information on officially-announced support can be found at
http://java.sun.com/products/jsp/industry.html.
Is Sun providing a reference implementation for the JSP specification?
The J2EE SDK is a reference implementation of the JavaTM 2 Platform, Enterprise Edition. Sun adapts
and integrates the Tomcat JSP and Java Servlet implementation into the J2EE SDK. The J2EE SDK can be
used as a development enviroment for applications prior to their deployment and distribution.
Tomcat a free, open-source implementation of Java Servlet and JavaServer Pages technologies
developed under the Jakarta project at the Apache Software Foundation, can be downloaded from
http://jakarta.apache.org. Tomcat is available for commercial use under the ASF license from the
Apache web site in both binary and source versions. An implementation of JSP technology is part of the
J2EE SDK.
How is JSP technology different from other products?
JSP technology is the result of industry collaboration and is designed to be an open, industry-standard
method supporting numerous servers, browsers and tools. JSP technology speeds development with
reusable components and tags, instead of relying heavily on scripting within the page itself. All JSP
implementations support a Java programming language-based scripting language, which provides
inherent scalability and support for complex operations.
Where do I get more information on JSP technology?
The first place to check for information on JSP technology is http://java.sun.com/products/jsp/. This
site includes numerous resources, as well as pointers to mailing lists and discussion groups for JSP
technology-related topics.
Technical FAQ
What is a JSP page?
A JSP page is a page created by the web developer that includes JSP technology-specific and custom
tags, in combination with other static (HTML or XML) tags. A JSP page has the extension .jsp or .jspx;
this signals to the web server that the JSP engine will process elements on this page. Using the web.xml
deployment descriptor, additional extensions can be associated with the JSP engine.
Test Pattern:
Paper1: 40 J2EE Questions (50 minutes)
Paper2: 40 JAVA Questions (50 minutes)
J2EE PAPER:
-------------------------------------------------------------------
1. What exception is thrown when Servlet initialization fails ?
(a) IOException
(b) ServletException
(c) RemoteException
ANS: (b)
------------------------------------------------------------------
2. How can a Servlet call a JSP error page ?
(a) This capability is not supported.
(b) When the servlet throws the exception, it will automatically be caught by the calling JSP page.
(c) The servlet needs to forward the request to the specific error page URL. The exception is passed
along as an attribute named "javax.servlet.jsp.jspException".
(d) The servlet needs to redirect the response to the specific error page, saving the exception off in a
cookie.
ANS: (c)
-------------------------------------------------------------------
3. What is the key difference between using a <jsp:forward> and HttpServletResponse.sendRedirect()?
(a) forward executes on the client while sendRedirect() executes on the server.
(b) forward executes on the server while sendRedirect() executes on the client.
(c) The two methods perform identically.
ANS: (b)
-------------------------------------------------------------------
4. Why beans are used in J2EE architecture in stead of writing all the code in JSPs ?
(a) Allows separation of roles between web developers and application developers
(b) Allows integration with Content Management tools
ANS: (a)
-------------------------------------------------------------------
5. Why DB connections are not written directly in JSPs ?
(a) Response is slow
(b) Not a standard J2EE architecture
(c) Load Balancing is not possible
(d) All the above
(e) Both (b) and (c)
ANS: I think answer is (e). I am not sure whether response from database is slow just because we
include the database access code in JSP page.
-------------------------------------------------------------------
6. How multiple EJB instances are managed ?
(a) Connection Pooling
(b) Caching of EJB instances
(c) EJB Passivation
(d) All the above
ANS: I think answer is (d)
-------------------------------------------------------------------
7. At what stage, the life cycle of a CMP bean can be assumed to be started ?
(a) before ejbCreate() method is executed
(b) after ejbCreate() method is executed
(c) in postCreate() method
(d) after executing ejbStore()
-------------------------------------------------------------------
8. Lot of Questions on "EJB Transactions" and how to manage them.
-------------------------------------------------------------------
9. In JSP, how can you know what HTTP method (GET or POST) is used by client request ?
(a) by using request.getMethod()
(b) by using request.setMethod()
(c) impossible to know
ANS: (a)
-------------------------------------------------------------------
10. What is legal about JSP scriplets
(a) A loop can begin in one Scriptlet and end in another
(b) Statements in Scriptlets should follow Java Syntax
(c) Semicolon is needed at the end of each statement in a Scriptlet
(d) All the above
ANS: (d)
-------------------------------------------------------------------
11. Which method is called first each time a Servlet is invoked ?
(a) Start()
(b) Run()
(c) Servive()
(d) init()
ANS: (d)
-------------------------------------------------------------------
12. The time between Command Execution and Response is called ______
(a) Granularity
(b) Latency
(c) Lag time
ANS: (c)
EXPLANATION:
Latency:
Latency is a measure of the temporal delay. Typically, in xDSL, latency refers to the delay in time
between the sending of a unit of data at the originating end of a connection and the reception of that
unit at the destination end.
In a computer system, latency is often used to mean any delay or waiting that increases real or
perceived response time beyond the response time desired. Within a computer, latency can be
removed or "hidden" by such techniques as prefetching (anticipating the need for data input requests)
and multithreading, or using parallelism across multiple execution threads.
In networking, the amount of time it takes a packet to travel from source to destination. Together,
latency and bandwidth define the speed and capacity of a network.
Granularity:
The extent to which a system contains separate components (like granules). The more components in a
system -- or the greater the granularity -- the more flexible it is.
Granularity is a term often used in parallel processing to indicate independent processes that could be
distributed to multiple CPUs. Fine granularity is illustrated by execution of statements or small loop
iterations as separate processes; coarse granularity involves subroutines or sets of subroutines as
separate processes. The more processes, the "finer" the granularity and the more overhead required to
keep track of them. Granularity can also be related to the temporal duration of a "task" at work. It is
not only the number of processes but also how much work each process does, relative to the time of
synchronization, that determines the overhead and reduces speedup figures.
Lag Time:
Lag Time is the amount of time between making an online request or command and receiving a
response. A primary goal of advertising network efficiency is to minimize lag time.
-------------------------------------------------------------------
13. 2 Questions on RMI and EJB related (I don't reemember them)
-------------------------------------------------------------------
14. Purpose of <jsp:plugin> tag
(a) used to incorporate Java applets into a Web page.
(b) Downloads a plugin to the client Web browser to execute an applet or Bean.
(c) Both (a) & (b)
ANS: (c)
EXPLANATION:
JSP Syntax :
<jsp:plugin
type="bean|applet"
code="classFileName"
codebase="classFileDirectoryName"
[ name="instanceName" ]
[ archive="URIToArchive, ..." ]
[ align="bottom|top|middle|left|right" ]
[ height="displayPixels" ]
[ width="displayPixels" ]
[ hspace="leftRightPixels" ]
[ vspace="topBottomPixels" ]
[ jreversion="JREVersionNumber | 1.1" ]
[ nspluginurl="URLToPlugin" ]
[ iepluginurl="URLToPlugin" ] >
[ <jsp:params>
[ <jsp:param name="parameterName" value="parameterValue" /> ]+
</jsp:params> ]
</jsp:plugin>
-------------------------------------------------------------------
15. Difference between <jsp:forward> and <jsp:include> tags
ANS:
<jsp:forward> transfers the control to the mentioned destination page.
<jsp:include> tag substitutes the output of the destination page. Control remains on the same page.
-------------------------------------------------------------------
16. Which of the following is true ?
(a) Unlimited data transfer can be done using POST method
(b) Data is visible in Browser URL when using POST method
(c) When large amounts of data transfer is to be done, GET method is used.
ANS: (a)
-------------------------------------------------------------------
17. EJB class should implement
(a) javax.ejb.EntityBean
(b) javax.ejb.rmi
(c) javax.ejb.EJBHome
(d) javax.ejb.EJBObject
ANS: I think the answer is (a)
-------------------------------------------------------------------
18. Generally Servlets are used for complete HTML generation. If you want to generate partial HTMLs
that include some static text (This should not be hard coded in Servlets) as well as some dynamic text,
what method do you use ?
(a) Serverside includes
(b) JSP code in HTML
(c) Not possible to generate incomplete HTMLs using Servlets
(Note: I don't remember the question word to word. But it is similar to what I have given)
-------------------------------------------------------------------
19. Which of the following can not be used as the scope when using a JavaBean with JSP?
(a) session
(b) application
(c) request
(d) response
ANS: (d)
-------------------------------------------------------------------
20. Which is true about Servlets
(a) Only one instance of Servlet is created in memory
(b) Multi-Threading is used to service multiple requests
(c) Both (a) & (b)
ANS: I think the answer is (c)
-------------------------------------------------------------------
21. What is Temporary Servlet ?
(a) Servlet that is destroyed at run time
(b) Servlet that exists for a session
(c) Servlet that is started and stopped for each request
ANS: (c)
EXPLANATION:
A temporary servlet is started when a request arrives and shut down after the response is generated.
A permanent servlet is loaded when the server is started and lives until the server is shut down.
* This is useful when startup costs are high, such as a servlet that establishes a connection to a
database.
* Also useful for permanent server-side service, such as an RMI server.
* Provides faster response to client requests when this is crucial.
Being temporary or permanent is part of the server configuration.
-------------------------------------------------------------------
22. Although it is not commonly done, what will you do if you want to have multiple instances of
Servlet in memory and if they have to share the execution of a user request ?
(a) Defnie Single Thread model
(b) Cannot be done
(Note: I don't remember the question & answers word to word. But it is similar to what I have given)
-------------------------------------------------------------------
23. In WebLogic 5.1, how can you make a JSP application work
(a) By changing the root directory
(b) By creating a vitual directory in Server console
(c) By creating a vitual directory in client console
-------------------------------------------------------------------
Technical Interview
________________
1) What is 'Open System' and 'Closed System' in Computer terminology ?
2) What is meant by Open Source ? Is Java Open Source or not ?
3) Explain MVC (Model-View-Controller) architecture ? What acts as controller ? How views get
updated ?
4) What are design patterns ? Explain 'FACADE Design Pattern' ?
5) What's the difference between CMM and CMMI ?
6) What is 'Requirements Development' in CMMI ?
7) How do you capture requirements ? Using what method you make sure that requirements are
properly captured?
8) What is UseCase ? What is the template to write UseCases ?
9) How do you perform testing ? Do you use any automated testing tools ? If so, what are they ?
10) I have a Web Server, Application Server, Servlet Engine, Database - all located on separate systems
behind firewalls. How will you design an application using 3-tier architecture in this case ?
11) What is 2-Phase Commit and 3-Phase Commit in database terminology ?
12) Will the 'View' get refreshed immediately when you update a database table. If it doesn't get
refreshed immediately, what method you use to refresh it ?
13) Some websites will have hierarchical display of items. (For eg, on click of a '+' symbol, all items
under this item gets listed.). How do you store such structure in database (Note: You can store as XML
object. But how do you store in database tables without using XML) ?
14) What are interfaces, abstract classes. What is their purpose and differences ?
15) What is 3 rd level of normalization ?
16) How do you implement TREE in Java ? How do you implement the same using C or C++ ?
17) What is the difference between Application and Web servers ?
__________________________
Remarks on Technical interview : The questions are mostly analysis and design related rather than
coding related. You should have clear idea of analysis & design in J2EE, how various J2EE components
fit into various layers.
NOTE: I have written whatever I remember. Some questions may not be complete or options may be a
bit different than the ones given here. Also I have written whatever answers I know. Don't take them as
final, as some of them may be wrong.
__________________________________________________________________
PATTERN :
__________________________________________________________________
35 multiple choice Questions in 35 minutes
Questions are mainly from CORE JAVA, JSP, SERVLETS, EJB and few DATABASE related ones.
IMPORTANT: Multiple answers are possible for few questions. You need to mark all the answers to get
the marks for those questions.
PAPER :
___________________________________________________________________
In the init(ServletConfig) method of Servlet life cycle, what method can be used to access the
ServletConfig object ?
(a) getServletInfo()
(b) getInitParameters()
(c) getServletConfig()
ANS: (c)
___________________________________________________________________
The Page directive in JSP is defined as follows:
<%@ page language="java" session="false" isErrorPage="false" %>
Then which of the implicit objects won't be available ?
(a) session, request
(b) exception, request
(c) exception, config
(d) session, exception
ANS: I think answer is (d)
___________________________________________________________________
ejbCreate() method of CMP bean returns
(a) null
(b) Primary Key class
(c) Home Object
(d) Remote Object
ANS: (a)
Explanation: ejbCreate() method of BMP bean returns the Primary Key, where as ejbCreate() method of
CMP bean returns null.
___________________________________________________________________
How can a EJB pass it's reference to another EJB ?
___________________________________________________________________
Which of the following is correct syntax for an Abstract class ?
(a) abstract double area() { }
(b) abstract double area()
(c) abstract double area();
(d) abstract double area(); { }
ANS: (c)
___________________________________________________________________
A JSP page is opened in a particular Session. A button is present in that JSP page onclick of which a new
Window gets opened.
(a) The Session is not valid in the new Window
(b) The Session is valid in the new Window
ANS: I think the answer is (b)
___________________________________________________________________
Which of the following JSP expressions are valid ?
(a) <%= "Sorry"+"for the"+"break" %>
(b) <%= "Sorry"+"for the"+"break"; %>
(c) <%= "Sorry" %>
(d) <%= "Sorry"; %>
ANS:
___________________________________________________________________
A class can be converted to a thread by implementing the interface __________
(a) Thread
(b) Runnable
ANS: (b)
___________________________________________________________________
What is the output of following block of program ?
boolean var = false;
if(var = true) {
System.out.println("TRUE");
} else {
System.out.println("FALSE");
}
(a) TRUE
(b) FALSE
(c) Compilation Error
(d) Run-time Error
ANS: (a)
EXPLANATION: The code compiles and runs fine and the 'if' test succeeds because 'var' is set to 'true'
(rather than tested for 'true') in the 'if' argument.
___________________________________________________________________
Which is not allowed in EJB programming ?
(a) Thread Management
(b) Transient Fields
(c) Listening on a Socket
ANS:
___________________________________________________________________
What happens if Database Updation code is written in ejbPassivate() method and if this method is
called ?
(a) Exception is thrown
(b) Successfully executes the Database Updation code
(c) Compilation error occurs indicating that Database Updation code should not be written in
ejbPassivate()
(d) ejbStore() method is called
ANS:
___________________________________________________________________
A Vector is declared as follows. What happens if the code tried to add 6 th element to this Vector
new vector(5,10)
(a) The element will be successfully added
(b) ArrayIndexOutOfBounds Exception
(c) The Vector allocates space to accommodate up to 15 elements
ANS: (a) and (c)
EXPLANATION: The 1 st argument in the constructor is the initial size of Vector and the 2 nd argument
in the constructor is the growth in size (for each allocation)
This Vector is created with 5 elements and when an extra element (6 th one) is tried to be added, the
vector grows in size by 10.
___________________________________________________________________
Which is the data structure used to store sorted map elements ?
(a) HashSet
(b) Hashmap
(c) Map
(d) TreeMap
ANS: I think the answer is (d)
___________________________________________________________________
SessionListerner defines following methods
(a) sessionCreated, sessionReplaced
(b) sessionCreated, sessionDestroyed
(c) sessionDestroyed, sessionReplaced
ANS:
___________________________________________________________________
Which of the following is true ?
(a) Stateless session beans doesn't preserve any state across method calls
(b) Stateful session beans can be accesses by multiple users at the same time
ANS: (a)
___________________________________________________________________
Stateful Session beans contain
(a) Home Interface
(b) Remote Interface
(c) Bean Class
(d) All
ANS: (d)
___________________________________________________________________
What is the Life Cycle of Session bean ?
___________________________________________________________________
Stateless session bean is instantiated by
(a) newInstance()
(b) create()
ANS:
___________________________________________________________________
A servlet implements Single Thread model
public class BasicServlet extends HttpServlet implements SingleThreadModel {
int number = 0;
public void service(HttpServletRequest req, HttpServletResponse res) {
}
}
Which is thread safe ?
(a) Only the variable num
(b) Only the HttpServletRequest object req
(c) Both the variable num & the HttpServletRequest object req
___________________________________________________________________
If you are trying to call an EJB that is timed out, what will happen ?
(a) Exception
(b) It gets executed
___________________________________________________________________
A method is defined in a class as :
void processUser(int i) { }
If this method is overriden in a sub class,_____
(a) the new method should return int
(b) the new method can return any type of values
(c) the argument list of new method should exactly match that of overriden method
(d) the return type of new method should exactly match that of overriden method
ANS: (c) & (d)
___________________________________________________________________
In a JSP page, a statement is declared as follows:
<%! String strTemp = request.getParameter("Name"); %>
And below that, an _expression appears as:
<% System.out.println("The Name of person is: "+strTemp); %>
What is the output of this _expression, if this JSP page is invoked in browser using URL :
http://localhost:8080/JSP/TrialPage.jsp?Name=Chetana
(Assume that this URL is correct)
(a) The Name of person is: Chetana
(b) The Name of person is:
(c) The Name of person is: null
(d) None
ANS: (a)
___________________________________________________________________
Without the use of Cartesian product, how many joining conditions are required to join 4 tables ?
(a) 1
(b) 2
(c) 3
(d) 4
ANS:
___________________________________________________________________
What is the output of following piece of code ?
int x = 2;
switch (x) {
case 1:System.out.println("1");
case 2:
case 3:System.out.println("3");
case 4:
case 5:System.out.println("5");
}
(a) No output
(b) 3 and 5
(c) 1, 3 and 5
(d) 3
ANS: (b)
___________________________________________________________________________________
Basically, the applet pretends to be a web browser, and the servlet doesn't know the difference. As far
as the servlet is concerned, the applet is just another HTTP client.
--------------------
3) In CMP of Entity beans
--------------------
4) What is the purpose of ejbLoad()
--------------------
5) What is the purpose of ejbStore()
--------------------
6) In EJB, when a system error occurs, which exception is thrown ?
(a) EJBException
(b) RemoteException
--------------------
7) In EJB, which of the following is an application level Exception ?
(a) NullPointerException
(b) ArrayOutOfBoundsException
(c) CreateException
(d) ObjectNotFoundException
(e) All the above
(f) None of the above
--------------------
8) CMP bean provides
(a) Empty implementation of ejbLoad() and ejbStore()
(a) Concrete implementation of ejbLoad() and ejbStore()
----------------------------------------------------
JSP and Mislleneous
----------------------------------------------------
WebLogic uses a Round-Robin strategy as default algorithm for forwarding the HTTP requests inside a
cluster. Weight-based and random algorithms are also available.
--------------------
4) How many Queues does a MDB listen to ?
(a) 1
(b) 2
(c) Any Number
(d) 10
ANS: (a)
--------------------
5) Where is the Deployment Descriptor placed ?
(a) WEB-INF directory
(b) WEB-INF/CLASSES directory
(c) It will be mentioned in CLASSPATH
(d) The place can be specified in APPLICATION.xml
--------------------
6) To denote distributed applications, What is the tag used in Deployment Descriptor ?
(a) distributable
(d) distributed="true"
(c) both a & b
--------------------
8) Empty JSP Tag definitions are given in Deployment Descriptor. Then which of the following syntaxes
are correct ?
(I don't remember the options)
-------------------
String _member;
void method1() {
for(int i=0;i<2048;i++) {
_member += "test";
}
}
void method2() {
String temp;
for(int i=0;i<2048;i++) {
temp += "test";
}
_member = temp;
}
}
(a) method1()
(b) method2()
(c) Both method1() and method2() takes same time for execution
ANS: (b)
Accessing method variables requires less overhead than accessing class variables.
--------------------
2) Integer.parseInt("12a") returns
(a) Exception
(b) 1
(c) 0
(d) -1
ANS: (a)
--------------------
3) By default, Strings to functions are passed using the method
(a) Call by Value
(b) Call by Reference
(c) Strings cannot be passed to function
ANS: (b)
String is a class defined in java.lang and in java all classes are passed by reference.
-------------------
--------------------
6) 't' is the reference to a class that extends THREAD. Then how to suspend the execution of this
thread ?
(a) t.yield()
(b) yield(t)
(c) yield()
(d) yield(100) where 100 is the milli seconds of time
--------------------
7) What is the functionality of instanceOf() ?
--------------------
8) How many String objects are created by the following statements ?
String str = " a+b=10 ";
trim(str)
str.replace(+,-);
(a) 1
(b) 2
(c) 3
(d) 4
ANS: (c)
Strings are immutable. So, for each String operation, one new object is generated.
--------------------
9) (A program is given. I don't remember exactly)
An ABSTRACT class is declared and the code is tried to instantiate it. The Question was whether it's
legal to do it or not ?
--------------------
10) A question on "interface"
--------------------
11) Cleaning operation in Java is done in the method
(a) finally()
(b) finalize()
(c) final()
--------------------
12) Question on whether Static method can be overriden
--------------------
13) How to prevent a class from being the Base Class ?
(a) declare it as final
(b) declare it as static
--------------------
14) If we want to read a very big text file with so many mega bytes of data, what shall we use ?
(a) FileInputStream
(b) InputStreamReader
(c) BufferedReader
--------------------
15) One Question on Inner Classes.
--------------------
16) One program on Overloading and Overriding
--------------------
17) A program given using try, catch and finally and it is asked to find out which statements get
executed ?
--------------------
18) What code, if written, below the (//code here) will display 0.
class Test {
public static void main(String argv[]) {
int i=0;
//code here
}
}
(a) System.out.println(i++)
(b) System.out.println(i+'0')
(c) System.out.println(i--)
(d) System.out.println(i)
ANS: (a),(c),(d)
The option (b) displays the ASCII value of '0'. So, the output in this case is: 48
--------------------
19) What is the better way of writing the Constructor with 2 parameters in the following code:
class Test {
int x,y;
Test(int a) {
x=a;
}
Test(int a, int b) {
x=a;
y=b;
}
}
----------------------------------------------------
TECHNICAL INTERVIEW
----------------------------------------------------
-------------------------------------------------------------------
Interview Question at ORACLE for JAVA platform holding 3 yrs of Exp
-------------------------------------------------------------------
Questions that remembered are,
1)Difference between Vector and ArrayList?
2)What is controller in your project?
3)How will u authentication a user?
4)Some servlet calls JSP and in JSP will initialize a servlet this way
Servlet1 s=new Servlet1();
s.doPost(request,response);
and this in turn calls a jsp and this JSP calls another Servlet what will be the output?
5)Any 2 errors and exceptions?
6)Difference between SAX and DOM?
7)Have u ever used <xsl:include>. How to include an xslt in another xslt ?
8)How will u get connection in ur project?
9)Which loads driver classloader or JVM?
10)Difference between Statement and PreparedStatement?
11)ResultSet points to which location by default?
12)What is ResultSetMetaData?
13)Types of Drivers in JDBC?
14)Difference between 3rd and 4th type java?
15)What is class?what is object?
16)What is object ? what is instance? What is the difference between object and instance?
17)What is encapsulation?
18)What is polymorphism? Types of polymorphism ? how will u achieve all types of polymorphism?
19)What is the difference between vector and Array?
20)What is the difference between HashTable and HashMap?
21)Are servlets and JSP's threadsafe ? how can u make them threadsafe?
22)What is multithreading? What Is synchronized?
23)How can u stop a thread?
Is stop()=sleep()
24)How to kill a thread?
25)Describe the design of ur project as MVC ? Methodologies? Flow of ur project?
26)How will u make transactions with creditcard? Ie will u deduct money from the card
Immediately after making transaction?
27)How will u insert and delete with a single java connection when u have referential integrity?
28)What is serialization? Any methods in serialization? What is externalization?
29)How will u achieve threads?
30)How will u set priorities of threads?
1)How to implement connection pooling by ourself?
2)Will service all doget , dopost or the reverse?
3)How can u implement cocoon on ur own?
4)How can u implement hashmap if u r not having it in java?
5)What is the difference between static binding and dynamic binding?
6)What is synchronization? Why is it used? What are its disadvantages?
7)How will u enforce synchronization?
8)How will u declare a synchronized block? What does this represent in the
Declaration of synchronized block?
9)Can u assign an instance of a class which implements an interface to an interface type?
10)What is servlet chaining?
11)Describe the life cycle of servlet starting from the request from a browser to the response it get?
12)If service method is used then doGet() and doPost() stand for what?
13)If we can access a sevlet through both GET and POST methods then which methods will u declare in
the sevlet class?
14)What is dynamic binding?Can u explain with an example?
15)Can u read all elements from an array?
16)If aaaa is an array then why aaaa.length why not aaaa.length()? Is array an object?
Class A{
Public void meth(){ }
}
class B extends A{
Public void meth(){
}
public static void main(String args[]){
A a=new A();
a.meth();//which method will this call
}
}
---------------------------------
-------------------------------------------------------------------
(5)What is Synchornize?
For Deadlock avoidance use Simplest algorithm where each process tells max number
of resources it will ever need. As process runs, it requests resources but never
exceeds max number of resources. System schedules processes and allocates resoures
in a way that ensures that no deadlock results.
------------------------------------------------------------------
7)Explain different way of using thread? :
-------------------------------------------------------------------
(9)How Servlet Maintain Session and EJB Maintain Session?
Servlets maintain session in ServleContext and EJB's in EJBContext.
-------------------------------------------------------------------
(10)Explain DOM and SAX Parser?
DOM parser is one which makes the entire XML passed as a tree Structure and
will have it in memory. Any modification can be done to the XML.
SAX parser is one which triggers predefined events when the parser
encounters the tags in XML. Event-driven parser. Entire XML will not be stored
in memory. Bit faster than DOM. NO modifications can be done to the XML.
-------------------------------------------------------------------
(11)What is HashMap and Map?
Map is Interface and Hashmap is class that implements that and its not
serialized HashMap is non serialized and Hashtable is serialized
-------------------------------------------------------------------
(12)Difference between HashMap and HashTable?
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.
-------------------------------------------------------------------
(12a) Difference between Vector and ArrayList?
-------------------------------------------------------------------
-------------------------------------------------------------------
16)Services of EJB?
Database management :
–Database connection pooling
–DataSource, offered by the J2EE server. Needed to access connection pool of the server.
–Database access is configured to the J2EE server -> easy to change database / database driver
Transaction management :
–Distributed transactions
–J2EE server offers transaction monitor which can be accessed by the client.
Security management :
–Authetication
–Authorization
–encryption
-------------------------------------------------------------------
17)When to choose EJB?
Server will be heavy loaded :
–Distribution of servers helps to achieve better performance.
Server should have replica for the case of failure of one server:
–Replication is invisible to the programmer
-------------------------------------------------------------------
-------------------------------------------------------------------
19) Alternative:Tuxedo
Tuxedo is a middleware that offers scalability services and transaction monitors.
C or C++ based.
Can be used with Java client by classes in JOLT package offered by BEA.
-------------------------------------------------------------------
20) J2EE server offers
DataSource:
–Object that can be used to achieve database connection from the connection pool.
–Can be accessed by the interface DataSource
Transaction monitor:
–Can be accessed by the interface UserTransaction.
Java Naming and the Directory Service :
-------------------------------------------------------------------
21)Java Naming and the Directory Service
Naming service is needed to locate beans home interfaces or other objects (DataSource,
UserTransaction):
–For example, jndi name of the DataSource
-------------------------------------------------------------------
-------------------------------------------------------------------
24)Entity Beans
-------------------------------------------------------------------
25) When to use which bean?
Entity beans are effective when application wants to access one row at a time.
If many rows needs to be fetched, using session beans can be better alternative
ava class (for example, Integer).
Entity beans are efficient when working with one row at a time
Cause a lot of network trafic.
Session Beans are efficient when client wants to access database directry.
–fetching/updating multiple rows from the database
-------------------------------------------------------------------
Container Types :
The deployment process installs J2EE application components in the following
types of J2EE containers. The J2EE components and container addressed in this
tutorial are shown in Figure 5.
An Enterprise JavaBeans (EJB) container manages the execution of all
enterprise beans for one J2EE application. Enterprise beans and their
container run on the J2EE server.
A web container manages the execution of all JSP page and servlet components
for one J2EE application. Web components and their container run on the J2EE
server.
An application client container manages the execution of all application
client components for one J2EE application. Application clients and their
container run on the client machine.
An applet container is the web browser and Java Plug-in combination running on
the client machine.
2. What will happen if you try to compile and run the following code
public class MyClass {
public static void main(String arguments[]) {
amethod(arguments);
}
public void amethod(String[] arguments) {
System.out.println(arguments);
System.out.println(arguments[1]);
}
}
1) error Can't make static reference to void amethod.
2) error method main not correct
3) error array must include parameter
4) a method must be declared with String
3. Which of the following will compile without error
1) import java.awt.*;
package Mypackage;
class Myclass {}
2) package MyPackage;
import java.awt.*;
class MyClass{}
3)
/*This is a comment */
package MyPackage;
import java.awt.*;
class MyClass{}
I/O’s
3. How can you change the current working directory using an instance of the File class called
fileName?
[a] fileName.chdir("DirName")
[b] fileName.cd("DirName")
[c] fileName.cwd("DirName")
[d] The File class does not support directly changing the current directory.
7.You have an 8-bit file using the character set defined by ISO 8859-8. You are writing an application to
display this file in a TextArea. The local encoding is already set to 8859-8. How can you write a chunk of
code to read the first line from this file?
You have three variables accessible to you:
- myfile is the name of the file you want to read
- stream is an InputStream object associated with this file
- s is a String object
Select all valid answers.
[a]
InputStreamReader reader = new InputStreamReader(stream, "8859-8");
BufferedReader buffer = new BufferedReader(reader);
s = buffer.readLine();
[b]
InputStreamReader reader = new InputStreamReader(stream);
BufferedReader buffer = new BufferedReader(reader);
s = buffer.readLine();
[c]
InputStreamReader reader = new InputStreamReader(myfile, "8859-8");
BufferedReader buffer = new BufferedReader(reader);
s = buffer.readLine();
[d]
InputStreamReader reader = new InputStreamReader(myfile);
BufferedReader buffer = new BufferedReader(reader);
s = buffer.readLine();
[e]
FileReader reader = new FileReader(myfile);
BufferedReader buffer = new BufferedReader(reader);
s = buffer.readLine();
8. Which of the following used to read and write to network sockets, which are super classes of Low
level streams?
[a] InputStream
[b] StreamReaders
[c] OutputStream
[d] Writers
[e] Readers
[f] Streams
9. What is the permanent effect on the file system of writing data to a new FileWriter("report"), given
the file report already exists?
[a] The data is appended to the file.
[b] The file is replaced with a new file.
[c] A checked exception is raised as the file already exists.
[d] A runtime exception is raised as the file already exists.
[e] The data is written to random locations within the file.
10. Choose all valid forms of the argument list for the FileOutputStream constructor shown below?
[a] FileOutputStream( FileDescriptor fd )
[b] FileOutputStream( String n, boolean a )
[c] FileOutputStream( boolean a )
[d] FileOutputStream()
[e] FileOutputStream( File f )
12. How can you replace the comment at the end of main() with code that will write the integers 0
through 9? Select the correct answer.
import java.io.*;
class Write {
public static void main(String[] args) throws Exception {
File file = new File("temp.txt");
FileOutputStream stream = new FileOutputStream(file);
// write integers here. . .
}
}
[a]
DataOutputStream filter = new DataOutputStream(stream);
for (int i = 0; i < 10; i++)
filter.writeInt(i);
[b]
for (int i = 0; i < 10; i++)
file.writeInt(i);
[c]
for (int i = 0; i < 10; i++)
stream.writeInt(i);
[d]
DataOutputStream filter = new DataOutputStream(stream);
for (int i = 0; i < 10; i++)
filter.write(i);
[e]
for (int i = 0; i < 10; i++)
stream.write(i);
13. Low Level Streams read input as bytes and writes as bytes, then select the correct declarations of
Streams.
[a] FileInputStream FIS = new FileInputStream("test.txt")
[b] File file = new File("test.txt"); FileInputStream FIS = new FileInputStream(file)
[c] File file = new File("c:\\"); File file1 = new File(file,"test.txt"); FileOutStream FOS = new
FileOutputStream(file1);
[d] FileInputStream FIS = new FileInputStream("c:\\","test.txt")
14. A "mode" argument such as "r" or "rw" is required in the constructor for the class(es):
[a] DataInputStream
[b] InputStream
[c] RandomAccessFile
[d] File
15. If raf is a RandomAccessFile, what is the result of compiling and executing the following code?
raf.seek( raf.length() );
[a] The code will not compile.
[b] An IOException will be thrown.
[c] The file pointer will be positioned immediately before the last character of the file.
[d] The file pointer will be positioned immediately after the last character of the file.
[e] None of the above
16. What happens if the file "Random.test" does not yet exist and you attempt to compile and run the
following code? Select the correct answer.
import java.io.*;
class Ran {
public static void main(String[] args) throws IOException {
RandomAccessFile out = new RandomAccessFile("Ran.test", "rw");
out.writeBytes("Nikhita");
}
}
[a] The code does not compile because RandomAccessFile is not created correctly.
[b] The code does not compile because RandomAccessFile does not implement the writeBytes()
method.
[c] The code compiles and runs but throws an IOException because "Ran.txt" does not yet exist.
[d] The code compiles and runs but nothing appears in the file "Ran.txt" that it creates.
[e] The code compiles and runs and "Nikhita" appears in the file "Ran.txt" that it creates.
17. What is the output displayed by the following code?
import java.io.*;
public class TestIPApp {
public static void main(String args[]) throws IOException {
RandomAccessFile file = new RandomAccessFile("test.txt", "rw");
file.writeBoolean(true);
file.writeInt(123456);
file.writeInt(7890);
file.writeLong(1000000);
file.writeInt(777);
file.writeFloat(.0001f);
file.seek(5);
System.out.println(file.readInt());
file.close();
}
}
[a] 123456
[b] 7890
[c] 1000000
[d] .0001
18. Can we serialize a Thread Object
UTIL
1. Which of the following implement clear notion of one item follows another (order)? [a] List
[b] Set
[c] Map
[d] Iterator
3. Collection interface iterator method returns Iterator(like Enumerator), through you can traverse a
collection from start to finish and safely remove elements.
[a] true
[b] false
5. Which interface describes a mapping between key to value, without duplicate key's.?
[a] List
[b] Map
[c] Iterator
[d] Enumerator
[e] Set
which class of the socket should we use for a given application 1. Server Socket 2. Datagram socket
2. How do we get the IP address of a machine from its hostname?
3. How do we perform a hostname lookup for an IP address?
4 How can we find out who is accessing my server?
5 How can we find out the current IP address for my machine?
6 Why can't an applet connect via sockets, or bind to a local port?
7 What are socket options, and why should we use them?
8 When a client connects to my server, why does no data come out?
9 What is the cause of a NoRouteToHost exception?
1.How do we display a particular web page from an applet?
2 How do we display more than one page from an applet?
3 How can we fetch files using HTTP?
4 How do we use a proxy server for HTTP requests?
5 What is a malformed URL, and why is it exceptional?
6 How do we URL encode the parameters of a CGI script?
7 Why is a security exception thrown when using java.net.URL or
java.net.URLConnection from an applet?
8 How do we prevent caching of HTTP requests?
JDBC
Name all the four types of drivers and where they are used
Difference between a Thin Client and a Thick Client
Where do we use the dynamic loading in JDBC. What are the advantages
Which method is used to achieve dynamic loading
What is the difference between Prepared Statement and a callable statement
Considering the SQL execution, which of the following are faster and why? 1. Prepared statement and
2. Statement
What is a Resultset
What are the advantages of Scrollable Resultset
Can the JDBC-ODBC Bridge be used with applets?
How do I start debugging problems related to the JDBC API?
What causes the "No suitable driver" error?
Is the JDBC-ODBC Bridge multi-threaded?
Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?
There is a method getColumnCount in the JDBC API. Is there a similar method to find the number of
rows in a result set?
Servlets/JSP’s
Why use RequestDispatcher to forward a request to another resource, instead of using a sendRedirect?
What is a benefit of using JavaBeans to separate business logic from presentation markup within the
JSP environment?
What type of scriptlet code is better-suited to being factored forward into a servlet?
How is a JSP page invoked and compiled?
How can we create XML pages using JSP technology?
How do we define a global variable in JSP page and what precautions are to be taken for the same
How do an applet attach to the existing HTTP session of a servlet?In other words, I want the servlet to
recognize that the applet's requests are coming from the same user.
How can we run a servlet or a JSP on an IIS server. What additional s/w’s are required to run a servlet or
a JSP on a non java supporting web server
How do we pass an object over a network if we have a firewall
What are the various ways of maintaining Session.
How do we chain the servlets and why do we give an alias name.
what is URL rewriting
Draw a flow diagram for the Life cycle of a servlet
The instantiation and the service methods are controlled by 1. the web server or 2. by the servlet
container? Explain
RMI
What is the need of Remote and Home interface. Why cant it be in one?
Can I develop an Entity Bean without implementing the create() method in the home interface?
What is the difference between Context, InitialContext and Session Context? How they are used?
Why an onMessage call in Message-driven bean is always a seperate transaction?
Why are ejbActivate() and ejbPassivate() included for stateless session bean even though they are
never required as it is a nonconversational bean?
Static variables in EJB should not be relied upon as they may break in clusters.Why?
If I throw a custom ApplicationException from a business method in Entity bean which is participating
in a transaction, would the transaction be rolled back by container?
Does Stateful Session bean support instance pooling?
Can I map more than one table in a CMP?
Can a Session Bean be defined without ejbCreate() method?
How to implement an entity bean which the PrimaryKey is an autonumeric field
What is clustering?
Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in
the HttpSession from inside an EJB?
If my session bean with single method insert record into 2 entity beans, how can know that the process
is done in same transaction (the attributes for these beans are Required)?
Types of transaction ?
What is bean managed transaction ?
Why does EJB needs two interface( Home and Remote Interface) ?
Difference between Jar, War, Ear file
Why does EJB needs two interface
WebLogic
class Another
{
public void amethod()
{
Outer.Inner i = new Outer().new Inner();
}
}
Classes defined in methods can be anonymous, in which case they must be instantiated at the same
point they are defined. These classes can't have explicit constructor and may implement interface or
extend other classes.
The Thread class resides in java.lang package and need not be imported.
The sleep and yield methods of Thread class are static methods.
The range of Thread priority in java is 1-10. The minimum priority is 1 and the maximum is 10. The
default priority of any thread in java is 5.
There are two ways to provide the behavior of a thread in java: extending the Thread class or
implementing the Runnable interface.
The only method of Runnable interface is "public void run();".
New thread take on the priority of the thread that spawned it.
Using the synchronized keyword in the method declaration, requires a thread obtain the lock for this
object before it can execute the method.
A synchronized method can be overridden to be not synchronized and vice versa.
In java terminology, a monitor is any object that has some synchronized code.
Both wait() and notify() methods must be called in synchronized code.
The notify() mthod moves one thread, that is waiting on this object's monitor, into the Ready state. This
could be any of the waiting threads.
The notifyAll() method moves all threads, waiting on this object's monitor into the Ready state.
Every object has a lock and at any moment that lock is controlled by, at most, one single thread.
There are two ways to mark code as synchronized:
a.) Synchronize an entire method by putting the synchronized modifier in the method's declaration.
b.) Synchronize a subset of a method by surrounding the desired lines of code with curly brackets ({}).
The argument to switch can be either byte, short , char or int.
The expression for an if and while statement in java must be a boolean.
Breaking to a label (using break <labelname>;) means that the loop at the label will be terminated and
any outer loop will keep iterating. While a continue to a label (using continue <lablename>;) continues
execution with the next iteration of the labeled loop.
A static method can only call static variables or other static methods, without using the instance of the
class. e.g. main() method can't directly access any non static method or variable, but using the instance
of the class it can.
instanceof is a java keyword not instanceOf.
The if() statement in java takes only boolean as an argument. Please note that if (a=true){}, provided a
is of type boolean is a valid statement and the code inside the if block will be executed.
The (-0.0 == 0.0) will return true, while (5.0==-5.0) will return false.
An abstract class may not have even a single abstract method but if a class has an abstract method it
has to be declared as abstract.
Collection is an Interface where as Collections is a helper class.
The default Layout Manager for Panel and Applet is Flow. For Frame and Window its BorderLayout.
The FlowLayout always honors the a component's preferred size.
BorderLayout honors the preferred width of components on the East and West, while the preferred
height is honored for the components in the North and South.
The java.awt.event package provides seven adapter classes, one for each listener interface. All these
adapter classes have do-nothing methods (empty bodies) , implementing listener interface.
A componenet subclass may handle its own events by calling enableEvents(), passing in an even mask.
The Listener interfaces inherit directly from java.util.EventListener interface.
A Container in java is a Component (Container extends Component) that can contain other
components.
Graphics class is abstract, hence cannot be instantiated.
The repaint() method invokes a component's update() method() which in turn invokes paint() method.
The Applet class extends Panel, Frame class extends Window.
A String in java is initialized to null, not empty string and an empty string is not same as a null string.
The statement float f = 5.0; will give compilation error as default type for floating values is double and
double can't be directly assigned to float without casting.
The equals() method in String class compares the values of two Strings while == compares the memory
address of the objects being compared.
e.g. String s = new String("test"); String s1 = new String("test");
s.equals(s1) will return true while s==s1 will return false.
The valueOf() method converts data from its internal format into a human-readable form. It is a static
method that is overloaded within String class for all of Java's built-in types, so that each type can be
converted properly into a string.
The main difference between Vector and ArrayList is that Vector is synchronized while the ArrayList is
not.
A Set is a collection, which cannot contain any duplicate elements and has no explicit order to its
elements.
A List is a collection, which can contain duplicate elements, and the elements are ordered.
A Map does not implement the Collection interface.
The following definition of main method is valid : static public void main(String[] args).
The main() method can be declared final.
The example of array declaration along with initialization - int k[] = new int[]{1,2,3,4,9};
The size of an array is given by arrayname.length.
The local variables (variables declared inside method) are not initialized by default. But the array
elements are always initialized wherever they are defined be it class level or method level.
In an array , the first element is at index 0 and the last at length-1. Please note that length is a special
array variable and not a method.
The octal number in java is preceded by 0 while the hexadecimal by 0x (x may be in small case or upper
case)
e.g.
octal :022
hexadecimal :0x12
A constructor cannot be native, abstract, static, synchronized or final.
Constructors are not inherited so not possible to override them.
A constructor body can include a return statement providing no value is returned .
A constructor never return a value. If you specify a return value, the JVM (java virtual machine) will
interpret it as a method.
A call to this() or super() in a constructor must be placed at the first line.
If a class contains no constructor declarations, then a default constructor that takes no arguments is
supplied. This default constructor invokes the no-argument constructor of the super class via super()
call (if there is any super class).
Be careful for static and abstract key word in the program.
Also be careful for private keyword in front of a class.
The UTF characters in java are as big as they need to be while Unicode characters are all 16 bits.
1. How can you achieve Multiple Inheritance in Java?
Java's interface mechanism can be used to implement multiple inheritance, with one important
difference from c++ way of doing MI: the inherited interfaces must be abstract. This obviates the need
to choose between different implementations, as with interfaces there are no implementations.
5. What is a transient variable?
A transient variable is a variable that may not be serialized. If you don't want some field not to be
serialized,you can mark that field transient or static.
6. What is the difference between Serializalble and Externalizable interface?
When you use Serializable interface, your class is serialized automatically by default. But you can
override writeObject() and readObject()two methods to control more complex object serailization
process. When you use Externalizable interface, you have a complete control over your class's
serialization process.
7. How many methods in the Externalizable interface?
There are two methods in the Externalizable interface. You have to implement these two methods in
order to make your class externalizable. These two methods are readExternal() and writeExternal().
8. How many methods in the Serializable interface?
There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the
object serialization tools that your class is serializable.
9. How to make a class or a bean serializable?
By implementing either the java.io.Serializable interface, or the java.io.Externalizable interface. As long
as one class in a class's inheritance hierarchy implements Serializable or Externalizable, that class is
serializable.
10. What is the serialization?
The serialization is a kind of mechanism that makes a class or a bean persistence by having its
properties or fields and state information saved and restored to and from storage.
11. What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to an object. A thread only executes
a synchronized method after it has acquired the lock for the method's object or class. Synchronized
statements are similar to synchronized methods. A synchronized statement can only be executed after
a thread has acquired the lock for the object or class referenced in the synchronized statement.
12. What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple
threads to shared resources. Without synchronization, it is possible for one thread to modify a shared
object while another thread is in the process of using or updating that object's value. This often causes
dirty data and leads to significant errors.
13. 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.
14. 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.
15. 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.
16. 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.
17. 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.
18. What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different return types.
19. 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.
20. 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.
21. 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.
22. What class allows you to read objects directly from a stream?
The ObjectInputStream class supports the reading of objects from input streams.
23. 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.
24. 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.
25. 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.
26. 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.
27. Can you write Java code for declaration of multiple inheritance in Java ?
Class C extends A implements B
{}
28. What do you mean by multiple inheritance in C++ ?
Multiple inheritance is a feature in C++ by which one class can be of different types. Say class
teachingAssistant is inherited from two classes say teacher and Student.
29. Write the Java code to declare any constant (say gravitational constant) and to get its value.
Class ABC
{
static final float GRAVITATIONAL_CONSTANT = 9.8;
public void getConstant()
{
system.out.println("Gravitational_Constant: " + GRAVITATIONAL_CONSTANT);
}
}
30. What are the disadvantages of using threads?
DeadLock.
31. Given two tables Student(SID, Name, Course) and Level(SID, level) write the SQL statement to get
the name and SID of the student who are taking course = 3 and at freshman level.
SELECT Student.name, Student.SID
FROM Student, Level
WHERE Student.SID = Level.SID
AND Level.Level = "freshman"
AND Student.Course = 3;
32. What do you mean by virtual methods?
virtual methods are used to use the polymorhism feature in C++. Say class A is inherited from class B. If
we declare say fuction f() as virtual in class B and override the same function in class A then at runtime
appropriate method of the class will be called depending upon the type of the object.
33. What do you mean by static methods?
By using the static method there is no need creating an object of that class to use that method. We can
directly call that method on that class. For example, say class A has static function f(), then we can call
f() function as A.f(). There is no need of creating an object of class A.
34. What do mean by polymorphism, inheritance, encapsulation?
Polymorhism: is a feature of OOPl that at run time depending upon the type of object the appropriate
method is called.
Inheritance: is a feature of OOPL that represents the "is a" relationship between different
objects(classes). Say in real life a manager is a employee. So in OOPL manger class is inherited from the
employee class.
Encapsulation: is a feature of OOPL that is used to hide the information.
39. why do you create interfaces, and when MUST you use one?
You would create interfaces when you have two or more functionalities talking to each other. Doing it
this way help you in creating a protocol between the parties involved.
40. What's the difference between the == operator and the equals() method? What test does
Object.equals() use, and why?
The == operator would be used, in an object sense, to see if the two objects were actually the same
object. This operator looks at the actually memory address to see if it actually the same object. The
equals() method is used to compare the values of the object respectively. This is used in a higher level
to see if the object values are equal. Of course the the equals() method would be overloaded in a
meaningful way for whatever object that you were working with.
41. Discuss the differences between creating a new class, extending a class and implementing an
interface; and when each would be appropriate.
* Creating a new class is simply creating a class with no extensions and no implementations. The
signature is as followspublic class MyClass(){}
* Extending a class is when you want to use the functionality of another class or classes. The extended
class inherits all of the functionality of the previous class. An example of this when you create your own
applet class and extend from java.applet.Applet. This gives you all of the functionality of the
java.applet.Applet class. The signature would look like this
public class MyClass extends MyBaseClass{}
* Implementing an interface simply forces you to use the methods of the interface implemented. This
gives you two advantages. This forces you to follow a standard(forces you to use certain methods) and
in doing so gives you a channel for polymorphism. This isn’t the only way you can do polymorphism but
this is one of the ways.
public class Fish implements Animal{}
42. Given a text file, input.txt, provide the statement required to open this file with the appropriate
I/O stream to be able to read and process this file.
43. Name four methods every Java class will have.
public String toString();
public Object clone();
public boolean equals();
public int hashCode();
44. What does the "abstract" keyword mean in front of a method? A class?
Abstract keyword declares either a method or a class. If a method has a abstract keyword in front of it,
it is called abstract method.Abstract method has no body. It has only arguments and return type.
Abstract methods act as placeholder methods that are implemented in the subclasses. Abstract classes
can't be instantiated.If a class is declared as abstract,no objects of that class can be created.If a class
contains any abstract method it must be declared as abstract.
46. Are constructors inherited? Can a subclass call the parent's class constructor? When?
You cannot inherit a constructor. That is, you cannot create a instance of a subclass using a constructor
of one of it's superclasses. One of the main reasons is because you probably don't want to overide the
superclasses constructor, which would be possible if they were inherited. By giving the developer the
ability to override a superclasses constructor you would erode the encapsulation abilities of the
language.
47. What synchronization constructs does Java provide? How do they work?
48. Why "bytecode"? Can you reverse-engineer the code from bytecode?
50. What does the "final" keyword mean in front of a variable? A method? A class?
FINAL for a variable : value is constant
FINAL for a method : cannot be overridden
FINAL for a class : cannot be derived
What is JAVA ?
Java is a pure object oriented programming language, which has derived C syntax and C++
object oriented programming features.
Is a compiled and interpreted language and is platform independent and
Can do graphics, networking, multithreading. It was initially called as OAK.
what is downcasting ?
Doing a cast from a base class to a more specific class. The cast does not convert the object, just
asserts it actually is a more specific extended object.
e.g. Dalamatian d = (Dalmatian) aDog;
Most people will stare blankly at you if you use the word downcast. Just use cast.
Declaration of Arrays ?
int a[] = new int[10]; int a[][] = new int[2][2];
Define class ?
A class is a one which defines new datatype, and is template of an object, and is a protoype.
Types of Constructors ?
Default Constructor, Parameterized Constructor, Copy Constructors
Garbage collector takes the responsibility releasing the memory of object implicitly.
What is Stream ?
It is an Abstraction that either produces or consumes information.
Two types : Byte Stream and Character Stream.
Print Writer is to Print output in Real World Programs.
What is a StringTokenizer ?
String Tokenizer provide parsing process in which it identifies the delimiters provided by the
user , by default delimiters are spaces, tab, newline etc. and separates them from the tokens. Tokens
are those which are separated by delimiters.
What are macros and Inline functions ? Which is best and Difference ?
Inline functions do Parameter passing, where as Macros do Text Substitution.
Its better to go for Inline functions than macros, else you may get different results.
What is Serialization ?
The process of writing the state of an object to a byte stream. and can restore these objects by using
deserialization.
Is also need to implement RMI, which allows a java object of one machine to invoke java object of
another machine.
ie., the object is passed as an argument by serializing it and the receiving machine deserializes it.
Canvas ScrollPane
Its a component Its a container.
A rectangular area where the application Implements horizontal and vertical
can draw or trap input events. scrolling.
73) What are the types of JDBC Driver Models and explain them?
Two tier model: In this model, Java applications interact directly with the database. A JDBC driver is
required to communicate with the particular database management system that is being accessed. SQL
statements are sent to the database and the results are given to user. This model is referred to as
client/server configuration where user is the client and the machine that has the database is called as
the server.
Three tier model: A middle tier is introduced in this model. The functions of this model are:
a) Collection of SQL statements from the client and handing it over to the database,
b) Receiving results from database to the client and
c) Maintaining control over accessing and updating of the above.
74) What are the steps involved for making a connection with a database or how do you connect to a
database?
a) Loading the driver : To load the driver, Class.forName( ) method is used.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
When the driver is loaded, it registers itself with the java.sql.DriverManager class as an available
database driver.
b) Making a connection with database : To open a connection to a given database,
DriverManager.getConnection( ) method is used.
Connection con = DriverManager.getConnection ("jdbc:odbc:somedb", "user", "password");
c) Executing SQL statements : To execute a SQL query, java.sql.statements class is used.
createStatement( ) method of Connection to obtain a new Statement object.
Statement stmt = con.createStatement( );
A query that returns data can be executed using the executeQuery( ) method of Statement. This
method executes the statement and returns a java.sql.ResultSet that encapsulates the retrieved data:
ResultSet rs = stmt.executeQuery("SELECT * FROM some table");
d) Process the results : ResultSet returns one row at a time. Next( ) method of ResultSet object
can be called to move to the next row. The getString( ) and getObject( ) methods are used for retrieving
column values:
while(rs.next( ) ) { String event = rs.getString("event");
Object count = (Integer) rs.getObject("count");
85) What are the different servers available for developing and deploying Servlets?
Ans: a) Java Web Server
b) JRun
g) Apache Server
h) Netscape Information Server
i) Web Logic
86) How many ways can we track client and what are they?
Ans: The servlet API provides two ways to track client state and they are:
a) Using Session tracking and b) Using Cookies.
90) Is it possible to communicate from an applet to servlet and how many ways and how?
Ans: Yes, there are three ways to communicate from an applet to servlet and they are:
a) HTTP Communication(Text-based and object-based)
b) Socket Communication
c) RMI Communication
25. Which of the following attributes are compulsory with an <applet> tag?.
code,height & width.
Access Modifiers: Which gives additional meaning to data, methods and classes.
29.Hostile Applets:Its an applet which when downloaded attempts to exploit your system's resources
in an inappropriate manner.It performs or causes you to perform an action which you would not
otherwise care to perform.
30.RemoteObjects: Objects that have methods that can be called accross virtual machines are Remote
Objects.An object becomes Remote by implementing Remote Interface.
33.What is a unicode?
Unicode is a standard that supports International Characters.
36. What is the method that gets invoked first in a stand alone application?.
The main()method.
50. Skeletons are server side proxies and stubs are client side proxies. True
MIME(Multipurpose Internet Mail Extension) is a general method by which the content of different
types of Internet objects can be identified.
69. Awt Components and Swing Components can be inter-mingled in an Application - False
75. When Swing components overlap with Heavyweight components, it is the latter that is on the
top - True
Constructor is a special kind of method that determines how an object is initialized when created.
10)What is casting?
Ans: Casting is used to convert the value of one type to another.
26)What is a package?
Ans: A package is a collection of classes and interfaces that provides a high-level layer of access
protection and name space management.
33) Can you have an inner class inside a method and what variables can you access?
Ans: Yes, we can have an inner class inside a method and final variables can be accessed.
39) What is the class and interface in java to create thread and which is the most advantageous
method?
Ans: Thread class and Runnable interface can be used to create threads and using Runnable interface is
the most advantageous method to create threads because we need not extend thread class here.
44) What is daemon thread and which method is used to create the daemon thread?
Ans: Daemon thread is a low priority thread which runs intermittently in the back ground doing the
garbage collection operation for the java runtime system. setDaemon method is used to create a
daemon thread.
45) Are there any global variables in Java, which can be accessed by other part of your program?
Ans: No, it is not the main method in which you define variables. Global variables are not possible
because concept of encapsulation is eliminated here.
52) What is an event and what are the models available for event handling?
Ans: An event is an event object that describes a state of change in a source. In other words, event
occurs when an action is generated, like pressing button, clicking mouse, selecting a list, etc. There
are two types of models for handling events and they are:
a) event-inheritance model and b) event-delegation model
56)What is meant by controls and what are different types of controls in AWT?
Ans: Controls are components that allow a user to interact with your application and the AWT supports
the following types of controls:
Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components.
These controls are subclasses of Component.
59) What is a layout manager and what are different types of layout managers available in java.awt?
Ans: A layout manager is an object that is used to organize components in a container. The different
layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout.
it has no return type; this is because constructor always has the class type implicitly as return
type
dynamic method dispatch
practical application of run time polymorphism or method overriding
all to overridden method is resolved at runt time, rather that compile time
superclass ref variable can refer to subclass object
Java uses this to resolve calls to overridden methods at run time
when overridden method is called through superclasss reference, Java determines which
version of that method to execute based upon type of object being referred to at time call
occurs
why overridden methods
dynamic runtime polymorphism is one of most powerful mechanisms that object
oriented design brings to bear on code reuse and robustness
ability of existing code libraries to call methods on instances of new classes without
recompiling while maintaining a clean abstract interface is the essence of the tool
using abstract classes
situations in which you want to define superclass that declares structure of given abstraction
without providing complete implementation of every method
i.e. superclass only defines generalized form to be shared by all subclasses, with specific details
to filled by subclass
any class that contains one or more abstract methods is abstract class
abstract keyword is used in front of class keyword
abstract classes cannot be instantiated
subclass of abstract class must either implement all methods or be declared abstract itself
although they cannot be instantiated, they can be used to create object ref variables for runtime
polymorphism
final has three uses
create named constants
prevent overriding
prevent inheritance
using assert
added in ver 1.4
used during program development to create an assertion
assertion is a condition that should be true during execution of program
e.g. if you have method that should always return positive integer
you can test it with assert statement
if at runtime, assertion is true, no action will take place
if false, assertion error will be thrown
used to test expected condition
not used for released code
Table of Contents
1. What's the JDBC 3.0 API?
2. Does the JDBC-ODBC bridge support the new features in the JDBC 3.0 API?
3. Can the JDBC-ODBC Bridge be used with applets?
4. How do I start debugging problems related to the JDBC API?
5. How can I use the JDBC API to access a desktop database like Microsoft Access over the
network?
6. What JDBC technology-enabled drivers are available?
7. What documentation is available for the JDBC API?
8. Are there any ODBC drivers that do not work with the JDBC-ODBC Bridge?
9. What causes the "No suitable driver" error?
10. 12. Why isn't the java.sql.DriverManager class being found?
11. How do I retrieve a whole row of data at once, instead of calling an individual
ResultSet.getXXX method for each column?
12. Why does the ODBC driver manager return 'Data source name not found and no default driver
specified Vendor: 0'
13. Are all the required JDBC drivers to establish connectivity to my database part of the JDK?
14. Is the JDBC-ODBC Bridge multi-threaded?
15. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?
16. Why can't I invoke the ResultSet methods afterLast and beforeFirst when the method next
works?
17. How can I retrieve a String or other object type without creating a new object each time?
18. There is a method getColumnCount in the JDBC API. Is there a similar method to find the
number of rows in a result set?
19. 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?
20. If I use the JDBC API, do I have to use ODBC underneath?
21. Once I have the Java 2 SDK, Standard Edition, from Sun, what else do I need to connect to a
database?
The JDBC 3.0 API is the latest update of the JDBC API. It contains many features, including
scrollable result sets and the SQL:1999 data types.
Back to Top
2. Does the JDBC-ODBC Bridge support the new features in the JDBC 3.0 API?
The JDBC-ODBC Bridge provides a limited subset of the JDBC 3.0 API.
Back to Top
Use of the JDBC-ODBC bridge from an untrusted applet running in a browser, such as Netscape
Navigator, isn't allowed. The JDBC-ODBC bridge doesn't allow untrusted code to call it for
security reasons. This is good because it means that an untrusted applet that is downloaded by
the browser can't circumvent Java security by calling ODBC. Remember that ODBC is native
code, so once ODBC is called the Java programming language can't guarantee that a security
violation won't occur. On the other hand, Pure Java JDBC drivers work well with applets. They
are fully downloadable and do not require any client-side configuration.
Finally, we would like to note that it is possible to use the JDBC-ODBC bridge with applets that
will be run in appletviewer since appletviewer assumes that applets are trusted. In general, it is
dangerous to turn applet security off, but it may be appropriate in certain controlled situations,
such as for applets that will only be used in a secure intranet environment. Remember to
exercise caution if you choose this option, and use an all-Java JDBC driver whenever possible to
avoid security problems.
Back to Top
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.)
Back to Top
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.
Back to Top
See our web page on JDBC technology-enabled drivers for a current listing.
Back to Top
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.
Back to Top
8. 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.
Back to Top
"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.
Back to Top
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.
Back to Top
11. 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.
Back to Top
12. 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
Back to Top
13. 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.
Back to Top
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.
Back to Top
15. 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.
Back to Top
16. 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.
Back to Top
17. 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.
Back to Top
18. 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.
Back to Top
19. 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.
Back to Top
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.
Back to Top
21. 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.
Back to Top
1. What's the JDBC 3.0 API?
2. Does the JDBC-ODBC bridge support the new features in the JDBC 3.0 API?
3. Can the JDBC-ODBC Bridge be used with applets?
4. How do I start debugging problems related to the JDBC API?
5. How can I use the JDBC API to access a desktop database like Microsoft Access over the
network?
6. What JDBC technology-enabled drivers are available?
7. What documentation is available for the JDBC API?
8. Are there any ODBC drivers that do not work with the JDBC-ODBC Bridge?
9. What causes the "No suitable driver" error?
10. 12. Why isn't the java.sql.DriverManager class being found?
11. How do I retrieve a whole row of data at once, instead of calling an individual ResultSet.getXXX
method for each column?
12. Why does the ODBC driver manager return 'Data source name not found and no default driver
specified Vendor: 0'
13. Are all the required JDBC drivers to establish connectivity to my database part of the JDK?
14. Is the JDBC-ODBC Bridge multi-threaded?
15. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?
16. Why can't I invoke the ResultSet methods afterLast and beforeFirst when the method next
works?
17. How can I retrieve a String or other object type without creating a new object each time?
18. There is a method getColumnCount in the JDBC API. Is there a similar method to find the
number of rows in a result set?
19. 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?
20. If I use the JDBC API, do I have to use ODBC underneath?
21. Once I have the Java 2 SDK, Standard Edition, from Sun, what else do I need to connect to a
database?
Back to top
2. Does the JDBC-ODBC Bridge support the new features in the JDBC 3.0 API?
The JDBC-ODBC Bridge provides a limited subset of the JDBC 3.0 API.
Back to top
Use of the JDBC-ODBC bridge from an untrusted applet running in a browser, such as Netscape
Navigator, isn't allowed. The JDBC-ODBC bridge doesn't allow untrusted code to call it for security
reasons. This is good because it means that an untrusted applet that is downloaded by the browser
can't circumvent Java security by calling ODBC. Remember that ODBC is native code, so once ODBC is
called the Java programming language can't guarantee that a security violation won't occur. On the
other hand, Pure Java JDBC drivers work well with applets. They are fully downloadable and do not
require any client-side configuration.
Finally, we would like to note that it is possible to use the JDBC-ODBC bridge with applets that will be
run in appletviewer since appletviewer assumes that applets are trusted. In general, it is dangerous to
turn applet security off, but it may be appropriate in certain controlled situations, such as for applets
that will only be used in a secure intranet environment. Remember to exercise caution if you choose
this option, and use an all-Java JDBC driver whenever possible to avoid security problems.
Back to top
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.)
Back to top
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.
Back to top
See our web page on JDBC technology-enabled drivers for a current listing.
Back to top
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.
Back to top
8. 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.
Back to top
"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.
Back to top
10. 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.
Back to top
11. 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.
Back to top
12. 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
Back to top
13. 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.
Back to top
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.
Back to top
15. 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.
Back to top
16. 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.
Back to top
17. 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.
Back to top
18. 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.
Back to top
19. 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.
Back to top
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.
Back to top
21. 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.
General FAQ
What is JavaServer Pages technology?
How does the JavaServer Pages technology work?
What is a servlet?
Why do I need JSP technology if I already have servlets?
Where can I get the most current version of the JSP specification?
How does the JSP specification relate to the Java 2 Platform, Enterprise Edition?
Which web servers support JSP technology?
Is Sun providing a reference implementation for the JSP specification?
How is JSP technology different from other products?
Where do I get more information on JSP technology?
Technical FAQ
What is a JSP page?
How do JSP pages work?
Does JSP technology require the use of other Java platform APIs?
How is a JSP page invoked and compiled?
What is the syntax for JavaServer Pages technology?
Can I create XML pages using JSP technology?
Can I generate and manipulate JSP pages using XML tools?
How do I use JavaBeans components (beans) from a JSP page?
General FAQ
JSP pages use XML tags and scriptlets written in the Java programming language to encapsulate the
logic that generates the content for the page. It passes any formatting (HTML or XML) tags directly back
to the response page. In this way, JSP pages separate the page logic from its design and display.
JSP technology is part of the Java technology family. JSP pages are compiled into servlets and may call
JavaBeans components (beans) or Enterprise JavaBeans components (enterprise beans) to perform
processing on the server. As such, JSP technology is a key component in a highly scalable architecture
for web-based applications.
JSP pages are not restricted to any specific platform or web server. The JSP specification represents a
broad spectrum of industry input.
What is a servlet?
A servlet is a program written in the Java programming language that runs on the server, as opposed to
the browser (applets). Detailed information can be found at http://java.sun.com/products/servlet.
JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-
based applications. However, JSP technology was designed to simplify the process of creating pages by
separating web presentation from web
JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-
based applications. However, JSP technology was designed to simplify the process of creating pages by
separating web presentation from web content. In many applications, the response sent to the client is
a combination of template data and dynamically-generated data. In this situation, it is much easier to
work with JSP pages than to do everything with servlets.
Where can I get the most current version of the JSP specification?
The JavaServer Pages 2.0 specification is available for download from here.
How does the JSP specification relate to the Java 2 Platform, Enterprise Edition?
The JSP 2.0 specification is an important part of the Java 2 Platform, Enterprise Edition 1.4. Using JSP
and Enterprise JavaBeans technologies together is a great way to implement distributed enterprise
applications with web-based front ends.
There are a number of JSP technology implementations for different web servers. The latest
information on officially-announced support can be found at
http://java.sun.com/products/jsp/industry.html.
The J2EE SDK is a reference implementation of the JavaTM 2 Platform, Enterprise Edition. Sun adapts
and integrates the Tomcat JSP and Java Servlet implementation into the J2EE SDK. The J2EE SDK can be
used as a development enviroment for applications prior to their deployment and distribution.
Tomcat a free, open-source implementation of Java Servlet and JavaServer Pages technologies
developed under the Jakarta project at the Apache Software Foundation, can be downloaded from
http://jakarta.apache.org. Tomcat is available for commercial use under the ASF license from the
Apache web site in both binary and source versions. An implementation of JSP technology is part of the
J2EE SDK.
JSP technology is the result of industry collaboration and is designed to be an open, industry-standard
method supporting numerous servers, browsers and tools. JSP technology speeds development with
reusable components and tags, instead of relying heavily on scripting within the page itself. All JSP
implementations support a Java programming language-based scripting language, which provides
inherent scalability and support for complex operations.
The first place to check for information on JSP technology is http://java.sun.com/products/jsp/. This
site includes numerous resources, as well as pointers to mailing lists and discussion groups for JSP
technology-related topics.
Technical FAQ
A JSP page is a page created by the web developer that includes JSP technology-specific and custom
tags, in combination with other static (HTML or XML) tags. A JSP page has the extension .jsp or .jspx;
this signals to the web server that the JSP engine will process elements on this page. Using the web.xml
deployment descriptor, additional extensions can be associated with the JSP engine.
A JSP engine interprets tags, and generates the content required - for example, by calling a bean,
accessing a database with the JDBC API or including a file. It then sends the results back in the form of
an HTML (or XML) page to the browser. The logic that generates the content is encapsulated in tags and
beans processed on the server.
Does JSP technology require the use of other Java platform APIs?
JSP pages are typically compiled into Java platform servlet classes. As a result, JSP pages require a Java
virtual machine that supports the Java platform servlet specification.
Pages built using JSP technology are typically implemented using a translation phase that is performed
once, the first time the page is called. The page is compiled into a Java Servlet class and remains in
server memory, so subsequent calls to the page have very fast response times.
The syntax card and reference can be viewed or downloaded from our website.
Yes, the JSP specification does support creation of XML documents. For simple XML generation, the
XML tags may be included as static template portions of the JSP page. Dynamic generation of XML tags
occurs through bean components or custom tags that generate XML output. See the white paper
Developing XML Solutions with JavaServer Pages Technology (PDF) for details.
The JSP 2.0 specification describes a mapping between JSP pages and XML documents. The mapping
enables the creation and manipulation of JSP pages using XML tools.
The Java 2 Platform, Enterprise Edition (J2EE) is a set of coordinated specifications and practices that
together enable solutions for developing, deploying, and managing multi-tier server-centric
applications. Building on the Java 2 Platform, Standard Edition (J2SE), the J2EE platform adds the
capabilities necessary to provide a complete, stable, secure, and fast Java platform to the enterprise
level. It provides value by significantly reducing the cost and complexity of developing and deploying
multi-tier solutions, resulting in services that can be rapidly deployed and easily enhanced.
Complete Web services support. The J2EE platform provides a framework for developing and
deploying web services on the Java platform. The Java API for XML-based RPC (JAX-RPC) enables
Java technology developers to develop SOAP based interoperable and portable web services.
Developers use the standard JAX-RPC programming model to develop SOAP based web service
clients and endpoints. A web service endpoint is described using a Web Services Description
Language (WSDL) document. JAX-RPC enables JAX-RPC clients to invoke web services developed
across heterogeneous platforms. In a similar manner, JAX-RPC web service endpoints can be
invoked by heterogeneous clients. For more info, see http://java.sun.com/webservices/.
Faster solutions delivery time to market. The J2EE platform uses "containers" to simplify
development. J2EE containers provide for the separation of business logic from resource and
lifecycle management, which means that developers can focus on writing business logic -- their
value add -- rather than writing enterprise infrastructure. For example, the Enterprise JavaBeans
(EJB) container (implemented by J2EE technology vendors) handles distributed communication,
threading, scaling, transaction management, etc. Similarly, Java Servlets simplify web
development by providing infrastructure for component, communication, and session
management in a web container that is integrated with a web server.
Freedom of choice. J2EE technology is a set of standards that many vendors can implement. The
vendors are free to compete on implementations but not on standards or APIs. Sun supplies a
comprehensive J2EE Compatibility Test Suite (CTS) to J2EE licensees. The J2EE CTS helps ensure
compatibility among the application vendors which helps ensure portability for the applications
and components written for the J2EE platform. The J2EE platform brings Write Once, Run
Anywhere (WORA) to the server.
Simplified connectivity. J2EE technology makes it easier to connect the applications and systems
you already have and bring those capabilities to the web, to cell phones, and to devices. J2EE
offers Java Message Service for integrating diverse applications in a loosely coupled,
asynchronous way. The J2EE platform also offers CORBA support for tightly linking systems
through remote method calls. In addition, the J2EE platform has J2EE Connectors for linking to
enterprise information systems such as ERP systems, packaged financial applications, and CRM
applications.
By offering one platform with faster solution delivery time to market, freedom of choice, and
simplified connectivity, the J2EE platform helps IT by reducing TCO and simultaneously avoiding
single-source for their enterprise software needs.
The primary technologies in the J2EE platform are: Java API for XML-Based RPC (JAX-RPC), JavaServer
Pages, Java Servlets, Enterprise JavaBeans components, J2EE Connector Architecture, J2EE
Management Model, J2EE Deployment API, Java Management Extensions (JMX), J2EE Authorization
Contract for Containers, Java API for XML Registries (JAXR), Java Message Service (JMS), Java Naming
and Directory Interface (JNDI), Java Transaction API (JTA), CORBA, and JDBC data access API.
The Java 2 Platform, Enterprise Edition version 1.4 features complete Web services support through the
new JAX-RPC 1.1 API, which supports service endpoints based on servlets and enterprise beans. JAX-
RPC 1.1 provides interoperability with Web services based on the WSDL and SOAP protocols. The J2EE
1.4 platform also supports the Web Services for J2EE specification (JSR 921), which defines deployment
requirements for Web services and utilizes the JAX-RPC programming model. In addition to numerous
Web services APIs, J2EE 1.4 platform also features support for the WS-I Basic Profile 1.0. This means
that in addition to platform independence and complete Web services support, J2EE 1.4 offers platform
Web services interoperability.
The J2EE 1.4 platform also introduces the J2EE Management 1.0 API, which defines the information
model for J2EE management, including the standard Management EJB (MEJB). The J2EE Management
1.0 API uses the Java Management Extensions API (JMX). The J2EE 1.4 platform also introduces the J2EE
Deployment 1.1 API, which provides a standard API for deployment of J2EE applications.
The J2EE platform now makes it easier to develop web front ends with enhancements to Java Servlet
and JavaServer Pages (JSP) technologies. Servlets now support request listeners and enhanced filters.
JSP technology has simplified the page and extension development models with the introduction of a
simple expression language, tag files, and a simpler tag extension API, among other features. This
makes it easier than ever for developers to build JSP-enabled pages, especially those who are familiar
with scripting languages.
Other enhancements to the J2EE platform include the J2EE Connector Architecture, which provides
incoming resource adapter and Java Message Service (JMS) pluggability. New features in Enterprise
JavaBeans (EJB) technology include Web service endpoints, a timer service, and enhancements to EJB
QL and message-driven beans. The J2EE 1.4 platform also includes enhancements to deployment
descriptors. They are now defined using XML Schema which can also be used by developers to validate
their XML structures.
The Java 2 SDK, Enterprise Edition 1.4 (J2EE 1.4 SDK) is a complete package for developing and
deploying J2EE 1.4 applications. The J2EE 1.4 SDK contains the Sun Java System Application Server
Platform Edition 8, the J2SE 1.4.2 SDK, J2EE 1.4 platform API documentation, and a slew of samples to
help developers learn about the J2EE platform and technologies and prototype J2EE applications. The
J2EE 1.4 SDK is for both development and deployment.
The J2EE 1.4 specification is final and you can use the J2EE 1.4 SDK to deploy applications today.
However, for improved reliability,scability, and performance, it is recommended that you deploy your
applications on J2EE 1.4 commercial implementations that will be available early in 2004. If you want to
deploy your application before 2004, and reliability,scability, and performance are critical, you should
consider using a high performance application server that supports J2EE v1.3 such as the Sun Java
System Application Server 7. Many application server vendors are expected to release J2EE platform
v1.4 versions of their product before the spring.
Q: Can applications written for the J2EE platform v1.3 run in a J2EE platform v1.4 implementation?
J2EE applications that are written to the J2EE 1.3 specification will run in a J2EE 1.4 implementation.
Backwards compatibility is a requirement of the specification.
Q: How is the J2EE architecture and the Sun Java Enterprise System related?
The J2EE architecture is the foundation of the Sun Java System Application Server, a component of the
Sun Java Enterprise System. The Sun Java System Application Server in the current Sun Java Enterprise
System is based on the J2EE platform v1.3, with additional support for Web services. Developers
familiar with J2EE technology can easily apply their skills to building applications, including Web
services applications, using the Sun Java Enterprise System. For more information, see the Sun Java
Enterprise System Web site.
Q: Can I get the source for the Sun Java System Application Server?
You can get the source for the J2EE 1.4.1 Reference Implementation from the Sun Community Source
Licensing site. The J2EE 1.4.1 Reference Implementation is the Sun Java System Application Server
Platform Edition 8 minus the following components:
The installer
The Web-based administration GUI
JavaServer Faces 1.0 and JSTL 1.1
Solaris specific enhancements for security and logging
Higher performance message queue implementation
For more information about the J2EE platform and how to get the specification, see
http://java.sun.com/j2ee/.
The most effective way to learn about the J2EE platform and what's new in the J2EE 1.4 platform is to
get hands on experience with the APIs by using the J2EE 1.4 SDK. The J2EE 1.4 SDK provides a J2EE 1.4
compatible application server as the foundation to develop and deploy Web services enabled, multi-
tier enterprise applications. You can download the J2EE 1.4 SDK from
http://java.sun.com/j2ee/1.4/download.html
For beginners, the J2EE documentation page provides links to a wide variety of self-paced learning
materials, such as tutorials and FAQs.
Developers looking for more advanced material should consult the Java BluePrints for the enterprise.
The Java BluePrints for the enterprise are the best practices philosophy for the design and building of
J2EE-based applications. The design guidelines document provides two things. First, it provides the
philosophy of building n-tier applications on the Java 2 platform. Second, it provides a set of design
patterns for designing these applications, as well as a set of examples or recipes on how to build the
applications.
Sun educational services also provides many training courses, which can lead to can lead to one of
three certifications: Sun Certified Web Component Developer, Sun Certified Business Component
Developer, or Sun Certified Enterprise Architect.
ISVs need the J2EE platform because it gives them a blueprint for providing a complete enterprise
computing solution on the Java platform. Enterprise developers need J2EE because writing distributed
business applications is hard, and they need a high-productivity solution that allows them to focus only
on writing their business logic and having a full range of enterprise-class services to rely on, like
transactional distributed objects, message oriented middleware, and naming and directory services.
When we say "Free" we mean that you don't pay Sun to develop or deploy the J2EE 1.4 SDK or the Sun
Java System Application Server Platform Edition 8. Free means that you don't pay Sun for
supplementary materials including documentation, tutorials and/or J2EE Blueprints. You are also free to
bundle and distribute (OEM) Sun Java System Application Server Platform Edition 8 with your software
distribution. When we say "Free", we mean "Free for All".
Here are some examples of how you can use Sun Java System Application Server Platform Edition 8 for
free.
If you are a developer you can build an application with the J2EE 1.4 SDK and then deploy it on the Sun
Java System Application Server Platform Edition 8 (included with the J2EE 1.4 SDK or available
separately). No matter how many developers are on your team, all of them can use the J2EE 1.4 SDK at
no charge. Once your application is ready for production, you can deploy including the Sun Java System
Application Server Platform 8 Edition in production on as many servers or CPUs as you want.
If you are an ISV, you don't have to pay to include Sun Java System Application Server Platform Edition 8
with your product, no matter how many copies of your software that you distribute. Bundling Sun Java
System Application Server Platform Edition 8 makes good business sense because it ensures that you
are distributing a J2EE 1.4 platform compatible server that doesn't lock you or your customers into a
proprietary product. ISV's that wish to bundle Sun Java System Application Server Platform Edition 8
(for free of course) should contact Sun OEM sales.
If you are a System Administrator or IT manager, you can install Sun Java System Application Server
Platform Edition 8 on as many servers and CPUs as you wish. Using Sun Java System Application Server
Platform Edition 8 also gives reduced cost and complexity by saving money on licensing fees and the
assurance of a J2EE 1.4 platform compatible application server that can be used with other J2EE 1.4
platform compatible application servers.
Q: Is support "Free"?
There are resources that are available for free on our site that may help you resolve your issues without
requiring technical support. For example you can ask questions on our forums, search for known issues
on the bug data base, review the documentation, or take a look at code samples and applications to
help you at no cost.
Production support is also available for a fee through Sun Service. For more information about
Developer Technical Service and Sun Service, please visit
http://wwws.sun.com/software/products/appsrvr/support.html.
Yes. The J2EE Compatibility Test Suite (CTS) is available for the J2EE platform. The J2EE CTS contains
over 5,000 tests for J2EE 1.4 and will contain more for later versions. This test suite tests compatibility
by performing specific application functions and checking results. For example, to test the JDBC call to
insert a row in a database, an EJB component makes a call to insert a row and then a call is made to
check that the row was inserted.
Q: What is the difference between being a J2EE licensee and being J2EE compatible?
A J2EE licensee has signed a commercial distribution license for J2EE. That means the licensee has the
compatibility tests and has made a commitment to compatibility. It does not mean the licensees
products are necessarily compatible yet. Look for the J2EE brand which signifies that the specific
branded product has passed the Compatibility Test Suite (CTS) and is compatible.
Q: What is the relationship of the Apache Tomcat open-source application server to the J2EE SDK?
Tomcat is based on the original implementation of the JavaServer Pages (JSP) and Java Servlet
specifications, which was donated by Sun to the Apache Software Foundation in 1999. Sun continues to
participate in development of Tomcat at Apache, focusing on keeping Tomcat current with new versions
of the specifications coming out of the Java Community Source ProcessSM. Sun adapts and integrates
the then-current Tomcat source code into new releases of the J2EE SDK. However, since Tomcat evolves
rapidly at Apache, there are additional differences between the JSP and Servlet implementations in the
J2EE SDK and in Tomcat between J2EE SDK releases. Tomcat source and binary code is governed by the
ASF license, which freely allows deployment and redistribution.
General
What is XML?
Who developed XML?
What are the key benefits of XML?
What are the applications of XML?
What is the relationship between XML and Java technology?
What are the benefits of using Java technology with XML?
What XML-related activities is Sun participating in?
Where can I find additional documentation?
Where can I send comments and suggestions?
Are there other Sun hosted XML mailing lists I can subscribe to?
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
GENERAL
Q. What is XML?
A. XML, the Extensible Markup Language, is a universal syntax for describing and structuring data
independent from the application logic. XML can be used to define unlimited languages for specific
industries and applications.
A. XML is an activity of the World Wide Web Consortium (W3C). The XML development effort started in
1996.
A diverse group of markup language experts, from industry to academia, developed a simplified version
of SGML (Standard Generalized Markup Language) for the Web. In February 1998, XML 1.0 specification
became a recommendation by the W3C.
A. XML promises to simplify and lower the cost of data interchange and publishing in a Web
environment. XML is a text-based syntax that is readable by both computer and humans. XML offers
data portability and reusability across different platforms and devices. It is also flexible and extensible,
allowing new tags to be added without breaking an existing document structure. Based on Unicode,
XML provides global language support.
Q. What are the applications of XML?
A. XML is poised to play a prominent role as a data interchange format in B2B Web applications such as
e-commerce, supply-chain management, workflow, and application integration. Another use of XML is
for structured information management, including information from databases. XML also supports
media-independent publishing, allowing documents to be written once and published in multiple
media formats and devices. On the client, XML can be used to create customized views into data.
A. XML and the Java technology are complementary. Java technology provides the portable,
maintainable code to process portable, reusable XML data. In addition, XML and Java technology have a
number of shared features that make them the ideal pair for Web computing, including being industry
standards, platform-independence, extensible, reusable, Web-centric, and internationalized.
A. Java technology offers a substantial productivity boost for software developers compared to
programming languages such as C or C++. In addition, developers using the Java platform can create
sophisticated programs that are reusable and maintainable compared to programs written with
scripting languages. Using XML and Java together, developers can build sophisticated, interoperable
Web applications more quickly and at a lower cost.
A. Sun is actively participating in W3C working groups for XML Stylesheet/Transformation Language
(XSL/T), XML Schema, Xlink, and XML Query. Sun is also participating in a number of other industry
consortia including Oasis, XML.org, and Apache.
A. The Java Technology & XML Documentation page has a comprehensive list of all documentation
related to Java Technology and XML available on this website.
Q. Are there other Sun hosted XML mailing lists I can subscribe to?
A. For general discussion about topics related to XML technologies in the Java platform, subscribe to
xml-interest@java.sun.com.
Back to Top
Java API for XML Processing (JAXP)
The Java API for XML Processing, or "JAXP" for short, enables applications to parse and transform XML
documents using an API that is independent of a particular XML processor implementation. JAXP also
provides a pluggability feature which enables applications to easily switch between particular XML
processor implementations.
To achieve the goal of XML processor independence, an application should limit itself to the JAXP API
and avoid implementation-dependent APIs. This may or may not be easy depending on the application.
JAXP includes industry standard APIs such as DOM and SAX.
The reason for the existance of JAXP is to facilitate the use of XML on the Java platform. For example,
current APIs such as DOM Level 2 do not provide a method to bootstrap a DOM Document object from
an XML input document, JAXP does. (When DOM Level 3 provides this functionality, a new version of
the JAXP specification will probably support the new Level 3 scheme also.) Other parts of JAXP such as
the javax.xml.transform portion do not have any other equivalent APIs that are XSLT processor
independent.
Back to Top
A. The Java Architecture for XML Binding (JAXB) simplifies the creation and maintenance of XML-
enabled Java applications. JAXB provides a binding compiler and a runtime framework to support a
two-way mapping between XML documents and Java objects. The binding compiler translates W3C
XML Schema into one or more Java classes without requiring the developer to write complex parsing
code. The schema-derived classes and binding framework enable error and validity checking of
incoming and outgoing XML documents, thereby making it possible to ensure that only valid, error-free
messages are accepted, processed, and generated by a system. For more information, see the
Reference Implementation and the Public Draft Specification, both available for download from the
JAXB homepage.
Q. What is the difference between JAXB, SAX, and DOM? Which one should I use?
A. SAX is an event-driven XML parser that is appropriate for high-speed processing of XML because it
does not produce a representation of the data in memory. DOM, on the other hand, produces an in-
memory data representation, which allows an application to manipulate the contents in memory. Both
SAX and DOM automatically perform structure validation. An application could perform content
validation with SAX and DOM, but such an application must provide the necessary extra code, which
might be complicated, error-prone, and difficult to maintain.
A JAXB application can perform structure and content validation with Java classes that it generates from
a schema. A JAXB application builds an in-memory data structure, like a DOM, by marshalling an XML
document to build a content tree, which contains objects that are instances of the derived classes.
However, unlike a DOM tree, a content tree is specific to one source schema, does not contain extra
tree-manipulation functionality, allows access to its data with the derived classes' accessor methods,
and is not built dynamically. For these reasons, a JAXB application uses memory more efficiently than a
DOM application does. If the content of a document is more dynamic and not well-constrained, DOM
and SAX are more appropriate than JAXB for processing XML content that does not have a well-known
schema prior to processing the content.
A. To build a JAXB application, start with an XML schema. The beta release requires that the schema
language be W3C 2001 Recommendation for XML Schema.
After obtaining an XML Schema, you build and use a JAXB application by performing these steps:
1. Generate the Java source files by submitting the XML Schema to the binding compiler.
You can use custom binding declarations to override the default binding of XML Schema
components to Java representations
3. With the classes and the binding framework, write Java applications that:
Build object trees representing XML data that is valid against the XML Schema by either
unmarshalling the data from a document or instantiating the classes you created.
Optionally validate the modifications to the data relative to the constraints expressed in
the XML Schema
A. JAXB is being developed through the Java Community Process (JCP) with an expert group consisting
of IBM, Software AG, BEA Systems, Hewlett-Packard, TIBCO Software Inc., Oracle, Fujitsu Limited,
Breeze Factor LLC, Macromedia, Inc. and Intalio, Inc. Sun is an active member of the W3C XML Schema
Working Group and is also working with other industry consortia such as OASIS and xml.org.
Q. Where can I read more about JAXB?
A. For a higher-level explanation of JAXB, refer to the JAXB chapters in the Java Web Services Tutorial.
Also note that a detailed user's guide is included as part of the JAXB distribution. For a more technical
and detailed description of JAXB, see the the latest version of the Specification, which you can
download from the JAXB homepage. Please note that the Specification is in Adobe Acrobat PDF format.
Download Adobe Acrobat for free.
Back to Top
A: The Java API for XML Messaging (JAXM) is an API designed specifically for the exchange of XML
business documents over the Internet. Examples of XML documents that might typically be exchanged
are purchase orders, order confirmations, and invoices. You can send non-XML data by adding
attachments to your message.
A: JAXM is based on the Simple Object Access Protocol (SOAP) 1.1 and SOAP with Attachments
specifications. JAXM also allows the implementation of standard protocols on top of the SOAP
implementation, such as SOAP-RP or the ebXML Transport, Routing & Packaging V1.0 - Message Service
Specification.
A: No, you are free to use the Java 2 Platform, Standard Edition (J2SE) as well as the Java 2 Platform,
Enterprise Edition (J2EE). A stand-alone client (a client that does not use a messaging provider) can use
the J2SE platform to send request-response messages to Web services that process request-response
messages. This requires no deployment or configuration from the client, so it is easy to do.
A: A messaging provider is a service that works with the messaging infrastructure to route and transmit
messages. What it does is completely transparent to the client sending or receiving a message. An
application that uses a messaging provider must use a connection that goes to the provider, called a
ProviderConnection object in the JAXM API. Using a messaging provider also requires some
deployment and configuration. Normally, a client using a messaging provider runs in a container --
either a servlet or a J2EE container. At deployment time, the client needs to give the container
information about the messaging provider. In the future, there will be a deployment tool that makes
this easy.
Yes. Intermediate recipients can be specified in a message's header. One way this capability can be used
is to automate business processes. For example, two businesses can agree to the conditions under
which they exchange XML documents so that they can implement the automatic generation of
messages and responses. Assume that two businesses have an arrangement specifying that purchase
orders will go first to the order entry department, then to the order confirmation department, then to
the shipping department, and finally to the billing department. Each department is an intermediate
recipient (called an actor). After an actor has done its part, it removes everything in the header that
relates to it and sends the message on to the next actor listed in the header.
A: Yes, you can use ebXML headers if you use an ebXML profile that is implemented on top of SOAP. A
profile is a standard protocol, such as ebXML TRP or SOAP-RP, that works on top of SOAP to give you
added functionality. You need to use a messaging provider that supports the profile, and you need to
arrange with your recipients to use the same profile.
Back to Top
A. The Java API for XML Registries (JAXR) API provides a uniform and standard Java API for accessing
different kinds of XML Registries. XML registries are an enabling infrastructure for building,
deployment, and discovery of Web services.
Q. What is the relationship between the JAXR API and other XML APIs?
A. Implementations of JAXR providers may use the Jav API for XML-Based RPC (JAX-RPC) for
communication between JAXR providers and registry providers that export a SOAP based RPC-like
interface (for example, UDDI).
Implementations of JAXR providers may use the Java API for XML Messaging (JAXM) API for
communication between JAXR providers and registry providers that export an XML Messaging-based
interface (for example, ebXML TRP).
The Java API for XML Processing (JAXP) and Java Architecture for XML Binding (JAXB) may be used by
implementers of JAXR providers and JAXR clients for processing XML content that is submitted to or
retrieved from the Registry.
Q. Why do we need a new JAXR API when we have the Java Naming and Directory Interface (JNDI)?
A. The JNDI API was designed with a very different set of requirements from the JAXR API. Both are
abstraction APIs over existing specifications. However, the abstraction in directory services differs
considerably from that of XML Registries used for publishing and discovery of Web services. The JAXR
API needs richer metadata capabilities for classification and association, as well as richer query
capabilities.
Q. Would it not be better to have enhanced the JNDI API with the added functionality of the JAXR
API?
A. That option was considered. Meeting the additional requirements of XML Registries requires an
elaborate information model. The JNDI API has an existing information model that is constrained by
design to address the requirements for directory services. Extending the JNDI API would overly
constrain the JAXR API and would create backward compatibility issues for the JNDI API.
Q. What is the purpose of Association in the JAXR information model? It is not used anywhere in the
API.
A. An Association relates two RegistryObjects to each other. An Association may be defined between
two objects in the registry and submitted using the GenericLifeCycleManager's saveObjects method.
Q. What is the purpose of Classification in the JAXR information model? It is not used anywhere in
the API.
Q. Why is JAXR an abstraction API and not targeted to a specific registry such as UDDI or ebXML?
A. An abstraction-based JAXR API gives developers the ability to write registry client programs that are
portable across different target registries. This is consistent with the Java philosophy of Write Once,
Run Anywhere. It also enables value-added capabilities beyond what the underlying registries are
capable of. For example, a non-JAXR UDDI client does not have the ability to do taxonomy browsing and
taxonomy-aware smart queries, which are available to a JAXR client for UDDI.
Q. Why does the JAXR API not use UDDI terms and concepts?
A. The JAXR API is not specific to UDDI or any other registry specification. It is an abstraction API that
covers multiple specifications. It is designed to enable developer choice in the use of a Web service
registry and/or repository. The JAXR API uses UDDI terms and concepts when they fit the JAXR
information model (for example, Service, ServiceBinding, and method names in BusinessQueryManager
and BusinessLifeCycleManager).
Q. Why did the JAXR information model use the ebXML Registry Information Model as its basis rather
than the UDDI data structures?
A. The JAXR API is designed to support multiple registries. The ebXML Registry Information Model is
more generic and extensible than the UDDI data structures. Because of this characteristic, it was
possible to extend the ebXML Registry Information Model to satisfy the needs of UDDI and other
registries.
Q. Why was the JAXR information model not designed from the ground up?
A. Information models take time to develop. It was easier to start with an existing information model
and improve upon it.
Back to Top
A. The Java API for XML-Based RPC (JAX-RPC) enables Java technology developers to build Web
applications and Web services incorporating XML-based RPC functionality according to the SOAP
(Simple Object Access Protocol) 1.1 specification.
Q. What is RPC?
A. RPC stands for remote procedure call, a mechanism that allows a client to execute procedures on
other systems. The RPC mechanism is often used in a distributed client/server model. The server
defines a service as a collection of procedures that may be called by remote clients.
A. The remote procedure call is represented by an XML-based protocol, such as SOAP. In addition to
defining envelope structure and encoding rules, the SOAP specification defines a convention for
representing remote procedure calls and responses.
A. An XML-based RPC server application can define, describe, and export a Web service as an RPC-
based service. WSDL (Web Service Description Language) specifies an XML format for describing a
service as a set of endpoints operating on messages. With the JAX-RPC API, developers can implement
clients and services described by WSDL.
Q. What are the modes of interaction between clients and JAX-RPC services?
1. Synchronous Request-Response: The client invokes a remote procedure and blocks until it
receives a return or an exception.
2.
3. One-Way RPC: The client invokes a remote procedure but it does not block or wait until it
receives a return. The runtime system for the JAX-RPC client may throw an exception.
4.
5. Non-Blocking RPC Invocation: The client invokes a remote procedure and continues processing
in the same thread without waiting for a return. Later, the client processes the remote method
return by blocking for the receive or polling for the return.
6.
A. Yes. For example, it may carry a unique transaction identifier or digital signature.
A. The xrpcc tool does in fact generate the WSDL file, but due to a bug it gets deleted along with the
source files if the -keep option is not specified. You can use the -keep option which will cause xrpcc to
not delete the WSDL or .java source files. If you also use the -s sourcepath option, all of the source files
will be placed in the sourcepath directory and then you can easily delete them. The WSDL file will still
be placed in the current directory or the directory specified by the -d option.
Back to Top
A. The Java 2 Platform, Enterprise Edition (J2EE) promotes the use of XML for data messaging between
loosely-coupled business systems. The J2EE reference implementation includes the Java API for XML
Parsing (JAXP).
JavaServer Pages (JSP) can generate and consume XML between multi-tier servers or between server
and client. Java Message Service (JMS) provides an asynchronous transport mechanism for XML data
messaging. Enterprise JavaBeans (EJB) offers a robust, synchronous transport mechanism by allowing a
business service object to be invoked by XML tags. EJB also uses XML to describe its deployment
properties, such as transactions and security.
JDBC Questions
1. What is JDBC?
JDBC may stand for Java Database Connectivity. It is also a trade mark. JDBC is a layer of
abstraction that allows users to choose between databases. It allows you to change to a
different database engine and to write to a single API. JDBC allows you to write database
applications in Java without having to concern yourself with the underlying details of a
particular database.
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.
1. Type 1 Drivers
Bridge drivers such as the jdbc-odbc bridge. They rely on an intermediary such as ODBC
to transfer the SQL calls to the database and also often rely on native code.
2. Type 2 Drivers
Use the existing database API to communicate with the database on the client. Faster
than Type 1, but need native code and require additional permissions to work in an
applet. Good for client-side connection.
3. Type 3 Drivers
Call the database API on the server.Flexible. Pure Java and no native code.
4. Type 4 Drivers
The hightest level of driver reimplements the database network API in Java. No native
code.
7.
1. java.sql.Driver
2. Connection
3. Statement
4. PreparedStatement
5. CallableStatement
6. ResultSet
7. ResultSetMetaData
8. DatabaseMetaData
3. There are three basic types of SQL statements, what are they?
1. Statement
2. callableStatement
3. PreparedStatement
This involves two steps: (1) loading the driver and (2) making the connection.
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");
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.
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");
Create a Statement object and calls the Statement.executeQuery method to select data from
the database. The results of the query are returned in a ResultSet object.
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
By default the result set cursor points to the row before the first row of the result set. A call to
next() retrieves the first result set row. The cursor can also be moved by calling one of the
following ResultSet methods:
o beforeFirst(): Default position. Puts cursor before the first row of the result set.
o first(): Puts cursor on the first row of the result set.
o last(): Puts cursor before the last row of the result set.
o afterLast() Puts cursor beyond last row of the result set. Calls to previous moves
backwards through the ResultSet.
o absolute(pos): Puts cursor at the row number position where absolute(1) is the first row
and absolute(-1) is the last row.
o relative(pos): Puts cursor at a row relative to its current position where relative(1) moves
row cursor one row forward.
2. If you want to use the percent sign (%) as the percent sign and not have it interpreted as the
SQL wildcard used in SQL LIKE queries, how to do that?
stmt.executeQuery("select tax from sales where tax like '10\%' {escape '\'}");
Note that such method can be extended to escape any other characters that the database
driver may interprete another way.
4. How to make an update?
You can update a value in a result set by calling the ResultSet.update method on the row
where the cursor is positioned. The type value here is the same used when retrieving a value
from the result set, for example, updateString updates a String value and updateDouble
updates a double value in the result set.
rs.first();
updateDouble("balance", rs.getDouble("balance") - 5.00);
The update applies only to the result set until the call to rs.updateRow(), which updates the
underlying database.
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.
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
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
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.
Both Statements and PreparedStatements have an additional constructor that accepts a scroll
type and an update type parameter. The scroll type value can be one of the following values:
You may verify that your database supports these types by calling
con.getMetaData().supportsResultSetConcurrency(ResultSet.SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
By default, every JDBC statement is sent to the database individually. To send multiple
statements at one time , use addBatch() method to append statements to the original
statement and call executeBatch() method to submit entire statement.
The return result of the addBatch() method is an array of row counts affected for each
statement executed in the batch job. If a problem occurred, a java.sql.BatchUpdateException is
thrown. An incomplete array of row counts can be obtained from BatchUpdateException by
calling its getUpdateCounts() method.
int itemnumber=400456;
To retrieve an image:
int itemnumber=400456;
byte[] imageBytes;//hold an image bytes to pass to createImage().
A class can be serialized to a binary database field in much the same way as the image. You
may use the code above to store and retrive an object.
int count=0;
Connection con=getConnection();
Statement stmt= con.createStatement();
stmt.executeQuery("select counter from aTable");
ResultSet rs = stmt.getResultSet();
if(rs.next()) {
if(rs.getMetaData().getColumnType(1) == Types.INTEGER) {
Integer i=(Integer)rs.getObject(1);
count=i.intValue();
}
}
rs.close();
Because java.util.Date represents both date and time. SQL has three types to represent date
and time.
o java.sql.Date -- (00/00/00)
o java.sql.Time -- (00:00:00)
o java.sql.Timestamp -- in nanoseconds
Calendar currenttime=Calendar.getInstance();
java.sql.Date startdate= new java.sql.Date((currenttime.getTime()).getTime());
or
Where do I get the Collections Framework for use with JDK 1.1?
What do I have to know about the Collections Framework to be a Certified Java Programmer?
What newsgroups/mailing lists are available to ask questions about the Collections Framework?
The TreeMap documentation states that it is a red-black tree based implementation of the
SortedMap interface. What are red-black trees?
How do you store a primitive data type within a Vector or other collections class?
Where can I find information about the design decisions made during the development of the
Collections Framework?
Which is the preferred collection class to use for storing database result sets?
How can I speed up array accesses and turn off array bounds checking?
How do I get the list of system properties that tell me things like which version of Java a user is
running and their platform-specific line separator?
How can I implement a List (ordered collection) that keeps an index (i.e. a Map) of its contents?
How can I save/load application settings that I would normally use .ini files or the Windows
Registry?
What collection works best for maintaining a family tree, where each node can have multiple
parents and multiple children, spouse relationships, etc.?
Do the keys() and elements() methods of a Hashtable enumerate things in the same order?
How do I treat an object I get out of a Vector (collection) as the type I put into it?
What is the difference between a singly linked list and doubley linked list?
What is a WeakHashMap? What is its use and when should you use it?
How do you control growth of vectors when their internal arrays are full?
Since Properties extends Hashtable, can I use the Hashtable methods to add elements to a
Properties list?
When I wrap a collection to be read-only or synchronized, why can't I call any of the collection
methods via reflection without getting an IllegalAccessException?
What is the minimum number of key-value pairs for which it makes sense to use a HashMap, as
opposed to using a pair of arrays (one for keys, the other for values) with brute-force key
searches?
Many people often need maps for very small numbers (2-5) of key-value pairs. When does it make
sense to forgo the convenience of the HashMap to avoid the associated overhead?
How can I implement a priority queue in Java? Has anyone created an open source version?
In a TreeMap, can I use a sorting algorithm other than the natural sorting for the keys?
Where can I learn (more) about Java's support for developing multi-threaded programs?
What are the differences between Vector and ArrayList? Which is best to use?
How should I implement object comparisons in a flexible manner? For example, I have a Person
class and sometimes I will compare based on name and sometimes I will compare based on age.
How can I retrieve the items in my HashSet / HashMap in the order they were added?
How can you get the hash code for an instance of a class if the class overrode hashCode()?
How can I easily shift the elements in a List / Vector such that all the elements rotate n elements?
Where can I find performance comparisons between the different collection implementations?
What happens if two threads perform a get of one hashmap at the same time?
This document answers frequently asked questions concerning the design of the Java collections
framework. It is derived from the large volume of traffic on the collections-comments alias. It serves as
a design rationale for the collections framework.
Collection Interface
1. Why doesn't Collection extend Cloneable and Serializable?
2. Why don't you provide an "apply" method in Collection to apply a given method ("upcall") to
all the elements of the Collection?
3. Why didn't you provide a "Predicate" interface, and related methods (e.g., a method to find
the first element in the Collection satisfying the predicate)?
4. Why don't you provide a form of the addAll method that takes an Enumeration (or an
Iterator)?
5. Why don't the concrete implementations in the JDK have Enumeration (or Iterator)
constructors?
6. Why don't you provide an Iterator.add method?
List Interface
1. Why don't you rename the List interface to Sequence; doesn't "list" generally suggest "linked
list"? Also, doesn't it conflict with java.awt.List?
2. Why don't you rename List's set method to replace, to avoid confusion with Set.
Map Interface
1. Why doesn't Map extend Collection?
Iterator Interface
1. Why doesn't Iterator extend Enumeration?
2. Why don't you provide an Iterator.peek method that allows you to look at the next element in
an iteration without advancing the iterator?
Miscellaneous
1. Why did you write a new collections framework instead of adopting JGL (a preexisting
collections package from ObjectSpace, Inc.) into the JDK?
2. Why don't you eliminate all of the methods and classes that return "views" (Collections
backed by other collection-like objects). This would greatly reduce aliasing.
3. Why don't you provide for "observable" collections that send out Events when they're
modified?
This is the most controversial design decision in the whole API. Clearly, static (compile time)
type checking is highly desirable, and is the norm in Java. We would have supported it if we
believed it were feasible. Unfortunately, attempts to achieve this goal cause an explosion in the
size of the interface hierarchy, and do not succeed in eliminating the need for runtime
exceptions (though they reduce it substantially).
Doug Lea, who wrote a popular Java collections package that did reflect mutability distinctions
in its interface hierarchy, no longer believes it is a viable approach, based on user experience
with his collections package. In his words (from personal correspondence) "Much as it pains me
to say it, strong static typing does not work for collection interfaces in Java."
To illustrate the problem in gory detail, suppose you want to add the notion of modifiability to
the Hierarchy. You need four new interfaces: ModifiableCollection, ModifiableSet,
ModifiableList, and ModifiableMap. What was previously a simple hierarchy is now a messy
heterarchy. Also, you need a new Iterator interface for use with unmodifiable Collections, that
does not contain the remove operation. Now can you do away with
UnsupportedOperationException? Unfortunately not.
Consider arrays. They implement most of the List operations, but not remove and add. They are
"fixed-size" Lists. If you want to capture this notion in the hierarchy, you have to add two new
interfaces: VariableSizeList and VariableSizeMap. You don't have to add VariableSizeCollection
and VariableSizeSet, because they'd be identical to ModifiableCollection and ModifiableSet, but
you might choose to add them anyway for consistency's sake. Also, you need a new variety of
ListIterator that doesn't support the add and remove operations, to go along with unmodifiable
List. Now we're up to ten or twelve interfaces, plus two new Iterator interfaces, instead of our
original four. Are we done? No.
Consider logs (such as error logs, audit logs and journals for recoverable data objects). They are
natural append-only sequences, that support all of the List operations except for remove and
set (replace). They require a new core interface, and a new iterator.
And what about immutable Collections, as opposed to unmodifiable ones? (i.e., Collections that
cannot be changed by the client AND will never change for any other reason). Many argue that
this is the most important distinction of all, because it allows multiple threads to access a
collection concurrently without the need for synchronization. Adding this support to the type
hierarchy requires four more interfaces.
Now we're up to twenty or so interfaces and five iterators, and it's almost certain that there are
still collections arising in practice that don't fit cleanly into any of the interfaces. For example,
the collection-views returned by Map are natural delete-only collections. Also, there are
collections that will reject certain elements on the basis of their value, so we still haven't done
away with runtime exceptions.
When all was said and done, we felt that it was a sound engineering compromise to sidestep
the whole issue by providing a very small set of core interfaces that can throw a runtime
exception.
2. Won't programmers have to surround any code that calls optional operations with a try-catch
clause in case they throw an UnsupportedOperationException?
It was never our intention that programs should catch these exceptions: that's why they're
unchecked (runtime) exceptions. They should only arise as a result of programming errors, in
which case, your program will halt due to the uncaught exception.
The Collection interface provides this functionality. We are not providing any public
implementations of this interface, as we think that it wouldn't be used frequently enough to
"pull its weight." We occasionally return such Collections, which are implemented easily atop
AbstractCollection (for example, the Collection returned by Map.values).
4. Why don't you provide for "gating functions" that facilitate the implementation of type-safe
collections?
We are extremely sympathetic to the desire for type-safe collections. Rather than adding a
"band-aid" to the framework that enforces type-safety in an ad hoc fashion, the framework has
been designed to mesh with all of the parameterized-types proposals currently being discussed.
In the event that parameterized types are added to the language, the entire collections
framework will support compile-time type-safe usage, with no need for explicit casts.
Unfortunately, this won't happen in the the 1.2 release. In the meantime, people who desire
runtime type safety can implement their own gating functions in "wrapper" collections
surrounding JDK collections.
While the names of the new collections methods do not adhere to the "Beans naming
conventions", we believe that they are reasonable, consistent and appropriate to their purpose.
It should be remembered that the Beans naming conventions do not apply to the JDK as a
whole; the AWT did adopt these conventions, but that decision was somewhat controversial.
We suspect that the collections APIs will be used quite pervasively, often with multiple method
calls on a single line of code, so it is important that the names be short. Consider, for example,
the Iterator methods. Currently, a loop over a collection looks like this:
Everything fits neatly on one line, even if the Collection name is a long expression. If we named
the methods "getIterator", "hasNextElement" and "getNextElement", this would no longer be
the case. Thus, we adopted the "traditional" JDK style rather than the Beans style.
Collection Interface
1. Why doesn't Collection extend Cloneable and Serializable?
Many Collection implementations (including all of the ones provided by the JDK) will have a
public clone method, but it would be mistake to require it of all Collections. For example, what
does it mean to clone a Collection that's backed by a terabyte SQL database? Should the
method call cause the company to requisition a new disk farm? Similar arguments hold for
serializable.
If the client doesn't know the actual type of a Collection, it's much more flexible and less error
prone to have the client decide what type of Collection is desired, create an empty Collection of
this type, and use the addAll method to copy the elements of the original collection into the
new one.
2. Why don't you provide an "apply" method in Collection to apply a given method ("upcall") to
all the elements of the Collection?
This is what is referred to as an "Internal Iterator" in the "Design Patterns" book (Gamma et al.).
We considered providing it, but decided not to as it seems somewhat redundant to support
internal and external iterators, and Java already has a precedent for external iterators (with
Enumerations). The "throw weight" of this functionality is increased by the fact that it requires a
public interface to describe upcalls.
3. Why didn't you provide a "Predicate" interface, and related methods (e.g., a method to find
the first element in the Collection satisfying the predicate)?
It's easy to implement this functionality atop Iterators, and the resulting code may actually look
cleaner as the user can inline the predicate. Thus, it's not clear whether this facility pulls its
weight. It could be added to the Collections class at a later date (implemented atop Iterator), if
it's deemed useful.
4. Why don't you provide a form of the addAll method that takes an Enumeration (or an
Iterator)?
Because we don't believe in using Enumerations (or Iterators) as "poor man's collections." This
was occasionally done in prior releases, but now that we have the Collection interface, it is the
preferred way to pass around abstract collections of objects.
5. Why don't the concrete implementations in the JDK have Enumeration (or Iterator)
constructors?
Again, this is an instance of an Enumeration serving as a "poor man's collection" and we're
trying to discourage that. Note however, that we strongly suggest that all concrete
implementations should have constructors that take a Collection (and create a new Collection
with the same elements).
The semantics are unclear, given that the contract for Iterator makes no guarantees about the
order of iteration. Note, however, that ListIterator does provide an add operation, as it does
guarantee the order of the iteration.
List Interface
1. Why don't you rename the List interface to Sequence; doesn't "list" generally suggest "linked
list"? Also, doesn't it conflict with java.awt.List?
People were evenly divided as to whether List suggests linked lists. Given the implementation
naming convention, <Implementation><Interface>, there was a strong desire to keep the core
interface names short. Also, several existing names (AbstractSequentialList, LinkedList) would
have been decidedly worse if we changed List to Sequence. The naming conflict can be dealt
with by the following incantation:
import java.util.*;
import java.awt.*;
import java.util.List; // Dictates interpretation of "List"
2. Why don't you rename List's set method to replace, to avoid confusion with Set.
It was decided that the "set/get" naming convention was strongly enough enshrined in the
language that we'd stick with it.
Map Interface
1. Why doesn't Map extend Collection?
This was by design. We feel that mappings are not collections and collections are not mappings.
Thus, it makes little sense for Map to extend the Collection interface (or vice versa).
If a Map is a Collection, what are the elements? The only reasonable answer is "Key-value
pairs", but this provides a very limited (and not particularly useful) Map abstraction. You can't
ask what value a given key maps to, nor can you delete the entry for a given key without
knowing what value it maps to.
Collection could be made to extend Map, but this raises the question: what are the keys?
There's no really satisfactory answer, and forcing one leads to an unnatural interface.
Maps can be viewed as Collections (of keys, values, or pairs), and this fact is reflected in the
three "Collection view operations" on Maps (keySet, entrySet, and values). While it is, in
principle, possible to view a List as a Map mapping indices to elements, this has the nasty
property that deleting an element from the List changes the Key associated with every element
before the deleted element. That's why we don't have a map view operation on Lists.
Iterator Interface
1. Why doesn't Iterator extend Enumeration?
We view the method names for Enumeration as unfortunate. They're very long, and very
frequently used. Given that we were adding a method and creating a whole new framework, we
felt that it would be foolish not to take advantage of the opportunity to improve the names. Of
course we could support the new and old names in Iterator, but it doesn't seem worthwhile.
2. Why don't you provide an Iterator.peek method that allows you to look at the next element in
an iteration without advancing the iterator?
Miscellaneous
1. Why did you write a new collections framework instead of adopting JGL (a preexisting
collections package from ObjectSpace, Inc.) into the JDK?
If you examine the goals for our Collections framework (in the Overview), you'll see that we are
not really "playing in the same space" as JGL. Quoting from the "Design Goals" Section of the
Java Collections Overview: "Our main design goal was to produce an API that was reasonably
small, both in size, and (more importantly) in 'conceptual weight.'"
JGL consists of approximately 130 classes and interfaces; its main goal was consistency with the
C++ Standard Template Library (STL). This was not one of our goals. Java has traditionally stayed
away from C++'s more complex features (e.g., multiple inheritance, operator overloading). Our
entire framework, including all infrastructure, contains approximately 25 classes and interfaces.
While this may cause some discomfort for some C++ programmers, we feel that it will be good
for Java in the long run. As the Java libraries mature, they inevitably grow, but we are trying as
hard as we can to keep them small and manageable, so that Java continues to be an easy, fun
language to learn and to use.
2. Why don't you eliminate all of the methods and classes that return "views" (Collections
backed by other collection-like objects). This would greatly reduce aliasing.
Given that we provide core collection interfaces behind which programmers can "hide" their
own implementations, there will be aliased collections whether the JDK provides them or not.
Eliminating all views from the JDK would greatly increase the cost of common operations like
making a Collection out of an array, and would do away with many useful facilities (like
synchronizing wrappers). One view that we see as being particularly useful is List.subList. The
existence of this method means that people who write methods taking List on input do not have
to write secondary forms taking an offset and a length (as they do for arrays).
3. Why don't you provide for "observable" collections that send out Events when they're
modified?
Primarily, resource constraints. If we're going to commit to such an API, it has to be something
that works for everyone, that we can live with for the long haul. We may provide such a facility
some day. In the meantime, it's not difficult to implement such a facility on top of the public
APIs.
Is it true that my RMI applet can make socket connections only to the host from which the applet
was downloaded from?
How can I download a file (for instance, a Microsoft Word document) from a server using a
servlet and an applet?
When used in an Applet/JApplet, does a Frame/JFrame show up inside the web page or as a new
window?
How do I show users with Java disabled what they are missing?
I'd like for my applet to load my own custom version of a core Java class, like java.lang.String.
How can I do this?
From one applet, how do I communicate with another applet loaded from the same server?
FAQ Entries in IO
How do I change what standard output or standard error goes to so it can go somewhere other
than the console?
How can I save/load application settings that I would normally use .ini files or the Windows
Registry?
How are the serial/parallel I/O ports set up and accessed from a Java program?
I'm writing to a socket using a buffered stream. When control returns after write() is invoked, has
the data been sent over the network or just copied to the buffer? How does the user get
notification of a network failure if the data is just put into the buffer?
Could you describe the architecture behind jGuru.com: JSP, Servlets, database, servers,
transactions etc...?
When using object streams over sockets, I have to flush the streams after each write operation. In
fact I even have to flush the output stream soon after creation. Is there a way out of this?
Is there any way to communicate between two classes within an application using InputStreams
and OutputStreams?
Under what circumstances would I use random access I/O over sequential, buffered I/O?
How do I detect end of stream in a non-blocking manner when reading a stream through
URL/URLConnection, if available() reports nothing to read on end of stream?
What is a stream?
How can I open the same file for reading as well as writing?
How to insert content into the middle of a file without overwriting the existing content?
How can I use Runtime.exec() to run MS-DOS commands without having MS-DOS shells popup
each time?
How can I reuse a StringWriter by flushing out its internal buffer? flush() doesn't seem to do it
and I'd like to avoid recreating the object many times.
How do I know that a particular file is in binary or text format without relying on the extention of
a file?
How can I start reading a file near the end, and not have to read all the bytes at the start too?
When do you use the Reader/Writer classes, instead of the InputStream/OutputStream classes?
How can I find out if a file is a text/ASCII file or binary file using Java?
Where can I find an example of a Java application that communicates with equipment via an
RS232 serial port?
How can I determine the byte length of an object that I serialize to a stream?
How can I get email addresses out of an MS Outlook database, and add knew ones?
Are there any third-party Java classes that support reading and interacting with SVG files?
How can I print colored text from Java to a terminal such as the Linux console?
Why are there two type of I/O in Java, namely byte streams and character (Reader/Writer)
streams?
Where can I learn (more) about Java's AWT (Abstract Window Toolkit)?
Where can I learn (more) about dealing with 2D (two dimensional) and 3D (three dimensional)
images, sound, speech, telelphony, and the rest of Java's support for advanced media handling?
Where can I learn (more) about Java's support for developing multi-threaded programs?
How do I write something in the end of a file? Do I have to read the entire file first putting it into a
buffer and then write it all again in a file with the line I want to write in the end? Or I can directly
write in the end of the file?
Is there any method in Java that will convert hexadecimal characters to binary characters?
How can I implement the Unix "cksum" command in Java? I'm using a CheckedInputStream and
creating a new instance of CRC32 to pass it, but I don't get the same checksum value as cksum
give me.
Is there an easy way of counting line numbers? Or do you have to go through the entire file?
Why aren't printing-related topics covered in the I/O FAQ? It seems like an I/O issue.
How are the mark() and reset() methods used with InputStream classes?
FAQ Entries in JDBC
I have the choice of manipulating database data using a byte[] or a java.sql.Blob. Which has best
performance?
I have the choice of manipulating database data using a String or a java.sql.Clob. Which has best
performance?
Say that a returned ResultSet has 100 rows. After looping through 60 rows, I want to return to
row number 40 without querying the database again. Is it possible?
How can I instantiate and load a new CachedRowSet object from a non-JDBC source?
Can I make a change to the transaction isolation level in the midst of executing the transaction?
How do I check what table-like database objects (table, view, temporary table, alias) are present
in a particular database?
How do I extract the SQL statements required to move all tables and views from an existing
database to another database?
How can I investigate the parameters to send into and receive from a database stored procedure?
Which is the preferred collection class to use for storing database result sets?
Where can I find a comprehensive list of JDBC drivers, including the databases they support?
Do I need to commit after an INSERT call in JDBC or does JDBC do it automatically in the DB?
Why must the CLASSPATH environment variable not include the path of the remote object's stub
classes on the server host?
How do I run rmiregistry and RMI servers in the background under Windows?
How can I control the lease period associated with a client's reference for my remote object?
Can my remote object obtain notification when there are no live references to it?
Where can I find a detailed comparison between RMI, DCOM and CORBA?
What's the cleanest way to have a client terminate a RMI server that is no longer needed?
Is it true that my RMI applet can make socket connections only to the host from which the applet
was downloaded from?
I get the exception "java.net.SocketException: Address already in use" whenever I try to run
rmiregistry. Why?
Why is that my remote objects can bind themselves only with a rmiregistry running on the same
host?
Is "pass by value" enforced for calls within the same VM to objects that implement
java.rmi.Remote? In other words, if I'm writing an object that implements java.rmi.Remote, can I
assume that calls to it that originate within the local VM will enjoy the same "copy by value"
rules for serializable parameters?
Q:
Explain the life cycle methods of a Servlet.
A: The javax.servlet.Servlet interface defines the three methods known as life-cycle method.
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
First the servlet is constructed, then initialized wih the init() method.
Any request from client are handled initially by the service() method before delegating to the
doXxx() methods in the case of HttpServlet.
The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected
and finalized.
TOP
Q:
What is the difference between the getRequestDispatcher(String path) method of
javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
A: The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts
parameter the path to the resource to be included or forwarded to, which can be relative to the
request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current
context root.
Q:
Explain the directory structure of a web application.
A: The directory structure of a web application consists of two parts.
A private directory called WEB-INF
A public resource directory which contains public resource folder.
Q:
What are the common mechanisms used for session tracking?
A: Cookies
SSL sessions
URL- rewriting
TOP
Q:
Explain ServletContext.
A: ServletContext interface is a window for a servlet to view it's environment. A servlet can use this
interface to get information such as initialization parameters for the web applicationor servlet
container's version. Every web application has one and only one ServletContext and is accessible to
all active resource of that application.
TOP
Q:
What is preinitialization of a servlet?
A: A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it
receives a request for that servlet first time. This is called lazy loading. The servlet specification
defines the <load-on-startup> element, which can be specified in the deployment descriptor to
make the servlet container load and initialize the servlet as soon as it starts up. The process of
loading a servlet before any request comes in is called preloading or preinitializing a servlet.
[ Received from Amit Bhoir ] TOP
Q:
What is the difference between Difference between doGet() and doPost()?
A: A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this
limitation. A request string for doGet() looks like the following:
http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN
doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters
are stored in a request itself, not in a request string, and it's impossible to guess the data
transmitted to a servlet only looking at a request string.
[ Received from Amit Bhoir ] TOP
Q:
What is the difference between HttpServlet and GenericServlet?
A: A GenericServlet has a service() method aimed to handle requests. HttpServlet extends
GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(),
doOptions(), doDelete(), doTrace() methods (HTTP 1.1).
Both these classes are abstract.
DB Interview Questions
Q:
What is SQL?
A: SQL stands for 'Structured Query Language'.
TOP
Q:
What is SELECT statement?
A: The SELECT statement lets you select a set of values from a table in a database. The values selected
from the database table would depend on the various conditions that are specified in the SQL query.
TOP
Q:
How can you compare a part of the name rather than the entire name?
A: SELECT * FROM people WHERE empname LIKE '%ab%'
Would return a recordset with records consisting empname the sequence 'ab' in empname .
TOP
Q:
What is the INSERT statement?
A: The INSERT statement lets you insert information into a database.
TOP
Q:
How do you delete a record from a database?
A: Use the DELETE statement to remove records or any particular column values from a database.
TOP
Q:
How could I get distinct entries from a table?
A: The SELECT statement in conjunction with DISTINCT lets you select a set of distinct values from a
table in a database. The values selected from the database table would of course depend on the
various conditions that are specified in the SQL query. Example
SELECT DISTINCT empname FROM emptable
TOP
Q:
How to get the results of a Query sorted in any order?
A: You can sort the results and return the sorted results to your program by using ORDER BY keyword
thus saving you the pain of carrying out the sorting yourself. The ORDER BY keyword is used for
sorting.
SELECT empname, age, city FROM emptable ORDER BY empname
TOP
Q:
How can I find the total number of records in a table?
A:
You could use the COUNT keyword , example
Q:
What is GROUP BY?
A: The GROUP BY keywords have been added to SQL because aggregate functions (like SUM) return the
aggregate of all column values every time they are called. Without the GROUP BY functionality,
finding the sum for each individual group of column values was not possible.
TOP
Q:
What is the difference among "dropping a table", "truncating a table" and "deleting all records"
from a table.
A: Dropping : (Table structure + Data are deleted), Invalidates the dependent objects ,Drops the
indexes
Truncating: (Data alone deleted), Performs an automatic commit, Faster than delete
Q:
What are the Large object types suported by Oracle?
A: Blob and Clob.
TOP
Q:
Difference between a "where" clause and a "having" clause.
A: Having clause is used only with group functions whereas Where is not used with.
TOP
Q:
What's the difference between a primary key and a unique key?
A:
Both primary key and unique enforce uniqueness of the column on which they are defined. But by
default primary key creates a clustered index on the column, where are unique creates a
nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs,
but unique key allows one NULL only.
TOP
Q:
What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How
can you avoid cursors?
A: Cursors allow row-by-row prcessing of the resultsets.
Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more
information.
Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network
roundtrip, where as a normal SELECT query makes only one rowundtrip, however large the resultset
is. Cursors are also costly because they require more resources and temporary storage (results in
more IO operations). Furthere, there are restrictions on the SELECT statements that can be used
with some types of cursors.
Most of the times, set based operations can be used instead of cursors.
TOP
Q:
What are triggers? How to invoke a trigger on demand?
A: Triggers are special kind of stored procedures that get executed automatically when an INSERT,
UPDATE or DELETE operation takes place on a table.
Triggers can't be invoked on demand. They get triggered only when an associated action (INSERT,
UPDATE, DELETE) happens on the table on which they are defined.
Triggers are generally used to implement business rules, auditing. Triggers can also be used to
extend the referential integrity checks, but wherever possible, use constraints for this purpose,
instead of triggers, as constraints are much faster.
Q:
What is a join and explain different types of joins.
A: Joins are used in queries to explain how different tables are related. Joins also let you select data
from a table depending upon data from another table.
Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT
OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.
TOP
Q:
What is a self join?
A: Self join is just like any other join, except that two instances of the same table will be joined in the
query.
Question: What is the difference between an Interface and an Abstract class?
Question: What is the purpose of garbage collection in Java, and when is it used?
Question: Describe synchronization in respect to multithreading.
Question: Explain different way of using thread?
Question: What are pass by reference and passby value?
Question: What is HashMap and Map?
Question: Difference between HashMap and HashTable?
Question: Difference between Vector and ArrayList?
Question: Difference between Swing and Awt?
Question: What is the difference between a constructor and a method?
Question: What is an Iterators?
Question: 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.
Question: What is an abstract class?
Question: What is static in java?
What is final?
Question:
Q:
What is the difference between an Interface and an Abstract class?
A: An Abstract class declares have at least one instance method that is declared abstract which will be
implemented by the subclasses. 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.
TOP
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.
TOP
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.
TOP
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.
TOP
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.
TOP
Q:
What is HashMap and Map?
A: Map is Interface and Hashmap is class that implements that.
TOP
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 non
synchronized and Hashtable is synchronized.
TOP
Q:
Difference between Vector and ArrayList?
A: Vector is synchronized whereas arraylist is not.
TOP
Q:
Difference between Swing and Awt?
A: AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works
faster than AWT.
TOP
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.
TOP
Q:
What is an Iterators?
A: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface.
This interface allows you to walk 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.
TOP
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.
TOP
Q:
What is an abstract class?
A: Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is
abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain
static data. Any class with an abstract method is automatically abstract itself, and must be declared
as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being
instantiated.
TOP
Q:
What is static in java?
A: Static means one per class, not one for each object no matter how many instance of a class might
exist. This means that you can use them without creating an instance of a class.Static methods are
implicitly final, because overriding is done based on the type of the object, and static methods are
attached to a class, not an object. A static method in a superclass can be shadowed by another static
method in a subclass, as long as the original method was not declared final. However, you can't
override a static method with a nonstatic method. In other words, you can't change a static method
into an instance method in a subclass.
TOP
Q:
What is final?
A: A final class can't be extended ie., final class may not be subclassed. A final method can't be
overridden when its class is inherited. You can't change value of a final variable (is a constant).
Java Interview Questions
Q:
What if the main method is declared as private?
A: The program compiles properly but at runtime it will give "Main method not public." message.
[ Received from Sandesh Sadhale] TOP
Q:
What if the static modifier is removed from the signature of the main method?
A: Program compiles. But at runtime throws an error "NoSuchMethodError".
[ Received from Sandesh Sadhale] TOP
Q:
What if I write static public void instead of public static void?
A: Program compiles and runs properly.
[ Received from Sandesh Sadhale] TOP
Q:
What if I do not provide the String array as the argument to the method?
A: Program compiles but throws a runtime error "NoSuchMethodError".
[ Received from Sandesh Sadhale] TOP
Q:
What is the first argument of the String array in main method?
A: The String array is empty. It does not have any element. This is unlike C/C++ where the first element
by default is the program name.
[ Received from Sandesh Sadhale] TOP
Q:
If I do not provide any arguments on the command line, then the String array of Main method will
be empty of null?
A: It is empty. But not null.
[ Received from Sandesh Sadhale] TOP
Q:
How can one prove that the array is not null but empty?
A: Print args.length. It will print 0. That means it is empty. But if it would have been null then it would
have thrown a NullPointerException on attempting to print args.length.
[ Received from Sandesh Sadhale] TOP
Q:
What environment variables do I need to set on my machine in order to be able to run Java
programs?
A: CLASSPATH and PATH are the two variables.
[ Received from Sandesh Sadhale] TOP
Q:
Can an application have multiple classes having main method?
A: Yes it is possible. While starting the application we mention the class name to be run. The JVM will
look for the Main method only in the class whose name you have mentioned. Hence there is not
conflict amongst the multiple classes having main method.
[ Received from Sandesh Sadhale] TOP
Q:
Can I have multiple main methods in the same class?
A: No the program fails to compile. The compiler says that the main method is already defined in the
class.
[ Received from Sandesh Sadhale] TOP
Q:
Do I need to import java.lang package any time? Why ?
A: No. It is by default loaded internally by the JVM.
[ Received from Sandesh Sadhale] TOP
Q:
Can I import same package/class twice? Will the JVM load the package twice at runtime?
A: One can import the same package or same class multiple times. Neither compiler nor JVM
complains abt it. And the JVM will internally load the class only once no matter how many times you
import the same class.
[ Received from Sandesh Sadhale] TOP
Q:
What are Checked and UnChecked Exception?
A: A checked exception is some subclass of Exception (or Exception itself), excluding class
RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility that the
exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method·
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses
also are unchecked. With an unchecked exception, however, the compiler doesn't force client
programmers either to catch the
exception or declare it in a throws clause. In fact, client programmers may not even know that the
exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt()
method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to
be. Errors often cannot be.
TOP
Q:
What is Overriding?
A: When a class defines a method using the same name, return type, and arguments as a method in its
superclass, the method in the class overrides the method in the superclass.
When the method is invoked for an object of the class, it is the new definition of the method that is
called, and not the method definition from superclass. Methods may be overridden to be more
public, not more private.
TOP
Q:
What are different types of inner classes?
A: Nested top-level classes, Member classes, Local classes, Anonymous classes
Nested top-level classes- If you declare a class within a class and specify the static modifier, the
compiler treats the class just like any other top-level class.
Any class outside the declaring class accesses the nested class with the declaring class name acting
similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static
variables.There can also be inner interfaces. All of these are of the nested top-level variety.
Member classes - Member inner classes are just like other member methods and member variables
and access to the member class is restricted, just like methods and variables. This means a public
member class acts similarly to a nested top-level class. The primary difference between member
classes and nested top-level classes is that member classes have access to the specific instance of
the enclosing class.
Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only
within the block of their declaration. In order for the class to be useful beyond the declaration block,
it would need to implement a
more publicly available interface.Because local classes are not members, the modifiers public,
protected, private, and static are not usable.
Anonymous classes - Anonymous inner classes extend local inner classes one level further. As
anonymous classes have no name, you cannot provide a constructor
Question: Are the imports checked for validity at compile time? e.g. will the code containing an import
such as java.lang.ABCD compile?
Question: Does importing a package imports the subpackages as well? e.g. Does importing
com.MyTest.* also import com.MyTest.UnitTests.*?
Question: What is the difference between declaring a variable and defining a variable?
Question: What is the default value of an object reference declared as an instance variable?
Question: Can a top level class be private or protected?
Question: What type of parameter passing does Java support?
Question: Primitive data types are passed by reference or pass by value?
Question: Objects are passed by value or by reference?
Question: What is serialization?
Question: How do I serialize an object to a file?
Question: Which methods of Serializable interface should I implement?
Question: How can I customize the seralization process? i.e. how can one have a control over the
serialization process?
Question: What is the common usage of serialization?
Question: What is Externalizable interface?
Question: What happens to the object references included in the object serialized?
Question: What one should take care of while serializing the object?
Question: What happens to the static fields of a class during serialization? Are these fields serialized as
a part of each serialized object?
Q:
Are the imports checked for validity at compile time? e.g. will the code containing an import such
as java.lang.ABCD compile?
A: Yes the imports are checked for the semantic validity at compile time. The code containing above
line of import will not compile. It will throw an error saying,can not resolve symbol
symbol : class ABCD
location: package io
import java.io.ABCD;
[ Received from Sandesh Sadhale] TOP
Q:
Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.*
also import com.MyTest.UnitTests.*?
A: No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in
the package MyTest only. It will not import any class in any of it's subpackage.
[ Received from Sandesh Sadhale] TOP
Q:
What is the difference between declaring a variable and defining a variable?
A: In declaration we just mention the type of the variable and it's name. We do not initialize it. But
defining means declaration + initialization.
e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both
definitions.
[ Received from Sandesh Sadhale] TOP
Q:
What is the default value of an object reference declared as an instance variable?
A: null unless we define it explicitly.
[ Received from Sandesh Sadhale] TOP
Q:
Can a top level class be private or protected?
A: No. A top level class can not be private or protected. It can have either "public" or no modifier. If it
does not have a modifier it is supposed to have a default access.If a top level class is declared as
private the compiler will complain that the "modifier private is not allowed here". This means that a
top level class can not be private. Same is the case with protected.
[ Received from Sandesh Sadhale] TOP
Q:
What type of parameter passing does Java support?
A: Java supports both pass by value as well as pass by reference.
[ Received from Sandesh Sadhale] TOP
Q:
Primitive data types are passed by reference or pass by value?
A: Primitive data types are passed by value.
[ Received from Sandesh Sadhale] TOP
Q:
Objects are passed by value or by reference?
A: Objects are always passed by reference. Thus any modifications done to an object inside the called
method will always reflect in the caller method.
[ Received from Sandesh Sadhale] TOP
Q:
What is serialization?
A: Serialization is a mechanism by which you can save the state of an object by converting it to a byte
stream.
[ Received from Sandesh Sadhale] TOP
Q:
How do I serialize an object to a file?
A: The class whose instances are to be serialized should implement an interface Serializable. Then you
pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will
save the object to a file.
[ Received from Sandesh Sadhale] TOP
Q:
Which methods of Serializable interface should I implement?
A: The serializable interface is an empty interface, it does not contain any methods. So we do not
implement any methods.
[ Received from Sandesh Sadhale] TOP
Q:
How can I customize the seralization process? i.e. how can one have a control over the
serialization process?
A: Yes it is possible to have control over serialization process. The class should implement
Externalizable interface. This interface contains two methods namely readExternal and
writeExternal. You should implement these methods and write the logic for customizing the
serialization process.
[ Received from Sandesh Sadhale] TOP
Q:
What is the common usage of serialization?
A: Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the
state of an object is to be saved, objects need to be serilazed.
[ Received from Sandesh Sadhale] TOP
Q:
What is Externalizable interface?
A: Externalizable is an interface which contains two methods readExternal and writeExternal. These
methods give you a control over the serialization mechanism. Thus if your class implements this
interface, you can customize the serialization process by implementing these methods.
[ Received from Sandesh Sadhale] TOP
Q:
What happens to the object references included in the object?
A: The serialization mechanism generates an object graph for serialization. Thus it determines whether
the included object references are serializable or not. This is a recursive process. Thus when an
object is serialized, all the included objects are also serialized alongwith the original obect.
[ Received from Sandesh Sadhale] TOP
Q:
What one should take care of while serializing the object?
A: One should make sure that all the included objects are also serializable. If any of the objects is not
serializable then it throws a NotSerializableException.
[ Received from Sandesh Sadhale] TOP
Q:
What happens to the static fields of a class during serialization? Are these fields serialized as a
part of each serialized object?
A: Yes the static fields do get serialized. If the static field is an object then it must have implemented
Serializable interface. The static fields are serialized as a part of every object. But the commonness
of the static fields across all the instances is maintained even after serialization
Question: Does Java provide any construct to find out the size of an object?
Question: Give a simplest way to find out the time a method takes for execution without
using any profiling tool?
Question: What are wrapper classes?
Question: Why do we need wrapper classes?
Question: What are checked exceptions?
Question: What are runtime exceptions?
Question: What is the difference between error and an exception??
Question: How to create custom exceptions?
Question: If I want an object of my class to be thrown as an exception object, what
should I do?
Question: If my class already extends from some other class what should I do if I want an
instance of my class to be thrown as an exception object?
Question: What happens to an unhandled exception?
Question: How does an exception permeate through the code?
Question: What are the different ways to handle exceptions?
Question: 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?
Question: Is it necessary that each try block must be followed by a catch block ?
Question: If I write return at the end of the try block, will the finally block still execute ?
Question: If I write System.exit (0); at the end of the try block, will the finally block still
execute?
Q:
Does Java provide any construct to find out the size of an object?
A: No there is not sizeof operator in Java. So there is not direct way to determine the size of an object
directly in Java.
[ Received from Sandesh Sadhale] TOP
Q:
Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.*
also import com.MyTest.UnitTests.*?
A: 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 ();
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.
[ Received from Sandesh Sadhale] TOP
Q:
What are wrapper classes?
A: 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.
[ Received from Sandesh Sadhale] TOP
Q:
Why do we need wrapper classes?
A: 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.
[ Received from Sandesh Sadhale] TOP
Q:
What are checked exceptions?
A: Checked exception are those which the Java compiler forces you to catch. e.g. IOException are
checked Exceptions.
[ Received from Sandesh Sadhale] TOP
Q:
What are runtime exceptions?
A: Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input
data or because of wrong business logic etc. These are not checked by the compiler at compile time.
[ Received from Sandesh Sadhale] TOP
Q:
What is the difference between error and an exception?
A: An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM
errors and you can not repair them at runtime. While exceptions are conditions that occur because
of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a
NullPointerException will take place if you try using a null reference. In most of the cases it is
possible to recover from an exception (probably by giving user a feedback for entering proper values
etc.).
[ Received from Sandesh Sadhale] TOP
Q:
How to create custom exceptions?
A: Your class should extend class Exception, or some more specific type thereof.
[ Received from Sandesh Sadhale] TOP
Q:
If I want an object of my class to be thrown as an exception object, what should I do?
A: The class should extend from Exception class. Or you can extend your class from some more precise
exception type also.
[ Received from Sandesh Sadhale] TOP
Q:
If my class already extends from some other class what should I do if I want an instance of my
class to be thrown as an exception object?
A: One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and
does not provide any exception interface as well.
[ Received from Sandesh Sadhale] TOP
Q:
What happens to an unhandled exception?
A: One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and
does not provide any exception interface as well.
[ Received from Sandesh Sadhale] TOP
Q:
How does an exception permeate through the code?
A: 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.
[ Received from Sandesh Sadhale] TOP
Q:
What are the different ways to handle exceptions?
A: There are two ways to handle exceptions,
1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
2. List the desired exceptions in the throws clause of the method and let the caller of the method
hadle those exceptions.
[ Received from Sandesh Sadhale] TOP
Q:
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.
[ Received from Sandesh Sadhale] TOP
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.
[ Received from Sandesh Sadhale] TOP
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.
[ Received from Sandesh Sadhale] TOP
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
Q:
What is synchronization and why is it important?
A: With respect to multithreading, synchronization is the capability to control
the access of multiple threads to shared resources. Without synchronization, it is possible for one
thread to modify a shared object while another thread is in the process of using or updating that
object's value. This often leads to
significant errors.
[ Received from Venkateswara Manam] TOP
Q:
How does Java handle integer overflows and underflows?
A: It uses those low order bytes of the result that can fit into the size of the type allowed by the
operation.
[ Received from Venkateswara Manam] TOP
Q:
Does garbage collection guarantee that a program will not run out of memory?
A: Garbage collection does not guarantee that a program will not run out of
memory. It is possible for programs to use up memory resources faster than they are garbage
collected. It is also possible for programs to create objects that are not subject to garbage collection
.
[ Received from Venkateswara Manam] TOP
Q:
What is the difference between preemptive scheduling and time slicing?
A: Under preemptive scheduling, the highest priority task executes until it enters
the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task
executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then
determines which task should execute next, based on priority and other factors.
[ Received from Venkateswara Manam] TOP
Q:
When a thread is created and started, what is its initial state?
A: A thread is in the ready state after it has been created and started.
[ Received from Venkateswara Manam] TOP
Q:
What is the purpose of finalization?
A: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup
processing before the object is garbage collected.
[ Received from Venkateswara Manam] TOP
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.
[ Received from Venkateswara Manam] TOP
Q:
What is the difference between a while statement and a do statement?
A: A while statement checks at the beginning of a loop to see whether the next
loop iteration should occur. A do statement checks at the end of a loop to see whether the next
iteration of a loop should occur. The do statement will
always execute the body of a loop at least once.
[ Received from Venkateswara Manam] TOP
Q:
What is the difference between static and non-static variables?
A: 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.
[ Received from Venkateswara Manam] TOP
Q:
How are this() and super() used with constructors?
A: Othis() is used to invoke a constructor of the same class. super() is used to
invoke a superclass constructor.
[ Received from Venkateswara Manam] TOP
Q:
What are synchronized methods and synchronized statements?
A: Synchronized methods are methods that are used to control access to an object. A thread only
executes a synchronized method after it has acquired the lock for the method's object or class.
Synchronized statements are similar to synchronized methods. A synchronized statement can only
be executed after a thread has acquired the lock for the object or class referenced in the
synchronized statement
Q:
What is a output comment?
A: A comment that is sent to the client in the viewable page source.The JSP engine handles an output
comment as uninterpreted HTML text, returning the comment in the HTML output sent to the
client. You can see the comment by viewing the page source from your Web browser.
JSP Syntax
<!-- comment [ <%= expression %> ] -->
Example 1
<!-- This is a commnet sent to client on
<%= (new java.util.Date()).toLocaleString() %>
-->
Q:
What is a Hidden Comment?
A: A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a
hidden comment, and does not process any code within hidden comment tags. A hidden comment
is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden
comment is useful when you want to hide or "comment out" part of your JSP page.
You can use any characters in the body of the comment except the closing --%> combination. If you
need to use --%> in your comment, you can escape it by typing --%\>.
JSP Syntax
<%-- comment --%>
Examples
<%@ page language="java" %>
<html>
<head><title>A Hidden Comment </title></head>
<body>
<%-- This comment will not be visible to the colent in the page source --%>
</body>
</html>
TOP
Q:
What is a Expression?
A: An expression tag contains a scripting language expression that is evaluated, converted to a String,
and inserted where the expression appears in the JSP file. Because the value of an expression is
converted to a String, you can use an expression within text in a JSP file. Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression
TOP
Q:
What is a Declaration?
A: A declaration declares one or more variables or methods for use later in the JSP source file.
A declaration must contain at least one complete declarative statement. You can declare any
number of variables or methods within one declaration tag, as long as they are separated by
semicolons. The declaration must be valid in the scripting language used in the JSP file.
Q:
What is a Scriptlet?
A: A scriptlet can contain any number of language statements, variable or method declarations, or
expressions that are valid in the page scripting language.Within scriptlet tags, you can
1.Declare variables or methods to use later in the file (see also Declaration).
2.Write expressions valid in the page scripting language (see also Expression).
3.Use any of the JSP implicit objects or any object declared with a <jsp:useBean> tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.
Scriptlets are executed at request time, when the JSP engine processes the client request. If the
scriptlet produces output, the output is stored in the out object, from which you can display it.
TOP
Q:
What are implicit objects? List them?
A: Certain objects that are available for the use in JSP documents without being declared first. These
objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re
listed below
request
response
pageContext
session
application
out
config
page
exception
TOP
Q:
Difference between forward and sendRedirect?
A: When you invoke a forward request, the request is sent to another resource on the server, without
the client being informed that a different resource is going to process the request. This process
occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the
web container to return to the browser indicating that a new URL should be requested. Because the
browser issues a completly new request any object that are stored as request attributes before the
redirect occurs will be lost. This extra round trip a redirect is slower than forward.
TOP
Q:
What are the different scope valiues for the <jsp:useBean>?
A: The different scope values for <jsp:useBean> are
1. page
2. request
3.session
4.application
TOP
Q:
Explain the life-cycle mehtods in JSP?
A:
THe generated servlet class for a JSP page implements the HttpJspPage interface of the
javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn
extends the Servlet interface of the javax.servlet package. the generated servlet class thus
implements all the methods of the these three interfaces. The JspPage interface declares only two
mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the
client-server protocol. However the JSP specification has provided the HttpJspPage interfaec
specifically for the JSp pages serving HTTP requests. This interface declares one method
_jspService().
The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any
other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the request and
the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of service. It is the
last method called n the servlet instance
Q:
What are the different kinds of enterprise beans?
A: Different kind of enterrise beans are Stateless session bean, Stateful session bean, Entity bean,
Message-driven bean...........
Q:
What is Session Bean?
A: A session bean is a non-persistent object that implements some business logic running on the
server. One way to think of a session object...........
Q:
What is Entity Bean?
A: The entity bean is used to represent data in the database. It provides an object-oriented interface
to ...........
Q:
What are the methods of Entity Bean?
A: An entity bean consists of 4 groups of methods, create methods...........
Q:
What is the difference between Container-Managed Persistent (CMP) bean and Bean-Managed
Persistent(BMP) ?
A: Container-managed persistence (CMP) and bean-managed persistence (BMP). With CMP, the
container manages the persistence of the entity bean............
Q:
What are the callback methods in Entity beans?
A: Callback methods allows the container to notify the bean of events in
its life cycle. The callback methods are defined in the javax.ejb.EntityBean interface............
Q:
What is software architecture of EJB?
A: Session and Entity EJBs consist of 4 and 5 parts respectively, a remote interface...........
Q:
Can Entity Beans have no create() methods?
A: Yes. In some cases the data is inserted NOT using Java application,...........
Q:
What is bean managed transaction?
A: If a developer doesn't want a Container to manage transactions, it's possible to implement all
database operations manually...........
Q:
What are transaction attributes?
A: The transaction attribute specifies how the Container must manage transactions for a method when
a client invokes the method via the enterprise bean’s home or...........
An enterprise bean is a server-side component that encapsulates the business logic of an application.
The business logic is the code that fulfills the purpose of the application. In an inventory control
application, for example, the enterprise beans might implement the business logic in methods called
checkInventoryLevel and orderProduct. By invoking these methods, remote clients can access the
inventory services provided by the application.
A normal bean can be used by us for storing simple that which we can use to transfer data between
classes. For eg:-
Organizational advantage
Allows us to further organize package structure through the use of namespaces
Callback advantage
More convenient way for defining callbacks, esp. with GUI code
Allows you to separate code logically instead of having a monolithic implementation.
Anonymous classes
A class with no name, which is why it’s called an “anonymous class”
Anonymous objects cannot be instantiated from outside the class in which the anonymous class
is defined
it can only be instantiated from within the same scope in which it is defined
Why use an anonymous class
It lessens the amount of “.java” files necessary to define the application.
anonymous classes can access the static and instance variables of the enclosing outer
class.
Can be time-savers
An anonymous class must implement all the abstract methods in the super class or the
interface.
An anonymous class always uses the default constructor from the super class to create an
instance
Ans: View is a precomplied SQL query which is used to select data from one or more tables. A view is
like a table but it doens't physically take any space. Viw is a good way to present data in a particualr
format if you use that query quite often.
View can also be used to restrict users from accessing the tables directly.
What is WebSphere?
Originally, WebSphere was a product (WebSphere Application Server). However, today WebSphere is an
IBM Brand as well as a set of strategic SWG products. Because the WebSphere Brand has "name
recognition", many of the SWG products included in the e-business application framework now have the
word WebSphere as part of its' name. For example, WebSphere Application Server, WebSphere
Commerce Suite, WebSphere Payment Manager, WebSphere Development Studio for iSeries, WebSphere
Transcoding Publisher, WebSphere Home Page Builder, WebSphere Translation Server, WebSphere Site
Analyzer, WebSphere Everyplace Access, WebSphere Studio, WebSphere Voice Server, WebSphere Portal
Server, WebSphere Personalization Server, WebSphere Edge Server, WebSphere Business Integrator and
WebSphere Host Integration. The core of the platform is still WebSphere Application Server, which
provides J2EE application deployment platform and many enterprise services
The console is a Java based application which needs to see the server that it is going to connect to in an
active state before it will display any information. This can be very frustrating. Due to it being written in
Java, the error messages produced can be deceptive
The console is capable of running on various platforms and when you order WebSphere V3 you will have
the ability to install under NT and various UNIX flavours. For most people, NT and Windows will probably
be the standard option.
In version 5.0 of WebSphere, Java based console has been replaced again by browser-based console in
order to resolve the issues of firewalls (Java-based console was not capable to connect through them),
and simplify / standardize the management of the product.
Please note that WebSphere does not run under 9X versions of Windows (95, 98, Me)
What Development Environment(s) are available to develop applications for WebSphere? IBM provides
several industrial strength development environments based on Eclipse development framework - from
most advanced to the least advanced - WebSphere Studio Enterprise Developer (WSED), WebSphere
Studio Application Developer - Integration Edition (WSAD-IE), WebSphere Studio Application Developer
(WSAD), and WebSphere Studio Site Developer (WSSD). Most of the people use WSAD, as it satisfies
most of the J2EE (EJB, JSP) and Web Services development needs. The old development environment
VisualAge for Java 3.5.3 and 4.0 is still supported, but it is being phased out by WSAD. Third-party
development environments are also available for WebSphere development (such as Borland JBuilder and
WebGain Studio).
Why would I use WebSphere - can't I do the same thing with Tomcat
WebSphere is an enterprise product. It provides such services as Workload Management, Session
Management, Connection Pooling, Security, sophisticated tools for management and deployment. It is
also tuned to work with various databases and be able to sustain high production loads. One of the
important characteristics of the enterprise product is also support from the company that produced it -
that's from IBM. If you are just designing a small site to be used somewhere on the web without having
to worry about multi-server environment, you might be all right with Tomcat. WebSphere requires
significant investment - it's not cheap - but it would return the costs for you once you establish a
significant customer base to use it.
multitasking
process based or thread based
process is a program in execution
process based allows two or more programs to execute concurrently
process is smallest unit of code that can be dispatched to scheduler
in thread based, thread is smallest unit of code that can be dispatched to scheduler
single program can perform two or more tasks simultaneously
process is heavy weight task requiring its own resources
threads, are light weight, sharing some resources of process among threads
therefore context switch is less expensive
enables you to write efficient programs by reducing CPU idle time to min
especially possible by interleaving input-output and CPU intensive processes
Java does not handle multiprogramming
rules for context switch
thread can voluntarily relinquish control: highest priority runnable thread is
started
pre-empted by higher priority thread
messaging
after you divide program into threads, you need to define how the threads will
communicate
Java messaging allows thread to enter sync method of an object and wait until some
other thread explicitly notifies it to come out