Вы находитесь на странице: 1из 246

Jakarta Struts Interview Questions

Q: What is Jakarta Struts Framework?


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

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" />

Q: What is Action Class?


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

Q: Write code of any Action Class?


A: Here is the code of Action Class that returns the ActionForward object.
TestAction.java
package roseindia.net;

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;

public class TestAction extends Action


{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
return mapping.findForward("testAction");
}
}
Q: What is ActionForm?
A: An Action Form is a JavaBeans that extends org.apache.struts.action.ActionForm. ActionForm
maintains the session state for web application and the ActionForm object is automatically populated
on the server side with data entered from a form on the client side.

Q: What is Struts Validator Framework?


A: Struts Framework provides the functionality to validate the form data. It can be use to validate the
data on the users browser as well as on the server side. Struts Framework emits the java scripts and it
can be used validate the form data on the client browser. Server side validation of form can be
accomplished by sub classing your From Bean with DynaValidatorForm class.
The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the
Validator framework is a part of Jakarta Commons project and it can be used with or without Struts.
The Validator framework comes integrated with the Struts Framework and can be used without doing
any extra settings.

Q. Give the Details of XML files used in Validator Framework?


A: The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml.
The validator-rules.xml defines the standard validation routines, these are reusable and used in
validation.xml. to define the form specific validations. The validation.xml defines the validations
applied to a form bean.
Q. How you will display validation fail errors on jsp page?
A: Following tag displays all the errors:
<html:errors/>

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.

14. What is ServiceLayer and Business Layer?


Ans: Business Layer is the place /layer where we place our business related coding, beans etc. Service
Layer is the interface of Business Layer to the client tier. So Service layer is very abstract layer, having
very high level business calls, like create Account, But create account has many calls or validations,
those details are placed in business layer. This way loose coupling is achieved between client and
business tiers. Because change in business layer, does not initiate a change in service layer as well.

15: What for ServiceLocator used?


Ans: This is a service layer pattern, for storing lookup values for all services, and provides this
information on request, and enhances performance as the JNDI lookup is made once only.

Core Java Interview Questions


Question: What is transient variable?
Answer: Transient variable can't be serialize. For example if a variable is declared as transient in a
Serializable class and the class is written to an ObjectStream, the value of the variable can't be written
to the stream instead when the class is retrieved from the ObjectStream the value of the variable
becomes null.

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.

Question: What do you understand by Synchronization?


Answer: Synchronization is a process of controlling the access of shared resources by the multiple
threads in such a manner that only one thread can access one resource at a time. In non synchronized
multithreaded application, it is possible for one thread to modify a shared object while another thread
is in the process of using or updating the object's value. Synchronization prevents such type of data
corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
// Appropriate method-related code.
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
synchronized (this) {
// Synchronized code here.
}
}

Question: What is Collection API?


Answer: The Collection API is a set of classes and interfaces that support operation on collections of
objects. These classes and interfaces are more flexible, more powerful, and more regular than the
vectors, arrays, and hash tables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

Question: Is Iterator a Class or Interface? What is its use?


Answer: Iterator is an interface which is used to step through the elements of a Collection.

Question: What is similarities/difference between an Abstract class and Interface?


Answer: Differences are as follows:
 Interfaces provide a form of multiple inheritance. A class can extend only one other class.
 Interfaces are limited to public methods and constants with no implementation. Abstract classes
can have a partial implementation, protected parts, static methods, etc.
 A Class may implement several interfaces. But in case of abstract class, a class may extend only
one abstract class.
 Interfaces are slow as it requires extra indirection to find corresponding method in the actual
class. Abstract classes are fast.
Similarities:
 Neither Abstract classes or Interface can be instantiated.

Question: How to define an Abstract class?


Answer: A class containing abstract method is called Abstract class. An Abstract class can't be
instantiated.
Example of Abstract class:
abstract class testAbstractClass
{
protected String myString;
public String getMyString()
{
return myString;
}
public abstract string anyAbstractFunction();
}

Question: How to define an Interface?


Answer: In Java Interface defines the methods but does not implement them.
 Interface can include constants.
 A class that implements the interfaces is bound to implement all the methods defined in
Interface.
Emaple of Interface:
public interface sampleInterface {
public void functionOne();

public long CONSTANT_ONE = 1000;


}
Question: Explain the user defined Exceptions?
Answer: User defined Exceptions are the separate Exception classes defined by the user for specific
purposed. An user defined can created by simply sub-classing it to the Exception class. This allows
custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
Example:
class myCustomException extends Exception {
// The class simply has to exist to be an exception
}

Question: Explain the new Features of JDBC 2.0 Core API?


Answer: The JDBC 2.0 API includes the complete JDBC API, which includes both core and Optional
Package API, and provides inductrial-strength database computing capabilities.
New Features in JDBC 2.0 Core API:
 Scrollable result sets- using new methods in the ResultSet interface allows programmatically
move the to particular row or to a position relative to its current position
 JDBC 2.0 Core API provides the Batch Updates functionality to the java applications.
 Java applications can now use the ResultSet.updateXXX methods.
 New data types - interfaces mapping the SQL3 data types
 Custom mapping of user-defined types (UTDs)
 Miscellaneous features, including performance hints, the use of character streams, full precision
for java.math.BigDecimal values, additional security, and support for time zones in date, time,
and timestamp values.

Question: Explain garbage collection?


Answer: Garbage collection is one of the most important feature of Java. Garbage collection is also
called automatic memory management as JVM automatically removes the unused variables/objects
(value is null) from the memory. User program can’t directly free the object from memory, instead it is
the job of the garbage collector to automatically free the objects that are no longer referenced by a
program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by
garbage collector when it determines no more references to the object exists. In Java, it is good idea to
explicitly assign null into a variable when no more in use. I Java on calling System.gc() and
Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects
will garbage collected.

Question: How you can force the garbage collection?


Answer: Garbage collection automatic process and can't be forced.

Question: Describe the principles of OOPS.


Answer: There are three main principals of oops which are called Polymorphism, Inheritance and
Encapsulation.

Question: Explain the Encapsulation principle.


Answer: Encapsulation is a process of binding or wrapping the data and the codes that operates on the
data into a single entity. This keeps the data safe from outside interface and misuse. One way to think
about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily
accessed by other code defined outside the wrapper.

Question: Explain the Inheritance principle.


Answer: Inheritance is the process by which one object acquires the properties of another object.

Question: Explain the Polymorphism principle.


Answer: The meaning of Polymorphism is something like one name many forms. Polymorphism
enables one entity to be used as general category for different types of actions. The specific action is
determined by the exact nature of the situation. The concept of polymorphism can be explained as
"one interface, multiple methods".

Question: Explain the different forms of Polymorphism.


Answer: From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:
1. Method overloading
2. Method overriding through inheritance
3. Method overriding through the Java interface

Question: What are Access Specifiers available in Java?


Answer: Access specifiers are keywords that determine the type of access to the member of a class.
These are:
1. Public
2. Protected
3. Private
4. Defaults

Question: Describe the wrapper classes in Java.


Answer: Wrapper class is wrapper around a primitive data type. An instance of a wrapper class
contains, or wraps, a primitive value of the corresponding type.
Following table lists the primitive types and the corresponding wrapper classes:
Primitive Wrapper
boolean java.lang.Boolean
byte java.lang.Byte
char java.lang.Character
double java.lang.Double
float java.lang.Float
int java.lang.Integer
long java.lang.Long
short java.lang.Short
void java.lang.Void
J2EE interview questions
What makes J2EE suitable for distributed multitiered Applications?
- The J2EE platform uses a multitiered distributed application model. Application logic is divided into
components according to function, and the various application components that make up a J2EE
application are installed on different machines depending on the tier in the multitiered J2EE
environment to which the application component belongs. The J2EE application parts are:
1. Client-tier components run on the client machine.
2. Web-tier components run on the J2EE server.
3. Business-tier components run on the J2EE server.
4. Enterprise information system (EIS)-tier software runs on the EIS server.

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 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:
1. Application clients and applets are client components.
2. Java Servlet and JavaServer Pages technology components are web components.
3. Enterprise JavaBeans components (enterprise beans) are business components.
4. Resource adapter components provided by EIS and tool vendors.

What do Enterprise JavaBeans components contain? - Enterprise JavaBeans components contains


Business code, which is logic that solves or meets the needs of a particular business domain such as
banking, retail, or finance, is handled by enterprise beans running in the business tier. All the business
code is contained inside an Enterprise Bean which receives data from client programs, processes it (if
necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also
retrieves data from storage, processes it (if necessary), and sends it back to the client program.

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 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. For example, an enterprise
bean module deployment descriptor declares transaction attributes and security authorizations for an
enterprise bean. Because deployment descriptor information is declarative, it can be changed without
modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts
upon the component accordingly.

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.

Java Swing interview questions


1) Can a class be it’s own event handler? Explain how to implement this.
Answer: Sure. an example could be a class that extends Jbutton and implements ActionListener. In the
actionPerformed method, put the code to perform when the button is pressed.

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.

3) How would you create a button with rounded edges?


Answer: there’s 2 ways. The first thing is to know that a JButton’s edges are drawn by a Border. so you
can override the Button’s paintComponent(Graphics) method and draw a circle or rounded rectangle
(whatever), and turn off the border. Or you can create a custom border that draws a circle or rounded
rectangle around any component and set the button’s border to it.
4) If I wanted to use a SolarisUI for just a JTabbedPane, and the Metal UI for everything else, how
would I do that?
Answer: in the UIDefaults table, override the entry for tabbed pane and put in the SolarisUI delegate. (I
don’t know it offhand, but I think it’s "com.sun.ui.motiflookandfeel.MotifTabbedPaneUI" - anything
simiar is a good answer.)

5) What is the difference between the ‘Font’ and ‘FontMetrics’ class?


Answer: The Font Class is used to render ‘glyphs’ - the characters you see on the screen. FontMetrics
encapsulates information about a specific font on a specific Graphics object. (width of the characters,
ascent, descent)
6) What class is at the top of the AWT event hierarchy?
Answer: java.awt.AWTEvent. if they say java.awt.Event, they haven’t dealt with swing or AWT in a
while.

7) Explain how to render an HTML page using only Swing.


Answer: Use a JEditorPane or JTextPane and set it with an HTMLEditorKit, then load the text into the
pane.

8) How would you detect a keypress in a JComboBox?


Answer: This is a trick. most people would say ‘add a KeyListener to the JComboBox’ - but the right
answer is ‘add a KeyListener to the JComboBox’s editor component.’

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?

11) Why would you use SwingUtilities.invokeAndWait or SwingUtilities.invokeLater?


A: I want to update a Swing component but I’m not in a callback. If I want the update to happen
immediately (perhaps for a progress bar component) then I’d use invokeAndWait. If I don’t care when
the update occurs, I’d use invokeLater.

12) If your UI seems to freeze periodically, what might be a likely reason?


A: A callback implementation like ActionListener.actionPerformed or MouseListener.mouseClicked is
taking a long time to execute thereby blocking the event dispatch thread from processing other UI
events.

13) Which Swing methods are thread-safe?


A: The only thread-safe methods are repaint(), revalidate(), and invalidate()

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.

Java interview questions


Q1: What are the advantages of OOPL?
Ans: Object oriented programming languages directly represent the real life objects. The features of
OOPL as inhreitance, polymorphism, encapsulation makes it powerful.
Q3: What do you mean by static methods?
Ans: 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.
Q4: What do you mean by virtual methods?
Ans: 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.
Q6: What are the disadvantages of using threads?
Ans: DeadLock.

Q2: What do you mean by multiple inheritance in C++ ?


Ans: 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.
Q3: Can you write Java code for declaration of multiple inheritance in Java ?
Ans: Class C extends A implements B
{
}

Java software engineering interview questions


Question 1: What is the three tier model?
Answer: It is the presentation, logic, backend

Question 2: Why do we have index table in the database?


Answer: Because the index table contain the information of the other tables. It will
be faster if we access the index table to find out what the other contain.

Question 3: Give an example of using JDBC access the database.


Answer:
try
{
Class.forName("register the driver");
Connection con = DriverManager.getConnection("url of db", "username","password");
Statement state = con.createStatement();
state.executeUpdate("create table testing(firstname varchar(20), lastname varchar(20))");
state.executeQuery("insert into testing values(’phu’,'huynh’)");
state.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}

Question 4: What is the different of an Applet and a Java Application


Answer: The applet doesn’t have the main function

Question 5: How do we pass a reference parameter to a function in Java?


Answer: Even though Java doesn’t accept reference parameter, but we can pass in the object for the
parameter of the function. For example in C++, we can do this:
void changeValue(int& a)
{ a++; }
void main()
{ int b=2;
changeValue(b);
}
however in Java, we cannot do the same thing. So we can pass the the int value into Integer object, and
we pass this object into the the function. And this function will change the object.

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


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

2) Describe synchronization in respect to multithreading.


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.

3) How is JavaBeans differ from Enterprise JavaBeans?


The JavaBeans architecture is meant to provide a format for general-purpose components. On the
other hand, the Enterprise JavaBeans architecture provides a format for highly specialized business
logic components.

4) In what ways do design patterns help build better software?


Design patterns helps software developers to reuse successful designs and architectures. It helps them
to choose design alternatives that make a system reusuable and avoid alternatives that compromise
reusability through proven techniques as design patterns.

5) Describe 3-Tier Architecture in enterprise application development.


In 3-tier architecture, an application is broken up into 3 separate logical layers, each with a well-defined
set of interfaces. The presentation layer typically consists of a graphical user interfaces. The business
layer consists of the application or business logic, and the data layer contains the data that is needed
for the application.

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.

Java Web programming interview questions


What is a Servlet?
Answer: Servlets are modules of Java code that run in a server application (hence the name "Servlets",
similar to "Applets" on the client side) to answer client requests.
How is Java unlike C++? (Asked by Sun)
Answer: Some language features of C++ have been removed. String manipulations in Java do not allow
for buffer overflows and other typical attacks. OS-specific calls are not advised, but you can still call
native methods. Everything is a class in Java. Everything is compiled to Java bytecode, not executable
(although that is possible with compiler tools).

1. Why do you prefer Java?


Answer: write once ,run anywhere.

2. Name some of the classes which provide the functionality of collation?


Answer: collator, rulebased collator, collationkey, collationelement iterator.

3. Awt stands for? and what is it?


Answer: AWT stands for Abstract window tool kit. It is a is a package that provides an integrated set of
classes to manage user interface components.

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.

How can you write a loop indefinitely?


for(;;) //for loop while(true); //always true

Can an anonymous class be declared as implementing an interface and extending a class? An


anonymous class may implement an interface or extend a superclass, but may not be declared to do
both.

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.

Servlet interview questions


What is a servlet?
Servlets are modules that extend request/response-oriented servers,such as Java-enabled web servers.
For example, a servlet might be responsible for taking data in an HTML order-entry form and applying
the business logic used to update a company’s order database. Servlets are to servers what applets are
to browsers. Unlike applets, however, servlets have no graphical user interface.
Whats the advantages using servlets over using CGI?
Servlets provide a way to generate dynamic documents that is both easier to write and faster to run.
Servlets also address the problem of doing server-side programming with platform-specific APIs: they
are developed with the Java Servlet API, a standard Java extension.

What are the general advantages and selling points of Servlets?


A servlet can handle multiple requests concurrently, and synchronize requests. This allows servlets to
support systems such as online real-time conferencing. Servlets can forward requests to other servers
and servlets. Thus servlets can be used to balance load among several servers that mirror the same
content, and to partition a single logical service over several servers, according to task type or
organizational boundaries.
Which package provides interfaces and classes for writing servlets? javax

What’s the Servlet Interface?


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

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 information does ServletRequest allow access to?


Information such as the names of the parameters passed in by the client, the protocol (scheme) being
used by the client, and the names of the remote host that made the request and the server that
received it. Also the input stream, as ServletInputStream.Servlets use the input stream to get data from
clients that use application protocols such as the HTTP POST and GET methods.

What type of constraints can ServletResponse interface set on the client?


It can set the content length and MIME type of the reply. It also provides an output stream,
ServletOutputStream and a Writer through which the servlet can send the reply data.

Explain servlet lifecycle?


Each servlet has the same life cycle: first, the server loads and initializes the servlet (init()), then the
servlet handles zero or more client requests (service()), after that the server removes the servlet
(destroy()). Worth noting that the last step on some servers is done when they shut down.

How does HTTP Servlet handle client requests?


An HTTP Servlet handles client requests through its service method. The service method supports
standard HTTP client requests by dispatching each request to a method designed to handle that
request.

Java applet interview questions


What is an Applet? Should applets have constructors?
- Applets are small programs transferred through Internet, automatically installed and run as part of
web-browser. Applets implements functionality of a client. Applet is a dynamic and interactive program
that runs inside a Web page displayed by a Java-capable browser. We don’t have the concept of
Constructors in Applets. Applets can be invoked either through browser or through Appletviewer utility
provided by JDK.

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.

Java AWT interview questions


Thanks to Sachin Rastogi for contributing these.
What is meant by Controls and what are different types of controls? - Controls are componenets that
allow a user to interact with your application. The AWT supports the following types of controls:
Labels
Push buttons
Check boxes
Choice lists
Lists
Scroll bars
Text components
These controls are subclasses of Component.
Which method of the component class is used to set the position and the size of a component? -
setBounds(). The following code snippet explains this:
txtName.setBounds(x,y,width,height);
places upper left corner of the text field txtName at point (x,y) with the width and height of the text
field set as width and height.
Which TextComponent method is used to set a TextComponent to the read-only state? - setEditable()
How can the Checkbox class be used to create a radio button? - By associating Checkbox objects with
a CheckboxGroup.
What methods are used to get and set the text label displayed by a Button object? - getLabel( ) and
setLabel( )
What is the difference between a Choice and a List? - Choice: A Choice is displayed in a compact form
that requires you to pull it down to see the list of available choices. Only one item may be selected
from a Choice. List: A List may be displayed in such a way that several List items are visible. A List
supports the selection of one or more List items.
What is the difference between a Scollbar and a Scrollpane? - A Scrollbar is a Component, but not a
Container. A Scrollpane is a Container and handles its own events and performs its own scrolling.
Which are true about the Container class?
The validate( ) method is used to cause a Container to be laid out and redisplayed.
The add( ) method is used to add a Component to a Container.
The getBorder( ) method returns information about a Container’s insets.
getComponent( ) method is used to access a Component that is contained in a Container.
Answers: a, b and d
Suppose a Panel is added to a Frame and a Button is added to the Panel. If the Frame’s font is set to
12-point TimesRoman, the Panel’s font is set to 10-point TimesRoman, and the Button’s font is not
set, what font will be used to display the Button’s label?
12-point TimesRoman
11-point TimesRoman
10-point TimesRoman
9-point TimesRoman
Answer: c.
What are the subclasses of the Container class? - The Container class has three major subclasses. They
are:
Window
Panel
ScrollPane
Which object is needed to group Checkboxes to make them exclusive? - CheckboxGroup.
What are the types of Checkboxes and what is the difference between them? - Java supports two
types of Checkboxes:
Exclusive
Non-exclusive.
In case of exclusive Checkboxes, only one among a group of items can be selected at a time. I f an item
from the group is selected, the checkbox currently checked is deselected and the new selection is
highlighted. The exclusive Checkboxes are also called as Radio buttons. The non-exclusive checkboxes
are not grouped together and each one can be selected independent of the other.
What is a Layout Manager and what are the different Layout Managers available in java.awt and
what is the default Layout manager for the panel and the panel subclasses? - A layout Manager is an
object that is used to organize components in a container. The different layouts available in java.awt
are:
FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion.
BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East and
West) and the center of a container.
CardLayout: The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.
GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid.
GridBagLayout:
The elements of a GridBagLayout are organized according to a grid.However, the elements are of
different sizes and may occupy more
than one row or column of the grid. In addition, the rows and columns may have different sizes.
The default Layout Manager of Panel and Panel sub classes is FlowLayout.
Can I add the same component to more than one container? - No. Adding a component to a container
automatically removes it from any previous parent (container).
How can we create a borderless window? - Create an instance of the Window class, give it a size, and
show it on the screen.
Frame aFrame = new Frame();
Window aWindow = new Window(aFrame);
aWindow.setLayout(new FlowLayout());
aWindow.add(new Button("Press Me"));
aWindow.getBounds(50,50,200,200);
aWindow.show();
Can I create a non-resizable windows? If so, how? - Yes. By using setResizable() method in class Frame.
Which containers use a BorderLayout as their default layout? Which containers use a FlowLayout as
their default layout? - The Window, Frame and Dialog classes use a BorderLayout as their default
layout. The Panel and the Applet classes use the FlowLayout as their default layout.
How do you change the current layout manager for a container?
Use the setLayout method
Once created you cannot change the current layout manager of a component
Use the setLayoutManager method
Use the updateLayout method
Answer: a.
What is the difference between a MenuItem and a CheckboxMenuItem?- The CheckboxMenuItem
class extends the MenuItem class to support a menu item that may be checked or unchecked.

Basic Java servlet interview questions


What is the difference between CGI and Servlet?
What is meant by a servlet?
What are the types of servlets? What is the difference between 2 types of Servlets?
What is the type of method for sending request from HTTP server ?
What are the exceptions thrown by Servlets? Why?
What is the life cycle of a servlet?
What is meant by cookies? Why is Cookie used?
What is HTTP Session?
What is the difference between GET and POST methods?
How can you run a Servlet Program?
What is the middleware? What is the functionality of Webserver?
What webserver is used for running the Servlets?
How do you invoke a Servelt? What is the difference in between doPost and doGet methods?
What is the difference in between the HTTPServlet and Generic Servlet? Explain their methods? Tell me
their parameter names also?
What are session variable in Servlets?
What is meant by Session? Tell me something about HTTPSession Class?
What is Session Tracking?
Difference between doGet and doPost?
What are the methods in HttpServlet?
What are the types of SessionTracking? Why do you use Session Tracking in HttpServlet?

J2EE interview questions


Thanks to Sachin Rastogi for contributing these.
What makes J2EE suitable for distributed multitiered Applications?
- The J2EE platform uses a multitiered distributed application model. Application logic is divided into
components according to function, and the various application components that make up a J2EE
application are installed on different machines depending on the tier in the multitiered J2EE
environment to which the application component belongs. The J2EE application parts are:
Client-tier components run on the client machine.
Web-tier components run on the J2EE server.
Business-tier components run on the J2EE server.
Enterprise information system (EIS)-tier software runs on the EIS server.
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 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 Pages technology components are web components.
Enterprise JavaBeans components (enterprise beans) are business components.
Resource adapter components provided by EIS and tool vendors.
What do Enterprise JavaBeans components contain? - Enterprise JavaBeans components contains
Business code, which is logic
that solves or meets the needs of a particular business domain such as banking, retail, or finance, is
handled by enterprise beans running in the business tier. All the business code is contained inside an
Enterprise Bean which receives data from client programs, processes it (if necessary), and sends it to
the enterprise information system tier for storage. An enterprise bean also retrieves data from storage,
processes it (if necessary), and sends it back to the client program.
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? - IManages 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:
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. For example, an enterprise
bean module deployment descriptor declares transaction attributes and security authorizations
for an enterprise bean. Because deployment descriptor information is declarative, it can be changed
without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor
and acts upon the component accordingly.
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.
Java GUI designer interview questions
What advantage do Java’s layout managers provide over traditional windowing systems? - Java uses
layout managers to lay out components in a consistent manner across all windowing platforms. Since
Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accomodate
platform-specific differences among windowing systems.
What is the difference between the paint() and repaint() methods? - The paint() method supports
painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT
painting thread.
How can the Checkbox class be used to create a radio button? - By associating Checkbox objects with
a CheckboxGroup
What is the difference between a Choice and a List? - A Choice is displayed in a compact form that
requires you to pull it down to see the list of available choices. Only one item may be selected from a
Choice. A List may be displayed in such a way that several List items are visible. A List supports the
selection of one or more List items.
What interface is extended by AWT event listeners? - All AWT event listeners extend the
java.util.EventListener interface.
What is a layout manager? - A layout manager is an object that is used to organize components in a
container
Which Component subclass is used for drawing and painting? - Canvas
What are the problems faced by Java programmers who dont use layout managers? - Without layout
managers, Java programmers are faced with determining how their GUI will be displayed across
multiple windowing systems and finding a common sizing and positioning that will work within the
constraints imposed by each windowing system
What is the difference between a Scrollbar and a ScrollPane? (Swing) - A Scrollbar is a Component,
but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its
own scrolling.
Java interview questions
What is the Collections API? - The Collections API is a set of classes and interfaces that support
operations on collections of objects
What is the List interface? - The List interface provides support for ordered collections of objects.
What is the Vector class? - The Vector class provides the capability to implement a growable array of
objects
What is an Iterator interface? - The Iterator interface is used to step through the elements of a
Collection
Which java.util classes and interfaces support event handling? - The EventObject class and the
EventListener interface support event processing
What is the GregorianCalendar class? - The GregorianCalendar provides support for traditional
Western calendars
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 is the SimpleTimeZone class? - The SimpleTimeZone class provides support for a Gregorian
calendar
What is the Map interface? - The Map interface replaces the JDK 1.1 Dictionary class and is used
associate keys with values
What is the highest-level event class of the event-delegation model? - The java.util.EventObject class
is the highest-level class in the event-delegation class hierarchy
What is the Collection interface? - The Collection interface provides support for the implementation of
a mathematical bag - an unordered collection of objects that may contain duplicates
What is the Set interface? - The Set interface provides methods for accessing the elements of a finite
mathematical set. Sets do not allow duplicate elements
What is the purpose of the enableEvents() method? - The enableEvents() method is used to enable an
event for a particular object. Normally, an event is enabled when a listener is added to an object for a
particular event. The enableEvents() method is used by objects that handle events by overriding their
event-dispatch methods.
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.
What is the difference between yielding and sleeping? - When a task invokes its yield() method, it
returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.
When a thread blocks on I/O, what state does it enter? - A thread enters the waiting state when it
blocks on I/O.
When a thread is created and started, what is its initial state? - A thread is in the ready state after it
has been created and started.
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 method is invoked to cause an object to begin executing as a separate thread? - The start()
method of the Thread class is invoked to cause an object to begin executing as a separate thread.
What is the purpose of the wait(), notify(), and notifyAll() methods? - The wait(),notify(), and
notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource.
When a thread executes an object’s wait() method, it enters the waiting state. It only enters the ready
state after another thread invokes the object’s notify() or notifyAll() methods.
What are the high-level thread states? - The high-level thread states are ready, running, waiting, and
dead
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.
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.
What happens when you invoke a thread’s interrupt method while it is sleeping or waiting? - When a
task’s interrupt() method is executed, the task enters the ready state. The next time the task enters the
running state, an InterruptedException is thrown.
What state is a thread in when it is executing? - An executing thread is in the running state
What are three ways in which a thread can enter the waiting state? - A thread can enter the waiting
state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an
object’s lock, or by invoking an object’s wait() method. It can also enter the waiting state by invoking its
(deprecated) suspend() method.
What method must be implemented by all threads? - All tasks must implement the run() method,
whether they are a subclass of Thread or implement the Runnable interface.
What are the two basic ways in which classes that can be run as threads may be defined? - A thread
class may be declared as a subclass of Thread, or it may implement the Runnable interface.
How can you store international / Unicode characters into a cookie? - One way is, before storing the
cookie URLEncode it. URLEnocder.encoder(str); And use URLDecoder.decode(str) when you get the
stored cookie.
Common JSP interview questions
What are the implicit objects? - Implicit objects are objects that are created by the web container and
contain information related to a particular request, page, or application. They are: request, response,
pageContext, session, application, out, config, page, exception.
Is JSP technology extensible? - Yes. JSP technology is extensible through the development of custom
actions, or tags, which are encapsulated in tag libraries.
How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using
it? - You can make your JSPs thread-safe by having them implement the SingleThreadModel interface.
This is done by adding the directive <%@ page isThreadSafe="false" %> within your JSP page. With this,
instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have
N instances of the servlet loaded and initialized, with the service method of each instance effectively
synchronized. You can typically control the number of instances (N) that are instantiated for all servlets
implementing SingleThreadModel through the admin screen for your JSP engine. More importantly,
avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as
mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race
condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including
the example above of not being able to use <%! %>. You should try really hard to make them thread-
safe the old fashioned way: by making them thread-safe
How does JSP handle run-time exceptions? - You can use the errorPage attribute of the page directive
to have uncaught run-time exceptions automatically forwarded to an error processing page. For
example: <%@ page errorPage="error.jsp" %>
redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request
processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@
page isErrorPage="true" %> Throwable object describing the exception may be accessed within the
error page via the exception implicit object. Note: You must always use a relative URL as the value for
the errorPage attribute.
How do I prevent the output of my JSP or Servlet pages from being cached by the browser? - You will
need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP
page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP
pages to prevent them from being cached at the browser. You need both the statements to take care of
some of the older browser versions.
<%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>
How do I use comments within a JSP page? - You can use “JSP-style” comments to selectively block out
code while debugging or simply to comment your scriptlets. JSP comments are not visible at the client.
For example:
<%-- the scriptlet is now commented out
<%
out.println("Hello World");
%>
--%>
You can also use HTML-style comments anywhere within your JSP page. These comments are visible at
the client. For example:
<!-- (c) 2004 -->
Of course, you can also use comments supported by your JSP scripting language within your scriptlets.
For example, assuming Java is the scripting language, you can have:
<%
//some comment
/**
yet another comment
**/
%>
Response has already been commited error. What does it mean? - This error show only when you try
to redirect a page after you already have written something in your page. This happens because HTTP
specification force the header to be set up before the lay out of the page can be shown (to make sure
of how it should be displayed, content-type="text/html” or “text/xml” or “plain-text” or “image/jpg",
etc.) When you try to send a redirect status (Number is line_status_402), your HTTP server cannot send
it right now if it hasn’t finished to set up the header. If not starter to set up the header, there are no
problems, but if it ’s already begin to set up the header, then your HTTP server expects these headers
to be finished setting up and it cannot be the case if the stream of the page is not over… In this last case
it’s like you have a file started with <HTML Tag><Some Headers><Body>some output (like testing your
variables.) Before you indicate that the file is over (and before the size of the page can be setted up in
the header), you try to send a redirect status. It s simply impossible due to the specification of HTTP 1.0
and 1.1
How do I use a scriptlet to initialize a newly instantiated bean? - A jsp:useBean action may optionally
have a body. If the body is specified, its contents will be automatically invoked when the specified bean
is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly
instantiated bean, although you are not restricted to using those alone.
The following example shows the “today” property of the Foo bean initialized to the current date when
it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.
<jsp:useBean id="foo" class="com.Bar.Foo" >
<jsp:setProperty name="foo" property="today"
value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>"/ >
<%-- scriptlets calling bean setter methods go here --%>
</jsp:useBean >
How can I enable session tracking for JSP pages if the browser has disabled cookies? - We know that
session tracking uses cookies by default to associate a session identifier with a unique user. If the
browser does not support cookies, or if cookies are disabled, you can still enable session tracking using
URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value
pair. However, for this to be effective, you need to append the session ID for each and every link that is
part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a
couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using
redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both
encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the
browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie.
Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each
other. Basically, we create a new session within hello1.jsp and place an object within this session. The
user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we
simply extract the object that was earlier placed in the session and display its contents. Notice that we
invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled,
the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session
object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and
try again. Each time you should see the maintenance of the session across pages. Do note that to get
this example to work with cookies disabled at the browser, your JSP engine has to support URL
rewriting.
hello1.jsp
<%@ page session="true" %>
<%
Integer num = new Integer(100);
session.putValue("num",num);
String url =response.encodeURL("hello2.jsp");
%>
<a href='<%=url%>'>hello2.jsp</a>
hello2.jsp
<%@ page session="true" %>
<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is "+i.intValue());
How can I declare methods within my JSP page? - You can declare methods for use within your JSP
page as declarations. The methods can then be invoked within any other methods you declare, or
within JSP scriptlets and expressions. Do note that you do not have direct access to any of the JSP
implicit objects like request, response, session and so forth from within JSP methods. However, you
should be able to pass any of the implicit JSP variables as parameters to the methods you declare. For
example:
<%!
public String whereFrom(HttpServletRequest req) {
HttpSession ses = req.getSession();
...
return req.getRemoteHost();
}
%>
<%
out.print("Hi there, I see that you are coming in from ");
%>
<%= whereFrom(request) %>
Another Example
file1.jsp:
<%@page contentType="text/html"%>
<%!
public void test(JspWriter writer) throws IOException{
writer.println("Hello!");
}
%>
file2.jsp
<%@include file="file1.jsp"%>
<html>
<body>
<%test(out);% >
</body>
</html>
Is there a way I can set the inactivity lease period on a per-session basis? - Typically, a default inactivity
lease period for all sessions is set within your JSP engine admin screen or associated properties file.
However, if your JSP engine supports the Servlet 2.1 API, you can manage the inactivity lease period on
a per-session basis. This is done by invoking the HttpSession.setMaxInactiveInterval() method, right
after the session has been created. For example:
<%
session.setMaxInactiveInterval(300);
%>
would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds.
How can I set a cookie and delete a cookie from within a JSP page? - A cookie, mycookie, can be
deleted using the following scriptlet:
<%
//creating a cookie
Cookie mycookie = new Cookie("aName","aValue");
response.addCookie(mycookie);
//delete a cookie
Cookie killMyCookie = new Cookie("mycookie", null);
killMyCookie.setMaxAge(0);
killMyCookie.setPath("/");
response.addCookie(killMyCookie);
%>
How does a servlet communicate with a JSP page? - The following code snippet shows how a servlet
instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into
the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request
dispatcher for downstream processing.
public void doPost (HttpServletRequest request, HttpServletResponse response) {
try {
govi.FormBean f = new govi.FormBean();
String id = request.getParameter("id");
f.setName(request.getParameter("name"));
f.setAddr(request.getParameter("addr"));
f.setAge(request.getParameter("age"));
//use the id to compute
//additional bean properties like info
//maybe perform a db query, etc.
// . . .
f.setPersonalizationInfo(info);
request.setAttribute("fBean",f);
getServletConfig().getServletContext().getRequestDispatcher
("/jsp/Bean1.jsp").forward(request, response);
} catch (Exception ex) {
...
}
}
The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope
via the useBean action.
jsp:useBean id="fBean" class="govi.FormBean" scope="request"
/ jsp:getProperty name="fBean" property="name"
/ jsp:getProperty name="fBean" property="addr"
/ jsp:getProperty name="fBean" property="age"
/ jsp:getProperty name="fBean" property="personalizationInfo" /
How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the
default? - One should be very careful when having JSP pages extend custom servlet classes as opposed
to the default one generated by the JSP engine. In doing so, you may lose out on any advanced
optimization that may be provided by the JSP engine. In any case, your new superclass has to fulfill the
contract with the JSP engine by:
Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage
otherwise Ensuring that all the methods in the Servlet interface are declared final Additionally, your
servlet superclass also needs to do the following:
The service() method has to invoke the _jspService() method
The init() method has to invoke the jspInit() method
The destroy() method has to invoke jspDestroy()
If any of the above conditions are not satisfied, the JSP engine may throw a translation error.
Once the superclass has been developed, you can have your JSP extend it as follows:
<%@ page extends="packageName.ServletName" %>
How can I prevent the word "null" from appearing in my HTML input text fields when I populate
them with a resultset that has null values? - You could make a simple wrapper function, like
<%!
String blanknull(String s) {
return (s == null) ? "" : s;
}
%>
then use it inside your JSP form, like
<input type="text" name="shoesize" value="<%=blanknull(shoesize)% >" >
How can I get to print the stacktrace for an exception occuring within my JSP page? - By printing out
the exception’s stack trace, you can usually diagonse a problem better when debugging JSP pages. By
looking at a stack trace, a programmer should be able to discern which method threw the exception
and which method called that method. However, you cannot print the stacktrace using the JSP out
implicit variable, which is of type JspWriter. You will have to use a PrintWriter object instead. The
following snippet demonstrates how you can print a stacktrace from within a JSP error page:
<%@ page isErrorPage="true" %>
<%
out.println(" ");
PrintWriter pw = response.getWriter();
exception.printStackTrace(pw);
out.println(" ");
%>
How do you pass an InitParameter to a JSP? - The JspPage interface defines the jspInit() and
jspDestroy() method which the page writer can use in their pages and are invoked in much the same
manner as the init() and destory() methods of a servlet. The example page below enumerates through
all the parameters and prints them to the console.
<%@ page import="java.util.*" %>
<%!
ServletConfig cfg =null;
public void jspInit(){
ServletConfig cfg=getServletConfig();
for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) {
String name=(String)e.nextElement();
String value = cfg.getInitParameter(name);
System.out.println(name+"="+value);
}
}
%>
How can my JSP page communicate with an EJB Session Bean? - The following is a code snippet that
demonstrates how a JSP page can interact with an EJB session bean:
<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome,
foo.Account" %>
<%!
//declare a "global" reference to an instance of the home interface of the session bean
AccountHome accHome=null;
public void jspInit() {
//obtain an instance of the home interface
InitialContext cntxt = new InitialContext( );
Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
}
%>
<%
//instantiate the session bean
Account acct = accHome.create();
//invoke the remote methods
acct.doWhatever(...);
// etc etc...
%>
Java Web development interview questions
Can we use the constructor, instead of init(), to initialize servlet? - Yes , of course you can use the
constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for
init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so
there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers
still will only call your no-arg constructor. So you won’t have access to a ServletConfig or
ServletContext.
How can a servlet refresh automatically if some new data has entered the database? - You can use a
client-side Refresh or Server Push.
The code in a finally clause will never fail to execute, right? - Using System.exit(1); in try block will not
allow finally code to execute.
How may messaging models do JMS provide for and what are they? - JMS provide for two messaging
models, publish-and-subscribe and point-to-point queuing.
What information is needed to create a TCP Socket? - The Local System?s IP Address and Port Number.
And the Remote System’s IPAddress and Port Number.
What Class.forName will do while loading drivers? - It is used to create an instance of a driver and
register it with the DriverManager. When you have loaded a driver, it is available for making a
connection with a DBMS.
How to Retrieve Warnings? - SQLWarning objects are a subclass of SQLException that deal with
database access warnings. Warnings do not stop the execution of an application, as exceptions do; they
simply alert the user that something did not happen as planned. A warning can be reported on a
Connection object, a Statement object (including PreparedStatement and CallableStatement objects),
or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order
to see the first warning reported on the calling object
SQLWarning warning = stmt.getWarnings();
if (warning != null)
{
while (warning != null)
{
System.out.println("Message: " + warning.getMessage());
System.out.println("SQLState: " + warning.getSQLState());
System.out.print("Vendor error code: ");
System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}
How many JSP scripting elements are there and what are they? - There are three scripting language
elements: declarations, scriptlets, expressions.
In the Servlet 2.4 specification SingleThreadModel has been deprecates, why? - Because it is not
practical to have such model. Whether you set isThreadSafe to true or false, you should take care of
concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the
page level.
What are stored procedures? How is it useful? - A stored procedure is a set of statements/commands
which reside in the database. The stored procedure is precompiled and saves the database the effort of
parsing and compiling sql statements everytime a query is run. Each Database has it’s own stored
procedure language, usually a variant of C with a SQL preproceesor. Newer versions of db’s support
writing stored procedures in Java and Perl too. Before the advent of 3-tier/n-tier architecture it was
pretty common for stored procs to implement the business logic( A lot of systems still do it). The
biggest advantage is of course speed. Also certain kind of data manipulations are not achieved in SQL.
Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when you
want to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC
Connection may be significant in these cases.
How do I include static files within a JSP page? - Static resources should always be included using the
JSP include directive. This way, the inclusion is performed just once during the translation phase. The
following example shows the syntax: Do note that you should always supply a relative URL for the file
attribute. Although you can also include static resources using the action, this is not advisable as the
inclusion is then performed for each and every request.
Why does JComponent have add() and remove() methods but Component does not? - because
JComponent is a subclass of Container, and can contain other components and jcomponents.
How can I implement a thread-safe JSP page? - You can make your JSPs thread-safe by having them
implement the SingleThreadModel interface. This is done by adding the directive <%@ page
isThreadSafe="false" % > within your JSP page.
EJB interview questions
Is is possible for an EJB client to marshal an object of class java.lang.Class to an EJB? - Technically yes,
spec. compliant NO! - The enterprise bean must not attempt to query a class to obtain information
about the declared members that are not otherwise accessible to the enterprise bean because of the
security rules of the Java language.
Is it legal to have static initializer blocks in EJB? - Although technically it is legal, static initializer blocks
are used to execute some piece of code before executing any constructor or method while instantiating
a class. Static initializer blocks are also typically used to initialize static fields - which may be illegal in
EJB if they are read/write - In EJB this can be achieved by including the code in either the ejbCreate(),
setSessionContext() or setEntityContext() methods.
Is it possible to stop the execution of a method before completion in a SessionBean? - Stopping the
execution of a method inside a Session Bean is not possible without writing code inside the Session
Bean. This is because you are not allowed to access Threads inside an EJB.
What is the default transaction attribute for an EJB? - There is no default transaction attribute for an
EJB. Section 11.5 of EJB v1.1 spec says that the deployer must specify a value for the transaction
attribute for those methods having container managed transaction. In WebLogic, the default
transaction attribute for EJB is SUPPORTS.
What is the difference between session and entity beans? When should I use one or the other? - An
entity bean represents persistent global data from the database; a session bean represents transient
user-specific data that will die when the user disconnects (ends his session). Generally, the session
beans implement business methods (e.g. Bank.transferFunds) that call entity beans (e.g.
Account.deposit, Account.withdraw)
Is there any default cache management system with Entity beans ? In other words whether a cache
of the data in database will be maintained in EJB ? - Caching data from a database inside the
Application Server are what Entity EJB’s are used for.The ejbLoad() and ejbStore() methods are used to
synchronize the Entity Bean state with the persistent storage(database). Transactions also play an
important role in this scenario. If data is removed from the database, via an external application - your
Entity Bean can still be “alive” the EJB container. When the transaction commits, ejbStore() is called and
the row will not be found, and the transaction rolled back.
Why is ejbFindByPrimaryKey mandatory? - An Entity Bean represents persistent data that is stored
outside of the EJB Container/Server. The ejbFindByPrimaryKey is a method used to locate and load an
Entity Bean into the container, similar to a SELECT statement in SQL. By making this method mandatory,
the client programmer can be assured that if they have the primary key of the Entity Bean, then they
can retrieve the bean without having to create a new bean each time - which would mean creating
duplications of persistent data and break the integrity of EJB.
Why do we have a remove method in both EJBHome and EJBObject? - With the EJBHome version of
the remove, you are able to delete an entity bean without first instantiating it (you can provide a
PrimaryKey object as a parameter to the remove method). The home version only works for entity
beans. On the other hand, the Remote interface version works on an entity bean that you have already
instantiated. In addition, the remote version also works on session beans (stateless and stateful) to
inform the container of your loss of interest in this bean.
How can I call one EJB from inside of another EJB? - EJBs can be clients of other EJBs. It just works. Use
JNDI to locate the Home Interface of the other bean, then acquire an instance reference, and so forth.
What is the difference between a Server, a Container, and a Connector? - An EJB server is an
application, usually a product such as BEA WebLogic, that provides (or should provide) for concurrent
client connections and manages system resources such as threads, processes, memory, database
connections, network connections, etc. An EJB container runs inside (or within) an EJB server, and
provides deployed EJB beans with transaction and security management, etc. The EJB container
insulates an EJB bean from the specifics of an underlying EJB server by providing a simple, standard API
between the EJB bean and its container. A Connector provides the ability for any Enterprise Information
System (EIS) to plug into any EJB server which supports the Connector architecture. See Sun’s J2EE
Connectors for more in-depth information on Connectors.
How is persistence implemented in enterprise beans? - Persistence in EJB is taken care of in two ways,
depending on how you implement your beans: container managed persistence (CMP) or bean managed
persistence (BMP) For CMP, the EJB container which your beans run under takes care of the persistence
of the fields you have declared to be persisted with the database - this declaration is in the deployment
descriptor. So, anytime you modify a field in a CMP bean, as soon as the method you have executed is
finished, the new data is persisted to the database by the container. For BMP, the EJB bean developer is
responsible for defining the persistence routines in the proper places in the bean, for instance, the
ejbCreate(), ejbStore(), ejbRemove() methods would be developed by the bean developer to make calls
to the database. The container is responsible, in BMP, to call the appropriate method on the bean. So, if
the bean is being looked up, when the create() method is called on the Home interface, then the
container is responsible for calling the ejbCreate() method in the bean, which should have functionality
inside for going to the database and looking up the data.
What is an EJB Context? - EJBContext is an interface that is implemented by the container, and it is also
a part of the bean-container contract. Entity beans use a subclass of EJBContext called EntityContext.
Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class
with information about its container, the client using the bean and the bean itself. They also provide
other functions. See the API docs and the spec for more details.
Is method overloading allowed in EJB? - Yes you can overload methods
Should synchronization primitives be used on bean methods? - No. The EJB specification specifically
states that the enterprise bean is not allowed to use thread primitives. The container is responsible for
managing concurrent access to beans at runtime.
Are we allowed to change the transaction isolation property in middle of a transaction? - No. You
cannot change the transaction isolation level in the middle of transaction.
For Entity Beans, What happens to an instance field not mapped to any persistent storage, when the
bean is passivated? - The specification infers that the container never serializes an instance of an Entity
bean (unlike stateful session beans). Thus passivation simply involves moving the bean from the
“ready” to the “pooled” bin. So what happens to the contents of an instance variable is controlled by
the programmer. Remember that when an entity bean is passivated the instance gets logically
disassociated from it’s remote object. Be careful here, as the functionality of passivation/activation for
Stateless Session, Stateful Session and Entity beans is completely different. For entity beans the
ejbPassivate method notifies the entity bean that it is being disassociated with a particular entity prior
to reuse or for dereference.
What is a Message Driven Bean, what functions does a message driven bean have and how do they
work in collaboration with JMS? - Message driven beans are the latest addition to the family of
component bean types defined by the EJB specification. The original bean types include session beans,
which contain business logic and maintain a state associated with client sessions, and entity beans,
which map objects to persistent data. Message driven beans will provide asynchrony to EJB based
applications by acting as JMS message consumers. A message bean is associated with a JMS topic or
queue and receives JMS messages sent by EJB clients or other beans. Unlike entity beans and session
beans, message beans do not have home or remote interfaces. Instead, message driven beans are
instantiated by the container as required. Like stateless session beans, message beans maintain no
client-specific state, allowing the container to optimally manage a pool of message-bean instances.
Clients send JMS messages to message beans in exactly the same manner as they would send messages
to any other JMS destination. This similarity is a fundamental design goal of the JMS capabilities of the
new specification. To receive JMS messages, message driven beans implement the
javax.jms.MessageListener interface, which defines a single “onMessage()” method. When a message
arrives, the container ensures that a message bean corresponding to the message topic/queue exists
(instantiating it if necessary), and calls its onMessage method passing the client’s message as the single
argument. The message bean’s implementation of this method contains the business logic required to
process the message. Note that session beans and entity beans are not allowed to function as message
beans.
Does RMI-IIOP support code downloading for Java objects sent by value across an IIOP connection in
the same way as RMI does across a JRMP connection? - Yes. The JDK 1.2 support the dynamic class
loading.
The EJB container implements the EJBHome and EJBObject classes. For every request from a unique
client, does the container create a separate instance of the generated EJBHome and EJBObject
classes? - The EJB container maintains an instance pool. The container uses these instances for the EJB
Home reference irrespective of the client request. while refering the EJB Object classes the container
creates a separate instance for each client request. The instance pool maintainence is up to the
implementation of the container. If the container provides one, it is available otherwise it is not
mandatory for the provider to implement it. Having said that, yes most of the container providers
implement the pooling functionality to increase the performance of the application server. The way it is
implemented is again up to the implementer.
What is the advantage of putting an Entity Bean instance from the “Ready State” to “Pooled state"? -
The idea of the “Pooled State” is to allow a container to maintain a pool of entity beans that has been
created, but has not been yet “synchronized” or assigned to an EJBObject. This mean that the instances
do represent entity beans, but they can be used only for serving Home methods (create or findBy),
since those methods do not relay on the specific values of the bean. All these instances are, in fact,
exactly the same, so, they do not have meaningful state. Jon Thorarinsson has also added: It can be
looked at it this way: If no client is using an entity bean of a particular type there is no need for cachig it
(the data is persisted in the database). Therefore, in such cases, the container will, after some time,
move the entity bean from the “Ready State” to the “Pooled state” to save memory. Then, to save
additional memory, the container may begin moving entity beans from the “Pooled State” to the “Does
Not Exist State", because even though the bean’s cache has been cleared, the bean still takes up some
memory just being in the “Pooled State".
Can a Session Bean be defined without ejbCreate() method? - The ejbCreate() methods is part of the
bean’s lifecycle, so, the compiler will not return an error because there is no ejbCreate() method.
However, the J2EE spec is explicit: the home interface of a Stateless Session Bean must have a single
create() method with no arguments, while the session bean class must contain exactly one ejbCreate()
method, also without arguments. Stateful Session Beans can have arguments (more than one create
method) stateful beans can contain multiple ejbCreate() as long as they match with the home interface
definition. You need a reference to your EJBObject to startwith. For that Sun insists on putting a method
for creating that reference (create method in the home interface). The EJBObject does matter here. Not
the actual bean.
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? - You can pass the HttpSession as parameter to an EJB method,
only if all objects in session are serializable.This has to be consider as “passed-by-value", that means
that it’s read-only in the EJB. If anything is altered from inside the EJB, it won’t be reflected back to the
HttpSession of the Servlet Container.The “pass-by-reference” can be used between EJBs Remote
Interfaces, as they are remote references. While it IS possible to pass an HttpSession as a parameter to
an EJB object, it is considered to be “bad practice (1)” in terms of object oriented design. This is
because you are creating an unnecessary coupling between back-end objects (ejbs) and front-end
objects (HttpSession). Create a higher-level of abstraction for your ejb’s api. Rather than passing the
whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a
value object (or structure) that holds all the data you need to pass back and forth between front-
end/back-end. Consider the case where your ejb needs to support a non-http-based client. This higher
level of abstraction will be flexible enough to support it. (1) Core J2EE design patterns (2001)
Is there any way to read values from an entity bean without locking it for the rest of the transaction
(e.g. read-only transactions)? We have a key-value map bean which deadlocks during some
concurrent reads. Isolation levels seem to affect the database only, and we need to work within a
transaction. - The only thing that comes to (my) mind is that you could write a ‘group accessor’ - a
method that returns a single object containing all of your entity bean’s attributes (or all interesting
attributes). This method could then be placed in a ‘Requires New’ transaction. This way, the current
transaction would be suspended for the duration of the call to the entity bean and the entity bean’s
fetch/operate/commit cycle will be in a separate transaction and any locks should be released
immediately. Depending on the granularity of what you need to pull out of the map, the group accessor
might be overkill.
What is the difference between a “Coarse Grained” Entity Bean and a “Fine Grained” Entity Bean? - A
‘fine grained’ entity bean is pretty much directly mapped to one relational table, in third normal form.
A ‘coarse grained’ entity bean is larger and more complex, either because its attributes include values
or lists from other tables, or because it ‘owns’ one or more sets of dependent objects. Note that the
coarse grained bean might be mapped to a single table or flat file, but that single table is going to be
pretty ugly, with data copied from other tables, repeated field groups, columns that are dependent on
non-key fields, etc. Fine grained entities are generally considered a liability in large systems because
they will tend to increase the load on several of the EJB server’s subsystems (there will be more objects
exported through the distribution layer, more objects participating in transactions, more skeletons in
memory, more EJB Objects in memory, etc.)
What is EJBDoclet? - EJBDoclet is an open source JavaDoc doclet that generates a lot of the EJB related
source files from custom JavaDoc comments tags embedded in the EJB source file.
Good questions asked during Java interview
Is “abc” a primitive value? - The String literal “abc” is not a primitive value. It is a String object.
What restrictions are placed on the values of each case of a switch statement? - During compilation,
the values of each case of a switch statement must evaluate to a value that can be promoted to an int
value.
What modifiers may be used with an interface declaration? - An interface may be declared as public
or abstract.
Is a class a subclass of itself? - A class is a subclass of itself.
What is the difference between a while statement and a do statement? - 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.
What modifiers can be used with a local inner class? - A local inner class may be final or abstract.
What is the purpose of the File class? - The File class is used to create objects that provide access to
the files and directories of a local file system.
Can an exception be rethrown? - Yes, an exception can be rethrown.
When does the compiler supply a default constructor for a class? - The compiler supplies a default
constructor for a class if no other constructors are provided.
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.
Which non-Unicode letter characters may be used as the first character of an identifier? - The non-
Unicode letter characters $ and _ may appear as the first character of an identifier
What restrictions are placed on method overloading? - Two methods may not have the same name
and argument list but different return types.
What is casting? - There are two types of casting, casting between primitive numeric types and casting
between object references. Casting between numeric types is used to convert larger values, such as
double values, to smaller values, such as byte values. Casting between object references is used to refer
to an object by a compatible class, interface, or array type reference.
What is the return type of a program’s main() method? - A program’s main() method has a void return
type.
What class of exceptions are generated by the Java run-time system? - The Java runtime system
generates RuntimeException and Error exceptions.
What class allows you to read objects directly from a stream? - The ObjectInputStream class supports
the reading of objects from input streams.
What is the difference between a field variable and a local variable? - A field variable is a variable that
is declared as a member of a class. A local variable is a variable that is declared local to a method.
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.
What is the relationship between a method’s throws clause and the exceptions that can be thrown
during the method’s execution? - A method’s throws clause must declare any checked exceptions that
are not caught within the body of the method.
Why are the methods of the Math class static? - So they can be invoked as if they are a mathematical
code library.
What are the legal operands of the instanceof operator? - The left operand is an object reference or
null value and the right operand is a class, interface, or array type.
What an I/O filter? - An I/O filter is an object that reads from one stream and writes to another, usually
altering the data in some way as it is passed from one stream to another.
If an object is garbage collected, can it become reachable again? - Once an object is garbage collected,
it ceases to exist. It can no longer become reachable again.
What are E and PI? - E is the base of the natural logarithm and PI is mathematical value pi.
Are true and false keywords? - The values true and false are not keywords.
What is the difference between the File and RandomAccessFile classes? - The File class encapsulates
the files and directories of the local file system. The RandomAccessFile class provides the methods
needed to directly access data contained in any part of a file.
What happens when you add a double value to a String? - The result is a String object.
What is your platform’s default character encoding? - If you are running Java on English Windows
platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely
8859_1.
Which package is always imported by default? - The java.lang package is always imported by default.
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.
How can my application get to know when a HttpSession is removed? - Define a Class
HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality
what you need in valueUnbound() method. Create an instance of that class and put that instance in
HttpSession.
Whats the difference between notify() and notifyAll()? - notify() is used to unblock one waiting thread;
notifyAll() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one
blocked thread can benefit from the change (for example, when freeing a buffer back into a pool).
notifyAll() is necessary (for correctness) if multiple threads should resume (for example, when releasing
a “writer” lock on a file might permit all “readers” to resume).
Why can’t I say just abs() or sin() instead of Math.abs() and Math.sin()? - The import statement does
not bring methods into your local name space. It lets you abbreviate class names, but not get rid of
them altogether. That’s just the way it works, you’ll get used to it. It’s really a lot safer this way.
However, there is actually a little trick you can use in some cases that gets you what you want. If your
top-level class doesn’t need to inherit from anything else, make it inherit from java.lang.Math. That
*does* bring all the methods into your local name space. But you can’t use this trick in an applet,
because you have to inherit from java.awt.Applet. And actually, you can’t use it on java.lang.Math at all,
because Math is a “final” class which means it can’t be extended.
Why are there no global variables in Java? - Global variables are considered bad form for a variety of
reasons: Adding state variables breaks referential transparency (you no longer can understand a
statement or expression on its own: you need to understand it in the context of the settings of the
global variables), State variables lessen the cohesion of a program: you need to know more to
understand how something works. A major point of Object-Oriented programming is to break up global
state into more easily understood collections of local state, When you add one variable, you limit the
use of your program to one instance. What you thought was global, someone else might think of as
local: they may want to run two copies of your program at once. For these reasons, Java decided to ban
global variables.
What does it mean that a class or member is final? - A final class can no longer be subclassed. Mostly
this is done for security reasons with basic classes like String and Integer. It also allows the compiler to
make some optimizations, and makes thread safety a little easier to achieve. Methods may be declared
final as well. This means they may not be overridden in a subclass. Fields can be declared final, too.
However, this has a completely different meaning. A final field cannot be changed after it’s initialized,
and it must include an initializer statement where it’s declared. For example, public final double c =
2.998; It’s also possible to make a static field final to get the effect of C++’s const statement or some
uses of C’s #define, e.g. public static final double c = 2.998;
What does it mean that a method or class is abstract? - An abstract class cannot be instantiated. Only
its subclasses can be instantiated. You indicate that a class is abstract with the abstract keyword like
this:
public abstract class Container extends Component {
Abstract classes may contain abstract methods. A method declared abstract is not actually
implemented in the current class. It exists only to be overridden in subclasses. It has no body. For
example,
public abstract float price();
Abstract methods may only be included in abstract classes. However, an abstract class is not required to
have any abstract methods, though most of them do. Each subclass of an abstract class must override
the abstract methods of its superclasses or itself be declared abstract.
What is a transient variable? - transient variable is a variable that may not be serialized.
How are Observer and Observable used? - Objects that subclass the Observable class maintain a list of
observers. When an Observable object is updated it invokes the update() method of each of its
observers to notify the observers that it has changed state. The Observer interface is implemented by
objects that observe Observable objects.
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 state does a thread enter when it terminates its processing? - When a thread terminates its
processing, it enters the dead state.
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 difference between the >> and >>> operators? - The >> operator carries the sign bit when
shifting right. The >>> zero-fills bits that have been shifted out.
Is sizeof a keyword? - The sizeof operator is not a keyword.
Does garbage collection guarantee that a program will not run out of memory? - 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
Can an object’s finalize() method be invoked while it is reachable? - An object’s finalize() method
cannot be invoked by the garbage collector while the object is still reachable. However, an object’s
finalize() method may be invoked by other objects.
What value does readLine() return when it has reached the end of a file? - The readLine() method
returns null when it has reached the end of a file.
Can a for statement loop indefinitely? - Yes, a for statement can loop indefinitely. For example,
consider the following: for(;;) ;
To what value is a variable of the String type automatically initialized? - The default value of an String
type is null.
What is a task’s priority and how is it used in scheduling? - A task’s priority is an integer value that
identifies the relative order in which it should be executed with respect to other tasks. The scheduler
attempts to schedule higher priority tasks before lower priority tasks.
What is the range of the short type? - The range of the short type is -(2^15) to 2^15 - 1.
What is the purpose of garbage collection? - The purpose of garbage collection is to identify and
discard objects that are no longer needed by a program so that their resources may be reclaimed and
reused.
What do you understand by private, protected and public? - These are accessibility modifiers. Private
is the most restrictive, while public is the least restrictive. There is no real difference between protected
and the default type (also known as package protected) within the context of the same package,
however the protected keyword allows visibility to a derived class in a different package.
What is Downcasting ? - Downcasting is the casting from a general to a more specific type, i.e. casting
down the hierarchy
Can a method be overloaded based on different return type but same argument type ? - No, because
the methods can be called without using their return type in which case there is ambiquity for the
compiler
What happens to a static var that is defined within a method of a class ? - Can’t do it. You’ll get a
compilation error
How many static init can you have ? - As many as you want, but the static initializers and class variable
initializers are executed in textual order and may not refer to class variables declared in the class whose
declarations appear textually after the use, even though these class variables are in scope.
What is the difference amongst JVM Spec, JVM Implementation, JVM Runtime ? - The JVM spec is the
blueprint for the JVM generated and owned by Sun. The JVM implementation is the actual
implementation of the spec by a vendor and the JVM runtime is the actual running instance of a JVM
implementation
Describe what happens when an object is created in Java? - Several things happen in a particular order
to ensure the object is constructed properly: Memory is allocated from heap to hold all instance
variables and implementation-specific data of the object and its superclasses. Implemenation-specific
data includes pointers to class and method data. The instance variables of the objects are initialized to
their default values. The constructor for the most derived class is invoked. The first thing a constructor
does is call the consctructor for its superclasses. This process continues until the constrcutor for
java.lang.Object is called, as java.lang.Object is the base class for all objects in java. Before the body of
the constructor is executed, all instance variable initializers and initialization blocks are executed. Then
the body of the constructor is executed. Thus, the constructor for the base class completes first and
constructor for the most derived class completes last.
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 the difference between instanceof and isInstance? - instanceof is used to check to see if an
object can be cast into a specified type without throwing a cast class exception. isInstance() Determines
if the specified Object is assignment-compatible with the object represented by this Class. This method
is the dynamic equivalent of the Java language instanceof operator. The method returns true if the
specified Object argument is non-null and can be cast to the reference type represented by this Class
object without raising a ClassCastException. It returns false otherwise.
Why does it take so much time to access an Applet having Swing Components the first time? -
Because behind every swing component are many Java objects and resources. This takes time to create
them in memory. JDK 1.3 from Sun has some improvements which may lead to faster execution of
Swing applications.
Junior Java programmer interview questions
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.
What is the difference between the Boolean & operator and the && operator? - If an expression
involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is
applied to the operand. When an expression involving the && operator is evaluated, the first operand is
evaluated. If the first operand returns a value of true then the second operand is evaluated. The &&
operator is then applied to the first and second operands. If the first operand evaluates to false, the
evaluation of the second operand is skipped.
How many times may an object’s finalize() method be invoked by the garbage collector? - An object’s
finalize() method may only be invoked once by the garbage collector.
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.
What is the argument type of a program’s main() method? - A program’s main() method takes an
argument of the String[] type.
Which Java operator is right associative? - The = operator is right associative.
Can a double value be cast to a byte? - Yes, a double value can be cast to a byte.
What is the difference between a break statement and a continue statement? - A break statement
results in the termination of the statement to which it applies (switch, for, do, or while). A continue
statement is used to end the current loop iteration and return control to the loop statement.
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.
What is the advantage of the event-delegation model over the earlier event-inheritance model? - The
event-delegation model has two advantages over the event-inheritance model. First, it enables event
handling to be handled by objects other than the ones that generate the events (or their containers).
This allows a clean separation between a component’s design and its use. The other advantage of the
event-delegation model is that it performs much better in applications where many events are
generated. This performance improvement is due to the fact that the event-delegation model does not
have to repeatedly process unhandled events, as is the case of the event-inheritance model.
How are commas used in the intialization and iteration parts of a for statement? - Commas are used
to separate multiple statements within the initialization and iteration parts of a for statement.
What is an abstract method? - An abstract method is a method whose implementation is deferred to a
subclass.
What value does read() return when it has reached the end of a file? - The read() method returns -1
when it has reached the end of a file.
Can a Byte object be cast to a double value? - No, an object cannot be cast to a primitive value.
What is the difference between a static and a non-static inner class? - A non-static inner class may
have object instances that are associated with instances of the class’s outer class. A static inner class
does not have any object instances.
If a variable is declared as private, where may the variable be accessed? - A private variable may only
be accessed within the class in which it is declared.
What is an object’s lock and which object’s have locks? - An object’s lock is a mechanism that is used
by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized
method of an object only after it has acquired the object’s lock. All objects and classes have locks. A
class’s lock is acquired on the class’s Class object.
What is the % operator? - It is referred to as the modulo or remainder operator. It returns the
remainder of dividing the first operand by the second operand.
When can an object reference be cast to an interface reference? - An object reference be cast to an
interface reference when the object implements the referenced interface.
Which class is extended by all other classes? - The Object class is extended by all other classes.
Can an object be garbage collected while it is still reachable? - A reachable object cannot be garbage
collected. Only unreachable objects may be garbage collected.
Is the ternary operator written x : y ? z or x ? y : z ? - It is written x ? y : z.
How is rounding performed under integer division? - The fractional part of the result is truncated. This
is known as rounding toward zero.
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.
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.
If a class is declared without any access modifiers, where may the class be accessed? - A class that is
declared without any access modifiers is said to have package access. This means that the class can
only be accessed by other classes and interfaces that are defined within the same package.
Does a class inherit the constructors of its superclass? - A class does not inherit constructors from any
of its superclasses.
What is the purpose of the System class? - The purpose of the System class is to provide access to
system resources.
Name the eight primitive Java types. - The eight primitive types are byte, char, short, int, long, float,
double, and boolean.
Which class should you use to obtain design information about an object? - The Class class is used to
obtain information about an object’s design.
Core Java interview questions
Can there be an abstract class with no abstract methods in it? - Yes
Can an Interface be final? - No
Can an Interface have an inner class? - Yes.
public interface abc
{
static int i=0; void dd();
class a1
{
a1()
{
int j;
System.out.println("inside");
};
public static void main(String a1[])
{
System.out.println("in interfia");
}
}
}
Can we define private and protected modifiers for variables in interfaces? - No
What is Externalizable? - Externalizable is an Interface that extends Serializable Interface. And sends
data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and
readExternal(ObjectInput in)
What modifiers are allowed for methods in an Interface? - Only public and abstract modifiers are
allowed for methods in interfaces.
What is a local, member and a class variable? - Variables declared within a method are “local”
variables. Variables declared within the class i.e not within any methods are “member” variables
(global variables). Variables declared within the class i.e not within any methods and are defined as
“static” are class variables
What are the different identifier states of a Thread? - The different identifiers of a Thread are: R -
Running or runnable thread, S - Suspended thread, CW - Thread waiting on a condition variable, MW -
Thread waiting on a monitor lock, MS - Thread suspended waiting on a monitor lock
What are some alternatives to inheritance? - Delegation is an alternative to inheritance. Delegation
means that you include an instance of another class as an instance variable, and forward messages to
the instance. It is often safer than inheritance because it forces you to think about each message you
forward, because the instance is of a known class, rather than a new class, and because it doesn’t force
you to accept all the methods of the super class: you can provide only the methods that really make
sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a
subclass).
Why isn’t there operator overloading? - Because C++ has proven by example that operator overloading
makes code almost impossible to maintain. In fact there very nearly wasn’t even method overloading in
Java, but it was thought that this was too useful for some very basic methods like print(). Note that
some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().
What does it mean that a method or field is “static"? - Static variables and methods are instantiated
only once per class. In other words they are class variables, not instance variables. If you change the
value of a static variable in a particular object, the value of that variable changes for all instances of
that class. Static methods can be referenced with the name of the class rather than the name of a
particular object of the class (though that works too). That’s how library methods like
System.out.println() work. out is a static field in the java.lang.System class.
How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?
String hostname = InetAddress.getByName("192.18.97.39").getHostName();
Difference between JRE/JVM/JDK?
Why do threads block on I/O? - Threads block on i/o (that is enters the waiting state) so that other
threads may execute while the I/O operation is performed.
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 leads to significant errors.
Is null a keyword? - The null value is not a keyword.
Which characters may be used as the second character of an identifier,but not as the first character
of an identifier? - The digits 0 through 9 may not be used as the first character of an identifier but they
may be used after the first character of an identifier.
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.
How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? - Unicode
requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually
represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit
and larger bit patterns.
What are wrapped classes? - Wrapped classes are classes that allow primitive types to be accessed as
objects.
What restrictions are placed on the location of a package statement within a source code file? - A
package statement must appear as the first line in a source code file (excluding blank lines and
comments).
What is the difference between preemptive scheduling and time slicing? - 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.
What is a native method? - A native method is a method that is implemented in a language other than
Java.
What are order of precedence and associativity, and how are they used? - Order of precedence
determines the order in which operators are evaluated in expressions. Associatity determines whether
an expression is evaluated left-to-right or right-to-left
What is the catch or declare rule for method declarations? - If a checked exception may be thrown
within the body of a method, the method must either catch the exception or declare it in its throws
clause.
Can an anonymous class be declared as implementing an interface and extending a class? - An
anonymous class may implement an interface or extend a superclass, but may not be declared to do
both.
What is the range of the char type? - The range of the char type is 0 to 2^16 - 1.
Java interview questions
What is garbage collection? What is the process that is responsible for doing that in java? -
Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process
What kind of thread is the Garbage collector thread? - It is a daemon thread.
What is a daemon thread? - These are the threads which can run without user intervention. The JVM
can exit when there are daemon thread by killing them abruptly.
How will you invoke any external process in Java? - Runtime.getRuntime().exec(….)
What is the finalize method do? - Before the invalid objects get garbage collected, the JVM give the
user a chance to clean up some resources before it got garbage collected.
What is mutable object and immutable object? - If a object value is changeable then we can call it as
Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is
immutable object. (Ex., String, Integer, Float, …)
What is the basic difference between string and stringbuffer object? - String is an immutable object.
StringBuffer is a mutable object.
What is the purpose of Void class? - The Void class is an uninstantiable placeholder class to hold a
reference to the Class object representing the primitive Java type void.
What is reflection? - Reflection allows programmatic access to information about the fields, methods
and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate
on their underlying counterparts on objects, within security restrictions.
What is the base class for Error and Exception? - Throwable
What is the byte range? -128 to 127
What is the implementation of destroy method in java.. is it native or java code? - This method is not
implemented.
What is a package? - To group set of classes into a single unit is known as packaging. Packages provides
wide namespace ability.
What are the approaches that you will follow for making a program very efficient? - By avoiding too
much of static methods avoiding the excessive and unnecessary use of synchronized methods Selection
of related classes based on the application (meaning synchronized classes for multiuser and non-
synchronized classes for single user) Usage of appropriate design patterns Using cache methodologies
for remote invocations Avoiding creation of variables within a loop and lot more.
What is a DatabaseMetaData? - Comprehensive information about the database as a whole.
What is Locale? - A Locale object represents a specific geographical, political, or cultural region
How will you load a specific locale? - Using ResourceBundle.getBundle(…);
What is JIT and its use? - Really, just a very fast compiler… In this incarnation, pretty much a one-pass
compiler – no offline computations. So you can’t look at the whole method, rank the expressions
according to which ones are re-used the most, and then generate code. In theory terms, it’s an on-line
problem.
Is JVM a compiler or an interpreter? - Interpreter
When you think about optimization, what is the best way to findout the time/memory consuming
process? - Using profiler
What is the purpose of assert keyword used in JDK1.4.x? - In order to validate certain expressions. It
effectively replaces the if block and automatically throws the AssertionError on failure. This keyword
should be used for the critical arguments. Meaning, without that the method does nothing.
How will you get the platform dependent values like line separator, path separator, etc., ? - Using
Sytem.getProperty(…) (line.separator, path.separator, …)
What is skeleton and stub? what is the purpose of those? - Stub is a client side representation of the
server, which takes care of communicating with the remote server. Skeleton is the server side
representation. But that is no more in use… it is deprecated long before in JDK.
What is the final keyword denotes? - final keyword denotes that it is the final implementation for that
method or variable or class. You can’t override that method/variable/class any more.
What is the significance of ListIterator? - You can iterate back and forth.
What is the major difference between LinkedList and ArrayList? - LinkedList are meant for sequential
accessing. ArrayList are meant for random accessing.
What is nested class? - If all the methods of a inner class is static then it is a nested class.
What is inner class? - If the methods of the inner class can only be accessed via the instance of the
inner class, then it is called inner class.
What is composition? - Holding the reference of the other class within some other class is known as
composition.
What is aggregation? - It is a special type of composition. If you expose all the methods of a composite
class and route the method call to the composite method through its reference, then it is called
aggregation.
What are the methods in Object? - clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll,
toString
Can you instantiate the Math class? - You can’t instantiate the math class. All the methods in this class
are static. And the constructor is not public.
What is singleton? - It is one of the design pattern. This falls in the creational pattern of the design
pattern. There will be only one instance for that entire JVM. You can achieve this by having the private
constructor in the class. For eg., public class Singleton { private static final Singleton s = new Singleton();
private Singleton() { } public static Singleton getInstance() { return s; } // all non static methods … }
What is DriverManager? - The basic service to manage set of JDBC drivers.
What is Class.forName() does and how it is useful? - It loads the class into the ClassLoader. It returns
the Class. Using that you can get the instance ( “class-instance".newInstance() ).
Basic Java interview questions
What is a Marker Interface? - An interface with no methods. Example: Serializable, Remote, Cloneable
What interface do you implement to do the sorting? - Comparable
What is the eligibility for a object to get cloned? - It must implement the Cloneable interface
What is the purpose of abstract class? - It is not an instantiable class. It provides the concrete
implementation for some/all the methods. So that they can reuse the concrete functionality by
inheriting the abstract class.
What is the difference between interface and abstract class? - Abstract class defined with methods.
Interface will declare only the methods. Abstract classes are very much useful when there is a some
functionality across various classes. Interfaces are well suited for the classes which varies in
functionality but with the same method signatures.
What do you mean by RMI and how it is useful? - RMI is a remote method invocation. Using RMI, you
can work with remote object. The function calls are as though you are invoking a local variable. So it
gives you a impression that you are working really with a object that resides within your own JVM
though it is somewhere.
What is the protocol used by RMI? - RMI-IIOP
What is a hashCode? - hash code value for this object which is unique for every object.
What is a thread? - Thread is a block of code which can execute concurrently with other threads in the
JVM.
What is the algorithm used in Thread scheduling? - Fixed priority scheduling.
What is hash-collision in Hashtable and how it is handled in Java? - Two different keys with the same
hash value. Two different entries will be kept in a single hash bucket to avoid the collision.
What are the different driver types available in JDBC? - 1. A JDBC-ODBC bridge 2. A native-API partly
Java technology-enabled driver 3. A net-protocol fully Java technology-enabled driver 4. A native-
protocol fully Java technology-enabled driver For more information: Driver Description
Is JDBC-ODBC bridge multi-threaded? - No
Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? - No
What is the use of serializable? - To persist the state of an object into any perminant storage device.
What is the use of transient? - It is an indicator to the JVM that those variables should not be
persisted. It is the users responsibility to initialize the value when read back from the storage.
What are the different level lockings using the synchronization keyword? - Class level lock Object level
lock Method level lock Block level lock
What is the use of preparedstatement? - Preparedstatements are precompiled statements. It is mainly
used to speed up the process of inserting/updating/deleting especially when there is a bulk processing.
What is callable statement? Tell me the way to get the callable statement? - Callablestatements are
used to invoke the stored procedures. You can obtain the callablestatement from Connection using the
following methods prepareCall(String sql) prepareCall(String sql, int resultSetType, int
resultSetConcurrency)
In a statement, I am executing a batch. What is the result of the execution? - It returns the int array.
The array contains the affected row count in the corresponding index of the SQL.
Can a abstract method have the static qualifier? - No
What are the different types of qualifier and what is the default qualifier? - public, protected, private,
package (default)
What is the super class of Hashtable? - Dictionary
What is a lightweight component? - Lightweight components are the one which doesn’t go with the
native call to obtain the graphical units. They share their parent component graphical units to render
them. Example, Swing components
What is a heavyweight component? - For every paint call, there will be a native call to get the graphical
units. Example, AWT.
What is an applet? - Applet is a program which can get downloaded into a client environment and start
executing there.
What do you mean by a Classloader? - Classloader is the one which loads the classes into the JVM.
What are the implicit packages that need not get imported into a class file? - java.lang
What is the difference between lightweight and heavyweight component? - Lightweight components
reuses its parents graphical units. Heavyweight components goes with the native graphical unit for
every component. Lightweight components are faster than the heavyweight components.
What are the ways in which you can instantiate a thread? - Using Thread class By implementing the
Runnable interface and giving that handle to the Thread class.
What are the states of a thread? - 1. New 2. Runnable 3. Not Runnable 4. Dead
What is a socket? - A socket is an endpoint for communication between two machines.
How will you establish the connection between the servlet and an applet? - Using the URL, I will
create the connection URL. Then by openConnection method of the URL, I will establish the
connection, through which I can be able to exchange data.
What are the threads will start, when you start the java program? - Finalizer, Main, Reference Handler,
Signal Dispatcher
Interview questions for Java junior developer position
What gives Java its “write once and run anywhere” nature? - Java is compiled to be a byte code which
is the intermediate language between source code and machine code. This byte code is not platorm
specific and hence can be fed to any platform. After being fed to the JVM, which is specific to a
particular operating system, the code platform specific machine code is generated thus making java
platform independent.
What are the four corner stones of OOP? - Abstraction, Encapsulation, Polymorphism and Inheritance.
Difference between a Class and an Object? - A class is a definition or prototype whereas an object is an
instance or living representation of the prototype.
What is the difference between method overriding and overloading? - Overriding is a method with
the same name and arguments as in a parent, whereas overloading is the same method name but
different arguments.
What is a “stateless” protocol? - Without getting into lengthy debates, it is generally accepted that
protocols like HTTP are stateless i.e. there is no retention of state between a transaction which is a
single request response combination.
What is constructor chaining and how is it achieved in Java? - A child object constructor always first
needs to construct its parent (which in turn calls its parent constructor.). In Java it is done via an implicit
call to the no-args constructor as the first statement.
What is passed by ref and what by value? - All Java method arguments are passed by value. However,
Java does manipulate objects by reference, and all object variables themselves are references
Can RMI and Corba based applications interact? - Yes they can. RMI is available with IIOP as the
transport protocol instead of JRMP.
You can create a String object as String str = “abc"; Why cant a button object be created as Button bt
= “abc";? Explain - The main reason you cannot create a button by Button bt1= “abc"; is because “abc”
is a literal string (something slightly different than a String object, by the way) and bt1 is a Button
object. The only object in Java that can be assigned a literal String is java.lang.String. Important to note
that you are NOT calling a java.lang.String constuctor when you type String s = “abc";
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 hs 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.
How many methods do u implement if implement the Serializable Interface? - The Serializable
interface is just a “marker” interface, with no methods of its own to implement. Other ‘marker’
interfaces are
java.rmi.Remote
java.util.EventListener
What are the practical benefits, if any, of importing a specific class rather than an entire package (e.g.
import java.net.* versus import java.net.Socket)? - It makes no difference in the generated class files
since only the classes that are actually used are referenced by the generated class file. There is another
practical benefit to importing single classes, and this arises when two (or more) packages have classes
with the same name. Take java.util.Timer and javax.swing.Timer, for example. If I import java.util.* and
javax.swing.* and then try to use “Timer", I get an error while compiling (the class name is ambiguous
between both packages). Let’s say what you really wanted was the javax.swing.Timer class, and the only
classes you plan on using in java.util are Collection and HashMap. In this case, some people will prefer
to import java.util.Collection and import java.util.HashMap instead of importing java.util.*. This will
now allow them to use Timer, Collection, HashMap, and other javax.swing classes without using fully
qualified class names in.
What is the difference between logical data independence and physical data independence? - Logical
Data Independence - meaning immunity of external schemas to changeds in conceptual schema.
Physical Data Independence - meaning immunity of conceptual schema to changes in the internal
schema.
What is a user-defined exception? - Apart from the exceptions already defined in Java package
libraries, user can define his own exception classes by extending Exception class.
Describe the visitor design pattern? - Represents an operation to be performed on the elements of an
object structure. Visitor lets you define a new operation without changing the classes of the elements
on which it operates. The root of a class hierarchy defines an abstract method to accept a visitor.
Subclasses implement this method with visitor.visit(this). The Visitor interface has visit methods for all
subclasses of the baseclass in the hierarchy.
Q1. How would you resolve conflicts in a single row of data in a Database table If your application is
distributed in nature?
Ans: The best way I can do is that I shall define an additional field as time stamp and should write
server date time in it, for any insertion or updation happens from whatever source (may be from the
same Java/J2EE application, or from a Microsoft Visual Basic application).And every updation of the
row is preceeded by a check for the time date with the one taken at the time of querying and looking
for a change in it. If there is any change, then shall go for a re querying the same row, and then
modifying the data (probably stored in a cache) and then firing the updation ( modifying the time
date field with the latest date time). Yes explicit locking for the row should be enabled, while doing the
final updation.
Q2. What are the main points you should take care while passing Serializable objects using
HttpSession ?
Ans: I should use response forward, instead of response sendRedirect. As response sendRedirect,
generated a fresh request and all the HttpSession objects will be Null. And should use
request.getSession(false), As a true argument value to this will create a new session and the earlier
session will be Null.
Q3. Given a requirements document, what would be your next step to designs?
Ans: Find out Actors and usecases out of the requirements phrase, sit with Business Analyst to
validate these information. Draw a Business Model for the project, validate it with customer.Once
approved, architects will define a broad level, sequence diagram, and class diagram, depicting all the
entities, flow of interaction. Once the design is reviewed by designers, application developers. Once it is
approved the phase of design will be over.
Q4. When is the right time for Test case identification activity to start?
Ans: Once the usecase or functional spec is ready and reviewed. Then Test cases identification task
should start and it should go parallel to the development activity.
Q5. What are the points very crucial while designing a OO Project?
Ans: Designers should remember that they are designing an application that has to run ultimately in a
production environment. So should be aware of the various facts pertaining to Clustering, Load
balancing etc. All application will grow over time and need for newer set of devices for clients will
evolve and the application should be flexible enough to take up these unforeseen future challenges.
Application should run faster and will lesser network overheads. And of course with features for
runtime inclusion of more functionality.
J2EE General Questions

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

Q: What is the Java 2 Platform, Enterprise Edition (J2EE)?


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.
Q: What are the main benefits of the J2EE platform?
The J2EE platform provides the following:
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.
Q: Can the J2EE platform interoperate with other WS-I implementations?
Yes, if the other implementations are WS-I compliant.
Q: What technologies are included in the J2EE platform?
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.
Q: What's new in the J2EE 1.4 platform?
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.
Q: What is the J2EE 1.4 SDK?
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.
Q: Which version of the platform should I use now -- 1.4 or 1.3?
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
Q: How can I learn about the J2EE platform?
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.
What tools can I use to build J2EE applications?
There are numerous choices of tools available for developing Java and J2EE applications. You can
download the Open Source NetBeans IDE for free at http://netbeans.org. Many of the J2EE compatible
vendors offer tools that support any J2EE compatible application server.
Q: Who needs the J2EE platform?
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.
Q: What do you mean by "Free"?
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.
Q: Are there compatibility tests for the J2EE platform?
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.

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.

1. What's the JDBC 3.0 API?


The JDBC 3.0 API is the latest update of the JDBC API. It contains many features, including scrollable
result sets and the SQL:1999 data types.
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
3. Can the JDBC-ODBC Bridge be used with applets?
Use of the JDBC-ODBC bridge from an untrusted applet running in a browser, such as Netscape
Navigator, isn't allowed. The JDBC-ODBC bridge doesn't allow untrusted code to call it for security
reasons. This is good because it means that an untrusted applet that is downloaded by the browser
can't circumvent Java security by calling ODBC. Remember that ODBC is native code, so once ODBC is
called the Java programming language can't guarantee that a security violation won't occur. On the
other hand, Pure Java JDBC drivers work well with applets. They are fully downloadable and do not
require any client-side configuration.
Finally, we would like to note that it is possible to use the JDBC-ODBC bridge with applets that will be
run in appletviewer since appletviewer assumes that applets are trusted. 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
6. What JDBC technology-enabled drivers are available?
See our web page on JDBC technology-enabled drivers for a current listing.
Back to Top
7. What documentation is available for the JDBC API?
See the JDBC technology home page for links to information about JDBC technology. This page links to
information about features and benefits, a list of new features, a section on getting started, online
tutorials, a section on driver requirements, and other information in addition to the specifications and
javadoc documentation.
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
9. What causes the "No suitable driver" error?
"No suitable driver" is an error that usually occurs during a call to the DriverManager.getConnection
method. The cause can be failing to load the appropriate JDBC drivers before calling the getConnection
method, or it can be specifying an invalid JDBC URL--one that isn't recognized by your JDBC driver. Your
best bet is to check the documentation for your JDBC driver or contact your JDBC driver vendor if you
suspect that the URL you are specifying is not being recognized by your JDBC driver.
In addition, when you are using the JDBC-ODBC Bridge, this error can occur if one or more the the
shared libraries needed by the Bridge cannot be loaded. If you think this is the cause, check your
configuration to be sure that the shared libraries are accessible to the Bridge.
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
14. Is the JDBC-ODBC Bridge multi-threaded?
No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC
Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded
Java programs may use the Bridge, but they won't get the advantages of multi-threading. In addition,
deadlocks can occur between locks held in the database and the semaphore used by the Bridge. We are
thinking about removing the synchronized methods in the future. They were added originally to make
things simple for folks writing Java programs that use a single-threaded ODBC driver.
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
20. If I use the JDBC API, do I have to use ODBC underneath?
No, this is just one of many possible solutions. We recommend using a pure Java JDBC technology-
enabled driver, type 3 or 4, in order to get all of the benefits of the Java programming language and the
JDBC API.
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.
FREQUENTLY ASKED QUESTIONS ABOUT JNDI

Who should use JNDI?


Any Java application that needs to access information about users, machines, networks, and services.
User information includes security credentials, phone numbers, electronic and postal mail addresses,
and application preferences. Machine information includes network addresses, machine configurations,
etc. In addition, any Java application that needs to either export objects or access objects exported by
other applications and services. Examples include printers, calendars, and networked file systems.
Can I use JNDI now?
Yes, Sun Microsystems has released JNDI as a Java Standard Extension. Sun Microsystems has also
released service providers that plug in seamlessly behind JNDI for a number of naming and directory
services: LDAP, NIS, CORBA (COS) Naming, and files. These and service providers produced by other
vendors are available for download.
Where is JNDI being used in the Java platform?
HotJava Views 1.1 is using JNDI to access LDAP. Enterprise APIs such as Enterprise JavaBeans, Java
Message Service, JDBC 2.0 make use of JNDI to for their naming and directory needs. RMI over IIOP
applications can use JNDI to access the CORBA (COS) naming service.
Who will provide implementations of JNDI?
At the time of this writing, IBM, Novell, Sun, and WebLogic have produced service providers for JNDI.
We maintain a listing of publicly available service providers.
What protocols does JNDI provide an interface to?
JNDI itself is independent of any specific directory access protocol. Individual service providers
determine the protocols to support. There will be provider implementations for popular protocols, such
as LDAP, NDS, DNS, and NIS(YP), supplied by different vendors.
How does JNDI relate to LDAP?
JNDI provides an excellent object-oriented abstraction of directory and naming. Developers using JNDI
can produce queries that use LDAP or other access protocols to retrieve results; however, they are not
limited to LDAP nor do they have to develop their applications wired to LDAP. JNDI supports the key
capabilities in LDAP v3.
How does JNDI relate to Netscape's Java LDAP API?
Netscape's API is LDAP-specific. It is used for low-level access to LDAP directories. It exposes details
about the protocol that applications typically do not need to know.
JNDI is a generic directory API for Java programs. It is analogous to the java.io.File class for accessing
files. There might be some administrative programs that need to manipulate a file at the protocol level
(such as NFS), but typically all Java applications use the File class to access to file system. Similarly, most
Java programs should use JNDI to access directories. Applications that need to manipulate directory
content at the protocol level may choose to use Netscape's API.
How does JNDI relate to OMG's CORBA standards for naming?
A Java CORBA application can use JNDI to access to the CORBA (COS) name service, as well as other
naming and directory services. It offers the application one interface for accessing all these naming and
directory services.
Using JNDI also paves the way for Java CORBA applications to use a distributed enterprise-level service
like LDAP to store object references.
How does JNDI relate to Microsoft's ADSI?
The Java ADSI package allows Java programs to access Active Directory based on the COM model.
Although it can be used to access other directories, it is a Windows-centric solution.
JNDI offers Java applications, regardless of whether they're running on Windows or accessing Active
Directory, to access directories using the Java object model. For example, you can manipulate objects
such as AWT and JavaBeans components, bind them into the directory, and look them back up without
having to do any translation or deal with data representation issues.
What is XFN and how does this relate to JNDI?
XFN is X/Open Federated Naming, a C-based standard for accessing multiple, possibly federated naming
and directory services. A programmer familiar with XFN will find it easy to use JNDI.
What about security?
Different directories have different ways of dealing with security. JNDI allows for applications to work in
conjunction with directory-specific security systems. In the future, JNDI-based applications will be able
to take advantage of any single sign-on mechanism developed for the Java platform.

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.

The exact format of a JSP page is described in the JSP specification..


How do JSP pages work?
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.
How is a JSP page invoked and compiled?
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.
What is the syntax for JavaServer Pages technology?
The syntax card and reference can be viewed or downloaded from our website.
Can I create XML pages using JSP technology?
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.
Can I generate and manipulate JSP pages using XML tools?
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.
How do I use JavaBeans components (beans) from a JSP page?
The JSP specification includes standard tags for bean use and manipulation. The useBean tag creates an
instance of a specific JavaBeans class. If the instance already exists, it is retrieved. Otherwise, it is
created. The setProperty and getProperty tags let you manipulate properties of the given object. These
tags are described in more detail in the JSP specification and tutorial

COMPANY NAME : Computer Associates, Hyderabad(15 Feb 2004)


------------------------------------------------------------
CATEGORY : JAVA - J2EE (2+ years experienced category)

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:fallback> text message for user </jsp:fallback> ]

</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
-------------------------------------------------------------------

COMPANY NAME : HP (Hewlett Packard-1 Feb 2004)


------------------------------------------------------------
CATEGORY : JAVA - J2EE (3+ years experienced category)

There are 3 interviews :


1. Technical interview
2. Program Manager interview
3. HR interview

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.

COMPANY NAME : i-Flex : 20 Feb 2004


------------------------------------------------------------
This is i-flex paper for 2+ years experienced in JAVA and J2EE.

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)

___________________________________________________________________________________

COMPANY NAME : iNautix,(14 Feb 2004:JAVA-J2EE(3+years experienced category)


1. Why do you want to leave current company ?
----------------------------------------------------
2. What is your role in project and how you manage you role at your company ?
----------------------------------------------------
3. How do you manage people, how you do reviews, testing ? Do you use any automated tools for
testing ? How do you do performance testing ?
----------------------------------------------------
4. How you manage configuration control ?
----------------------------------------------------
5. What is the difference between forward tag and sendRedirect() ?
----------------------------------------------------
6. What is a singleton class ?
----------------------------------------------------
7. What is the difference between Abstract class and Interface. In what situations, they can be used ?
----------------------------------------------------
8. How do you send data from an applet to Servlet ? What are the steps involved in it ?
Answer :
It's pretty straightforward. You can use the java.net.URLConnection and java.net.URL classes to open a
standard HTTP connection to the web server. The server then passes this information to the servlet in
the normal way.

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.

9. What is Polymorphism. Explain ?


----------------------------------------------------
10.What are the types of Polymorphism ? What is Run-Time polymorphism ?
----------------------------------------------------
11. Why do you want to leave current company ?
12. Explain MVC architecture and functionalities of various components ?
13. I have a file of very very large file size at client side, and I have a JSP page. Using this JSP page, if I
want to send the file to a servlet (this servlet will store it somewhere), what is the best method to do
it ?
14. What is the difference between normal beans and EJBs ?
15. How system level services in EJBs are managed ? And tell about Deployment Descriptor ?
16. What are various types of EJBs ?

MANHATTAN ASSOCIATES(17 Jan 2004-JAVA - J2EE (2+ years))


----------------------------------------------------
EJB
----------------------------------------------------
1) What is true about 'Primary Key class' in Entity Beans ?
(a) Used to identify the entity bean based on EJB type, Home Interface and Container Context.
(b) Used to identify the entity bean based on EJB type, Remote Interface and Container Context.
(c) The definition of Primary Key class can be deferred till deployment
--------------------
2) The Home Interface in Entity beans
(a) Provides at least one create() method
(b) May not provide any create() method
(c) Provides at least one findByPrimaryKey() method
(d) May not provide any findByPrimaryKey() method

--------------------
3) In CMP of Entity beans

(a) Constructor with no arguments is defined


(b) Constructor is not defined

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

1) What is the purpose of XSL


(a) Convert XML to HTML
(b) Convert HTML to XML
ANS: (a)
--------------------
2) resultSet has the following methods
(a) next()
(b) first()
(c) a & b
(d) No methods
--------------------
3) In WebLogic clusters, what is the load balancing algorithm ?
(a) RoundRobin
(b) FIFO
(c) LIFO
ANS: (a)

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)

An MDB can be associated with only one Queue or Topic

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

7) Can a JSP be converted to SERVLET and the vice versa always ?


(a) YES
(b) NO
--------------------

8) Empty JSP Tag definitions are given in Deployment Descriptor. Then which of the following syntaxes
are correct ?
(I don't remember the options)
-------------------

9) One small question on <jsp:useBean> tag


----------------------------------------------------
JAVA
----------------------------------------------------
1) Which of the following 2 methods executes faster ?
class Trial {

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

4) What is the difference between OVERRIDING and OVERLOADING


--------------------
5) What is the output of following program ?
class Test {
public static void main(String args[]) {
for(int i=0;i<2;i++) {
System.out.println(i--);
}
}
}
(a) Goes into infinite loop
(b) 0,1
(c) 0,1,2
(d) None
ANS: (a)

--------------------
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) {

//Code for very complex operations will be written


//in this place

x=a;
}

Test(int a, int b) {

//Code for very complex operations will be written


//in this place (same code as in above constructor)

x=a;
y=b;
}
}

----------------------------------------------------
TECHNICAL INTERVIEW
----------------------------------------------------

1) Tell about yourself


2) Why do you want to leave the present company ?
3) What do you know about our (Manhattan Associates) company ?
4) About EJB types. CMP, BMP, Session, Entity beans, their differences, when to use what type of
beans ?
5) Can a Client Context call ejbRemove() method ?
6) Who calls the methods ejbLoad() and ejbStore() and where the state information is stored when they
are called ?
7) Do you know about Sequence Diagrams in UML ?
8) Which is faster in execution - JSP or SERVLET ? Why ?
9) What is the difference between Callable Statement and Prepared Statement?
10) Can we declare final method in abstract class ?
11) Can we declare abstract method in final class ?
12) What is the difference between Inner Join and Outer Join ?
13) How can you pass an object of data from one JSP to another JSP ?
ANS: Using Session or request.getParameter() or Hidden Variables.
14) When these methods are used ? ejbActivate(), ejbPassivate() and ejbRemove() ?
15) What is the difference between ejbPassivate() and ejbRemove() ?
16) Can the same object of Stateless Session bean be shared by multiple clients ?
17) Can the same object of Stateful Session bean be shared by multiple clients ?
18) How do you manage transactions in EJB ?
19) What is the difference between response.redirect() and forward and request dispatcher ? Which is
faster ?
20) In java, which has more wider scope ? Default or Private ?
----------------------------------------------------

COMPANY NAME : NOVARTIS(7 Feb 2004, Saturday-JAVA-J2EE(3+ years)


__________________________________________________________________
1) Question on Static Methods, whether they can be overloaded or not
--------------------
2) A java program on nested (inner) loops and it is asked what is the output of the program.
--------------------
3) Once a Servlet is initialized, how do you get the initialization parameters ?
(a) Initialization parameters will not be stored
(b) They will be stored in instance variables
(c) using config.getInitParameters()
ANS: I think answer is (c)
-------------------
4) A question on functionality of <forward> tag in JSP
--------------------
5) If the cookies are disabled, how can you maintain the Session.
ANS: URL rewriting
--------------------
6) If there are strict timelines and if you want to get high performance for JSP to DB access, what
method you suggest ?
(a) Moving application server in to same manchine as Database
(b) By storing results in Cache
(c) By implementing Connection Pooling
ANS: I think answer is (c)
--------------------
7) A question on MVC architecture and the functionality of Controller and View.
--------------------
8) Question on Design Pattern. (I don't remember it)
--------------------
9) Which Design Pattern hides the complexities of all sub-systems ?
(I don't remember the options and also don't know answer.)
--------------------
10) In CMP bean, which method executes only once in life time
(a) setEntityContext()
(b) create()
(c) remove()
(d) find()
ANS: I think answer is (b)
--------------------
11) Which bean can be called as Multi-Threaded bean ?
(a) Entity beans
(b) Stateless Session beans
(c) Stateful Session beans
(d) Pooled Stateless Session beans
ANS: I think answer is (d)
--------------------
12) A question on Threads in Java, whether we need to mention the word "Daemon" explicitly to make
a thread as Daemon.
--------------------
13) A question on Transactions of EJB. I think the question is something similar to - "Which is faster ?"
(a) TRANSACTION_UNREPEATABLE_READ
(b) TRANSACTION_REPEATABLE_READ
(c) TRANSACTION_COMMIT_READ
(d) TRANSACTION_UNCOMMIT_READ
(I don't know answer and also I am not sure of options. but the options are something similar to this.)
--------------------
14) Question on EJB Home Object, Remote Object and what functionalities will be performed by each.
--------------------
15) What is the difference between Server and Container
(a) A Container can have multiple Servers
(b) A Server can have multiple Containers
(c) A Server can have only one Container
ANS: I think answer is (b)
--------------------
16) ejbStore() method is equivalent to
(a) SELECT
(b) INSERT
(c) UPDATE
(d) DELETE
ANS: I think answer is (c)
--------------------
17) A question on where the garbage collection is done. I think the answer is : "finalize()" method
--------------------
18) A question properties of Primary key in Entity Beans (I don't remember the options exactly.)
(a) Primary key consists of only basic data types in java
(b) Primary key can contain composite data types
_________________________
Remarks on Technical Test : It's a bit difficult and lot of questions are on EJBs, JSPs and Design Patterns.

-------------------------------------------------------------------
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
}
}

if u want to call a method of class B then how can u achieve this?

17)What is static variable? What is static method?


18)Can u call a static method on a class object,can u access Static variables through class objects?
19)What is the diffrenence between AWT and Swing?
20)How will u add a button to a frame?
21)Cant we add a component directly to a frame? Why?
22)What are the different types of panes available?
23)What are the uses of different types of panes?
24)What is a layered pane?
25)What is event delegation model?describe it with an example?
26)Public void Methos(){
Int I;
Int a[]=new int[10];
S.O.P(i);
For(int k=0;k<a.length;k++)
S.O.P(a[ k]);
}
What will be the output of this method

27)What is the difference between getActionCommand() And getSource() on event object?


28)What is a tier? What is the difference between tier and system or computer?
29)What do u mean by portability?
30)What do u mean by platform independence?
31)Completely view of MVC and n tier architecture and differences?
32)What is the difference between JradioButton and Jradiobuttongroup.
33)If u add 2 Jradiobuttons to a panel and check the first one and then the second one
Then which one will be selected
34)What are the methods of authorization in jsp or servlets?
35)What is webapplication?
36)What are the various methods of declaring a TLD in a taglib directive in jsp?
37)What is TLD?
38)Implicit objects of jsp are available in destroy() method or not?
39)What is translation unit in jsp?
40)What is context in webapplication?
41)What are multiple and single processor servers? How session is handled
42)When the server is multi processor server?
43)If server crashes the threads will continue running or will they stop?what happens to the sevlet?
44)Explain MVC pattern by taking any one component ex JtextField or Jbutton?
45)What is GridBagLayout?
46)If we want to change the entire path of the server ,where should we touch in a application server?
47)If we have 3 jsp's as model.jsp, controller.jsp, view.jsp then will it be a MVC architecture?
48)What is a classloader?
49)What is dynamic typing, static typing ?
50)Is java dynamic typed language?
51)What are the types of sevlet containers?
52)What is web.xml?
53)What is pooling of sevlets?
54)If we have two abstract classes A,B then can we extend both the classes in a single class?
55)What are the different types of thread priorities?
56)What is SAX?
57)What is the difference between SAX and DOM?
58)What is the difference between RequestDispatcher.forward(request req,response res)
And response.sencRedirect("url");?
59)What are implicit objects in jsp?
60)Why cocoon ?why not struts?what is cocoon?
61)How are u implementing session in ur application?
62)What is serialization? What are the methods in implementing serialization?
63)If u have a single table in database how to normalize it?
64)Is servlet thread safe ? life cycle of JSp?
65)What is the difference between checked exception an runtime exception?
66)Interrupt() method throws which exception?
67)Why jsp is used if we have sevlets>
68)Difference between a String and Stirng Buffer?
69)How to increment the capacity of a StringBuffer?
70)If String S="x";
S+"y";
Then what is S?
71)How can u set the priorities of thread ? What are the priorities available?
72)Difference between Vector and ArrayList other than Synchronization?
73)What do u mean by precompiled statement?
74)Difference between application server and webserver ?
75)Can we have a try without catch and with a finally?What is the use of having finally?
76)what is the superclass of an exception?
77)Is sevlet threadsafe?

---------------------------------
-------------------------------------------------------------------
(5)What is Synchornize?

Synchronize is a technique by which a particular block is made accessible only


by a single instance at any time. (OR) When two or more objects try to access a
resource, the method of letting in one object to access a resource is called sync
-------------------------------------------------------------------
(6)How to prevent Dead Lock?
Using synchronization mechanism.

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? :

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
-------------------------------------------------------------------
(8)what are pass by reference and passby value?
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.

-------------------------------------------------------------------
(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?

Vector is serialized whereas arraylist is not


-------------------------------------------------------------------
(13)Difference between Swing and Awt?
AWT are heavy-weight componenets. Swings are light-weight components. Hence
swing works faster than AWT.

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

14) Explain types of Enterprise Beans?


Session beans -> Associated with a client and keeps states for a client
Entity Beans -> Represents some entity in persistent storage such as a database
-------------------------------------------------------------------

15) What is enterprise bean?


Server side reusable java component
Offers services that are hard to implement by the programmer
Sun: Enterprise Bean architecture is a component architecture for the
deployment and development of component-based distributed business applications.
Applications written using enterprise java beans are scalable, transactional and
multi-user secure. These applications may be written once and then deployed on
any server plattform that supports enterprise java beans specification.

Enterprise beans are executed by the J2EE server.


First version 1.0 contained session beans, entity beans were not included.
Entity beans were added to version 1.1 which came out during year 1999.
Current release is EJB version 1.2

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

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

Enterprise java beans can be distributed /replicated into separate machines


Distribution/replication offers
–Load balancing, load can be divided into separate servers.
–Failover, if one server fails, others can keep on processing normally.
–Performance, one server is not so heavy loaded. Also, for example Weblogic has thread pools for
improving performance in one server.

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

Distributed transactions are needed "


–J2EE server offers transaction monitor that takes care of transaction management.
–Distributed transactions are invisible to the programmer

Other services vs. money :


Weblogic J2EE server ~ 80 000 mk and Jbuilder X Professional Edition ~ 5 000mk

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

18)Why not to use free J2EE servers?


–no tecnical support
–harder to use (no graphical user interface ...)
–no integration to development tools (for example, Jbuilder)
–Bugs? Other problems during project?

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

Faster that J2EE server?


Harder to program?
Harder to debug?

Implementation is platform dependent.

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

Directory service is needed to store and retrieve properties by their name:


–jndi name: java:comp/env/propertyName

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

22)XML – deployment descriptor

ejb-jar.xml + server-specific xml- file Which is then Packed in a jar – file


together with bean classes.
Beans are packaged into EJB JAR file , Manifest file is used to list EJB’s and
jar file holding Deployment descriptor.
-------------------------------------------------------------------
23) Session Bean

Developer programs three classes:


–Home interface, contains methods for creating (and locating for entity beans) bean instances.
–Remote interface, contains business methods the bean offers.
–Bean class, contains the business logic of the enterprise bean.

-------------------------------------------------------------------
24)Entity Beans

Represents one row in the database:


–Easy way to access database
–business logic concept to manipulate data.

Container managed persistence vs. bean managed persistence:

Programmer creates three or four classes:


–Home interface for locating beans
–Remote interface that contains business methods for clients.
–Bean class that implements bean’s behaviour.
–Primary key class – that represents primary key in the database. Used to locate beans.
Primary key class is not needed if primary key is a single field that could

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

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

26) Explain J2EE Arch?


Normally, thin-client multitiered applications are hard to write because they
involve many lines of intricate code to handle transaction and state management,
multithreading, resource pooling, and other complex low-level details.
The component-based and platform-independent J2EE architecture makes J2EE
applications easy to write because business logic is organized into reusable
components and the J2EE server provides underlying services in the form of a
container for every component type. Because you do not have to develop these
services yourself, you are free to concentrate on solving the business problem
at hand.

Containers and Services :


Component are installed in their containers during deployment and 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.
The assembly process involves specifying container settings for each component
in the J2EE application and for the J2EE application itself. Container settings
customize the underlying support provided by the J2EE Server, which include
services such as security, transaction management, Java Naming and Directory
InterfaceTM (JNDI) lookups, and remote connectivity.

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.

Java Basic and fundamental Questions

What is the difference between an Abstract class and Interface ?


What is user defined exception?
What do you know about the garbage collector ?
What is the difference between C++ & Java ?
Explain RMI Architecture?
How do you communicate in between Applets & Servlets ?
What is the use of Servlets ?
What is JDBC? How do you connect to the Database ?
In an HTML form I have a Button which makes us to open another page in 15 seconds. How will do you
that ?
What is the difference between Process and Threads ?
What is the difference between RMI & Corba ?
What are the services in RMI ?
How will you initialize an Applet ?
What is the order of method invocation in an Applet ?
When is update method called ?
How will you pass values from HTML page to the Servlet ?
Have you ever used HashTable and Dictionary ?
How will you communicate between two Applets ?
What are statements in JAVA ?
What is JAR file ?
What is JNI ?
What is the base class for all swing components ?
What is JFC ?
What is Difference between AWT and Swing ?
Considering notepad/IE or any other thing as process, What will happen if you start notepad or IE 3
times? Where 3 processes are started or 3 threads are started ?
How does thread synchronization occurs inside a monitor ?
How will you call an Applet using a Java Script function ?
Is there any tag in HTML to upload and download files ?
Why do you Canvas ?
How can you push data from an Applet to Servlet ?
What are 4 drivers available in JDBC ?
How you can know about drivers and database information ?
If you are truncated using JDBC, How can you know ..that how much data is truncated ?
And What situation , each of the 4 drivers used ?
How will you perform transaction using JDBC ?
In RMI, server object first loaded into the memory and then the stub reference is sent to the client ? or
whether a stub reference is directly sent to the client ?
Suppose server object is not loaded into the memory, and the client request for it , what will happen?
What is serialization ?
Can you load the server object dynamically? If so, what are the major 3 steps involved in it ?
What is difference RMI registry and OSAgent ?
To a server method, the client wants to send a value 20, with this value exceeds to 20,. a message
should be sent to the client ? What will you do for achieving for this ?
What are the benefits of Swing over AWT ?
Where the CardLayout is used ?
What is the Layout for ToolBar ?
What is the difference between Grid and GridbagLayout ?
How will you add panel to a Frame ?
What is the corresponding Layout for Card in Swing ?
What is light weight component ?
Can you run the product development on all operating systems ?
What is the webserver used for running the Servlets ?
What is Servlet API used for conneting database ?
What is bean ? Where it can be used ?
What is difference in between Java Class and Bean ?
Can we send object using Sockets ?
What is the RMI and Socket ?
How to communicate 2 threads each other ?
What are the files generated after using IDL to Java Compilet ?
What is the protocol used by server and client ?
Can I modify an object in CORBA ?
What is the functionality stubs and skeletons ?
What is the mapping mechanism used by Java to identify IDL language ?
Diff between Application and Applet ?
What is serializable Interface ?
What is the difference between CGI and Servlet ?
What is the use of Interface ?
Why Java is not fully objective oriented ?
Why does not support multiple Inheritance ?
What it the root class for all Java classes ?
What is polymorphism ?
Suppose If we have variable ' I ' in run method, If I can create one or more thread each thread will
occupy a separate copy or same variable will be shared ?
In servlets, we are having a web page that is invoking servlets username and password ? which is cheks
in the database ? Suppose the second page also If we want to verify the same information whethe it
will connect to the database or it will be used previous information?
What are virtual functions ?
Write down how will you create a binary Tree ?
What are the traverses in Binary Tree ?
Write a program for recursive Traverse ?
What are session variable in Servlets ?
What is client server computing ?
What is Constructor and Virtual function? Can we call Virtual funciton in a constructor ?
Why we use OOPS concepts? What is its advantage ?
What is the middleware ? What is the functionality of Webserver ?
Why Java is not 100 % pure OOPS ? ( EcomServer )
When we will use an Interface and Abstract class ?
What is an RMI?
How will you pass parameters in RMI ? Why u serialize?
What is the exact difference in between Unicast and Multicast object ? Where we will use ?
What is the main functionality of the Remote Reference Layer ?
How do you download stubs from a Remote place ?
What is the difference in between C++ and Java ? can u explain in detail ?
I want to store more than 10 objects in a remote server ? Which methodology will follow ?
What is the main functionality of the Prepared Statement ?
What is meant by static query and dynamic query ?
What are the Normalization Rules ? Define the Normalization ?
What is meant by Servelet? What are the parameters of the service method ?
What is meant by Session ? Tell me something about HTTPSession Class ?
How do you invoke a Servelt? What is the difference in between doPost and doGet methods ?
What is the difference in between the HTTPServlet and Generic Servlet ? Expalin their methods ? Tell
me their parameter names also ?
Have you used threads in Servelet ?
Write a program on RMI and JDBC using StoredProcedure ?
How do you sing an Applet ?
In a Container there are 5 components. I want to display the all the components names, how will you
do that one ?
Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA ?
Tell me the latest versions in JAVA related areas ?
What is meant by class loader ? How many types are there? When will we use them ?
How do you load an Image in a Servlet ?
What is meant by flickering ?
What is meant by distributed Application ? Why we are using that in our applications ?
What is the functionality of the stub ?
Have you used any version control ?
What is the latest version of JDBC ? What are the new features
are added in that ? Explain 2 tier and 3 -tier Architecture ?
What is the role of the webserver ?
How have you done validation of the fileds in your project ?
What is the main difficulties that you are faced in your project ?
What is meant by cookies ? Explain ?
Problem faced in your earlier project
How OOPS concept is achieved in Java
Features for using Java
How does Java 2.0 differ from Java 1.0
Public static void main – Explain
What are command line arguments
Explain about the three-tier model
Difference between String & StringBuffer
Wrapper class. Is String a Wrapper Class
What are the restriction for static method
Purpose of the file class
Default modifier in Interface
Difference between Interface & Abstract class
Can abstract be declared as Final
Can we declare variables inside a method as Final Variables
What is the package concept and use of package
How can a dead thread be started
Difference between Applet & Application
Life cycle of the Applet
Can Applet have constructors
Differeence between canvas class & graphics class
Explain about Superclass & subclass
Difference between TCP & UDP
What is AppletStub
Explain Stream Tokenizer
What is the difference between two types of threads
Checked & Unchecked exception
Use of throws exception
What is finally in exception handling
Vector class
What will happen to the Exception object after exception handling
Two types of multi-tasking
Two ways to create the thread
Synchronization
I/O Filter
How can you retrieve warnings in JDBC
Can applet in different page communicate with each other
Four driver Manager
Features of JDBC 20
Explain about stored procedures
Servlet Life cycle
Why do you go for servlet rather than CGI
How to generate skeleton & Stub classes
Explain lazy activation
Firewalls in RMI
What is meant by Java ?
What is meant by a class ?
What is meant by a method ?
What are the OOPS concepts in Java ?
What is meant by encapsulation ? Explain with an example
What is meant by inheritance ? Explain with an example
What is meant by polymorphism ? Explain with an example
Is multiple inheritance allowed in Java ? Why ?
What is meant by Java interpreter ?
What is meant by JVM ?
What is a compilation unit ?
What is meant by identifiers ?
What are the different types of modifiers ?
What are the access modifiers in Java ?
What are the primitive data types in Java ?
What is meant by a wrapper class ?
What is meant by static variable and static method ?
What is meant by Garbage collection ?
What is meant by abstract class
What is meant by final class, methods and variables ?
What is meant by interface ?
What is meant by a resource leak ?
What is the difference between interface and abstract class ?
What is the difference between public private, protected and static
What is meant by method overloading ?
What is meant by method overriding ?
What is singleton class ?
What is the difference between an array and a vector ?
What is meant by constructor ?
What is meant by casting ?
What is the difference between final, finally and finalize ?
What is meant by packages ?
What are all the packages ?
Name 2 calsses you have used ?
Name 2 classes that can store arbitrary number of objects ?
What is the difference between java.applet.* and java.applet.Applet ?
What is a default package ?
What is meant by a super class and how can you call a super class ?
What is anonymous class ?
Name interfaces without a method ?
What is the use of an interface ?
What is a serializable interface ?
How to prevent field from serialization ?
What is meant by exception ?
How can you avoid the runtime exception ?
What is the difference between throw and throws ?
What is the use of finally ?
Can multiple catch statements be used in exceptions ?
Is it possible to write a try within a try statement ?
What is the method to find if the object exited or not ?
What is meant by a Thread ?
What is meant by multi-threading ?
What is the 2 way of creating a thread ? Which is the best way and why ?
What is the method to find if a thread is active or not ?
What are the thread-to-thread communcation ?
What is the difference between sleep and suspend ?
Can thread become a member of another thread ?
What is meant by deadlock ?
How can you avoid a deadlock ?
What are the three typs of priority ?
What is the use of synchronizations ?
Garbage collector thread belongs to which priority ?
What is meant by time-slicing ?
What is the use of ‘this’ ?
How can you find the length and capacity of a string buffer ?
How to compare two strings ?
What are the interfaces defined by Java.lang ?
What is the purpose of run-time class and system class
What is meant by Stream and Types ?
What is the method used to clear the buffer ?
What is meant by Stream Tokenizer ?
What is serialization and de-serialisation ?
What is meant by Applet ?
How to find the host from which the Applet has originated ?
What is the life cycle of an Applet ?
How do you load an HTML page from an Applet ?
What is meant by Applet Stub Interface ?
What is meant by getCodeBase and getDocumentBase method ?
How can you call an applet from a HTML file
What is meant by Applet Flickering ?
What is the use of parameter tag ?
What is audio clip Interface and what are all the methods in it ?
What is the difference between getAppletInfo and getParameterInfo ?
How to communicate between applet and an applet ?
What is meant by event handling ?
What are all the listeners in java and explain ?
What is meant by an adapter class ?
What are the types of mouse event listeners ?
What are the types of methods in mouse listeners ?
What is the difference between panel and frame ?
What is the default layout of the panel and frame ?
What is meant by controls and types ?
What is the difference between a scroll bar and a scroll panel.
What is the difference between list and choice ?
How to place a component on Windows ?
What are the different types of Layouts ?
What is meant by CardLayout ?
What is the difference between GridLayout and GridBagLayout
What is the difference between menuitem and checkboxmenu item.
What is meant by vector class, dictionary class , hash table class,and property class ?
Which class has no duplicate elements ?
What is resource bundle ?
What is an enumeration class ?
What is meant by Swing ?
What is the difference between AWT and Swing ?
What is the difference between an applet and a Japplet
What are all the components used in Swing ?
What is meant by tab pans ?
What is the use of JTree ?
How can you add and remove nodes in Jtree.
What is the method to expand and collapse nodes in a Jtree ?
What is the use of JTable ?
What is meant by JFC ?
What is the class in Swing to change the appearance of the Frame in Runtime.
How to reduce flicking in animation ?
What is JDBC ?
How do you connect to the database ? What are the steps ?
What are the drivers available in JDBC ? Explain
How can you load the driver ?
What are the different types of statement s ?
How can you created JDBC statements ?
How will you perform transactions using JDBC ?
What are the two drivers for web apllication?
What are the different types of 2 tier and 3 tier architecture ?
How can you retrieve warning in JDBC ?
What is the exception thrown by JDBC ?
What is meants by PreparedStatement ?
What is difference between PreparedStatement and Statement ?
How can you call the stored procedures ?
What is meant by a ResultSet ?
What is the difference between ExecuteUpdate and ExecuteQuery ?
How do you know which driver is connected to a database ?
What is DSN and System DSN and differentiate these two ?
What is meant by TCP, IP, UDP ?
What is the difference between TCP and UDP ?
What is a proxy server ?
What is meant by URL
What is a socket and server sockets ?
When MalformedURLException and UnknownHost Exception throws ?
What is InetAddress ?
What is datagram and datagram packets and datagram sockets ?
Write the range of multicast socket IP address ?
What is meant by a servlet ?
What are the types of servlets ? Explain
What is the different between a Servlet and a CGI.
What is the difference between 2 types of Servlets ?
What is the type of method for sending request from HTTP server ?
What are the exceptions thrown by Servlets ? Why ?
What is the life cycle of a servlet ?
What is meant by cookies ?
What is HTTP Session ?
What is the difference between GET and POST methods ?
How can you run a Servlet Program ?
How to commuincate between an applet and a servlet ?
What is a Servlet-to-Servlet communcation ?
What is Session Tracking ?
What are the security issues in Servlets ?
What is HTTP Tunneling
How do you load an image in a Servlet ?
What is Servlet Chaining ?
What is URL Rewriting ?
What is context switching ?
What is meant by RMI ?
Explain RMI Architecture ?
What is meant by a stub ?
What is meant by a skelotn ?
What is meant by serialisation and deserialisation ?
What is meant by RRL ?
What is the use of TL ?
What is RMI Registry ?
What is rmic ?
How will you pass parameter in RMI ?
What exceptions are thrown by RMI ?
What are the steps involved in RMI ?
What is meant by bind(), rebind(), unbind() and lookup() methods
What are the advanatages of RMI ?
What is JNI ?
What is Remote Interface ?
What class is used to create Server side object ?
What class is used to bind the server object with RMI Registry ?
What is the use of getWriter method ?
What is meant by Javabeans ?
What is JAR file ?
What is meant by manifest files ?
What is Introspection ?
What are the steps involved to create a bean ?
Say any two properties in Beans ?
What is persistence ?
What is the use of beaninfo ?
What are the interfaces you used in Beans ?
What are the classes you used in Beans ?
Java OOPS

1. Which of the following lines will compile without warning or error.


1) float f=1.3;
2) char c="a";
3) byte b=257;
4) boolean b=null;
5) int i=10;

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{}

4. A byte can be of what size


1) -128 to 127
2) (-2 power 8 )-1 to 2 power 8
3) -255 to 256
4)depends on the particular implementation of the Java Virtual machine
5. What will be printed out if this code is run with the following command line?
java myprog good morning
public class myprog{
public static void main(String argv[])
{
System.out.println(argv[2]);
}
}
myprog
good
morning
Exception raised: "java.lang.ArrayIndexOutOfBoundsException: 2"
6. What is the difference between an Abstract class and Interface ?
7. What is user defined exception?
8. What do you know about the garbage collector ?
9. What is the difference between C++ & Java ?
10. What is difference in between Java Class and Bean ?
Multithreading
What is a thread and how do we create and start one?
When should we use Runnable over extending the Thread class?
What threads are executed with a Hello, World application?
When should we use the synchronized modifier?
How do we implement a timer thread?
How do we assign a priority to a thread?
How do we synchronize threads?
How do we use wait() and notify()?
What is a ThreadGroup?
How do we list all threads that are running?
What is a daemon thread?
How do we suspend a thread for a certain time?
How do we check the state of a thread?
How do we create a thread pool?
Why is Thread.stop() deprecated?
So, how do we stop a thread then?
How do we pause a thread?
How do we interrupt a thread?
What is the AWT Thread and when is it started?
What is the event dispatch thread?
What does it mean for an object or method to be thread-safe?
How can we restart a thread that has stopped execution?
What is InterruptedException and how do I use it?
What is a deadlock? What is starvation?
Which thread is notified when notify() is invoked?
How much slower is a synchronized method?
How do we wait for a thread to finish?
What does Thread-safe mean?
When is a thread object garbage collected?
How do we pass the output of one thread as the input to another (using Readers/Writers)?
How do we pass the output of one thread as the input to another (using nputStream/OutputStream)?
What is a ThreadLocal variable?
What is the difference between Process and Threads ?
How does thread synchronization occurs inside a monitor ?

I/O’s

1. Which of the following can be performed using the File class?


[a] Change the current directory
[b] To get the name of the parent directory
[c] Delete a file
[d] Find if a file contains text or binary information

2. Which of the following will compile without error?


[a] File f = new File("/","autoexec.bat");
[b] DataInputStream d = new DataInputStream(System.in);
[c] OutputStreamWriter o = new OutputStreamWriter(System.out);
[d] RandomAccessFile r = new RandomAccessFile("OutFile");

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.

4. A directory can be created using a method from the following class(es)?


[a] File
[b] DataOutput
[c] Directory
[d] FileDescriptor
[e] FileOutputStream

5. If we run the following code on a on a PC from the directory c:\source:


import java.io.*;
class Path {
public static void main(String[] args) throws Exception {
File file = new File("Ran.txt");
System.out.println(file.getAbsolutePath());
}
}
What do you expect the output to be? Select the one right answer.
[a] Ran.txt
[b] source\Ran.txt
[c] c:\source\Ran.txt
[d] c:\source
[e] null

6. Which of the following correctly illustrate how an InputStreamReader can be created?


[a] new InputStreamReader(new FileInputStream("data.txt"));
[b] new InputStreamReader(new FileReader("data.txt"));
[c] new InputStreamReader(new BufferedReader("data.txt"));
[d] new InputStreamReader("data.txt");
[e] new InputStreamReader(System.in);

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 )

11. What does the following code do?


File f = new File("hello.txt");
FileOutputStream out = new FileOutputStream(f);
Select the one right answer.
[a] Create a new file named "hello.txt" if it does not yet exist. It also opens the file so you can write to it
and read from it.
[b] Create a new file named "hello.txt" if it does not yet exist.The file is not opened.
[c] Open a file named "hello.txt" so that you can write to it and read from it, but does not create the file
if it does not yet exist.
[d] Open a file named "hello.txt" so that you can write to it but cannot read from it.
[e] Create an object that you can now use to create and open the file named "hello.txt" and write to
and read from the file.

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

2. Which of the following allows duplicates, and introduces positional indexing.?


[a] Set
[b] Map
[c] Iterator
[d] List

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

4. HashSet, TreeSet classes implement Set interface?


[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

6. Which of the following gives Stack and Queue functionality?


[a] Map
[b] Collection
[c] List
[d] Set
Networking

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

How do we connect an RMI clients to Remote RMI Servers


What does Naming.bind and Naming.lookUp methods do
If we have added a method in class and we need to invoke this method, then explain the procedure to
do the same
What is Marshalling and Un Marshalling and how is it different from Object Serialization
Why do we get the exception "java.net.SocketException: Address already in use" when we try to run
the registry?
How does the distributed garbage collector detect a client that disconnects? Is it advisable to use
System.exit for graceful client termination?
what is the difference between UnicastRemote Object and Multicast Remote Object.
How do we implement Pass by reference and Pass by value in RMI
In which circumstances do we use static fields in the Remote interface.
How do we locate the RMI Registry
J2EE/EJB

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

How do stubs work in a WebLogic Server cluster?


What happens when a failure occurs and the stub cannot connect to a WebLogic Server instance?
How does a server know when another server is unavailable?
How are notifications made when a server is added to a cluster?
How do clients learn about new WebLogic Server instances?
How do clients handle DNS requests to failed servers?
How many WebLogic Servers can I have on a multi-cpu machine?
Should we use a separate network for multicast in a cluster?
What should we do if the cluster "hangs" or "freezes"?
Why does FOR UPDATE in Oracle 8 cause an ORA-01002 error?
What causes an OCIW32.dll error?
What transaction isolation levels does the WebLogic jDriver for Oracle support?
How do I use Unicode codesets with the WebLogic jDriver for Oracle driver?
How do I use OS Authentication with WebLogic jDriver for Oracle and Connection Pools?
What type of object is returned by ResultSet.getObject()?
How do I limit the number of Oracle database connections generated by WebLogic Server?
How do I call Oracle stored procedures that take no parameters?
How do I bind string values in a PreparedStatement?
Why do I get unexpected characters from 8-bit character sets in WebLogic jDriver for Oracle?
How do I learn what codesets are available in Oracle?
How do I look up an "ORA" SQLException?

Quick Revision Tips


An identifier in java must begin with a letter , a dollar sign($), or an underscore (-); subsequent
characters may be letters, dollar signs, underscores, or digits.
There are three top-level elements that may appear in a file. None of these elements is required. If they
are present, then they must appear in the following order:
-package declaration
-import statements
-class definitions
A java source file (.java file) can't have more than one public class , interface or combination of both.
"goto" is a keyword in Java.
NULL is not a keyword, but null is a keyword in Java.
A final class can't be subclassed.
A final method can't be overridden but a non final method can be overridden to final method.
Abstract classes can't be instantiated and should be subclassed.
Primitive Wrapper classes are immutable.
A static method can't refer to "this" or "super".
A static method can't be overridden to non-static and vice versa.
The variables in java can have the same name as method or class.
All the static variables are initialized when the class is loaded.
An interface can extend more than one interface, while a class can extend only one class.
The variables in an interface are implicitly final and static. If the interface , itself, is declared as public
the methods and variables are implicitly public.
Variables cannot be synchronized.
Instance variables of a class are automatically initialized, but local variables of a function need to be
initialized explicitly.
An abstract method cannot be static because the static methods can't be overridden.
The lifecycle methods of an Applet are init(), start(), stop() and destroy().
The transient keyword is applicable to variables only.
The native keyword is applicable to methods only.
The final keyword is applicable to methods , variables and classes.
The abstract keyword is applicable to methods and classes.
The static keyword is applicable to variables, methods or a block of code called static initializes.
A native method can't be abstract but it can throw exception(s).
A final class cannot have abstract methods.
A class can't be both abstract and final.
A transient variable may not be serialized.
All methods of a final class are automatically final.
While casting one class to another subclass to superclass is allowed without any type casting.
e.g.. A extends B , B b = new A(); is valid but not the reverse.
The String class in java is immutable. Once an instance is created, the string it contains cannot be
changed.
e.g. String s1 = new String("test"); s1.concat("test1"); Even after calling concat() method on s1, the
value of s1 will remain to be "test". What actually happens is a new instance is created.
But the StringBuffer class is mutable.
The + and += operators are the only cases of operator overloading in java and is applicable to Strings.
Bit-wise operators - &, ^ and | operate on numeric and boolean operands.
The short circuit logical operators && and || provide logical AND and OR operations on boolean types
and unlike & and | , these are not applicable to integral types. The valuable additional feature provided
by these operators is the right operand is not evaluated if the result of the operation can be
determined after evaluating only the left operand.
The difference between x = ++y; and x = y++;
In the first case y will be incremented first and then assigned to x. In second case first y will be assigned
to x then it will be incremented.
Please make sure you know the difference between << , >> and >>>(unsigned rightshift) operators.
The initialization values for different data types in java is as follows
byte = 0, int = 0, short = 0, char = '\u0000', long = 0L, float = 0.0f, double = 0.0d, boolean = false,
object referenece (of any object) = null.
Setting the object reference to null makes it a candidate for garbage collection.
An overriding method may not throw a checked exception unless the overridden method also throws
that exception or a superclass of that exception.
Interface methods can't be native, static, synchronized, final, private, protected or abstract.
Abstract classes can have constructors , and it can be called by super() when its subclassed.
A final variable is a constant and a static variable is like a global variable.
The String class is a final class, it can't be subclassed.
The Math class has a private constructor, it can't be instantiated.
The random() method of Math class in java returns a random number , a double , between 0.0 and 1.0.
The java.lang.Throwable class has two subclasses : Exception and Error.
An Error indicates serious problems that a reasonable application should not try to catch. Most such
errors are abnormal conditions.
The two kinds of exceptions in java are : Compile time (Checked ) and Run time (Unchecked)
exceptions. All subclasses of Exception except the RunTimeException and its subclasses are checked
exceptions.
Examples of Checked exception : IOException, ClassNotFoundException.
Examples of Runtime exception :ArrayIndexOutOfBoundsException,NullPointerException,
ClassCastException, ArithmeticException, NumberFormatException.
The unchecked exceptions do not have to be caught.
A try block may not be followed by a catch but in that case, finally block must follow try.
While using multiple catch blocks, the type of exception caught must progress from the most specific
exception to catch to the superclass(es) of these exceptions.
More than one exception can be listed in the throws clause of a method using commas. e.g. public void
myMethod() throws IOException, ArithmeticException.
On dividing an integer by 0 in java will throw ArithmeticException.
The various methods of Java.lang.Object are
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString and wait.
The Java.lang.System is a final class and can't be subclassed.
Garbage collection in java cannot be forced. The methods used to call garbage collection thread are
System.gc() and Runtime.gc()
To perform some task when an object is about to be garbage collected, you can override the finalize()
method of the Object class. The JVM only invokes finalize() method once per object. The signature of
finalize() method of Object class is : protected void finalize() throws Throwable.
The parent classes of input and output streams : InputStream and OutputStream class are abstract
classes.
File class can't be used to create a new file. For that any other output stream class such as
FileOutputStream or filter streams like PrintWriter should be used. Please note that java will create a
file only when the file is not available.
For the RandomAccessFile constructor, the mode argument must either be equal to "r" or "rw".
In java, console input is accomplished by reading from System.in .
System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream.
Both FileInputStream and FileOutputStream classes throws FileNotFoundException. In earlier versions
of java, FileOutputStream() threw an IOException when an output could not be created.
System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream.
A method can't be overridden to be more private. e.g.. a public method can only be overridden to be
public.
Both primitives and object references can be cast.
If inner class is declared in a method then it can access only final variables of the particular method but
can access all variables of the enclosing class.
To refer to a field or method in the outer class instance from within the inner class, use
Outer.this.fieldname .
Inner classes may not declare static initializers or static members unless they are compile time
constants i.e. static final var = value;
A nested class cannot have the same name as any of its enclosing classes.
Inner class may be private, protected, final, abstract or static.
An example of creation of instance of an inner class from some other class:
class Outer
{
public class Inner{}
}

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.

35. What are the advantages of OOPL?


Object oriented programming languages directly represent the real life objects. The features of OOPL as
inhreitance, polymorphism, encapsulation makes it powerful.

36. How many methods do u implement if implement the Serializable Interface?


The Serializable interface is just a "marker" interface, with no methods of its own to implement.

37. Are there any other 'marker' interfaces?


java.rmi.Remote
java.util.EventListener

38. What is the difference between instanceof and isInstance?


instanceof is used to check to see if an object can be cast into a specified type without throwing a cast
class exception. isInstance() determines if the specified object is assignment-compatible with the object
represented by this Class. This method is the dynamic equivalent of the Java language instanceof
operator. The method returns true if the specified Object argument is nonnull and can be cast to the
reference type represented by this Class object without raising a
ClassCastException. It returns false otherwise.

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.

45. Does Java have destructors?


No garbage collector does the job working in the background

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?

49. Does Java have "goto"?


No

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 r the four cornerstones of OOP ?


Abstraction : Can manage complexity through abstraction. Gives the complete
overview of a particular task and the details are handled by its derived classes. Ex : Car.
Encapsulation : Nothing but data hiding, like the variables declared under private of a particular
class are accessed only in that class and cannot access in any other the class.
Inheritance : Is the process in which one object acquires the properties of another object, ie.,
derived object.
Polymorphism : One method different forms, ie., method overriding and interfaces are the
examples of polymorphism.

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.

What is Java Interpreter ?


It is Java Virtual Machine. ie., a java program compiles the Unicode to intermediary code called as
Bytecode which is not an executable code. that is executed by Java interpreter.

What are Java Buzzwords ?


Simple : Easy to learn.
Secure : Provided by firewalls between networked applications.
Portable : Can be dynamically downloaded at various platforms connect to internet.
OOP : Four Corner stones.
Multithread : Can perform more than one task concurrently in a single program.
Robust : overcomes problems of de-allocation of memory and exceptions.
Interpreted : Convert into byte code and the executes by JVM.
Distributed : Concept of RMI.
Dynamic : Verifying and accessing objects at run time.

What are public static void main(String args[]) and System.out.println() ?


Public keyword is an access specifier.
Static allows main() to be called without having to instantiate a particular instance of class.
Void does not return any value.
main() is the method where java application begins.
String args[] receives any command line arguments during runtime.

System is a predefined class that provides access to the system.


out is output stream connected to console.
println displays the output.

What are identifiers and literals ?


Identifiers are the variables that are declared under particular datatype.
Literals are the values assigned to the Identifiers.

What is Typed language ?


This means that the variables are at first must be declared by a particular datatype whereas this is not
the case with javascript.

Scope and lifetime of variables ?


scope of variables is only to that particular block
lifetime will be till the block ends.
variables declared above the block within the class are valid to that inner block also.

Casting Incompatible types ?


Can be done either implicitly and explicitly. ie., int b = (int) c; where c is float.
There are two types of castings related to classes : 1) unicast and 2)multicast.

Declaration of Arrays ?
int a[] = new int[10]; int a[][] = new int[2][2];

What does String define ?


String is an array of characters, but in java it defines an object.
and the variable of type string can be assigned to another variable of type String.

What r bitwise operators and bitwise logical operators ?


~, &, |, ^, >>, >>>, <<, &=, != and ~, &, |
How do you define break and Label ?
We can declare as break <label name > and the label is declared as <label name> : { ….. };
The break statement can be declared anywhere in the program ie either inside the label or outside the
label.

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.

Define this , finalize, and final( for variables, methods, classes ) ?


this is used inside any method to refer to the current object. and is mostly avoided.
finalize method is used to perform the actions specified in this method just before an object is
destroyed. ie just before garbage collector process.
final with variables is we cant change the literals of the variables ie nothing but const.
final with method means we cant override that method.
final with class means we cannot have derived classes of that particular class.

What is passed by reference ?


Objects are passed by reference.
In java we can create an object pointing to a particular location ie NULL location by specifying : <class
name> <object name>;
and also can create object that allocates space for the variables declared in that particular class by
specifying : <object name > = new <class name>();

Explain about Static ?


When a member is declared as static it can be accessed before any objects of its class are created and
without any reference to any object.
these are global variables, no copy of these variables can be made.
static can also be declared for methods. and cannot refer to this or super.

What r nested classes ?


There are two types : static and non-static.
static class means the members in its enclosing class (class within class) can be accessed by creating an
object and cannot be accessed directly without creating the object.
non-static class means inner class and can be accessed directly with the object created for the outer
class no need to create again an object like static class.

Briefly about super() ?


This is used to initialize constructor of base class from the derived class and also access the variables of
base class like super.i = 10.

method overloading : same method name with different arguments.


method overriding : same method name and same number of arguments.
What is Dynamic Method Dispatch ?
this is the mechanism by which a call to an overridden function is resolved at runtime rather than at
compile time. And this is how Java implements runtime polymorphism.

What r abstract classes ?


To create a superclass that only defines generalized form that will be shared by all its subclasses,
leaving it to each subclass to fill in the details.
we cannot declare abstract constructors and abstract static methods.
An abstract class contains at least one abstract method.
And this abstract class is not directly instantiated with new operator.
Can create a reference to abstract class and can be point to subclass object.

What is Object class and java.lang ?


Object class is the superclass of all the classes and means that reference variable of type object can
refer to an object of any other class. and also defines methods like finalise,wait.
java.lang contains all the basic language functions and is imported in all the programs implicitly.

What r packages and why ? how to execute a program in a package ?


Package is a set of classes, which can be accessed by themselves and cannot be accessed outside the
package. and can be defined as package <pkg name>.
Package name and the directory name must be the same.
And the execution of programs in package is done by : java mypack.account
where mypack is directory name and account is program name.

What does a java source file can contain ?


specifying package name.
importing more than one package
specifying classes and there methods
………………

Why interface and what extends what ?


Interface is similar to abstract classes. this define only method declarations and definitions are specified
in the classes which implements these interfaces.
and “ one interface multiple methods “ signifies the polymorphism concept.
Here an interface can extend another interface.
and a class implements more than one interface.

How Exception handling is done in Java ?


Is managed via 5 keywords :
try : statements that you want to monitor the exceptions contain in try block.
catch : the exception thrown by try is catched by this.
throw : to manually throw exception we go for this.
throws : Exception that is thrown out of a method must be specified by throws after the method
declaration.
finally : this block is executed whether or not an exception is thrown. and also it is executed just before
the method returns. and this is optional block.

What r checked and unchecked Exceptions ?


* Unchecked Exceptions are those which r not included in throws list and are derived from
RuntimeException which are automatically available and are in java.lang.
* Checked Exceptions are those which cannot handle by itself.

What is Thread and multithread ? How is thread created ?


Thread is a small unit of dispatchable code. ie., a single program can perform more than one task
simultaneously. This is a light weight process and is of low cost.
MultiThreading writes more efficient programs and make maximum use of CPU ie., it minimizes its idle
time.
A Thread is created in two ways :
By implementing the runnable interface.
By extending the Thread class itself.
First way is used to update only run() method. ie we can use only run() method in this class.
Second way is used to define several methods overridden by derived class.
Generally we override only run() method so we go for runnable interface.

What are the various states and methods of thread ?


States : Running, Ready to run, Suspended, Resumed, blocked and terminated.
Methods : getName, getPriority, isAlive, join, run, sleep, start.
Thread priorities are MIN_PRIORITY, MAX_PRIORITY, NORM_PRIORITY.

What is interprocess synchronization ? ( also called Monitor, Semaphore )


Consider a small box namely MONITOR that can hold only one thread. Once a thread enters a
monitor, all other threads must wait until that thread exits the monitor.
In this way, a monitor can be used to protect a shared asset from being manipulated by more
than one thread at a time.
Once a thread is inside a synchronized method, no other thread can call any other synchronized
method on the same object.

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.

How to enter data in java ?


First specify :
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
then say br.read(), and this is put in do while loop to receive as many as we require.

Define Inline Functions ?


In ordinary functions, during the program execution, at any function call the controller jumps to
the function definition, performs operation and returns the value, then comes back to the program.
whereas in Inline functions the controller copies the complete function definition into the program and
performs operations.

What are the four components in URL ?


http:// www. yahoo .com : 8080 / index.html
http: --- > is protocol
www. yahoo .com --- is IP address
8080 -- port number and is a pointer to memory location.
index.html -- file path to be loaded

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.

How to Declare a pointer to function ?


int func_name(float) //ordinary declaration of function.
int (*func_name_ptr)(float) // Declaration of pointer.
Assigning the Address can be done as :
func_name_ptr = func_name. // Return type and Signatures must be Same.
Invoking a function pointer : int x = (*func_name_ptr)(values as specified);

What is a file ? What is a Directory ?


File : Describes the properties of file, like permissions, time, date, directory path, and to navigate
subdirectory hierarchies.
Directory : Is a file that contains list of other files and directories .

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.

Interfaces include by java.lang ?


Java.lang is the package of all the classes.
And is automatically imported into all Java programs.
Intefaces : Cloneable, Comparable, Runnable.

What is user defined exception?


To handle situations specific to our applications we go for User Defined Exceptions.
and are defined by User using throw keyword.
What is the difference between process and threads?
Process is a heavy weight task and is more cost.
Thread is a light weight task which is of low cost.
A Program can contain more than one thread.
A program under execution is called as process.

What is the difference between CGI and Servlet ?


CGI suffered serious performance problems. servlets performance is better.
CGI create separate process to handle client request. and Servlets do not.
CGI is platform dependent, whereas Servlet is platform-independent b’cauz written in java.
Servlets can communicate with applets, databases and RMI mechanisms.

What is update method called?


This method is called when your Applet has requested that a portion of its window to be
redrawn. Default version of update() first fills an applet with the default background color and then
calls paint(); This is a default method in the applet class to which we can extend it.

What are Vector, Hashtable, LinkedList and Enumeration?


Vector : The Vector class provides the capability to implement a growable array of objects.
Hashtable : The Hashtable class implements a Hashtable data structure. A Hashtable indexes and stores
objects in a dictionary using hash codes as the object's keys. Hash codes are integer values that identify
objects.
LinkedList: Removing or inserting elements in the middle of an array can be done using LinkedList. A
LinkedList stores each object in a separate link whereas an array stores object references in consecutive
locations.
Enumeration: An object that implements the Enumeration interface generates a series of elements,
one at a time. It has two methods, namely hasMoreElements( ) and nextElement( ). HasMoreElemnts( )
tests if this enumeration has more elements and nextElement method returns successive elements of
the series.

What are statements in Java (JDBC) ?


Statement -- To be used createStatement() method for executing single SQL statement
PreparedStatement -- To be used preparedStatement() method for executing same SQL statement over
and over
CallableStatement -- To be used prepareCall( ) method for multiple SQL statements over and over.

What is a JAR file?


Jar file allows to efficiently deploying a set of classes and their associated resources. The elements in a
jar file are compressed, which makes downloading a Jar file much faster than separately downloading
several uncompressed files.
The package java.util.zip contains classes that read and write jar files.
What is JNI?
java native interface : The machanism to integrate C code with a java program is called the Java Native
Interface.

What is the base class for all swing components?


Jcomponent

What is JFC? java foundation classes


(i) Pluggable Look-and-Feel
(ii) Accessibility API
(iii) Java 2D/API(JDK 1.2).
(iv) Drag and Drop Support(JDK 1.2)

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.

72) What is the difference between JDBC and ODBC?


a) OBDC is for Microsoft and JDBC is for Java applications.
b) ODBC can't be directly used with Java because it uses a C interface.
c) ODBC makes use of pointers which have been removed totally from Java.
d) ODBC mixes simple and advanced features together and has complex options for simple
queries. But JDBC is designed to keep things simple while allowing advanced capabilities when
required.
e) ODBC requires manual installation of the ODBC driver manager and driver on all client
machines. JDBC drivers are written in Java and JDBC code is automatically installable, secure, and
portable on all platforms.
JDBC API is a natural Java interface and is built on ODBC. JDBC retains some of the basic features of
ODBC.

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");

77) What is stored procedure?


Ans: Stored procedure is a group of SQL statements that forms a logical unit and performs a particular
task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database.
Stored procedures can be compiled and executed with different parameters and results and may have
any combination of input/output parameters.
78) How to create and call stored procedures?
Ans: To create stored procedures:
Create procedure procedurename (specify in, out and in out parameters)
BEGIN
Any multiple SQL statement;
END;

To call stored procedures:


CallableStatement csmt = con.prepareCall("{call procedure name(?,?)}");
csmt.registerOutParameter(column no., data type);
csmt.setInt(column no., column name)
csmt.execute( );

79) What is servlet?


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

81) What is the difference between an applet and a servlet?


Servlets are to servers what applets are to browsers.
Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.

82) What is the difference between doPost and doGet methods?


a) doGet() method is used to get information, while doPost( ) method is used for posting information.
b) doGet() requests can't send large amount of information and is limited to 240-255 characters.
However, doPost( )requests passes all of its data, of unlimited length.
c) A doGet( ) request is appended to the request URL in a query string and this allows the exchange is
visible to the client, whereas a doPost() request passes directly over the socket connection as part of
its HTTP request body and the exchange are invisible to the client.

83) What is the life cycle of a servlet?


Ans: Each Servlet has the same life cycle:
a) A server loads and initializes the servlet by init () method.
b) The servlet handles zero or more client's requests through service( ) method.
c) The server removes the servlet through destroy() method.

84) Who is loading the init() method of servlet?


Ans: Web server

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

Steps involved for applet-servlet communication:


1) Get the server URL. URL url = new URL();
2) Connect to the host URLConnection Con = url.openConnection();
3) Initialize the connection Con.setUseCatches(false):
Con.setDoOutput(true);
Con.setDoInput(true);
4) Data will be written to a byte array buffer so that we can tell the server the length of the data.
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
5) Create the OutputStream to be used to write the data to the buffer.
DataOutputStream out = new DataOutputStream(byteout);

91) What is connection pooling?


Ans: With servlets, opening a database connection is a major bottleneck because we are creating and
tearing down a new connection for every page request and the time taken to create connection will be
more.
Creating a connection pool is an ideal approach for a complicated servlet. With a connection pool,
we can duplicate only the resources we need to duplicate rather than the entire servlet. A connection
pool can also intelligently manage the size of the pool and make sure each connection remains valid. A
number of connection pool packages are currently available. Some like DbConnectionBroker are freely
available from Java Exchange Works by creating an object that dispenses connections and connection
Ids on request.
The ConnectionPool class maintains a Hastable, using Connection objects as keys and Boolean
values as stored values. The Boolean value indicates whether a connection is in use or not. A program
calls getConnection( ) method of the ConnectionPool for getting Connection object it can use; it calls
returnConnection( ) to give the connection back to the pool.

92) Why should we go for interservlet communication?


Servlets running together in the same server communicate with each other in several ways.
The three major reasons to use interservlet communication are:
a) Direct servlet manipulation - allows to gain access to the other currently loaded servlets and
perform certain tasks (through the ServletContext object)
b) Servlet reuse - allows the servlet to reuse the public methods of another servlet.
c) Servlet collaboration - requires to communicate with each other by sharing specific information
(through method invocation)

93) Is it possible to call servlet with parameters in the URL?


Ans: Yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy).

94) What is Servlet chaining?


Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single
request. In servlet chaining, one servlet's output is piped to the next servlet's input. This process
continues until the last servlet is reached. Its output is then sent back to the client.

95) How do servlets handle multiple simultaneous requests?


The server has multiple threads that are available to handle requests. When a request comes in, it is
assigned to a thread, which calls a service method (for example: doGet(), doPost( ) and service( ) ) of
the servlet. For this reason, a single servlet object can have its service methods called by many threads
at once.

96) What is the difference between TCP/IP and UDP?


Ans: TCP/IP is a two-way communication between the client and the server and it is a reliable and there
is a confirmation regarding reaching the message to the destination. It is like a phone call.
UDP is a one-way communication only between the client and the server and it is not a reliable
and there is no confirmation regarding reaching the message to the destination. It is like a postal mail.

97) What is Inet address?


Ans: Every computer connected to a network has an IP address. An IP address is a number that
uniquely identifies each computer on the Net. An IP address is a 32-bit number.
98) What is Domain Naming Service(DNS)?
Ans: It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The
Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a
string of characters.
For example, www.mascom.com implies com is the domain name reserved for US commercial
sites, moscom is the name of the company and www is the name of the specific computer, which is
mascom's server.

99) What is URL?


Ans: URL stands for Uniform Resource Locator and it points to resource files on the Internet.
URL has four components:
http://www.Pentafour.com:80/index.html
http - protocol name, Pentafour - IP address or host name, 80 - port number and index.html - file
path.

100) What is RMI and steps involved in developing an RMI object?


Ans: Remote Method Invocation (RMI) allows java object that executes on one machine and to invoke
the method of a Java object to execute on another machine.
The steps involved in developing an RMI object are:
a) Define the interfaces
b) Implementing these interfaces
c) Compile the interfaces and their implementations with the java compiler
d) Compile the server implementation with RMI compiler
e) Run the RMI registry
f) Run the application

101) What is RMI architecture?


a) Application layer ---- contains the actual object definition
b) Proxy layer ---- consists of stub and skeleton
c) Remote Reference layer ---- gets the stream of bytes from the transport layer and sends it to
the proxy layer
d) Transportation layer ---- responsible for handling the actual machine-to-machine
communication
102) what is UnicastRemoteObject?
Ans: All remote objects must extend UnicastRemoteObject, which provides functionality that is needed
to make objects available from remote machines.

103) Explain the methods, rebind( ) and lookup() in Naming class?


Ans: rebind( ) of the Naming class(found in java.rmi) is used to update the RMI registry on the server
machine. Naming. rebind("AddSever", AddServerImpl);
lookup( ) of the Naming class accepts one argument, the rmi URL and returns a reference to an
object of type AddServerImpl.

104) What is a Java Bean?


Ans: A Java Bean is a software component that has been designed to be reusable in a variety of
different environments.

106) What is BDK?


Ans: BDK, Bean Development Kit is a tool that enables to create, configure and connect a set of set of
Beans and it can be used to test Beans without writing a code.

107) What is JSP?


Ans: JSP is a dynamic scripting capability for web pages that allows Java as well as a few special tags to
be embedded into a web file (HTML/XML, etc). The suffix traditionally ends with .jsp to indicate to the
web server that the file is a JSP files. JSP is a server side technology - you can't do any client side
validation with it.
The advantages are:
a) The JSP assists in making the HTML more functional. Servlets on the other hand allow
outputting of HTML but it is a tedious process.
b) It is easy to make a change and then let the JSP capability of the web server you are using deal
with compiling it into a servlet and running it.

108) What are JSP scripting elements?


Ans: JSP scripting elements lets to insert Java code into the servlet that will be generated from the
current JSP page.
There are three forms:
a) Expressions of the form <%= expression %> that are evaluated and inserted into the output,
b) Scriptlets of the form <% code %> that are inserted into the servlet's service method, and
c) Declarations of the form <%! Code %> that are inserted into the body of the servlet class,
outside of any existing methods.

109) What are JSP Directives?


Ans: A JSP directive affects the overall structure of the servlet class. It usually has the following form:
<%@ directive attribute="value" %>
However, you can also combine multiple attribute settings for a single directive, as follows: <%@
directive attribute1="value1" attribute 2="value2" ... attributeN ="valueN" %>
There are two main types of directive: page, which lets to do things like import classes, customize
the servlet superclass, and the like; and include, which lets to insert a file into the servlet class at the
time the JSP file is translated into a servlet

110) What are Predefined variables or implicit objects?


Ans: To simplify code in JSP expressions and scriptlets, we can use eight automatically defined variables,
sometimes called implicit objects. They are request, response, out, session, application, config,
pageContext, and page.

5. What is Bootstrapping in RMI?


Dynamic loading of stubs and skeletons is known as Boot Strapping.

6. What are different types of Exceptions?.


Runtime exceptions, Errors, Program Exceptions

9. What is servlet tunnelling?.


Used in applet to servlet communications, a layer over http is built so as to enable object serialization.

11.What is the frontend in Java?.Also what is Backend?.


Frontend: Applet
Backend : Oracle, Ms-Access(Using JDBC).

25. Which of the following attributes are compulsory with an <applet> tag?.
code,height & width.

26. What does 'CODEBASE' in an applet tag specify?.


Files absolute path.

Access Modifiers: Which gives additional meaning to data, methods and classes.

28. Tools provided by JDK


(i) javac - compiler
(ii) java - interpretor
(iii) jdb - debugger
(iv) javap - Disassembles
(v) appletviewer - Applets
(vi) javadoc - documentation generator
(vii) javah - 'C' header file generator

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.

31.Compiling: Conversion of Programmer-readable Text into Bytecodes,which are platform


independent,is known as Compiling.

32.Java Primitive Data Types:


Byte-8-bit, short-16-bit, int-32-bit, Long-64-bit, Float-32-bit floating point, Double-64-bit floating point,
Char-16-bit Unicode

33.What is a unicode?
Unicode is a standard that supports International Characters.

34. What are blocks?.


They are statements appearing within braces {}.
35. What are types of Java applications?.
(i) Standalone applications(No browser).
(ii) Applets(Browser).

36. What is the method that gets invoked first in a stand alone application?.
The main()method.

37. What is throwing an Exception?.


The act of passing an Exception Object to the runtime system is called Throwing an Exception.

38. What are the packages in JDK?.


There are 8 packages
(i) java.lang(ii)java.util(iii)java.io(iv)java.applet(v) java.awt
(vi) java.awt.image(vii)java.awt.peer(viii)java.awt.net

40. What is runnable?.


Its an Interface through which Java implements Threads.The class can extend from any class but if it
implements Runnable,Threads can be used in that particular application.

41. What is preemptive and Non-preemptive Time Scheduling?.


Preemptive: Running tasks are given small portions of time to execute by using time-slicing.
Non-Preemptive: One task doesn't give another task a chance to run until its finished or has normally
yielded its time.

42. What is synchronization?.


Two or more threads trying to access the same method at the same point of time leads to
synchronization.If that particular method is declared as synchronized only one thread can access it at a
time. Another thread can access it only if the first thread's task is complete.

47.executeQuery() returns ResultSet.

48.Throwable class is a sub-class of object and implements Serializable.

50. Skeletons are server side proxies and stubs are client side proxies. True

52. Netscape introduced JScript language - True

53. EventDelegation model was introduced by JDK 1.1 - False

54. StringTokenizer provides two constructors - False

55. java.applet is one of the smallest package in Java API - True

57. What is IP?.


IP is Internet Protocol. It is the network protocol which is used to send information from one computer
to another over the network over the internet in the form of packets.

MIME(Multipurpose Internet Mail Extension) is a general method by which the content of different
types of Internet objects can be identified.

61. What is an abstract class?.


A class which cannot be Instantiated.

63.How many standard ports are available?.


1024.

65. What are different ways of Session-Tracking?.


(i) User-Authorization
(ii) Hidden Files
(iii) Persistant Cookies
(iv) URL Rewriting.

67. What is a Swing?.


It is a GUI component with a plug gable look and feel.

68. What is default Look-and-Feel of a Swing Component?.


Java Look-and-Feel.

69. Awt Components and Swing Components can be inter-mingled in an Application - False

71. What does x mean in javax.swing?. Extension of java.

72. Images can be displayed on Swing Components - True

73. Borders can be changed or added for a LightWeight Components - True

74. Swing Components are always rectangular - False

75. When Swing components overlap with Heavyweight components, it is the latter that is on the
top - True

77. What are invisible components?.


They are light weight components that perform no painting, but can take space in the GUI.

79. What are the borders provided by Swing?.


(i) Simple (ii) Matte iii) Titled iv) Compound.

83. What is the superclass of exception?. Throwable.

86. What are the restrictions imposed by a Security Manager on Applets?.


i) cannot read or write files on the host that's executing it.
ii) cannot load libraries or define native methods.
iii) cannot make network connections except to the host that it came from
iv) cannot start any program on the host that's executing it.
v) cannot read certain system properties.
vi) windows that an applet brings up look different than windows that an application brings up.

2)what is the difference between Procedural and OOPs?


Ans: a) In procedural program, programming logic follows certain procedures and the instructions are
executed one after another. In OOPs program, unit of program is object, which is nothing but
combination of data and code.
b) In procedural program,data is exposed to the whole program whereas in OOPs program,it is
accessible within the object and which in turn assures the security of the code.

4)What is the difference between Assignment and Initialization?


Ans: Assignment can be done as many times as desired whereas initialization can be done only once.

5)What are Class, Constructor and Primitive data types?


Ans: Class is a template for multiple objects with similar features and it is a blue print for objects. It
defines a type of object according to the data the object can hold and the operations the object can
perform.

Constructor is a special kind of method that determines how an object is initialized when created.

Primitive data types are 8 types and they are:


byte, short, int, long
float, double
boolean
char

6)What is an Object and how do you allocate memory to it?


Ans: Object is an instance of a class and it is a software unit that combines a structured set of data with
a set of operations for inspecting and manipulating that data. When an object is created using new
operator, memory is allocated to it.

7)What is the difference between constructor and method?


Ans: Constructor will be automatically invoked when an object is created whereas method has to be
called explicitly.

8)What are methods and how are they defined?


Ans: Methods are functions that operate on instances of classes in which they are defined. Objects can
communicate with each other using methods and can call methods in other classes.
Method definition has four parts. They are name of the method, type of object or primitive type
the method returns, a list of parameters and the body of the method. A method's signature is a
combination of the first three parts mentioned above.
9)What is the use of bin and lib in JDK?
Ans: Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all
packages.

10)What is casting?
Ans: Casting is used to convert the value of one type to another.

12)What is the difference between an argument and a parameter?


Ans: While defining method, variables passed in the method are called parameters. While using those
methods, values passed to those variables are called arguments.

16)What is Garbage Collection and how to call it explicitly?


Ans: When an object is no longer referred to by any variable, java automatically reclaims memory used
by that
object. This is known as garbage collection.
System.gc() method may be used to call it explicitly.

17)What is finalize() method ?


Ans: finalize () method is used just before an object is destroyed and can be called just prior to garbage
collection.

18)What are Transient and Volatile Modifiers?


Ans: Transient: The transient modifier applies to variables only and it is not stored as part of its object's
Persistent state. Transient variables are not serialized.
Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable
modified by
volatile can be changed unexpectedly by other parts of the program.

19)What is method overloading and method overriding?


Ans: Method overloading: When a method in a class having the same method name with different
arguments is said to be method overloading.
Method overriding : When a method in a class having the same method name with same arguments is
said to be method overriding.

20)What is difference between overloading and overriding?


Ans: a) In overloading, there is a relationship between methods available in the same class whereas in
overriding, there is relationship between a superclass method and subclass method.
b) Overloading does not block inheritance from the superclass whereas overriding blocks
inheritance from the superclass.
c) In overloading, separate methods share the same name whereas in overriding,subclass method
replaces the superclass.
d) Overloading must have different method signatures whereas overriding must have same
signature.

21) What is meant by Inheritance and what are its advantages?


Ans: Inheritance is the process of inheriting all the features from a class. The advantages of inheritance
are reusability of code and accessibility of variables and methods of the super class by subclasses.

22)What is the difference between this() and super()?


Ans: this() can be used to invoke a constructor of the same class whereas super() can be used to invoke
a super class constructor.

23)What is the difference between superclass and subclass?


Ans: A super class is a class that is inherited whereas sub class is a class that does the inheriting.

24) What modifiers may be used with top-level class?


Ans: public, abstract and final can be used for top-level class.

25)What are inner class and anonymous class?


Ans: Inner class : classes defined in other classes, including those defined in methods are called inner
classes.
An inner class can have any accessibility including private.
Anonymous class : Anonymous class is a class defined inside a method without a name and is
instantiated and declared in the same place and cannot have explicit constructors.

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.

27) What is a reflection package?


Ans: java.lang.reflect package has the ability to analyze itself in runtime.

28) What is interface and its use?


Ans: Interface is similar to a class which may contain method's signature only but not bodies and it is a
formal set of method and constant declarations that must be defined by the class that implements it.
Interfaces are useful for:
a) Declaring methods that one or more classes are expected to implement
b) Capturing similarities between unrelated classes without forcing a class relationship.
c) Determining an object's programming interface without revealing the actual body of the class.

30) What is the difference between Integer and int?


Ans: a) Integer is a class defined in the java.lang package, whereas int is a primitive data type defined in
the Java language itself. Java does not automatically convert from one to the other.
b) Integer can be used as an argument for a method that requires an object, whereas int can be used
for calculations.

32) What is the difference between abstract class and interface?


Ans: a) All the methods declared inside an interface are abstract whereas abstract class must have at
least one abstract method and others may be concrete or abstract.
b) In abstract class, key word abstract must be used for the methods
Whereas interface we need not use that keyword for the methods.
c) Abstract class must have subclasses whereas interface can't have subclasses.

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.

36) What is the difference between exception and error?


Ans: The exception class defines mild error conditions that your program encounters.
Ex: Arithmetic Exception, FilenotFound exception
Exceptions can occur when
-- try to open the file, which does not exist
-- the network connection is disrupted
-- operands being manipulated are out of prescribed ranges
-- the class file you are interested in loading is missing
The error class defines serious error conditions that you should not attempt to recover from. In
most cases it is advisable to let the program terminate when such an error is encountered.
Ex: Running out of memory error, Stack overflow error.

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.

42) When you will synchronize a piece of your code?


Ans: When you expect your code will be accessed by different threads and these threads may change a
particular data causing data corruption.

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.

47)What is the difference between applications and applets?


Ans: a)Application must be run on local machine whereas applet needs no explicit installation on local
machine.
b)Application must be run explicitly within a java-compatible virtual machine whereas applet loads and
runs itself automatically in a java-enabled browser.
d)Application starts execution with its main method whereas applet starts execution with its init
method.
e)Application can run with or without graphical user interface whereas applet must run within a
graphical user interface.

48)How does applet recognize the height and width?


Ans:Using getParameters() method.

49)When do you use codebase in applet?


Ans:When the applet class file is not in the same directory, codebase is used.

51)How do you set security in applets?


Ans: using setSecurityManager() method

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

54)What is source and listener ?


Ans: source : A source is an object that generates an event. This occurs when the internal state of that
object changes in some way.
listener : A listener is an object that is notified when an event occurs. It has two major
requirements. First, it must have been registered with one or more sources to receive notifications
about specific types of events. Second, it must implement methods to receive and process these
notifications.

55) What is adapter class?


Ans: An adapter class provides an empty implementation of all methods in an event listener interface.
Adapter classes are useful when you want to receive and process only some of the events that are
handled by a particular event listener interface. You can define a new class to act listener by extending
one of the adapter classes and implementing only those events in which you are interested.

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.

57) What is the difference between choice and list?


Ans: A Choice is displayed in a compact form that requires you to pull it down to see the list of available
choices and only one item may be selected from a choice.
A List may be displayed in such a way that several list items are visible and it supports the
selection of one or more list items.

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.

61) Which containers use a Border layout as their default layout?


Ans: Window, Frame and Dialog classes use a BorderLayout as their layout.
62) Which containers use a Flow layout as their default layout?
Ans: Panel and Applet classes use the FlowLayout as their default layout.

63) What are wrapper classes?


Ans: Wrapper classes are classes that allow primitive types to be accessed as objects.

65) What is the difference between set and list?


Ans: Set stores elements in an unordered way but does not contain duplicate elements, whereas list
stores elements in an ordered way but may contain duplicate elements.

what is the basic difference in rmi & corba.


both are distributed technologies.
rmi is used when both client & server are in java.
corba is used when client & server are written in different lang.
IDL comes into picture. as it changes native calls to java or vice versa.

what does class.forName(driver) do?


it requests for the driver & loads the driver.

statement.execute() returns resultset.


what type of resultset is it?
---> sql result set

JSP interview questions


What is JSP? Describe its concept. JSP is a technology that combines HTML/XML markup languages
and elements of Java programming Language to return dynamic content to the Web client, It is
normally used to handle Presentation logic of a web application, although it may have business logic.
What are the lifecycle phases of a JSP?
JSP page looks like a HTML page but is a servlet. When presented with JSP page the JSP engine does the
following 7 phases.
Page translation: -page is parsed, and a java file which is a servlet is created.
Page compilation: page is compiled into a class file
Page loading : This class file is loaded.
Create an instance :- Instance of servlet is created
jspInit() method is called
_jspService is called to handle service calls
_jspDestroy is called to destroy it when the servlet is not required.
What is a translation unit? JSP page can include the contents of other HTML pages or other JSP files.
This is done by using the include directive. When the JSP engine is presented with such a JSP page it is
converted to one servlet class and this is called a translation unit, Things to remember in a translation
unit is that page directives affect the whole unit, one variable declaration cannot occur in the same unit
more than once, the standard action jsp:useBean cannot declare the same bean twice in one unit.
How is JSP used in the MVC model? JSP is usually used for presentation in the MVC pattern (Model
View Controller ) i.e. it plays the role of the view. The controller deals with calling the model and the
business classes which in turn get the data, this data is then presented to the JSP for rendering on to
the client.
What are context initialization parameters? Context initialization parameters are specified by the
<context-param> in the web.xml file, these are initialization parameter for the whole application and
not specific to any servlet or JSP.
What is a output comment? A comment that is sent to the client in the viewable page source. The JSP
engine handles an output comment as un-interpreted 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.
What is a Hidden Comment? A comment 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.
What is a Expression? Expressions are act as place holders for language expression, expression is
evaluated each time the page is accessed.
What is a Declaration? It 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 semicolons separate them. The declaration
must be valid in the scripting language used in the JSP file.
What is a Scriptlet? 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
declare variables or methods to use later in the file, write expressions valid in the page scripting
language, use any of the JSP implicit objects or any object declared with a <jsp:useBean>.
What are the implicit objects? List them. 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 are:
request
response
pageContext
session
application
out
config
page
exception
What’s the difference between forward and sendRedirect? 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 completely with in the web container And
then returns to the calling method. When a sendRedirect 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 completely 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.
What are the different scope values for the <jsp:useBean>? The different scope values for
<jsp:useBean> are:
page
request
session
application
Why are JSP pages the preferred API for creating a web-based client program? Because no plug-ins or
security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and
more module application design because they provide a way to separate applications programming
from web page design. This means personnel involved in web page design do not need to understand
Java programming language syntax to do their jobs.
Is JSP technology extensible? Yes, it is. JSP technology is extensible through the development of
custom actions, or tags, which are encapsulated in tag libraries.
What is difference between custom JSP tags and beans? Custom JSP tag is a tag you defined. You
define how a tag, its attributes and its body are interpreted, and then group your tags into collections
called tag libraries that can be used in any number of JSP files. Custom tags and beans accomplish the
same goals – encapsulating complex behavior into simple and accessible forms. There are several
differences:
Custom tags can manipulate JSP content; beans cannot.
Complex operations can be reduced to a significantly simpler form with custom tags than with beans.
Custom tags require quite a bit more work to set up than do beans.
Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one
servlet and used in a different servlet or JSP page.
Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.

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

with keyword interface, you can fully abstract a class' interface


you specify what a class does, but not how
lack instance variables
methods declared without body
any number of classes can implement interface
class can implement any number of interfaces
class must create complete set of methods
class free to determine implementation
interfaces are designed to support dynamic method resolution at runtime
variables can be declared inside interface; are final and static implicitly
all members are implicitly public if interface is declared public
polymorphism can be implemented by having multiple implementation of interfaces

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

Java implements it as object String, and not as an array


therefore, numerous constructors are available
also, numerous methods can be used for it
String is in Java.lang and is final
strings are immutable
stringBuffer available as option
One potential use of inner classes is to help define the interface of a class

• A Vector is like an array of Objects


• Differences between arrays and Vectors:
– Arrays have special syntax; Vectors don’t
– You can have an array of any type, but a Vector holds Objects
– An array is a fixed size, but a Vector expands as you add things to it
• This means you don’t need to know the size beforehand
• A Vector is like an array of Objects
• The advantage of a Vector is that you don’t need to know beforehand how big to make it
• The disadvantage of a Vector is that you can’t use the special syntax for arrays
• You should never use an array that you hope is “big enough”--use a Vector instead

1. 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.
2. What is the difference between the Boolean & operator and the && operator? - If an
expression involving the Boolean & operator is evaluated, both operands are evaluated. Then
the & operator is applied to the operand. When an expression involving the && operator is
evaluated, the first operand is evaluated. If the first operand returns a value of true then the
second operand is evaluated. The && operator is then applied to the first and second operands.
If the first operand evaluates to false, the evaluation of the second operand is skipped.
3. How many times may an object’s finalize() method be invoked by the garbage collector? - An
object’s finalize() method may only be invoked once by the garbage collector.
4. 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.
5. What is the argument type of a program’s main() method? - A program’s main() method takes
an argument of the String[] type.
6. Which Java operator is right associative? - The = operator is right associative.
7. Can a double value be cast to a byte? - Yes, a double value can be cast to a byte.
8. What is the difference between a break statement and a continue statement? - A break
statement results in the termination of the statement to which it applies (switch, for, do, or
while). A continue statement is used to end the current loop iteration and return control to the
loop statement.
9. 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.
10. What is the advantage of the event-delegation model over the earlier event-inheritance
model? - The event-delegation model has two advantages over the event-inheritance model.
First, it enables event handling to be handled by objects other than the ones that generate the
events (or their containers). This allows a clean separation between a component’s design and
its use. The other advantage of the event-delegation model is that it performs much better in
applications where many events are generated. This performance improvement is due to the
fact that the event-delegation model does not have to repeatedly process unhandled events, as
is the case of the event-inheritance model.
11. How are commas used in the intialization and iteration parts of a for statement? - Commas
are used to separate multiple statements within the initialization and iteration parts of a for
statement.
12. What is an abstract method? - An abstract method is a method whose implementation is
deferred to a subclass.
13. What value does read() return when it has reached the end of a file? - The read() method
returns -1 when it has reached the end of a file.
14. Can a Byte object be cast to a double value? - No, an object cannot be cast to a primitive value.
15. What is the difference between a static and a non-static inner class? - A non-static inner class
may have object instances that are associated with instances of the class’s outer class. A static
inner class does not have any object instances.
16. If a variable is declared as private, where may the variable be accessed? - A private variable
may only be accessed within the class in which it is declared.
17. What is an object’s lock and which object’s have locks? - An object’s lock is a mechanism that is
used by multiple threads to obtain synchronized access to the object. A thread may execute a
synchronized method of an object only after it has acquired the object’s lock. All objects and
classes have locks. A class’s lock is acquired on the class’s Class object.
18. What is the % operator? - It is referred to as the modulo or remainder operator. It returns the
remainder of dividing the first operand by the second operand.
19. When can an object reference be cast to an interface reference? - An object reference be cast
to an interface reference when the object implements the referenced interface.
20. Which class is extended by all other classes? - The Object class is extended by all other classes.
21. Can an object be garbage collected while it is still reachable? - A reachable object cannot be
garbage collected. Only unreachable objects may be garbage collected.
22. Is the ternary operator written x : y ? z or x ? y : z ? - It is written x ? y : z.
23. How is rounding performed under integer division? - The fractional part of the result is
truncated. This is known as rounding toward zero.
24. 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.
25. 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.
26. If a class is declared without any access modifiers, where may the class be accessed? - A class
that is declared without any access modifiers is said to have package access. This means that
the class can only be accessed by other classes and interfaces that are defined within the same
package.
27. Does a class inherit the constructors of its superclass? - A class does not inherit constructors
from any of its superclasses.
28. What is the purpose of the System class? - The purpose of the System class is to provide access
to system resources.
29. Name the eight primitive Java types. - The eight primitive types are byte, char, short, int, long,
float, double, and boolean.
30. Which class should you use to obtain design information about an object? - The Class class is
used to obtain information about an object’s design.
31. What is garbage collection? What is the process that is responsible for doing that in java? -
Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this
process
32. What kind of thread is the Garbage collector thread? - It is a daemon thread.
33. What is a daemon thread? - These are the threads which can run without user intervention.
The JVM can exit when there are daemon thread by killing them abruptly.
34. How will you invoke any external process in Java? - Runtime.getRuntime().exec(….)
35. What is the finalize method do? - Before the invalid objects get garbage collected, the JVM give
the user a chance to clean up some resources before it got garbage collected.
36. What is mutable object and immutable object? - If a object value is changeable then we can
call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an
object, it is immutable object. (Ex., String, Integer, Float, …)
37. What is the basic difference between string and stringbuffer object? - String is an immutable
object. StringBuffer is a mutable object.
38. What is the purpose of Void class? - The Void class is an uninstantiable placeholder class to
hold a reference to the Class object representing the primitive Java type void.
39. What is reflection? - Reflection allows programmatic access to information about the fields,
methods and constructors of loaded classes, and the use reflected fields, methods, and
constructors to operate on their underlying counterparts on objects, within security restrictions.
40. What is the base class for Error and Exception? - Throwable
41. What is the byte range? -128 to 127
42. What is the implementation of destroy method in java.. is it native or java code? - This
method is not implemented.
43. What is a package? - To group set of classes into a single unit is known as packaging. Packages
provides wide namespace ability.
44. What are the approaches that you will follow for making a program very efficient? - By
avoiding too much of static methods avoiding the excessive and unnecessary use of
synchronized methods Selection of related classes based on the application (meaning
synchronized classes for multiuser and non-synchronized classes for single user) Usage of
appropriate design patterns Using cache methodologies for remote invocations Avoiding
creation of variables within a loop and lot more.
45. What is a DatabaseMetaData? - Comprehensive information about the database as a whole.
46. What is Locale? - A Locale object represents a specific geographical, political, or cultural region
47. How will you load a specific locale? - Using ResourceBundle.getBundle(…);
48. What is JIT and its use? - Really, just a very fast compiler… In this incarnation, pretty much a
one-pass compiler – no offline computations. So you can’t look at the whole method, rank the
expressions according to which ones are re-used the most, and then generate code. In theory
terms, it’s an on-line problem.
49. Is JVM a compiler or an interpreter? - Interpreter
50. When you think about optimization, what is the best way to findout the time/memory
consuming process? - Using profiler
51. What is the purpose of assert keyword used in JDK1.4.x? - In order to validate certain
expressions. It effectively replaces the if block and automatically throws the AssertionError on
failure. This keyword should be used for the critical arguments. Meaning, without that the
method does nothing.
52. How will you get the platform dependent values like line separator, path separator, etc., ? -
Using Sytem.getProperty(…) (line.separator, path.separator, …)
53. What is skeleton and stub? what is the purpose of those? - Stub is a client side representation
of the server, which takes care of communicating with the remote server. Skeleton is the server
side representation. But that is no more in use… it is deprecated long before in JDK.
54. What is the final keyword denotes? - final keyword denotes that it is the final implementation
for that method or variable or class. You can’t override that method/variable/class any more.
55. What is the significance of ListIterator? - You can iterate back and forth.
56. What is the major difference between LinkedList and ArrayList? - LinkedList are meant for
sequential accessing. ArrayList are meant for random accessing.
57. What is nested class? - If all the methods of a inner class is static then it is a nested class.
58. What is inner class? - If the methods of the inner class can only be accessed via the instance of
the inner class, then it is called inner class.
59. What is composition? - Holding the reference of the other class within some other class is
known as composition.
60. What is aggregation? - It is a special type of composition. If you expose all the methods of a
composite class and route the method call to the composite method through its reference, then
it is called aggregation.
61. What are the methods in Object? - clone, equals, wait, finalize, getClass, hashCode, notify,
notifyAll, toString
62. Can you instantiate the Math class? - You can’t instantiate the math class. All the methods in
this class are static. And the constructor is not public.
63. What is singleton? - It is one of the design pattern. This falls in the creational pattern of the
design pattern. There will be only one instance for that entire JVM. You can achieve this by
having the private constructor in the class. For eg., public class Singleton { private static final
Singleton s = new Singleton(); private Singleton() { } public static Singleton getInstance() { return
s; } // all non static methods … }
64. What is DriverManager? - The basic service to manage set of JDBC drivers.
65. What is Class.forName() does and how it is useful? - It loads the class into the ClassLoader. It
returns the Class. Using that you can get the instance ( “class-instance".newInstance() ).
66. Inq adds a question: Expain the reason for each keyword of

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?

1. What's the JDBC 3.0 API?

The JDBC 3.0 API is the latest update of the JDBC API. It contains many features, including
scrollable result sets and the SQL:1999 data types.

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

3. Can the JDBC-ODBC Bridge be used with applets?

Use of the JDBC-ODBC bridge from an untrusted applet running in a browser, such as Netscape
Navigator, isn't allowed. The JDBC-ODBC bridge doesn't allow untrusted code to call it for
security reasons. This is good because it means that an untrusted applet that is downloaded by
the browser can't circumvent Java security by calling ODBC. Remember that ODBC is native
code, so once ODBC is called the Java programming language can't guarantee that a security
violation won't occur. On the other hand, Pure Java JDBC drivers work well with applets. They
are fully downloadable and do not require any client-side configuration.

Finally, we would like to note that it is possible to use the JDBC-ODBC bridge with applets that
will be run in appletviewer since appletviewer assumes that applets are trusted. 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

6. What JDBC technology-enabled drivers are available?

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

Back to Top

7. What documentation is available for the JDBC API?

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

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

9. What causes the "No suitable driver" error?

"No suitable driver" is an error that usually occurs during a call to the
DriverManager.getConnection method. The cause can be failing to load the appropriate JDBC
drivers before calling the getConnection method, or it can be specifying an invalid JDBC URL--
one that isn't recognized by your JDBC driver. Your best bet is to check the documentation for
your JDBC driver or contact your JDBC driver vendor if you suspect that the URL you are
specifying is not being recognized by your JDBC driver.

In addition, when you are using the JDBC-ODBC Bridge, this error can occur if one or more the
the shared libraries needed by the Bridge cannot be loaded. If you think this is the cause, check
your configuration to be sure that the shared libraries are accessible to the Bridge.

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

14. Is the JDBC-ODBC Bridge multi-threaded?

No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The
JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC.
Multi-threaded Java programs may use the Bridge, but they won't get the advantages of multi-
threading. In addition, deadlocks can occur between locks held in the database and the
semaphore used by the Bridge. We are thinking about removing the synchronized methods in
the future. They were added originally to make things simple for folks writing Java programs
that use a single-threaded ODBC driver.

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

20. If I use the JDBC API, do I have to use ODBC underneath?

No, this is just one of many possible solutions. We recommend using a pure Java JDBC
technology-enabled driver, type 3 or 4, in order to get all of the benefits of the Java
programming language and the JDBC API.
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?

1. What's the JDBC 3.0 API?


The JDBC 3.0 API is the latest update of the JDBC API. It contains many features, including scrollable
result sets and the SQL:1999 data types.

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

3. Can the JDBC-ODBC Bridge be used with applets?

Use of the JDBC-ODBC bridge from an untrusted applet running in a browser, such as Netscape
Navigator, isn't allowed. The JDBC-ODBC bridge doesn't allow untrusted code to call it for security
reasons. This is good because it means that an untrusted applet that is downloaded by the browser
can't circumvent Java security by calling ODBC. Remember that ODBC is native code, so once ODBC is
called the Java programming language can't guarantee that a security violation won't occur. On the
other hand, Pure Java JDBC drivers work well with applets. They are fully downloadable and do not
require any client-side configuration.

Finally, we would like to note that it is possible to use the JDBC-ODBC bridge with applets that will be
run in appletviewer since appletviewer assumes that applets are trusted. 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

6. What JDBC technology-enabled drivers are available?

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

Back to top

7. What documentation is available for the JDBC API?

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

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

9. What causes the "No suitable driver" error?

"No suitable driver" is an error that usually occurs during a call to the DriverManager.getConnection
method. The cause can be failing to load the appropriate JDBC drivers before calling the getConnection
method, or it can be specifying an invalid JDBC URL--one that isn't recognized by your JDBC driver. Your
best bet is to check the documentation for your JDBC driver or contact your JDBC driver vendor if you
suspect that the URL you are specifying is not being recognized by your JDBC driver.

In addition, when you are using the JDBC-ODBC Bridge, this error can occur if one or more the the
shared libraries needed by the Bridge cannot be loaded. If you think this is the cause, check your
configuration to be sure that the shared libraries are accessible to the Bridge.

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

14. Is the JDBC-ODBC Bridge multi-threaded?

No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC
Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded
Java programs may use the Bridge, but they won't get the advantages of multi-threading. In addition,
deadlocks can occur between locks held in the database and the semaphore used by the Bridge. We are
thinking about removing the synchronized methods in the future. They were added originally to make
things simple for folks writing Java programs that use a single-threaded ODBC driver.

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

20. If I use the JDBC API, do I have to use ODBC underneath?

No, this is just one of many possible solutions. We recommend using a pure Java JDBC technology-
enabled driver, type 3 or 4, in order to get all of the benefits of the Java programming language and the
JDBC API.

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

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

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.

The exact format of a JSP page is described in the JSP specification..

How do JSP pages work?

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.

How is a JSP page invoked and compiled?

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.

What is the syntax for JavaServer Pages technology?

The syntax card and reference can be viewed or downloaded from our website.

Can I create XML pages using JSP technology?

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.

Can I generate and manipulate JSP pages using XML tools?

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.

How do I use JavaBeans components (beans) from a JSP page?


The JSP specification includes standard tags for bean use and manipulation. The useBean tag creates an
instance of a specific JavaBeans class. If the instance already exists, it is retrieved. Otherwise, it is
created. The setProperty and getProperty tags let you manipulate properties of the given object. These
tags are described in more detail in the JSP specification and tutorial

1. What is the Java 2 Platform, Enterprise Edition (J2EE)?


2. What are the main benefits of the J2EE platform?
3. Can the J2EE platform interoperate with other WS-I implementations?
4. What technologies are included in the J2EE platform?
5. What's new in the J2EE 1.4 platform?
6. What is the J2EE 1.4 SDK?
7. Which version of the platform should I use now -- 1.4 or 1.3?
8. Can applications written for the J2EE platform v1.3 run in a J2EE platform v1.4
implementation?
9. How is the J2EE architecture and the Sun Java Enterprise System related?
10. Can I get the source for the Sun Java System Application Server?
11. How can I learn about the J2EE platform?
12. What tools can I use to build J2EE applications?
13. Who needs the J2EE platform?
14. What do you mean by "Free"?
15. Is support "Free"?
16. Are there compatibility tests for the J2EE platform?
17. What is the difference between being a J2EE licensee and being J2EE compatible?
18. What is the relationship of the Apache Tomcat open-source application server to the J2EE
SDK?

Q: What is the Java 2 Platform, Enterprise Edition (J2EE)?

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.

Q: What are the main benefits of the J2EE platform?

The J2EE platform provides the following:

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

Q: Can the J2EE platform interoperate with other WS-I implementations?

Yes, if the other implementations are WS-I compliant.

Q: What technologies are included in the J2EE platform?

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.

Q: What's new in the J2EE 1.4 platform?

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.

Q: What is the J2EE 1.4 SDK?

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.

Q: Which version of the platform should I use now -- 1.4 or 1.3?

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

Q: How can I learn about the J2EE platform?

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.

What tools can I use to build J2EE applications?


There are numerous choices of tools available for developing Java and J2EE applications. You can
download the Open Source NetBeans IDE for free at http://netbeans.org. Many of the J2EE compatible
vendors offer tools that support any J2EE compatible application server.

Q: Who needs the J2EE platform?

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.

Q: What do you mean by "Free"?

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.

Q: Are there compatibility tests for the J2EE platform?

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

Java API for XML Processing (JAXP)

 What is the Java API for XML Processing (JAXP)?



 Where can I read more about JAXP?

Back to Top

Java Architecture for XML Binding (JAXB)

 What is Java Architecture for XML Binding (JAXB)?



 What is the difference between JAXB, SAX, and DOM? Which one should I use?

 How does JAXB work?

 Who is involved in developing JAXB?

 Where can I read more about JAXB?

Back to Top

Java API for XML Messaging (JAXM)

 What is the Java API for XML Messaging (JAXM)?



 What standards is JAXM based on?

 Do I have to use the J2EE platform to use JAXM?

 What is a messaging provider?

 Do I have to use a messaging provider?

 Can a JAXM message be routed to more than one destination?

 Can I use ebXML headers in a JAXM message?

Back to Top

Java API for XML Registries (JAXR)

 What is the Java API for XML Registries (JAXR)?



 What is the relationship between the JAXR API and other XML APIs?

 Why do we need a new JAXR API when we have the Java Naming and Directory Interface (JNDI)?

 Would it not be better to have enhanced the JNDI API with the added functionality of the JAXR
API?

 What is the purpose of Association in the JAXR information model? It is not used anywhere in
the API.

 What is the purpose of Classification in the JAXR information model? It is not used anywhere in
the API.

 Why is JAXR an abstraction API and not targeted to a specific registry such as UDDI or ebXML?

 Why does the JAXR API not use UDDI terms and concepts?

 Why did the JAXR information model use the ebXML Registry Information Model as its basis
rather than the UDDI data structures?

 Why was the JAXR information model not designed from the ground up?

Back to Top

Java API for XML-Based RPC (JAX-RPC)

 What is the Java API for XML-Based RPC (JAX-RPC)?



 How does JAX-RPC use SOAP?

 What is RPC?

 How is XML related to RPC?

 What does JAX-RPC have to do with Web services?

 What are the modes of interaction between clients and JAX-RPC services?

 Can a remote method call or response carry service context information?

 Why doesn't xrpcc generate a WSDL file?

Back to Top

Java 2 Platform, Enterprise Edition (J2EE)

 Does the Java 2 Platform, Enterprise Edition (J2EE) use XML?



 Can I generate dynamic XML documents using JavaServer Pages (JSP)?

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.

Q. Who developed XML?

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.

Q. What are the key benefits of XML?

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.

Q. What is the relationship between XML and Java technology?

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.

Q. What are the benefits of using Java technology with XML?

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.

Q. What XML-related activities is Sun participating in?

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.

Q. Where can I find additional documentation?

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. Where can I send comments and suggestions?

A. For feedback on the project, please send email to xml-feedback@sun.com.

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)

Q. What is 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.

Q. Where can I read more about JAXP?

A. See the JAXP FAQ for more information.

Back to Top

Java Architecture for XML Binding (JAXB)

Q. What is Java Architecture for XML Binding (JAXB)?

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.

Q. How does JAXB work?

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

2. Compile the Java source code.

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.

 Access and modify the data.

Optionally validate the modifications to the data relative to the constraints expressed in
the XML Schema

 Marshal the data to new XML documents.

Q. Who is involved in developing JAXB?

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

Java API for XML Messaging (JAXM)

Q. What is the Java API for XML Messaging (JAXM)?

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.

Q: What standards is JAXM based on?

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.

Q. Do I have to use the J2EE platform to use JAXM?

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.

Q. What is a messaging provider?

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.

Q. Do I have to use a messaging provider?


A: No. You need to use a messaging provider only when your application requires one-way
(asynchronous) messaging. In this type of messaging, a message is sent to a recipient as one operation,
and the recipient responds at some later time in a different operation. If you application uses a request-
response style of messaging, in which the response to a message is sent back as part of the same
operation, you do not need a messaging provider. When you do not use a messaging provider, you use
a SOAPConnection object, which supports the simpler request-response messaging model.

Q. Can a JAXM message be routed to more than one destination?

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.

Q. Can I use ebXML headers in a JAXM message?

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

Java API for XML Registries (JAXR)

Q. What is the Java API for XML Registries (JAXR)?

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.

A. A Classification classifies a RegistryObject. A Classification may be defined for a RegistryObject and


submitted using the GenericLifeCycleManager's saveObjects method.

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

Java API for XML-Based RPC (JAX-RPC)

Q. What is the Java API for XML-Based RPC (JAX-RPC)?

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. How does JAX-RPC use SOAP?

A. Please refer to JSR-101.

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.

Q. How is XML related to RPC?

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.

Q. What does JAX-RPC have to do with Web services?

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?

A. There are three different modes:

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.

Q. Can a remote method call or response carry service context information?

A. Yes. For example, it may carry a unique transaction identifier or digital signature.

Q. Why doesn't xrpcc generate a WSDL file?

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

Java 2 Platform, Enterprise Edition

Q. Does the Java 2 Platform, Enterprise Edition (J2EE) use XML?

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.

Q. Can I generate dynamic XML documents using JSP pages?


A. JSP pages enables the authoring of XML pages. XML pages can be generated using JSP pages, which
include elements to produce the dynamic portions of the document. The JSP specification includes a
powerful tag extension mechanism that can be used to perform XML-based operations, such as
applying an XSLT transformation to an XML document.

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.

2. What are the two major components of JDBC?

One implementation interface for database manufacturers, the other implementation


interface for application and applet writers.

3. What is JDBC Driver interface?

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

4. What are the common tasks of JDBC?


o Create an instance of a JDBC driver or load JDBC drivers through jdbc.drivers
o Register a driver
o Specify a database
o Open a database connection
o Submit a query
o Receive results

5. How to use JDBC to connect Microsoft Access?

Please see this page for detailed information.


6. What are four types of JDBC 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.

2. What packages are used by JDBC?

There are at least 8 packages:

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

4. What are the flow statements of JDBC?


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

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

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

6. How can you load the drivers?

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

Eg.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

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

E.g.
Class.forName("jdbc.DriverXYZ");

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

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

8. How can you make the connection?

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

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

9. How can you create JDBC statements?


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

Statement stmt = con.createStatement();

10. How to make a query?

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.

Statement stmt = con.createStatement();


ResultSet results = stmt.executeQuery("SELECT data FROM aDatabase ");

11. How can you retrieve data from the ResultSet?

Use get methods to retrieve data from returned ResultSet object.

ResultSet rs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");


String s = rs.getString("COF_NAME");

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

12. How to navigate the ResultSet?

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.

8. What are the different types of Statements?

1. Statement (use createStatement method)


2. Prepared Statement (Use prepareStatement method)
3. Callable Statement (Use prepareCall)

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?

Use escape keyword. For example:

stmt.executeQuery("select tax from sales where tax like '10\%' {escape '\'}");

3. How to escape ' symbol found in the input line?

You may use a method to do so:

static public String escapeLine(String s) {


String retvalue = s;
if (s.indexOf ("'") != -1 ) {
StringBuffer hold = new StringBuffer();
char c;
for(int i=0; i < s.length(); i++ ) {
if ((c=s.charAt(i)) == '\'' ) {
hold.append ("''");
}else {
hold.append(c);
}
}
retvalue = hold.toString();
}
return retvalue;
}

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?

Creates a Statement object and calls the Statement.executeUpdate method.

String updateString = "INSERT INTO aDatabase VALUES (some text)";


int count = stmt.executeUpdate(updateString);

5. How to update a ResultSet?

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.

To delete the current row, use rs.deleteRow().

To insert a new row, use rs.moveToInsertRow().

6. How can you use PreparedStatement?

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

PreparedStatement updateSales = con.prepareStatement("UPDATE COFFEES SET SALES = ?


WHERE COF_NAME LIKE ?");

7. How to call a Stored Procedure from JDBC?


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

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

8. How to Retrieve Warnings?

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

SQLWarning warning = stmt.getWarnings();


if (warning != null) {

while (warning != null) {


System.out.println("Message: " + warning.getMessage());
System.out.println("SQLState: " + warning.getSQLState());
System.out.print("Vendor error code: ");
System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}

9. How to Make Updates to Update ResultSets?

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.

Connection con = DriverManager.getConnection("jdbc:mySubprotocol:mySubName");


Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = ("SELECT COF_NAME, PRICE FROM COFFEES");
10. How to set a scroll type?

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:

o ResultSet.TYPE_FORWARD_ONLY Default behavior in JDBC 1.0, application can only call


next() on the result set.
o ResultSet.SCROLL_SENSITIVE ResultSet is fully navigable and updates are reflected in the
result set as they occur.
o ResultSet.SCROLL_INSENSITIVE Result set is fully navigable, but updates are only visible
after the result set is closed. You need to create a new result set to see the results.

9. How to set update type parameter?

In the constructors of Statements and PreparedStatements, you may use

o ResultSet.CONCUR_READ_ONLY The result set is read only.


o ResultSet.CONCUR_UPDATABLE The result set can be updated.

You may verify that your database supports these types by calling
con.getMetaData().supportsResultSetConcurrency(ResultSet.SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);

10. How to do a batch job?

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.

Statement stmt = con.createStatement();


stmt.addBatch("update registration set balance=balance-5.00 where theuser="+theuser);
stmt.addBatch("insert into auctionitems(description, startprice)
values("+description+","+startprice+")");
...
int[] results = stmt.executeBatch();

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.

11. How to store and retrieve an image?


To store an image, you may use the code:

int itemnumber=400456;

File file = new File(itemnumber+".jpg");


FileInputStream fis = new FileInputStream(file);
PreparedStatement pstmt = con.prepareStatement("update auctionitems set theimage=? where
id= ?");
pstmt.setBinaryStream(1, fis, (int)file.length()):
pstmt.setInt(2, itemnumber);
pstmt.executeUpdate();
pstmt.close();
fis.close();

To retrieve an image:

int itemnumber=400456;
byte[] imageBytes;//hold an image bytes to pass to createImage().

PreparedStatement pstmt = con.prepareStatement("select theimage from auctionitems where


id= ?");
pstmt.setInt(1, itemnumber);
ResultSet rs=pstmt.executeQuery();
if(rs.next()) {
imageBytes = rs.getBytes(1);
}
pstmt.close();
rs.close();

Image auctionimage = Toolkit.getDefaultToolkit().createImage(imageBytes);

12. How to store and retrive an object?

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.

13. How to use meta data to check a column type?

Use getMetaData().getColumnType() method to check data type. For example to retrieve an


Integer, you may check it first:

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();

14. Why cannot java.util.Date match with java.sql.Date?

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

Note that they are subclasses of java.util.Date.

15. How to convert java.util.Date value to java.sql.Date?

Use the code below:

Calendar currenttime=Calendar.getInstance();
java.sql.Date startdate= new java.sql.Date((currenttime.getTime()).getTime());

or

SimpleDateFormat template = new SimpleDateFormat("yyyy-MM-dd");


java.util.Date enddate = new java.util.Date("10/31/99");
java.sql.Date sqlDate = java.sql.Date.valueOf(template.format(enddate));

FAQ Entries in Collections

Why is the Dictionary class not an interface?

What other frameworks are there for general data structures?


Where can I find an article comparing JGL and the Collections Framework?

Where can I learn how to use the Collections Framework?

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?

How do I use an Iterator to go through a Collection?

How do I use a ListIterator to go through a List backwards?

How do I count the frequency of some word/object?

How do I properly alphabetize (sort) a list of strings in a language-sensitive manner?

How do I do a case-insensitive string sort in a language-insensitive manner?

How do I sort objects into their reverse natural ordering?

How do I use Enumeration to iterate through a collection?

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 I make an array larger?

How do you store a primitive data type within a Vector or other collections class?

How do I create linked lists if there are no pointers?

How do I use an array with the Collections Framework?

Which is faster, synchronizing a HashMap or using a Hashtable for thread-safe access?

Where can I get the Collections Framework?

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?

Why doesn't the Iterator interface extend the Enumeration interface?

How do I print a Collection?

How do I synchronize a collection?


How do I do a case-sensitive sort in a language-insensitive manner?

How do I get the length of an array?

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 do I sort an array?

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

Is there a way to create a homogenous collection in Java?


How do I make a collection where all the elements within it are a specific data type?

What's the fastest way to traverse all the elements of a Vector?

How does a Hashtable internally maintain the key-value pairs?

How do I look through each element of a HashMap?

How do I create a read-only collection?

How can I process through the keys of a Hashtable in sorted order?

Which collections in Java are synchronized and which aren't?

What are the differences between ArrayList and LinkedList?

Where can I find Java packages for expressing numerical formulas?

Where can I find additional implementations of the Collections Framework API?

How do I read input from a stream "one word at a time"?

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 polymorphic algorithm?


What is meant by natural ordering of objects in the context of the collections framework?

What is a fail-fast iterator?

How do you sort the elements of a vector?

What is stable sorting?

What is a WeakHashMap? What is its use and when should you use it?

What is the function of a load factor in a Hashtable?

How do you control growth of vectors when their internal arrays are full?

How to sort the messages in JavaMail?

When did Strings start caching their hash codes?

How can you retrieve the Hashtable's load factor?

Why can't I add a collection to itself?

What is meant by compatible equals() and hashCode() methods?

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 a weak reference and what are they used for?

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 does ArrayList increase its capacity?

How can I implement a priority queue in Java? Has anyone created an open source version?

What is the default initial size for a Hashtable / HashMap?


How do you create a multi-dimensional List?

In a TreeMap, can I use a sorting algorithm other than the natural sorting for the keys?

What are the differences between HashMap and Hashtable?

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.

Does the equals() method of an array do element-level checking?

How can I retrieve the items in my HashSet / HashMap in the order they were added?

How do you sort an ArrayList (or any list) of user-defined objects?

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?

What's the most optimum way of swapping two elements in a List?

What's the purpose of the IdentityHashMap?

How do I convert an old-style Enumeration to something in the Collections Framework?

How do I retrieve the values of a Hashtable/HashMap in sorted order?

How can I add a Collection to another Collection?

Where can I find performance comparisons between the different collection implementations?

How can I use two iterators to go through a collection?

When will Java have support for type-safe collections?

How do I traverse a map backwards?

How do I traverse a sorted set backwards?

How can I go through an Iterator mulitple times?

What's new to the Collections Framework in Java 1.4?

How can I add an array of objects to a collection?

Is Vector's clone method thread-safe?


Where can I find an example of the Java 1.4 LinkedHashSet and LinkedHashMap classes?

How do I load property settings with the Properties class?

How do I save properties settings with the Properties class?

What happens if two threads perform a get of one hashmap at the same time?

Java Collections API Design FAQ

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.

Core Interfaces - General Questions


1. Why don't you support immutability directly in the core collection interfaces so that you can
do away with optional operations (and UnsupportedOperationException)?
2. Won't programmers have to surround any code that calls optional operations with a try-catch
clause in case they throw an UnsupportedOperationException?
3. Why isn't there a core interface for "bags" (AKA multisets)?
4. Why don't you provide for "gating functions" that facilitate the implementation of type-safe
collections?
5. Why didn't you use "Beans-style names" for consistency?

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?

Core Interfaces - General Questions


1. Why don't you support immutability directly in the core collection interfaces so that you can
do away with optional operations (and UnsupportedOperationException)?

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.

3. Why isn't there a core interface for "bags" (AKA multisets)?

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.

5. Why didn't you use "Beans-style names" for consistency?

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:

for (Iterator i = c.iterator(); i.hasNext(); )


System.out.println(i.next());

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

6. Why don't you provide an Iterator.add method?

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?

It can be implemented atop the current Iterators (a similar pattern to


java.io.PushbackInputStream). We believe that its use would be rare enough that it isn't worth
including in the interface that everyone has to implement.

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.

FAQ Entries in Applets

How can my applet or application communicate with my servlet?

Is it true that my RMI applet can make socket connections only to the host from which the applet
was downloaded from?

How do I communicate with a JSP page from an applet?

How can I download a file (for instance, a Microsoft Word document) from a server using a
servlet and an applet?

How do I get an applet to load a new page into the browser?

How can I change the size of an Applet/JApplet in a Web Page?


What is the syntax of the <APPLET> tag?

When used in an Applet/JApplet, does a Frame/JFrame show up inside the web page or as a new
window?

What are the main differences between applets and applications?

How do I show users with Java disabled what they are missing?

Can I use menus and a menu bar in an applet?

What System properties are visible from an applet?

How can I get the real local host IP address in an applet?

I get a ClassCastException when I try to load my applet, what's wrong?

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?

How do I communicate with an applet from JavaScript?

How can I upload a (image) file through an applet ?

How do I load a serialized applet?

How do I communicate with JavaScript from an applet?

From one applet, how do I communicate with another applet loaded from the same server?

FAQ Entries in IO

Can I use a BufferedOutputStream with an ObjectOutputStream to serialize an object?

What happened to printf or how do I format the numbers I need to print?

How do I change what standard output or standard error goes to so it can go somewhere other
than the console?

How do I append to end of a file in Java?

How can I save/load application settings that I would normally use .ini files or the Windows
Registry?

How can I accept a password from the console without an echo?

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?

How do I check for end-of-file when reading from a stream?

Is there any way to communicate between two classes within an application using InputStreams
and OutputStreams?

How can I wake a thread that is blocked on a call to InputStream.read()?

How can I efficiently compare two binary files for equality?

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?

Where can I find a regular expression package in Java?

How do I read text from standard input?

How do I create a temporary file?

How do I write text to a file?

How do I copy a file?

What is a stream?

How can I open the same file for reading as well as writing?

Where can I find Java packages for expressing numerical formulas?

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 do I read a file created by program X in Java?

How can you combine multiple input streams to be treated as one?

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 read or write binary files written in little-endian format?

How can I make a file writable that is currently read-only?

How do I communicate with a USB port from Java?

How can I find out if a file is a text/ASCII file or binary file using Java?

How can I trap system-specific key sequences like Ctrl-Alt-Del?

Are there any good books about Java I/O?

Where can I find an example of a Java application that communicates with equipment via an
RS232 serial port?

What is a resource leak?

How can I create a record-based file data structure in Java?

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?

How can I write a text document in PDF format?

What is the correct order of ObjectInputStream/ObjectOutputStream creation on the client and


the server when sending objects over a network connection?

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 networking capabilities?

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.

What's the serialver syntax to get the serialVersionUID of an array?

Is there an easy way of counting line numbers? Or do you have to go through the entire file?

What is piped I/O used for?

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?

How do I extract a BLOB from a database?

I have the choice of manipulating database data using a String or a java.sql.Clob. Which has best
performance?

How can I make batch updates using JDBC?

What are SQL3 data types?

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?

What is a JDBC 2.0 DataSource?


What types of DataSource objects are specified in the Optional Package?

How can I instantiate and load a new CachedRowSet object from a non-JDBC source?

How do I implement a RowSetReader? I want to populate a CachedRowSet myself and the


documents specify that a RowSetReader should be used. The single method accepts a
RowSetInternal caller and returns void. What can I do in the readData method?

How does a custom RowSetReader get called from a CachedRowSet?

How can I create a custom RowSetMetaData object from scratch?

What is a database URL?

What types of JDBC drivers exist?

How do I create a database connection?

What is the difference between a Statement and a PreparedStatement?

What is Metadata and why should I use it?

What is the advantage of using a PreparedStatement?

What is a "dirty read"?

Can I make a change to the transaction isolation level in the midst of executing the transaction?

At a glance, how does the Java Database Connectivity (JDBC) work?

How do I check what table-like database objects (table, view, temporary table, alias) are present
in a particular database?

How do I check what table types exist in a database?

How can I investigate the physical structure of a database?

How do I extract SQL table column type information?

How do I extract the SQL statements required to move all tables and views from an existing
database to another database?

How do I find all database stored procedures in a database?

How can I investigate the parameters to send into and receive from a database stored procedure?

What properties should I supply to a database driver in order to connect to a database?

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?

FAQ Entries in RMI

Why must the CLASSPATH environment variable not include the path of the remote object's stub
classes on the server host?

Do you need an HTTP server to use RMI?

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?

How does the Distributed Garbage Collection algorithm work?

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?

What are the different RMI system configurations possible?

When would I use the java.rmi.server.codebase property?

What is the purpose of the java.rmi.server.useCodebaseOnly property?

What's new in RMI under Java 2?

How does Java RMI differ from Jini?


Is there another RMI FAQ that I can look at?

Is there a mailing list for RMI discussions?

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?

How do I send a ResultSet back to a client using RMI?

Servlet Interview Questions

Question: Explain the life cycle methods of a Servlet.


Question: What if the static modifier is removed from the signature of the main method?
Question: Explain the directory structure of a web application.
Question: What are the common mechanisms used for session tracking?
Question: Explain ServletContext.
Question:
What is preinitialization of a servlet?
Question:
What is the difference between Difference between doGet() and doPost()?
Question:
What is the difference between HttpServlet and GenericServlet?

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.

The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot


accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context
root.
TOP

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.

WEB-INF folder consists of


1. web.xml
2. classes directory
3. lib directory
TOP

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

Question: What is SQL?


Question: What is SELECT statement?
Question: How can you compare a part of the name rather than the entire name?
Question:

What is the INSERT statement?


Question: How do you delete a record from a database?
Question: How could I get distinct entries from a table?
Question: How to get the results of a Query sorted in any order?
Question: How can I find the total number of records in a table?
Question: What is GROUP BY?
Question: What is the difference among "dropping a table", "truncating a table" and "deleting all
records" from a table?
Question: What are the Large object types suported by Oracle?
Question: Difference between a "where" clause and a "having" clause ?
Question: What's the difference between a primary key and a unique key?
Question: What are cursors? Explain different types of cursors. What are the disadvantages of cursors?
How can you avoid cursors?
Question: What are triggers? How to invoke a trigger on demand?
Question: What is a join and explain different types of joins.
Question: What is a self join?

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

SELECT COUNT(*) FROM emp WHERE age>40


TOP

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

Delete : (Data alone deleted), Doesn’t perform automatic commit


TOP

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

Question: What if the main method is declared as private?


Question: What if the static modifier is removed from the signature of the main method?
Question: What if I write static public void instead of public static void?
Q:Question: What if I do not provide the String array as the argument to the method?
Question: What is the first argument of the String array in main method?
Question: If I do not provide any arguments on the command line, then the String array of Main
method will be empty of null?
Question: How can one prove that the array is not null but empty?
Question: What environment variables do I need to set on my machine in order to be able to run Java
programs?
Question: Can an application have multiple classes having main method?
Question: Can I have multiple main methods in the same class?
Question: Do I need to import java.lang package any time? Why ?
Question: Can I import same package/class twice? Will the JVM load the package twice at runtime?

Question: What are Checked and UnChecked Exception?


Question: What is Overriding?
Question: What are different types of inner classes?

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 ();

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

Remember that if the time taken for execution is too small, it might show that it is taking zero
milliseconds for execution. Try it on a method which is big enough, in the sense the one which is
doing considerable amout of processing.
[ 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

Question: How are Observer and Observable used?


Question: What is synchronization and why is it important?
Question: How does Java handle integer overflows and underflows?
Question: Does garbage collection guarantee that a program will not run out of
memory?
Question: What is the difference between preemptive scheduling and time slicing?
Question: When a thread is created and started, what is its initial state?
Question: What is the purpose of finalization?
Question: What is the Locale class?
Question: What is the difference between a while statement and a do statement?
Question: What is the difference between static and non-static variables?
Question: How are this() and super() used with constructors?
Question: What are synchronized methods and synchronized statements?
Q:
How are Observer and Observable used?
A: Objects that subclass the Observable class maintain a list of observers. When an Observable object
is updated it invokes the update() method of each of its observers to notify the observers that it has
changed state. The Observer interface is implemented by objects that observe Observable objects.
[Received from Venkateswara Manam] TOP

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

JSP Interview Questions

Question: What is a output comment?


Question: What is a Hidden comment?
Question: What is an Expression?
Question: What is a Declaration ?
Question: What is a Scriptlet?
Question: What are implicit objects? List them?
Question: Difference between forward and sendRedirect?
Question: What are the different scope values for the <jsp:useBean>?
Question: Explain the life-cycle methods in JSP?

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() %>
-->

Displays in the page source:


<!-- This is a commnet sent to client on January 24, 2004 -->
TOP

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.

<%! somedeclarations %>


<%! int i = 0; %>
<%! int a, b, c; %>
TOP

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

EJB Interview Questions

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.

Types of Enterprise Beans:


Enterprise Bean Type Purpose
Session Performs a task for a client; implements a Web service Entity Represents a business entity
object that exists in persistent
storage
Message-Driven Acts as a listener for the Java Message Service API,
processing messages asynchronously

A normal bean can be used by us for storing simple that which we can use to transfer data between
classes. For eg:-

Q:: why java does not support multiple inheritance??

Java does something called "chaining of constructors"-- meaning that


when u instantiate an object, java will call its super-class
constructor, super-super-class (thts incorrect terminology, but i my
point is clear) constructor. this is done to ensure a proper state
of the class when it is created.

hence, if a class inherit 2 super-classes, the chaining of


constructor will be violated-- there will be ambiguity as to which
parent constructo to call.
There is a method to get the maximum memory available to JVM
"Runtime.getRuntime().maxMemory()" but I am unaware of any method for
getting the systam memory size

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.
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().
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.
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.
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.
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.
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.
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.
What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different return types.
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.
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.
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.
What are the disadvantages of using threads?
DeadLock.
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.
What is the difference between instanceof and isInstance?
instanceof is used to check to see if an object can be cast into a specified type without throwing a cast
class
exception. isInstance() determines if the specified object is assignment-compatible with the object
represented by this Class. This method is the dynamic equivalent of the Java language instanceof
operator.
The method returns true if the specified Object argument is nonnull and can be cast to the reference
type
represented by this Class object without raising a ClassCastException. It returns false otherwise.

Advantages of using inner classes


 Object-oriented advantage
 Allows you to turn things into objects that you wouldn’t normally turn into objects

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

 Major advantage of inner classes is the ability to create adaptor


 classes that implement an interface.
 * Make all inner classes private to ensure hidden implementation.
 * Rather than handle classes returning inner classes, they
 return interfaces.
 • Inner classes frequently used with event handling in applets.

Anonymous classes
 A class with no name, which is why it’s called an “anonymous class”

 Combines the following into one step:


 class declaration
 creation of an instance of the 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

 Useful when implementing listeners in GUI programs


 See sample code in access folder of slide7.zip

Rules for Anonymous classes


 An anonymous class must always extend a super class or implement an interface but it cannot
have an explicit extends or implements clause

 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

When to use Inner Classes


 In general
 Use when you do NOT need to reuse or extend the class outside the containing class.
 e.g., for handling events that are specific to that applet
 Non-Anonymous Inner Classes
 Use when you create several different instances of the same inner class within the same
applet
 e.g., MoverButton
 Anonymous Inner Classes
 Use when you only need one instance of that class and never need to reuse it.
 Remember the Rule: limit code to 1 or 2 lines!
 if you need more, put it in a method of the applet or use a non-anonymous inner
class

1. What are two methods of retrieving SQL?


2. What cursor type do you use to retrieve multiple recordsets?
3. What action do you have to perform before retrieving data from the next result set of a stored
procedure?
4. What is the basic form of a SQL statement to read data out of a table?
5. What structure can you have the database make to speed up table reads?
6. What is a "join"?
7. What is a "constraint"?
8. What is a "primary key"?
9. What is a "functional dependency"? How does it relate to database table design?
10. What is a "trigger"?
11. What is "index covering" of a query?
12. What is a SQL view?

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.

1. What are the different types of joins?


2. Explain normalization with examples.
3. What cursor type do you use to retrieve multiple recordsets?
4. Diffrence between a "where" clause and a "having" clause
5. What is the difference between "procedure" and "function"?
6. How will you copy the structure of a table without copying the data?
7. How to find out the database name from SQL*PLUS command prompt?
8. Tadeoffs with having indexes
9. Talk about "Exception Handling" in PL/SQL?
10. What is the diference between "NULL in C" and "NULL in Oracle?"
11. What is Pro*C? What is OCI?
12. Give some examples of Analytical functions.
13. What is the difference between "translate" and "replace"?
14. What is DYNAMIC SQL method 4?
15. How to remove duplicate records from a table?
16. What is the use of ANALYZing the tables?
17. How to run SQL script from a Unix Shell?
18. What is a "transaction"? Why are they necessary?
19. Explain Normalizationa dn Denormalization with examples.
20. When do you get contraint violtaion? What are the types of constraints?
21. How to convert RAW datatype into TEXT?
22. Difference - Primary Key and Aggregate Key
23. How functional dependency is related to database table design?
24. What is a "trigger"?
25. Why can a "group by" or "order by" clause be expensive to process?
26. What are "HINTS"? What is "index covering" of a query?
27. What is a VIEW? How to get script for a view?
28. What are the Large object types suported by Oracle?
29. What is SQL*Loader?
30. Difference between "VARCHAR" and "VARCHAR2" datatypes.
31. What is the difference among "dropping a table", "truncating a table" and "deleting all records"
from a table.
32. Difference between "ORACLE" and "MICROSOFT ACCESS" databases.
33. How to create a database link ?

Java and EJB - Interview Questions

1. What is Entity Bean and Session Bean ?


2. What are the methods of Entity Bean?
3. How does Stateful Session bean store its state ?
4. Why does Stateless Session bean not store its state even though it has ejbActivate and
ejbPassivate ?
5. What are the services provided by the container ?
6. Types of transaction ?
7. What is bean managed transaction ?
8. Why does EJB needs two interface( Home and Remote Interface) ?
9. What are transaction attributes ?
10. What is the difference between Container managed persistent bean and Bean managed
persistent entity bean ?
11. What is J2EE ?
12. What is JTS ?
13. How many entity beans used and how many tables can u use in EJB project ?
14. What is scalable,portability in J2EE?
15. What is Connection pooling?Is it advantageous?
16. Method and class used for Connection pooling ?
17. How to deploy in J2EE(i.e Jar,War file) ?
18. How is entity bean created using Container managed entity bean ?
19. Sotware architechture of EJB ?
20. In Entity bean will the create method in EJB home and ejbCreate in Entity bean have the same
parameters ?
21. What methods do u use in Servlet – Applet communication ?
22. What are the types of Servlet ?
23. Difference between HttpServlet and Generic Servlets ?
24. Difference between doGet and doPost ?
25. What are the methods in HttpServlet?
26. What are the types of SessionTracking?
27. What is Cookie ? Why is Cookie used ?
28. If my browser does not support Cookie,and my server sends a cookie instance What will
happen ?
29. Why do u use Session Tracking in HttpServlet ?
30. Can u use javaScript in Servlets ?
31. What is the capacity the doGet can send to the server ?
32. What are the type of protocols used in HttpServlet ?
33. Difference between TCP/IP and IP protocol ?
34. Why do you use UniCastRemoteObject in RMI ?
35. How many interfaces are used in RMI?
36. Can Rmi registry be written in the code, without having to write it in the command prompt
and if yes where?
37. Why is Socket used ?
38. What are the types of JDBC drivers ?
39. Explain the third driver(Native protocol driver) ?
40. Which among the four driver is pure Java driver ?
41. What are the Isolation level in JDBC transaction ?
42. How do you connect with the database ?
43. How do you connect without the Class.forName (" ") ?
44. What does Class.forName return ?
45. What are the types of statement ?
46. Why is preparedStatement,CallableStatement used for?
47. In real time project which driver did u use ?
48. Difference between AWT and Swing compenents ?
49. Is there any heavy weight component in Swings ?
50. Can the Swing application if you upload in net, be compatible with your browser?
51. What should you do get your browser compatible with swing components?
52. What are the methods in Applet ?
53. When is init(),start() called ?
54. When you navigate from one applet to another what are the methods called ?
55. What is the difference between Trusted and Untrusted Applet ?
56. What is Exception ?
57. What are the ways you can handle exception ?
58. When is try,catch block used ?
59. What is finally method in Exceptions ?
60. What are the types of access modifiers ?
61. What is protected and friendly ?
62. What are the other modifiers ?
63. Is synchronised modifier ?
64. What is meant by polymorphism ?
65. What is inheritance ?
66. What is method Overloading ? What is this in OOPS ?
67. What is method Overriding ? What is it in OOPS ?
68. Does java support multi dimensional arrays ?
69. Is multiple inheritance used in Java ?
70. How do you send a message to the browser in JavaScript ?
71. Does javascript support multidimensional arrays ?
72. Why is XML used mainly?
73. Do use coding for database connectivity in XML?
74. What is DTD ?
75. Is there any tool in java that can create reports ?

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

What is the WebSphere Application Server Console?


In V3 of WebSphere a new concept was introduced, the remote management console. Previously in V2
you had connected to WebSphere through a Java-based application within a browser. The change has
allowed more functionality to be introduced, although it does not come without pitfalls.

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.

What is Workload Management?


Workload Management is an ability to route requests from the clients (browsers) to different servers in
the server farm (several servers behind the same entry point) - in such a way, that it would be
transparent for the client browser (he would not know and would not care about it), where (which
server) his/her requests went to. WebSphere provides ability to cluster and clone its services so that they
can be easily expanded from single-server to multi-server environment.

What is Session Management?


J2EE Servlet API supports cookie-based HTTP sessions - information about currently logged in user, for
example. It does not provide, however, any support for distributing those sessions across multiple
servers. In WebSphere, there is a notion of persistent sessions, where session information is stored in the
relational database (such as Oracle and DB2). If one of the servers suddenly fails, the user will be
automatically redirected to another server, and his session information will be preserved - he/she would
not have to relogin. This might not seem important for some small application, but for enterprise trading
system where crucial financial information is stored in sessions, it might be quite critical - having user
loosing his/her session would mean lost business - lost $$$ for the company.

What is Connection Pooling?


JDBC 2.0 which is part of J2EE 1.2-1.3 specification, supports the notion of connection pooling - reusing
the database connection for processing several database operations by several independent threads -
such as servlet invocations, Enterprise Java Beans, or simple Java applications. Obtaining the connection
from the database and then closing it is a performance expensive process, which may exhaust the
database ability to handle requests. Connection pooling creates a pool of connections within memory,
that maintains them while their in use and does not actually close them - just returns them to the pool
when these connections are no longer needed. Java Naming and Directory Interface (JNDI) API is utilized
for this purpose to lookup the connections through use of Data Sources (literally, sources of data from
the databases). Several best practices exist regarding use of connection pooling, including always using
try-catch-finally blocks to process database transactions safely.

What Security Services does WebSphere provide?


WebSphere supports a variety of security specifications including J2EE role-based security, where each
resource is protected by defining roles that have access to that particular resource. For instance, Servlet
may be protected by specifying roles that have access to GET or POST methods on its url. EJB can be
protected on the method level by specifying which roles are allowed to invoke which method. Roles are
abstract entities but can be associated with operating system (Windows NT or UNIX) users, or special
registries based on Lightweight Directory Access Protocol (LDAP) - such as Microsoft ActiveDirectory or
IBM SecureWay - which allow managing this information.
Threads

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