0% found this document useful (0 votes)
25 views159 pages

Ilovepdf Merged

This document discusses various Java concepts. It provides definitions and differences for key terms like abstract class vs interface, checked vs unchecked exceptions, user defined exceptions, differences between Java and C++, statements in Java, JAR files, JNI, serialization, null interfaces, synchronized keyword, singleton class, compilation unit, wrapper classes, reasons for no multiple inheritance in Java, why Java is not 100% object-oriented, resource bundles, transient variables, Collection API and differences between abstract class and interface.

Uploaded by

Mayur chaudhari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views159 pages

Ilovepdf Merged

This document discusses various Java concepts. It provides definitions and differences for key terms like abstract class vs interface, checked vs unchecked exceptions, user defined exceptions, differences between Java and C++, statements in Java, JAR files, JNI, serialization, null interfaces, synchronized keyword, singleton class, compilation unit, wrapper classes, reasons for no multiple inheritance in Java, why Java is not 100% object-oriented, resource bundles, transient variables, Collection API and differences between abstract class and interface.

Uploaded by

Mayur chaudhari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 159

Core Java Interview Questions

1) What is the difference between an Abstract class and


Interface?
1. Abstract classes may have some executable methods and methods left
unimplemented. Interfaces contain no implementation code.
2. An class can implement any number of interfaces, but subclass at most one abstract
class.
3. An abstract class can have nonabstract methods. All methods of an interface are
abstract.
4. An abstract class can have instance variables. An interface cannot.
5. An abstract class can define constructor. An interface cannot.
6. An abstract class can have any visibility: public, protected, private or none
(package). An interface's visibility must be public or none (package).
7. An abstract class inherits from Object and includes methods such as clone() and
equals().

2) What are checked and unchecked exceptions?


Java defines two kinds of exceptions :
• Checked exceptions : Exceptions that inherit from the Exception class are
checked exceptions. Client code has to handle the checked exceptions thrown by
the API, either in a catch clause or by forwarding it outward with the throws clause.
Examples - SQLException, IOxception.
• Unchecked exceptions : RuntimeException also extends from Exception. However,
all of the exceptions that inherit from RuntimeException get special treatment.
There is no requirement for the client code to deal with them, and hence they are
called unchecked exceptions. Example Unchecked exceptions are
NullPointerException, OutOfMemoryError, DivideByZeroException typically,
programming errors.

3) What is a user defined exception?


User-defined exceptions may be implemented by
• defining a class to respond to the exception and
• embedding a throw statement in the try block where the exception can occur or
declaring that the method throws the exception (to another method where it is
handled).
The developer can define a new exception by deriving it from the Exception class as follows:

public class MyException extends Exception {


/* class definition of constructors (but NOT the exception handling code) goes h
public MyException() {
super();
}

public MyException( String errorMessage ) {


super( errorMessage );
}
}

The throw statement is used to signal the occurance of the exception within a try block.
Often, exceptions are instantiated in the same statement in which they are thrown using the
syntax.

throw new MyException("I threw my own exception.")

To handle the exception within the method where it is thrown, a catch statement that
handles MyException, must follow the try block. If the developer does not want to handle
the exception in the method itself, the method must pass the exception using the syntax:

public myMethodName() throws MyException

4) What is the difference between C++ & Java?


Well as Bjarne Stroustrup says "..despite the syntactic similarities, C++ and Java are very
different languages. In many ways, Java seems closer to Smalltalk than to C++..". Here are
few I discovered:
• Java is multithreaded
• Java has no pointers
• Java has automatic memory management (garbage collection)
• Java is platform independent (Stroustrup may differ by saying "Java is a platform"
• Java has built-in support for comment documentation
• Java has no operator overloading
• Java doesn’t provide multiple inheritance
• There are no destructors in Java

5) What are statements in JAVA ?


Statements are equivalent to sentences in natural languages. A statement forms a complete
unit of execution. The following types of expressions can be made into a statement by
terminating the expression with a semicolon
• Assignment expressions
• Any use of ++ or --
• Method calls
• Object creation expressions
These kinds of statements are called expression statements. In addition to these kinds of
expression statements, there are two other kinds of statements. A declaration statement
declares a variable. A control flow statement regulates the order in which statements get
executed. The for loop and the if statement are both examples of control flow statements.

6) What is JAR file?


JavaARchive files are a big glob of Java classes, images, audio, etc., compressed to make
one simple, smaller file to ease Applet downloading. Normally when a browser encounters
an applet, it goes and downloads all the files, images, audio, used by the Applet separately.
This can lead to slower downloads.
7)What is JNI?
JNI is an acronym of Java Native Interface. Using JNI we can call functions which are written
in other languages from Java. Following are its advantages and disadvantages.
Advantages:
• You want to use your existing library which was previously written in other
language.
• You want to call Windows API function.
• For the sake of execution speed.
• You want to call API function of some server product which is in c or c++ from java
client.
Disadvantages:
• You can’t say write once run anywhere.
• Difficult to debug runtime error in native code.
• Potential security risk.
• You can’t call it from Applet.

8) What is serialization?
Quite simply, object serialization provides a program the ability to read or write a whole
object to and from a raw byte stream. It allows Java objects and primitives to be encoded
into a byte stream suitable for streaming to some type of network or to a file-system, or
more generally, to a transmission medium or storage facility. A seralizable object must
implement the Serilizable interface. We use ObjectOutputStream to write this object to a
stream and ObjectInputStream to read it from the stream.

9) Why there are some null interface in java ? What does it


mean ? Give me some null interfaces in JAVA?
Null interfaces act as markers..they just tell the compiler that the objects of this class need
to be treated differently..some marker interfaces are : Serializable, Remote, Cloneable

10) Is synchronised a modifier?indentifier??what is it??


It's a modifier. 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.

11) What is singleton class?where is it used?


Singleton is a design pattern meant to provide one and only one instance of an object.
Other objects can get a reference to this instance through a static method (class constructor
is kept private). Why do we need one? Sometimes it is necessary, and often sufficient, to
create a single instance of a given class. This has advantages in memory management, and
for Java, in garbage collection. Moreover, restricting the number of instances may be
necessary or desirable for technological or business reasons--for example, we may only
want a single instance of a pool of database connections.
12) What is a compilation unit?
The smallest unit of source code that can be compiled, i.e. a .java file.

13) Is string a wrapper class?


String is a class, but not a wrapper class. Wrapper classes like (Integer) exist for each
primitive type. They can be used to convert a primitive data value into an object, and vice-
versa.

14) Why java does not have multiple inheritance?


The Java design team strove to make Java:
• Simple, object oriented, and familiar
• Robust and secure
• Architecture neutral and portable
• High performance
• Interpreted, threaded, and dynamic
The reasons for omitting multiple inheritance from the Java language mostly stem from the
"simple, object oriented, and familiar" goal. As a simple language, Java's creators wanted a
language that most developers could grasp without extensive training. To that end, they
worked to make the language as similar to C++ as possible (familiar) without carrying over
C++'s unnecessary complexity (simple).
In the designers' opinion, multiple inheritance causes more problems and confusion than it
solves. So they cut multiple inheritance from the language (just as they cut operator
overloading). The designers' extensive C++ experience taught them that multiple
inheritance just wasn't worth the headache.

15) Why java is not a 100% oops?


Many people say this because Java uses primitive types such as int, char, double. But then
all the rest are objects. Confusing question..

16) What is a resource bundle?


In its simplest form, a resource bundle is represented by a text file containing keys and a
text value for each key.

17) What is transient variable?


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.
18) What is Collection API?
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 hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

19) Is Iterator a Class or Interface? What is its use?


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

20) What is similarities/difference between an Abstract


class and Interface?
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 to find corresponding method
in in the actual class. Abstract classes are fast.
Similarities:
• Neither Abstract classes or Interface can be instantiated.

21) What is a transient variable?


A transient variable is a variable that may not be serialized.

22) Which containers use a border Layout as their default


layout?
The window, Frame and Dialog classes use a border layout as their default layout.

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

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

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

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

27) What's new with the stop(), suspend() and resume()


methods in JDK 1.2?
The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

28) Is null a keyword?


The null value is not a keyword.

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

30) What method is used to specify a container's layout?


The setLayout() method is used to specify a container's layout.

31) Which containers use a FlowLayout as their default


layout?
The Panel and Applet classes use the FlowLayout as their default layout.

32) What state does a thread enter when it terminates its


processing?
When a thread terminates its processing, it enters the dead state.
33) What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections
of objects.

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

35) What is the List interface?


The List interface provides support for ordered collections of objects.

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

37) What is the Vector class?


The Vector class provides the capability to implement a growable array of objects

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

39) What is an Iterator interface?


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

40) 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.
41) Which method of the Component class is used to set
the position and size of a component?
setBounds()

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

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

44) Which java.util classes and interfaces support event


handling?
The EventObject class and the EventListener interface support event processing.

45) Is sizeof a keyword?


The sizeof operator is not a keyword.

46) What are wrapped classes?


Wrapped classes are classes that allow primitive types to be accessed as objects.

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

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

50) What is the immediate superclass of the Applet class?


Panel

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

52) Name three Component subclasses that support


painting.
The Canvas, Frame, Panel, and Applet classes support painting.

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

54) What is the immediate superclass of the Dialog class?


Window

55) What is clipping?


Clipping is the process of confining paint operations to a limited area or shape.

56) What is a native method?


A native method is a method that is implemented in a language other than Java.

57) Can a for statement loop indefinitely?


Yes, a for statement can loop indefinitely. For example, consider the following:
for(;;) ;

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

59) When a thread blocks on I/O, what state does it


enter?
A thread enters the waiting state when it blocks on I/O.

60) To what value is a variable of the String type


automatically initialized?
The default value of an String type is null.

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

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

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

64) What class is the top of the AWT event hierarchy?


The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy.
65) 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.

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

67) What is the range of the short type?


The range of the short type is -(2^15) to 2^15 - 1.

68) What is the range of the char type?


The range of the char type is 0 to 2^16 - 1.

69) In which package are most of the AWT events that


support the event-delegation model defined?
Most of the AWT-related events of the event-delegation model are defined in the
java.awt.event package. The AWTEvent class is defined in the java.awt package.

70) What is the immediate superclass of Menu?


MenuItem

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

72) Which class is the immediate superclass of the


MenuComponent class.
Object

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

75) Name three subclasses of the Component class.


Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or
TextComponent

76) What is the GregorianCalendar class?


The GregorianCalendar provides support for traditional Western calendars.

77) Which Container method is used to cause a container


to be laid out and redisplayed?
validate()

78) What is the purpose of the Runtime class?


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

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

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

81) What is the argument type of a program's main()


method?
A program's main() method takes an argument of the String[] type.
82) Which Java operator is right associative?
The = operator is right associative.

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

84) Can a double value be cast to a byte?


Yes, a double value can be cast to a byte.

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

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

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

88) Name two subclasses of the TextComponent class.


TextField and TextArea

89) What is the advantage of the event-delegation model


over the earlier eventinheritance 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.
90) Which containers may have a MenuBar?
Frame

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

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

93) What is an abstract method?


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

94) How are Java source code files named?


A Java source code file takes the name of a public class or interface that is defined within
the file. A source code file may contain at most one public class or interface. If a public class
or interface is defined within a source code file, then the source code file must take the
name of the public class or interface. If no public class or interface is defined within a source
code file, then the file must take on a name that is different than its classes and interfaces.
Source code files use the .java extension.

95) What is the relationship between the Canvas class and


the Graphics class?
A Canvas object provides access to a Graphics object via its paint() method.

96) What are the high-level thread states?


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

97) 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.
98) Can a Byte object be cast to a double value?
No, an object cannot be cast to a primitive value.

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

100) What is the difference between the String and


StringBuffer classes?
String objects are constants. StringBuffer objects are not.

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

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

103) What is the Dictionary class?


The Dictionary class provides the capability to store key-value pairs.

104) How are the elements of a BorderLayout organized?


The elements of a BorderLayout are organized at the borders (North, South, East, and
West) and the center of a container.

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

107) What is the difference between a Window and a


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

108) Which class is extended by all other classes?


The Object class is extended by all other classes.

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

110) Is the ternary operator written x : y ? z or x ? y : z ?


It is written x ? y : z.

111) What is the difference between the Font and


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

112) How is rounding performed under integer division?


The fractional part of the result is truncated. This is known as rounding toward zero.

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

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

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

117) What is the SimpleTimeZone class?


The SimpleTimeZone class provides support for a Gregorian calendar.

118) What is the Map interface?


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

119) Does a class inherit the constructors of its


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

120) For which statements does it make sense to use a


label?
The only statements for which it makes sense to use a label are those statements that can
enclose a break or continue statement.

121) What is the purpose of the System class?


The purpose of the System class is to provide access to system resources.
122) Which TextComponent method is used to set a
TextComponent to the read-only state?
setEditable()

123) How are the elements of a CardLayout organized?


The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.

124) Is &&= a valid Java operator?


No, it is not.

125) Name the eight primitive Java types?


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

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

127) What is the relationship between clipping and


repainting?
When a window is repainted by the AWT painting thread, it sets the clipping regions to the
area of the window that requires repainting.

128) Is "abc" a primitive value?


The String literal "abc" is not a primitive value. It is a String object.

129) What is the relationship between an event-listener


interface and an event-adapter class?
An event-listener interface defines the methods that must be implemented by an event
handler for a particular kind of event. An event adapter provides a default implementation
of an event-listener interface.

130) 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.
131) What modifiers may be used with an interface
declaration?
An interface may be declared as public or abstract.

132) Is a class a subclass of itself?


A class is a subclass of itself.

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

134) What event results from the clicking of a button?


The ActionEvent event is generated as the result of the clicking of a button.

135) How can a GUI component handle its own events?


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

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

137) How are the elements of a GridBagLayout organized?


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

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

140) What modifiers can be used with a local inner class?


A local inner class may be final or abstract.

141) What is the difference between static and non-static


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

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

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

144) Can an exception be rethrown?


Yes, an exception can be rethrown.

145) Which Math method is used to calculate the absolute


value of a number?
The abs() method is used to calculate absolute values.

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

148) When is the finally clause of a try-catch-finally


statement executed?
The finally clause of the try-catch-finally statement is always executed unless the thread of
execution terminates or an exception occurs within the execution of the finally clause.

149) Which class is the immediate superclass of the


Container class?
Component

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

151) How can the Checkbox class be used to create a radio


button?
By associating Checkbox objects with a CheckboxGroup.

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

153) What restrictions are placed on method overloading?


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

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

156) What is the return type of a program's main()


method?
A program's main() method has a void return type.

157) Name four Container classes.


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

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

159) What class of exceptions are generated by the Java


run-time system?
The Java runtime system generates RuntimeException and Error exceptions.

160) What class allows you to read objects directly from a


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

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

162) Under what conditions is an object's finalize()


method invoked by the garbage collector?
The garbage collector invokes an object's finalize() method when it detects that the object
has become unreachable.
163) 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.

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

165) What is the difference between the JDK 1.02 event


model and the event-delegation model introduced with
JDK 1.1?
The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model,
components are required to handle their own events. If they do not handle a particular
event, the event is inherited by (or bubbled up to) the component's container. The container
then either handles the event or it is bubbled up to its container and so on, until the
highest-level container has been tried..
In the event-delegation model, specific objects are designated as event handlers for GUI
components. These objects implement event-listener interfaces. The event-delegation
model is more efficient than the event-inheritance model because it eliminates the
processing required to support the bubbling of unhandled events.

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

167) Why are the methods of the Math class static?


So they can be invoked as if they are a mathematical code library.

168) What Checkbox method allows you to tell if a


Checkbox is checked?
getState()

169) What state is a thread in when it is executing?


An executing thread is in the running state.
170) 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.

171) How are the elements of a GridLayout organized?


The elements of a GridBad layout are of equal size and are laid out using the squares of a
grid.

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

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

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

175) What classes of exceptions may be thrown by a throw


statement?
A throw statement may throw any expression that may be assigned to the Throwable type.

176) What are E and PI?


E is the base of the natural logarithm and PI is mathematical value pi.

177) Are true and false keywords?


The values true and false are not keywords.

178) What is a void return type?


A void return type indicates that a method does not return a value.
179) 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
eventdispatch methods.

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

181) What happens when you add a double value to a


String?
The result is a String object.

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

183) Which package is always imported by default?


The java.lang package is always imported by default.

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

185) How are this and super used?


this is used to refer to the current object instance. super is used to refer to the variables
and methods of the superclass of the current object instance.

186) 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.
187) What is a compilation unit?
A compilation unit is a Java source code file.

188) What interface is extended by AWT event listeners?


All AWT event listeners extend the java.util.EventListener interface.

189) 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 thrownby the
overridden method.

190) How can a dead thread be restarted?


A dead thread cannot be restarted.

191) What happens if an exception is not caught?


An uncaught exception results in the uncaughtException() method of the thread's
ThreadGroup being invoked, which eventually results in the termination of the program in
which it is thrown.

192) What is a layout manager?


A layout manager is an object that is used to organize components in a container.

193) Which arithmetic operations can result in the


throwing of an ArithmeticException?
Integer / and % can result in the throwing of an ArithmeticException.

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

195) Can an abstract class be final?


An abstract class may not be declared as final.
196) 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.

197) What happens if a try-catch-finally statement does


not have a catch clause to handle an exception that is
thrown within the body of the try statement?
The exception propagates up to the next higher level try-catch statement (if any) or results
in the program's termination.

198) What is numeric promotion?


Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so
that integer and floating-point operations may take place. In numerical promotion, byte,
char, and short values are converted to int values. The int values are also converted to long
values, if necessary. The long and float values are converted to double values, as required.

199) What is the difference between a Scrollbar and a


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

200) What is the difference between a public and a non-


public class?
A public class may be accessed outside of its package. A non-public class may not be
accessed outside of its package.

201) To what value is a variable of the boolean type


automatically initialized?
The default value of the boolean type is false.

202) Can try statements be nested?


Try statements may be tested.
203) What is the difference between the prefix and postfix
forms of the ++ operator?
The prefix form performs the increment operation and returns the value of the increment
operation. The postfix form returns the current value all of the expression and then
performs the increment operation on that value.

204) What is the purpose of a statement block?


A statement block is used to organize a sequence of statements as a single statement
group.

205) What is a Java package and how is it used?


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

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


A top-level class may be public, abstract, or final.

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

208) How does a try statement determine which catch


clause should be used to handle an exception?
When an exception is thrown within the body of a try statement, the catch clauses of the try
statement are examined in the order in which they appear. The first catch clause that is
capable of handling the exception is executed. The remaining catch clauses are ignored.

209) Can an unreachable object become reachable again?


An unreachable object may become reachable again. This can happen when the object's
finalize() method is invoked and the object performs an operation which causes it to
become accessible to reachable objects.

210) When is an object subject to garbage collection?


An object is subject to garbage collection when it becomes unreachable to the program in
which it is used.
211) 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.

212) What methods are used to get and set the text label
displayed by a Button object?
getLabel() and setLabel()

213) Which Component subclass is used for drawing and


painting?
Canvas

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

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

216) What are the problems faced by Java programmers


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

217) What is the difference between an if statement and a


switch statement?
The if statement is used to select among two alternatives. It uses a boolean expression to
decide which alternative should be executed. The switch statement is used to select among
multiple alternatives. It uses an int expression to determine which alternative should be
executed.
218) What happens when you add a double value to a
String?
The result is a String object.

219) What is the List interface?


The List interface provides support for ordered collections of objects.
Exception Interview Questions
1) What is an Exception?
An exception is an abnormal condition that arises in a code sequence at run time. In other
words, an exception is a run-time error.

2) What is a Java Exception?


A Java exception is an object that describes an exceptional condition i.e., an error condition
that has occurred in a piece of code. When this type of condition arises, an object
representing that exception is created and thrown in the method that caused the error by
the Java Runtime. That method may choose to handle the exception itself, or pass it on.
Either way, at some point, the exception is caught and processed.

3) What are the different ways to generate and Exception?


There are two different ways to generate an Exception.
1. Exceptions can be generated by the Java run-time system.
Exceptions thrown by Java relate to fundamental errors that violate the rules of the
Java language or the constraints of the Java execution environment.
2. Exceptions can be manually generated by your code.
Manually generated exceptions are typically used to report some error condition to
the caller of a method.

4) Where does Exception stand in the Java tree hierarchy?


• java.lang.Object
• java.lang.Throwable
• java.lang.Exception
• java.lang.Error

5) Is it compulsory to use the finally block?


It is always a good practice to use the finally block. The reason for using the finally block is,
any unreleased resources can be released and the memory can be freed. For example while
closing a connection object an exception has occurred. In finally block we can close that
object. Coming to the question, you can omit the finally block when there is a catch block
associated with that try block. A try block should have at least a catch or a finally block.

6) How are try, catch and finally block organized?


A try block should associate with at least a catch or a finally block. The sequence of try,
catch and finally matters a lot. If you modify the order of these then the code won’t
compile. Adding to this there can be multiple catch blocks associated with a try block. The
final concept is there should be a single try, multiple catch blocks and a single finally block
in a try-catch-finally block.

7) What is a throw in an Exception block?


“throw” is used to manually throw an exception (object) of type Throwable class or a
subclass of Throwable. Simple types, such as int or char, as well as non-Throwable
classes, such as String and Object, cannot be used as exceptions. The flow of execution
stops immediately after the throw statement; any subsequent statements are not
executed.

throw ThrowableInstance;

ThrowableInstance must be an object of type Throwable or a subclass of Throwable.

throw new NullPointerException("thrownException");

8) What is the use of throws keyword?


If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception. You do
this by including a throws clause in the method’s declaration. A throws clause lists the
types of exceptions that a method might throw.

type method-name(parameter-list) throws exception-list


{
// body of method
}
Warning: main(http://www.javabeat.net/javabeat/templates/faqs/faqs_middle.html):
failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in
/home/content/k/k/s/kkskrishna/html/faqs/exception/exception-faqs-1.html on line 1

Warning: main(http://www.javabeat.net/javabeat/templates/faqs/faqs_middle.html):
failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in
/home/content/k/k/s/kkskrishna/html/faqs/exception/exception-faqs-1.html on line 1

Warning: main(): Failed opening 'http://www.javabeat.net/javabeat/templates/faqs/f


(include_path='.:/usr/local/lib/php') in /home/content/k/k/s/kkskrishna/html/faqs/
on line 195

Here, exception-list is a comma-separated list of the exceptions that a method can

static void throwOne() throws IllegalAccessException {

System.out.println("Inside throwOne.");
9) What are Checked Exceptions and Unchecked
Exceptions?
The types of exceptions that need not be included in a methods throws list are called
Unchecked Exceptions.
• ArithmeticException
• ArrayIndexOutOfBoundsException
• ClassCastException
• IndexOutOfBoundsException
• IllegalStateException
• NullPointerException
• SecurityException
The types of exceptions that must be included in a methods throws list if that method can
generate one of these exceptions and does not handle it itself are called Checked
Exceptions.
• ClassNotFoundException
• CloneNotSupportedException
• IllegalAccessException
• InstantiationException
• InterruptedException
• NoSuchFieldException
• NoSuchMethodException

10) What are Chained Exceptions?


The chained exception feature allows you to associate another exception with an exception.
This second exception describes the cause of the first exception. Lets take a simple
example. You are trying to read a number from the disk and using it to divide a number.
Think the method throws an ArithmeticException because of an attempt to divide by zero
(number we got). However, the problem was that an I/O error occurred, which caused the
divisor to be set improperly (set to zero). Although the method must certainly throw an
ArithmeticException, since that is the error that occurred, you might also want to let the
calling code know that the underlying cause was an I/O error. This is the place where
chained exceptions come in to picture.

Throwable getCause( )

Throwable initCause(Throwable causeExc)


JDBC Interview Questions
11) I have the choice of manipulating database data using
a byte[] or a java.sql.Blob. Which has best performance?
java.sql.Blob, since it does not extract any data from the database until you explicitly ask it
to. The Java platform 2 type Blob wraps a database locator (which is essentially a pointer to
byte). That pointer is a rather large number (between 32 and 256 bits in size) - but the
effort to extract it from the database is insignificant next to extracting the full blob content.
For insertion into the database, you should use a byte[] since data has not been uploaded
to the database yet. Thus, use the Blob class only for extraction.
Conclusion: use the java.sql.Blob class for extraction whenever you can.

12) I have the choice of manipulating database data using


a String or a java.sql.Clob. Which has best performance?
java.sql.Clob, since it does not extract any data from the database until you explicitly ask it
to. The Java platform 2 type Clob wraps a database locator (which is essentially a pointer to
char). That pointer is a rather large number (between 32 and 256 bits in size) - but the
effort to extract it from the database is insignificant next to extracting the full Clob content.
For insertion into the database, you should use a String since data need not been
downloaded from the database. Thus, use the Clob class only for extraction.
Conclusion: Unless you always intend to extract the full textual data stored in the
particular table cell, use the java.sql.Clob class for extraction whenever you can.

13) Do I need to commit after an INSERT call in JDBC or


does JDBC do it automatically in the DB?
If your autoCommit flag (managed by the Connection.setAutoCommit method) is false, you
are required to call the commit() method - and vice versa.

14) How can I retrieve only the first n rows, second n rows
of a database using a particular WHERE clause ? For
example, if a SELECT typically returns a 1000 rows, how do
first retrieve the 100 rows, then go back and retrieve the
next 100 rows and so on ?
Use the Statement.setFetchSize method to indicate the size of each database fetch. Note
that this method is only available in the Java 2 platform. For Jdk 1.1.X and Jdk 1.0.X, no
standardized way of setting the fetch size exists. Please consult the Db driver manual.

15) What does ResultSet actually contain? Is it the actual


data of the result or some links to databases? If it is the
actual data then why can't we access it after connection is
closed?
A ResultSet is an interface. Its implementation depends on the driver and hence ,what it
"contains" depends partially on the driver and what the query returns.
For example with the Odbc bridge what the underlying implementation layer contains is an
ODBC result set. A Type 4 driver executing a stored procedure that returns a cursor - on an
oracle database it actually returns a cursor in the database. The oracle cursor can however
be processed like a ResultSet would be from the client.
Closing a connection closes all interaction with the database and releases any locks that
might have been obtained in the process.

16) What are SQL3 data types?


The next version of the ANSI/ISO SQL standard defines some new datatypes, commonly
referred to as the SQL3 types. The primary SQL3 types are:
STRUCT: This is the default mapping for any SQL structured type, and is manifest by the
java.sql.Struct type.
REF: Serves as a reference to SQL data within the database. Can be passed as a parameter
to a SQL statement. Mapped to the java.sql.Ref type.
BLOB: Holds binary large objects. Mapped to the java.sql.Blob type.
CLOB: Contains character large objects. Mapped to the java.sql.Clob type.
ARRAY: Can store values of a specified type. Mapped to the java.sql.Array type.
You can retrieve, store and update SQL3 types using the corresponding getXXX(), setXXX(),
and updateXXX() methods defined in ResultSet interface

17) How can I manage special characters (for example: " _


' % ) when I execute an INSERT query? If I don't filter the
quoting marks or the apostrophe, for example, the SQL
string will cause an error.
The characters "%" and "_" have special meaning in SQL LIKE clauses (to match zero or
more characters, or exactly one character, respectively). In order to interpret them literally,
they can be preceded with a special escape character in strings, e.g. "\". In order to specify
the escape character used to quote these characters, include the following syntax on the
end of the query:

{escape 'escape-character'}
For example, the query
SELECT NAME FROM IDENTIFIERS WHERE ID LIKE '\_%' {escape '\'}

finds identifier names that begin with an underbar.

18) What is SQLJ and why would I want to use it instead of


JDBC?
SQL/J is a technology, originally developed by Oracle Corporation, that enables you to
embed SQL statements in Java. The purpose of the SQLJ API is to simplify the development
requirements of the JDBC API while doing the same thing. Some major databases (Oracle,
Sybase) support SQLJ, but others do not. Currently, SQLJ has not been accepted as a
standard, so if you have to learn one of the two technologies, I recommend JDBC.

19) How do I insert an image file (or other raw data) into
a database?
All raw data types (including binary documents or images) should be read and uploaded to
the database as an array of bytes, byte[]. Originating from a binary file,
1. Read all data from the file using a FileInputStream.
2. Create a byte array from the read data.
3. Use method setBytes(int index, byte[] data); of java.sql.PreparedStatement to
upload the data.

20) How can I pool my database connections so I don't


have to keep reconnecting to the database?
• you gets a reference to the pool
• you gets a free connection from the pool
• you performs your different tasks
• you frees the connection to the pool
Since your application retrieves a pooled connection, you don't consume your time to
connect / disconnect from your data source.

21) Will a call to PreparedStatement.executeQuery()


always close the ResultSet from the previous
executeQuery()?
A ResultSet is automatically closed by the Statement that generated it when that Statement
is closed, re-executed, or is used to retrieve the next result from a sequence of multiple
results.

22) How do I upload SQL3 BLOB & CLOB data to a


database?
Although one may simply extract BLOB & CLOB data from the database using the methods
of the java.sql.CLOB and java.sql.BLOB, one must upload the data as normal java
datatypes. The example below inserts a BLOB in the form of a byte[] and a CLOB in the
form of a String into the database

Inserting SQL3 type data [BLOB & CLOB]


private void runInsert() {
try {
// Log
this.log("Inserting values ... ");

// Open a new Statement


PreparedStatement stmnt = conn.prepareStatement(
"insert Lobtest (image, name) values (?, ?)");

// Create a timestamp to measure the insert time


Date before = new java.util.Date();

for(int i = 0; i < 500; i++) {


// Set parameters
stmnt.setBytes(1, blobData);
stmnt.setString(2, "i: " + i + ";" + clobData);

// Perform insert
int rowsAffected = stmnt.executeUpdate();
}

// Get another timestamp to complete the time measurement


Date after = new java.util.Date();
this.log(" ... Done!");
log("Total run time: " + (
after.getTime() - before.getTime()));
// Close database resources
stmnt.close();
} catch(SQLException ex) {
this.log("Hmm... " + ex);
}
}

23) What is the difference between client and server


database cursors?
What you see on the client side is the current row of the cursor which called a Result
(ODBC) or ResultSet (JDBC). The cursor is a server-side entity only and remains on the
server side.

24) Are prepared statements faster because they are


compiled? if so, where and when are they compiled?
Prepared Statements aren't actually compiled, but they are bound by the JDBC driver.
Depending on the driver, Prepared Statements can be a lot faster - if you re-use them.
Some drivers bind the columns you request in the SQL statement. When you execute
Connection.prepareStatement(), all the columns bindings take place, so the binding
overhead does not occur each time you run the Prepared Statement. For additional
information on Prepared Statement performance and binding see JDBC Performance Tips on
IBM's website.
25) Is it possible to connect to multiple databases
simultaneously? Can one extract/update data from
multiple databases with a single statement?
In general, subject, as usual, to the capabilities of the specific driver implementation, one
can connect to multiple databases at the same time. At least one driver ( and probably
others ) will also handle commits across multiple connections. Obviously one should check
the driver documentation rather than assuming these capabilities.
As to the second part of the question, one needs special middleware to deal with multiple
databases in a single statement or to effectively treat them as one database. DRDA (
Distributed Relational Database Architecture -- I, at least, make it rhyme with "Gerta" ) is
probably most commonly used to accomplish this.
Oracle has a product called Oracle Transparent Gateway for IBM DRDA and IBM has a
product called DataJoiner that make multiple databases appear as one to your application.
No doubt there are other products available. XOpen also has papers available regarding
DRDA.

26) Why do I get an UnsupportedOperationException?


JDBC 2.0, introduced with the 1.2 version of Java, added several capabilities to JDBC.
Instead of completely invalidating all the older JDBC 1.x drivers, when you try to perform a
2.0 task with a 1.x driver, an UnsupportedOperationException will be thrown. You need to
update your driver if you wish to use the new capabilities.

27) What advantage is there to using prepared statements


if I am using connection pooling or closing the connection
frequently to avoid resource/connection/cursor
limitations?
The ability to choose the 'best' efficiency ( or evaluate tradeoffs, if you prefer, ) is, at times,
the most important piece of a mature developer's skillset. This is YAA ( Yet Another Area, )
where that maxim applies. Apparently there is an effort to allow prepared statements to
work 'better' with connection pools in JDBC 3.0, but for now, one loses most of the original
benefit of prepared statements when the connection is closed. A prepared statement
obviously fits best when a statement differing only in variable criteria is executed over and
over without closing the statement.
However, depending on the DB engine, the SQL may be cached and reused even for a
different prepared statement and most of the work is done by the DB engine rather than the
driver. In addition, prepared statements deal with data conversions that can be error prone
in straight ahead, built on the fly SQL; handling quotes and dates in a manner transparent
to the developer, for example.

28) What is JDBC, anyhow?


JDBC is Java's means of dynamically accessing tabular data, and primarily data in relational
databases, in a generic manner, normally using standard SQL statements.
29) Can I reuse a Statement or must I create a new one
for each query?
When using a JDBC compliant driver, you can use the same Statement for any number of
queries. However, some older drivers did not always "respect the spec." Also note that a
Statement SHOULD automatically close the current ResultSet before executing a new query,
so be sure you are done with it before re-querying using the same Statement.

30) What is a three-tier architecture?


A three-tier architecture is any system which enforces a general separation between the
following three parts:
1. Client Tier or user interface
2. Middle Tier or business logic
3. Data Storage Tier
Applied to web applications and distributed programming, the three logical tiers usually
correspond to the physical separation between three types of devices or hosts:

31) What separates one tier from another in the context of


n-tiered architecture?
It depends on the application.
In a web application, for example, where tier 1 is a web-server, it may communicate with a
tier 2 Application Server using RMI over IIOP, and subsequently tier 2 may communicate
with tier 3 (data storage) using JDBC, etc.
Each of these tiers may be on separate physical machines or they may share the same box.
The important thing is the functionality at each tier.
• Tier 1 - Presentation - should be concerned mainly with display of user interfaces
and/or data to the client browser or client system.
• Tier 2 - Application - should be concerned with business logic
Tier 3+ - Storage/Enterprise Systems - should be focused on data persistence and/or
communication with other Enterprise Systems.

32) What areas should I focus on for the best performance


in a JDBC application?
These are few points to consider:
• Use a connection pool mechanism whenever possible.
• Use prepared statements. These can be beneficial, for example with DB specific
escaping, even when used only once.
• Use stored procedures when they can be created in a standard manner. Do watch
out for DB specific SP definitions that can cause migration headaches.
• Even though the jdbc promotes portability, true portability comes from NOT
depending on any database specific data types, functions and so on.
• Select only required columns rather than using select * from Tablexyz.
• Always close Statement and ResultSet objects as soon as possible.
• Write modular classes to handle database interaction specifics.
• Work with DatabaseMetaData to get information about database functionality.
• Softcode database specific parameters with, for example, properties files.
• Always catch AND handle database warnings and exceptions. Be sure to check for
additional pending exceptions.
• Test your code with debug statements to determine the time it takes to execute
your query and so on to help in tuning your code. Also use query plan functionality
if available.
• Use proper ( and a single standard if possible ) formats, especially for dates.
• Use proper data types for specific kind of data. For example, store birthdate as a
date type rather than, say, varchar.

33) How can I insert multiple rows into a database in a


single transaction?
//turn off the implicit commit

Connection.setAutoCommit(false);
//..your insert/update/delete goes here
Connection.Commit();
a new transaction is implicitly started.

34) How do I convert a java.sql.Timestamp to a


java.util.Date?
While Timesteamp extends Date, it stores the fractional part of the time within itself instead
of within the Date superclass. If you need the partial seconds, you have to add them back
in.

Date date = new Date(ts.getTime() + (ts.getNanos() / 1000000 ));

35) What is SQL?


SQL is a standardized language used to create, manipulate, examine, and manage relational
databases.

36) Is Class.forName(Drivername) the only way to load a


driver? Can I instantiate the Driver and use the object of
the driver?
Yes, you can use the driver directly. Create an instance of the driver and use the connect
method from the Driver interface. Note that there may actually be two instances created,
due to the expected standard behavior of drivers when the class is loaded.

37) What's new in JDBC 3.0?


Probably the new features of most interest are:
• Savepoint support
• Reuse of prepared statements by connection pools
• Retrieval of auto-generated keys
• Ability to have multiple open ResultSet objects
• Ability to make internal updates to the data in Blob and Clob objects
• Ability to Update columns containing BLOB, CLOB, ARRAY and REF types
• Both java.sql and javax.sql ( JDBC 2.0 Optional Package ) are expected to be
included with J2SE 1.4.

38) Why do I get the message "No Suitable Driver"?


Often the answer is given that the correct driver is not loaded. This may be the case, but
more typically, the JDBC database URL passed is not properly constructed. When a
Connection request is issued, the DriverManager asks each loaded driver if it understands
the URL sent. If no driver responds that it understands the URL, then the "No Suitable
Driver" message is returned.

39) When I create multiple Statements on my Connection,


only the current Statement appears to be executed. What's
the problem?
All JDBC objects are required to be threadsafe. Some drivers, unfortunately, implement this
requirement by processing Statements serially. This means that additional Statements are
not executed until the preceding Statement is completed.

40) Can a single thread open up mutliple connections


simultaneously for the same database and for same table?
The general answer to this is yes. If that were not true, connection pools, for example,
would not be possible. As always, however, this is completely dependent on the JDBC
driver.
You can find out the theoretical maximum number of active Connections that your driver
can obtain via the DatabaseMetaData.getMaxConnections method.

41) Can I ensure that my app has the latest data?


Typically an application retrieves multiple rows of data, providing a snapshot at an instant of
time. Before a particular row is operated upon, the actual data may have been modified by
another program. When it is essential that the most recent data is provided, a JDBC 2.0
driver provides the ResultSet.refreshRow method.

42) What does normalization mean for java.sql.Date and


java.sql.Time?
These classes are thin wrappers extending java.util.Date, which has both date and time
components. java.sql.Date should carry only date information and a normalized instance
has the time information set to zeros. java.sql.Time should carry only time information and
a normalized instance has the date set to the Java epoch ( January 1, 1970 ) and the
milliseconds portion set to zero.
43) What's the best way, in terms of performance, to do
multiple insert/update statements, a PreparedStatement
or Batch Updates?
Because PreparedStatement objects are precompiled, their execution can be faster than
that of Statement objects. Consequently, an SQL statement that is executed many times is
often created as a PreparedStatement object to increase efficiency.
A CallableStatement object provides a way to call stored procedures in a standard manner
for all DBMSes. Their execution can be faster than that of PreparedStatement object.
Batch updates are used when you want to execute multiple statements together. Actually,
there is no conflict here. While it depends on the driver/DBMS engine as to whether or not
you will get an actual performance benefit from batch updates, Statement,
PreparedStatement, and CallableStatement can all execute the addBatch() method.

44) What is JDO?


JDO provides for the transparent persistence of data in a data store agnostic manner,
supporting object, hierarchical, as well as relational stores.

45) What is the difference between setMaxRows(int) and


SetFetchSize(int)? Can either reduce processing time?
setFetchSize(int) defines the number of rows that will be read from the database when the
ResultSet needs more rows. The method in the java.sql.Statement interface will set the
'default' value for all the ResultSet derived from that Statement; the method in the
java.sql.ResultSet interface will override that value for a specific ResultSet. Since database
fetches can be expensive in a networked environment, fetch size has an impact on
performance.
setMaxRows(int) sets the limit of the maximum nuber of rows in a ResultSet object. If this
limit is exceeded, the excess rows are "silently dropped". That's all the API says, so the
setMaxRows method may not help performance at all other than to decrease memory
usage. A value of 0 (default) means no limit.

46) What is DML?


DML is an abbreviation for Data Manipulation Language. This portion of the SQL standard is
concerned with manipulating the data in a database as opposed to the structure of a
database. The core verbs for DML are SELECT, INSERT, DELETE, UPDATE, COMMIT and
ROLLBACK.

47) What is DDL?


DDL is an abbreviation for Data Definition Language. This portion of the SQL standard is
concerned with the creation, deletion and modification of database objects like tables,
indexes and views. The core verbs for DDL are CREATE, ALTER and DROP. While most
DBMS engines allow DDL to be used dynamically ( and available to JDBC ), it is often not
supported in transactions.
48) How can I get information about foreign keys used in a
table?
DatabaseMetaData.getImportedKeys() returns a ResultSet with data about foreign key
columns, tables, sequence and update and delete rules.

49) How do I disallow NULL values in a table?


Null capability is a column integrity constraint, normally aplied at table creation time. Note
that some databases won't allow the constraint to be applied after table creation. Most
databases allow a default value for the column as well. The following SQL statement
displays the NOT NULL constraint:

CREATE TABLE CoffeeTable (


Type VARCHAR(25) NOT NULL,
Pounds INTEGER NOT NULL,
Price NUMERIC(5, 2) NOT NULL
)

50) What isolation level is used by the DBMS when


inserting, updating and selecting rows from a database?
The answer depends on both your code and the DBMS. If the program does not explicitly set
the isolation level, the DBMS default is used. You can determine the default using
DatabaseMetaData.getDefaultTransactionIsolation() and the level for the current Connection
with Connection.getTransactionIsolation(). If the default is not appropriate for your
transaction, change it with Connection.setTransactionIsolation(int level).
JDBC Interview Questions
11) I have the choice of manipulating database data using
a byte[] or a java.sql.Blob. Which has best performance?
java.sql.Blob, since it does not extract any data from the database until you explicitly ask it
to. The Java platform 2 type Blob wraps a database locator (which is essentially a pointer to
byte). That pointer is a rather large number (between 32 and 256 bits in size) - but the
effort to extract it from the database is insignificant next to extracting the full blob content.
For insertion into the database, you should use a byte[] since data has not been uploaded
to the database yet. Thus, use the Blob class only for extraction.
Conclusion: use the java.sql.Blob class for extraction whenever you can.

12) I have the choice of manipulating database data using


a String or a java.sql.Clob. Which has best performance?
java.sql.Clob, since it does not extract any data from the database until you explicitly ask it
to. The Java platform 2 type Clob wraps a database locator (which is essentially a pointer to
char). That pointer is a rather large number (between 32 and 256 bits in size) - but the
effort to extract it from the database is insignificant next to extracting the full Clob content.
For insertion into the database, you should use a String since data need not been
downloaded from the database. Thus, use the Clob class only for extraction.
Conclusion: Unless you always intend to extract the full textual data stored in the
particular table cell, use the java.sql.Clob class for extraction whenever you can.

13) Do I need to commit after an INSERT call in JDBC or


does JDBC do it automatically in the DB?
If your autoCommit flag (managed by the Connection.setAutoCommit method) is false, you
are required to call the commit() method - and vice versa.

14) How can I retrieve only the first n rows, second n rows
of a database using a particular WHERE clause ? For
example, if a SELECT typically returns a 1000 rows, how do
first retrieve the 100 rows, then go back and retrieve the
next 100 rows and so on ?
Use the Statement.setFetchSize method to indicate the size of each database fetch. Note
that this method is only available in the Java 2 platform. For Jdk 1.1.X and Jdk 1.0.X, no
standardized way of setting the fetch size exists. Please consult the Db driver manual.

15) What does ResultSet actually contain? Is it the actual


data of the result or some links to databases? If it is the
actual data then why can't we access it after connection is
closed?
A ResultSet is an interface. Its implementation depends on the driver and hence ,what it
"contains" depends partially on the driver and what the query returns.
For example with the Odbc bridge what the underlying implementation layer contains is an
ODBC result set. A Type 4 driver executing a stored procedure that returns a cursor - on an
oracle database it actually returns a cursor in the database. The oracle cursor can however
be processed like a ResultSet would be from the client.
Closing a connection closes all interaction with the database and releases any locks that
might have been obtained in the process.

16) What are SQL3 data types?


The next version of the ANSI/ISO SQL standard defines some new datatypes, commonly
referred to as the SQL3 types. The primary SQL3 types are:
STRUCT: This is the default mapping for any SQL structured type, and is manifest by the
java.sql.Struct type.
REF: Serves as a reference to SQL data within the database. Can be passed as a parameter
to a SQL statement. Mapped to the java.sql.Ref type.
BLOB: Holds binary large objects. Mapped to the java.sql.Blob type.
CLOB: Contains character large objects. Mapped to the java.sql.Clob type.
ARRAY: Can store values of a specified type. Mapped to the java.sql.Array type.
You can retrieve, store and update SQL3 types using the corresponding getXXX(), setXXX(),
and updateXXX() methods defined in ResultSet interface

17) How can I manage special characters (for example: " _


' % ) when I execute an INSERT query? If I don't filter the
quoting marks or the apostrophe, for example, the SQL
string will cause an error.
The characters "%" and "_" have special meaning in SQL LIKE clauses (to match zero or
more characters, or exactly one character, respectively). In order to interpret them literally,
they can be preceded with a special escape character in strings, e.g. "\". In order to specify
the escape character used to quote these characters, include the following syntax on the
end of the query:

{escape 'escape-character'}
For example, the query
SELECT NAME FROM IDENTIFIERS WHERE ID LIKE '\_%' {escape '\'}

finds identifier names that begin with an underbar.

18) What is SQLJ and why would I want to use it instead of


JDBC?
SQL/J is a technology, originally developed by Oracle Corporation, that enables you to
embed SQL statements in Java. The purpose of the SQLJ API is to simplify the development
requirements of the JDBC API while doing the same thing. Some major databases (Oracle,
Sybase) support SQLJ, but others do not. Currently, SQLJ has not been accepted as a
standard, so if you have to learn one of the two technologies, I recommend JDBC.

19) How do I insert an image file (or other raw data) into
a database?
All raw data types (including binary documents or images) should be read and uploaded to
the database as an array of bytes, byte[]. Originating from a binary file,
1. Read all data from the file using a FileInputStream.
2. Create a byte array from the read data.
3. Use method setBytes(int index, byte[] data); of java.sql.PreparedStatement to
upload the data.

20) How can I pool my database connections so I don't


have to keep reconnecting to the database?
• you gets a reference to the pool
• you gets a free connection from the pool
• you performs your different tasks
• you frees the connection to the pool
Since your application retrieves a pooled connection, you don't consume your time to
connect / disconnect from your data source.

21) Will a call to PreparedStatement.executeQuery()


always close the ResultSet from the previous
executeQuery()?
A ResultSet is automatically closed by the Statement that generated it when that Statement
is closed, re-executed, or is used to retrieve the next result from a sequence of multiple
results.

22) How do I upload SQL3 BLOB & CLOB data to a


database?
Although one may simply extract BLOB & CLOB data from the database using the methods
of the java.sql.CLOB and java.sql.BLOB, one must upload the data as normal java
datatypes. The example below inserts a BLOB in the form of a byte[] and a CLOB in the
form of a String into the database

Inserting SQL3 type data [BLOB & CLOB]


private void runInsert() {
try {
// Log
this.log("Inserting values ... ");

// Open a new Statement


PreparedStatement stmnt = conn.prepareStatement(
"insert Lobtest (image, name) values (?, ?)");

// Create a timestamp to measure the insert time


Date before = new java.util.Date();

for(int i = 0; i < 500; i++) {


// Set parameters
stmnt.setBytes(1, blobData);
stmnt.setString(2, "i: " + i + ";" + clobData);

// Perform insert
int rowsAffected = stmnt.executeUpdate();
}

// Get another timestamp to complete the time measurement


Date after = new java.util.Date();
this.log(" ... Done!");
log("Total run time: " + (
after.getTime() - before.getTime()));
// Close database resources
stmnt.close();
} catch(SQLException ex) {
this.log("Hmm... " + ex);
}
}

23) What is the difference between client and server


database cursors?
What you see on the client side is the current row of the cursor which called a Result
(ODBC) or ResultSet (JDBC). The cursor is a server-side entity only and remains on the
server side.

24) Are prepared statements faster because they are


compiled? if so, where and when are they compiled?
Prepared Statements aren't actually compiled, but they are bound by the JDBC driver.
Depending on the driver, Prepared Statements can be a lot faster - if you re-use them.
Some drivers bind the columns you request in the SQL statement. When you execute
Connection.prepareStatement(), all the columns bindings take place, so the binding
overhead does not occur each time you run the Prepared Statement. For additional
information on Prepared Statement performance and binding see JDBC Performance Tips on
IBM's website.
25) Is it possible to connect to multiple databases
simultaneously? Can one extract/update data from
multiple databases with a single statement?
In general, subject, as usual, to the capabilities of the specific driver implementation, one
can connect to multiple databases at the same time. At least one driver ( and probably
others ) will also handle commits across multiple connections. Obviously one should check
the driver documentation rather than assuming these capabilities.
As to the second part of the question, one needs special middleware to deal with multiple
databases in a single statement or to effectively treat them as one database. DRDA (
Distributed Relational Database Architecture -- I, at least, make it rhyme with "Gerta" ) is
probably most commonly used to accomplish this.
Oracle has a product called Oracle Transparent Gateway for IBM DRDA and IBM has a
product called DataJoiner that make multiple databases appear as one to your application.
No doubt there are other products available. XOpen also has papers available regarding
DRDA.

26) Why do I get an UnsupportedOperationException?


JDBC 2.0, introduced with the 1.2 version of Java, added several capabilities to JDBC.
Instead of completely invalidating all the older JDBC 1.x drivers, when you try to perform a
2.0 task with a 1.x driver, an UnsupportedOperationException will be thrown. You need to
update your driver if you wish to use the new capabilities.

27) What advantage is there to using prepared statements


if I am using connection pooling or closing the connection
frequently to avoid resource/connection/cursor
limitations?
The ability to choose the 'best' efficiency ( or evaluate tradeoffs, if you prefer, ) is, at times,
the most important piece of a mature developer's skillset. This is YAA ( Yet Another Area, )
where that maxim applies. Apparently there is an effort to allow prepared statements to
work 'better' with connection pools in JDBC 3.0, but for now, one loses most of the original
benefit of prepared statements when the connection is closed. A prepared statement
obviously fits best when a statement differing only in variable criteria is executed over and
over without closing the statement.
However, depending on the DB engine, the SQL may be cached and reused even for a
different prepared statement and most of the work is done by the DB engine rather than the
driver. In addition, prepared statements deal with data conversions that can be error prone
in straight ahead, built on the fly SQL; handling quotes and dates in a manner transparent
to the developer, for example.

28) What is JDBC, anyhow?


JDBC is Java's means of dynamically accessing tabular data, and primarily data in relational
databases, in a generic manner, normally using standard SQL statements.
29) Can I reuse a Statement or must I create a new one
for each query?
When using a JDBC compliant driver, you can use the same Statement for any number of
queries. However, some older drivers did not always "respect the spec." Also note that a
Statement SHOULD automatically close the current ResultSet before executing a new query,
so be sure you are done with it before re-querying using the same Statement.

30) What is a three-tier architecture?


A three-tier architecture is any system which enforces a general separation between the
following three parts:
1. Client Tier or user interface
2. Middle Tier or business logic
3. Data Storage Tier
Applied to web applications and distributed programming, the three logical tiers usually
correspond to the physical separation between three types of devices or hosts:

31) What separates one tier from another in the context of


n-tiered architecture?
It depends on the application.
In a web application, for example, where tier 1 is a web-server, it may communicate with a
tier 2 Application Server using RMI over IIOP, and subsequently tier 2 may communicate
with tier 3 (data storage) using JDBC, etc.
Each of these tiers may be on separate physical machines or they may share the same box.
The important thing is the functionality at each tier.
• Tier 1 - Presentation - should be concerned mainly with display of user interfaces
and/or data to the client browser or client system.
• Tier 2 - Application - should be concerned with business logic
Tier 3+ - Storage/Enterprise Systems - should be focused on data persistence and/or
communication with other Enterprise Systems.

32) What areas should I focus on for the best performance


in a JDBC application?
These are few points to consider:
• Use a connection pool mechanism whenever possible.
• Use prepared statements. These can be beneficial, for example with DB specific
escaping, even when used only once.
• Use stored procedures when they can be created in a standard manner. Do watch
out for DB specific SP definitions that can cause migration headaches.
• Even though the jdbc promotes portability, true portability comes from NOT
depending on any database specific data types, functions and so on.
• Select only required columns rather than using select * from Tablexyz.
• Always close Statement and ResultSet objects as soon as possible.
• Write modular classes to handle database interaction specifics.
• Work with DatabaseMetaData to get information about database functionality.
• Softcode database specific parameters with, for example, properties files.
• Always catch AND handle database warnings and exceptions. Be sure to check for
additional pending exceptions.
• Test your code with debug statements to determine the time it takes to execute
your query and so on to help in tuning your code. Also use query plan functionality
if available.
• Use proper ( and a single standard if possible ) formats, especially for dates.
• Use proper data types for specific kind of data. For example, store birthdate as a
date type rather than, say, varchar.

33) How can I insert multiple rows into a database in a


single transaction?
//turn off the implicit commit

Connection.setAutoCommit(false);
//..your insert/update/delete goes here
Connection.Commit();
a new transaction is implicitly started.

34) How do I convert a java.sql.Timestamp to a


java.util.Date?
While Timesteamp extends Date, it stores the fractional part of the time within itself instead
of within the Date superclass. If you need the partial seconds, you have to add them back
in.

Date date = new Date(ts.getTime() + (ts.getNanos() / 1000000 ));

35) What is SQL?


SQL is a standardized language used to create, manipulate, examine, and manage relational
databases.

36) Is Class.forName(Drivername) the only way to load a


driver? Can I instantiate the Driver and use the object of
the driver?
Yes, you can use the driver directly. Create an instance of the driver and use the connect
method from the Driver interface. Note that there may actually be two instances created,
due to the expected standard behavior of drivers when the class is loaded.

37) What's new in JDBC 3.0?


Probably the new features of most interest are:
• Savepoint support
• Reuse of prepared statements by connection pools
• Retrieval of auto-generated keys
• Ability to have multiple open ResultSet objects
• Ability to make internal updates to the data in Blob and Clob objects
• Ability to Update columns containing BLOB, CLOB, ARRAY and REF types
• Both java.sql and javax.sql ( JDBC 2.0 Optional Package ) are expected to be
included with J2SE 1.4.

38) Why do I get the message "No Suitable Driver"?


Often the answer is given that the correct driver is not loaded. This may be the case, but
more typically, the JDBC database URL passed is not properly constructed. When a
Connection request is issued, the DriverManager asks each loaded driver if it understands
the URL sent. If no driver responds that it understands the URL, then the "No Suitable
Driver" message is returned.

39) When I create multiple Statements on my Connection,


only the current Statement appears to be executed. What's
the problem?
All JDBC objects are required to be threadsafe. Some drivers, unfortunately, implement this
requirement by processing Statements serially. This means that additional Statements are
not executed until the preceding Statement is completed.

40) Can a single thread open up mutliple connections


simultaneously for the same database and for same table?
The general answer to this is yes. If that were not true, connection pools, for example,
would not be possible. As always, however, this is completely dependent on the JDBC
driver.
You can find out the theoretical maximum number of active Connections that your driver
can obtain via the DatabaseMetaData.getMaxConnections method.

41) Can I ensure that my app has the latest data?


Typically an application retrieves multiple rows of data, providing a snapshot at an instant of
time. Before a particular row is operated upon, the actual data may have been modified by
another program. When it is essential that the most recent data is provided, a JDBC 2.0
driver provides the ResultSet.refreshRow method.

42) What does normalization mean for java.sql.Date and


java.sql.Time?
These classes are thin wrappers extending java.util.Date, which has both date and time
components. java.sql.Date should carry only date information and a normalized instance
has the time information set to zeros. java.sql.Time should carry only time information and
a normalized instance has the date set to the Java epoch ( January 1, 1970 ) and the
milliseconds portion set to zero.
43) What's the best way, in terms of performance, to do
multiple insert/update statements, a PreparedStatement
or Batch Updates?
Because PreparedStatement objects are precompiled, their execution can be faster than
that of Statement objects. Consequently, an SQL statement that is executed many times is
often created as a PreparedStatement object to increase efficiency.
A CallableStatement object provides a way to call stored procedures in a standard manner
for all DBMSes. Their execution can be faster than that of PreparedStatement object.
Batch updates are used when you want to execute multiple statements together. Actually,
there is no conflict here. While it depends on the driver/DBMS engine as to whether or not
you will get an actual performance benefit from batch updates, Statement,
PreparedStatement, and CallableStatement can all execute the addBatch() method.

44) What is JDO?


JDO provides for the transparent persistence of data in a data store agnostic manner,
supporting object, hierarchical, as well as relational stores.

45) What is the difference between setMaxRows(int) and


SetFetchSize(int)? Can either reduce processing time?
setFetchSize(int) defines the number of rows that will be read from the database when the
ResultSet needs more rows. The method in the java.sql.Statement interface will set the
'default' value for all the ResultSet derived from that Statement; the method in the
java.sql.ResultSet interface will override that value for a specific ResultSet. Since database
fetches can be expensive in a networked environment, fetch size has an impact on
performance.
setMaxRows(int) sets the limit of the maximum nuber of rows in a ResultSet object. If this
limit is exceeded, the excess rows are "silently dropped". That's all the API says, so the
setMaxRows method may not help performance at all other than to decrease memory
usage. A value of 0 (default) means no limit.

46) What is DML?


DML is an abbreviation for Data Manipulation Language. This portion of the SQL standard is
concerned with manipulating the data in a database as opposed to the structure of a
database. The core verbs for DML are SELECT, INSERT, DELETE, UPDATE, COMMIT and
ROLLBACK.

47) What is DDL?


DDL is an abbreviation for Data Definition Language. This portion of the SQL standard is
concerned with the creation, deletion and modification of database objects like tables,
indexes and views. The core verbs for DDL are CREATE, ALTER and DROP. While most
DBMS engines allow DDL to be used dynamically ( and available to JDBC ), it is often not
supported in transactions.
48) How can I get information about foreign keys used in a
table?
DatabaseMetaData.getImportedKeys() returns a ResultSet with data about foreign key
columns, tables, sequence and update and delete rules.

49) How do I disallow NULL values in a table?


Null capability is a column integrity constraint, normally aplied at table creation time. Note
that some databases won't allow the constraint to be applied after table creation. Most
databases allow a default value for the column as well. The following SQL statement
displays the NOT NULL constraint:

CREATE TABLE CoffeeTable (


Type VARCHAR(25) NOT NULL,
Pounds INTEGER NOT NULL,
Price NUMERIC(5, 2) NOT NULL
)

50) What isolation level is used by the DBMS when


inserting, updating and selecting rows from a database?
The answer depends on both your code and the DBMS. If the program does not explicitly set
the isolation level, the DBMS default is used. You can determine the default using
DatabaseMetaData.getDefaultTransactionIsolation() and the level for the current Connection
with Connection.getTransactionIsolation(). If the default is not appropriate for your
transaction, change it with Connection.setTransactionIsolation(int level).
Struts Interview Questions
1) What is Struts?
The core of the Struts framework is a flexible control layer based on standard technologies
like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta
Commons packages. Struts encourages application architectures based on the Model 2
approach, a variation of the classic Model-View-Controller (MVC) design paradigm.
Struts provides its own Controller component and integrates with other technologies to
provide the Model and the View. For the Model, Struts can interact with standard data
access technologies, like JDBC and EJB, as well as most any third-party packages, like
Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts works well with
JavaServer Pages, including JSTL and JSF, as well as Velocity Templates, XSLT, and other
presentation systems.
The Struts framework provides the invisible underpinnings every professional web
application needs to survive. Struts helps you create an extensible development
environment for your application, based on published standards and proven design patterns.

2) What is Jakarta Struts Framework?


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

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

4) How you will make available any Message Resources


Definitions file to the Struts Framework Environment?
T Message Resources Definitions file are simple .properties files and these files contains the
messages that can be used in the struts project. Message Resources Definitions files can be
added to the struts-config.xml file through <message-resources /> tag.
Example:

<message-resources parameter=\"MessageResources\" />.

5) What is Action Class?


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.

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

7) What is Struts Validator Framework?


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

8) Give the Details of XML files used in Validator


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

9) How you will display validation fail errors on jsp page?


Following tag displays all the errors:

<html:errors/$gt;

10) How you will enable front-end validation based on the


xml in validation.xml?
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.
11) How to get data from the velocity page in a action
class?
We can get the values in the action classes by using data.getParameter(\"variable name
defined in the velocity page\");
Spring Interview Questions
1) What is Spring?
Spring is a lightweight inversion of control and aspect-oriented container framework.

2) Explain Spring?
• Lightweight : Spring is lightweight when it comes to size and transparency. The
basic version of spring framework is around 1MB. And the processing overhead is
also very negligible.
• Inversion of control (IoC) : Loose coupling is achieved in spring using the
technique Inversion of Control. The objects give their dependencies instead of
creating or looking for dependent objects.
• Aspect oriented (AOP) : Spring supports Aspect oriented programming and
enables cohesive development by separating application business logic from system
services.
• Container : Spring contains and manages the life cycle and configuration of
application objects.
• Framework : Spring provides most of the intra functionality leaving rest of the
coding to the developer.

3) What are the different modules in Spring framework?


• The Core container module
• Application context module
• AOP module (Aspect Oriented Programming)
• JDBC abstraction and DAO module
• O/R mapping integration module (Object/Relational)
• Web module
• MVC framework module

4) What is the structure of Spring framework?

5) What is the Core container module?


This module is provides the fundamental functionality of the spring framework. In this
module BeanFactory is the heart of any spring-based application. The entire framework
was built on the top of this module. This module makes the Spring container.

6) What is Application context module?


The Application context module makes spring a framework. This module extends the
concept of BeanFactory, providing support for internationalization (I18N) messages,
application lifecycle events, and validation. This module also supplies many enterprise
services such JNDI access, EJB integration, remoting, and scheduling. It also provides
support to other framework.

7) What is AOP module?


The AOP module is used for developing aspects for our Spring-enabled application. Much of
the support has been provided by the AOP Alliance in order to ensure the interoperability
between Spring and other AOP frameworks. This module also introduces metadata
programming to Spring. Using Spring’s metadata support, we will be able to add
annotations to our source code that instruct Spring on where and how to apply aspects.

8) What is JDBC abstraction and DAO module?


Using this module we can keep up the database code clean and simple, and prevent
problems that result from a failure to close database resources. A new layer of meaningful
exceptions on top of the error messages given by several database servers is bought in this
module. In addition, this module uses Spring’s AOP module to provide transaction
management services for objects in a Spring application.

9) What are object/relational mapping integration


module?
Spring also supports for using of an object/relational mapping (ORM) tool over straight
JDBC by providing the ORM module. Spring provide support to tie into several popular ORM
frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction
management supports each of these ORM frameworks as well as JDBC.

10) What is web module?


This module is built on the application context module, providing a context that is
appropriate for web-based applications. This module also contains support for several web-
oriented tasks such as transparently handling multipart requests for file uploads and
programmatic binding of request parameters to your business objects. It also contains
integration support with Jakarta Struts.

11) What is web module?


Spring comes with a full-featured MVC framework for building web applications. Although
Spring can easily be integrated with other MVC frameworks, such as Struts, Spring’s MVC
framework uses IoC to provide for a clean separation of controller logic from business
objects. It also allows you to declaratively bind request parameters to your business
objects. It also can take advantage of any of Spring’s other services, such as I18N
messaging and validation.
12) What is a BeanFactory?
A BeanFactory is an implementation of the factory pattern that applies Inversion of Control
to separate the application’s configuration and dependencies from the actual application
code.

13) What is AOP Alliance?


AOP Alliance is an open-source project whose goal is to promote adoption of AOP and
interoperability among different AOP implementations by defining a common set of
interfaces and components.

14) What is Spring configuration file?


Spring configuration file is an XML file. This file contains the classes information and
describes how these classes are configured and introduced to each other.

15) What does a simple spring application contain?


These applications are like any Java application. They are made up of several classes, each
performing a specific purpose within the application. But these classes are configured and
introduced to each other through an XML file. This XML file describes how to configure the
classes, known as the Spring configuration file.

16) What is XMLBeanFactory?


BeanFactory has many implementations in Spring. But one of the most useful one is
org.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based
on the definitions contained in an XML file. To create an XmlBeanFactory, pass a
java.io.InputStream to the constructor. The InputStream will provide the XML to the
factory. For example, the following code snippet uses a java.io.FileInputStream to provide
a bean definition XML file to XmlBeanFactory.

BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml"));

To retrieve the bean from a BeanFactory, call the getBean() method by passing the name of
the bean you want to retrieve.

MyBean myBean = (MyBean) factory.getBean("myBean");

17) What are important ApplicationContext


implementations in spring framework?
• ClassPathXmlApplicationContext – This context loads a context definition from
an XML file located in the class path, treating context definition files as class path
resources.
• FileSystemXmlApplicationContext – This context loads a context definition from
an XML file in the filesystem.
• XmlWebApplicationContext – This context loads the context definitions from an
XML file contained within a web application.

18) Explain Bean lifecycle in Spring framework?


1. The spring container finds the bean’s definition from the XML file and instantiates
the bean.
2. Using the dependency injection, spring populates all of the properties as specified in
the bean definition.
3. If the bean implements the BeanNameAware interface, the factory calls
setBeanName() passing the bean’s ID.
4. If the bean implements the BeanFactoryAware interface, the factory calls
setBeanFactory(), passing an instance of itself.
5. If there are any BeanPostProcessors associated with the bean, their post-
ProcessBeforeInitialization() methods will be called.
6. If an init-method is specified for the bean, it will be called.
7. Finally, if there are any BeanPostProcessors associated with the bean, their
postProcessAfterInitialization() methods will be called.

19) What is bean wiring?


Combining together beans within the Spring container is known as bean wiring or wiring.
When wiring beans, you should tell the container what beans are needed and how the
container should use dependency injection to tie them together.

20) How do add a bean in spring application?


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/d
<beans>
<bean id="foo" class="com.act.Foo"/>
<bean id="bar" class="com.act.Bar"/>
</beans>

In the bean tag the id attribute specifies the bean name and the class attribute specifies the
fully qualified class name.

21) What are singleton beans and how can you create
prototype beans?
Beans defined in spring framework are singleton beans. There is an attribute in bean tag
named ‘singleton’ if specified true then bean becomes singleton and if set to false then the
bean becomes a prototype bean. By default it is set to true. So, all the beans in spring
framework are by default singleton beans.

<beans>
<bean id="bar" class="com.act.Foo" singleton=”false”/>
</beans>
22) What are the important beans lifecycle methods?
There are two important bean lifecycle methods. The first one is setup which is called when
the bean is loaded in to the container. The second method is the teardown method which is
called when the bean is unloaded from the container.

23) How can you override beans default lifecycle methods?


The bean tag has two more important attributes with which you can define your own custom
initialization and destroy methods. Here I have shown a small demonstration. Two new
methods fooSetup and fooTeardown are to be added to your Foo class.

<beans>
<bean id="bar" class="com.act.Foo" init-method=”fooSetup” destroy=”fooTeardown”/
</beans>

24) What are Inner Beans?


When wiring beans, if a bean element is embedded to a property tag directly, then that
bean is said to the Inner Bean. The drawback of this bean is that it cannot be reused
anywhere else.

25) What are the different types of bean injections?


There are two types of bean injections.
1. By setter
2. By constructor

26) What is Auto wiring?


You can wire the beans as you wish. But spring framework also does this work for you. It
can auto wire the related beans together. All you have to do is just set the autowire
attribute of bean tag to an autowire type.

<beans>
<bean id="bar" class="com.act.Foo" Autowire=”autowire type”/>
</beans>

27) What are different types of Autowire types?


There are four different types by which autowiring can be done.
◦ byName
◦ byType
◦ constructor
◦ autodetect
28) What are the different types of events related to
Listeners?
There are a lot of events related to ApplicationContext of spring framework. All the events
are subclasses of org.springframework.context.Application-Event. They are
• ContextClosedEvent – This is fired when the context is closed.
• ContextRefreshedEvent – This is fired when the context is initialized or refreshed.
• RequestHandledEvent – This is fired when the web context handles any request.

29) What is an Aspect?


An aspect is the cross-cutting functionality that you are implementing. It is the aspect of
your application you are modularizing. An example of an aspect is logging. Logging is
something that is required throughout an application. However, because applications tend to
be broken down into layers based on functionality, reusing a logging module through
inheritance does not make sense. However, you can create a logging aspect and apply it
throughout your application using AOP.

30) What is a Jointpoint?


A joinpoint is a point in the execution of the application where an aspect can be plugged in.
This point could be a method being called, an exception being thrown, or even a field being
modified. These are the points where your aspect’s code can be inserted into the normal
flow of your application to add new behavior.

31) What is an Advice?


Advice is the implementation of an aspect. It is something like telling your application of a
new behavior. Generally, and advice is inserted into an application at joinpoints.

32) What is a Pointcut?


A pointcut is something that defines at what joinpoints an advice should be applied. Advices
can be applied at any joinpoint that is supported by the AOP framework. These Pointcuts
allow you to specify where the advice can be applied.

33) What is an Introduction in AOP?


An introduction allows the user to add new methods or attributes to an existing class. This
can then be introduced to an existing class without having to change the structure of the
class, but give them the new behavior and state.

34) What is a Target?


A target is the class that is being advised. The class can be a third party class or your own
class to which you want to add your own custom behavior. By using the concepts of AOP,
the target class is free to center on its major concern, unaware to any advice that is being
applied.

35) What is a Proxy?


A proxy is an object that is created after applying advice to a target object. When you think
of client objects the target object and the proxy object are the same.

36) What is meant by Weaving?


The process of applying aspects to a target object to create a new proxy object is called as
Weaving. The aspects are woven into the target object at the specified joinpoints.

37) What are the different points where weaving can be


applied?
• Compile Time
• Classload Time
• Runtime

38) What are the different advice types in spring?


• Around : Intercepts the calls to the target method
• Before : This is called before the target method is invoked
• After : This is called after the target method is returned
• Throws : This is called when the target method throws and exception
• Around : org.aopalliance.intercept.MethodInterceptor
• Before : org.springframework.aop.BeforeAdvice
• After : org.springframework.aop.AfterReturningAdvice
• Throws : org.springframework.aop.ThrowsAdvice

39) What are the different types of AutoProxying?


• BeanNameAutoProxyCreator
• DefaultAdvisorAutoProxyCreator
• Metadata autoproxying

40) What is the Exception class related to all the


exceptions that are thrown in spring applications?
DataAccessException - org.springframework.dao.DataAccessException
41) What kind of exceptions those spring DAO classes
throw?
The spring’s DAO class does not throw any technology related exceptions such as
SQLException. They throw exceptions which are subclasses of DataAccessException.

42) What is DataAccessException?


DataAccessException is a RuntimeException. This is an Unchecked Exception. The user is
not forced to handle these kinds of exceptions.

43) How can you configure a bean to get DataSource from


JNDI?
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jdbc/myDatasource</value>
</property>
</bean>

44) How can you create a DataSource connection pool?


<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driver">
<value>${db.driver}</value>
</property>
<property name="url">
<value>${db.url}</value>
</property>
<property name="username">
<value>${db.username}</value>
</property>
<property name="password">
<value>${db.password}</value>
</property>
</bean>

45) How JDBC can be used more efficiently in spring


framework?
JDBC can be used more efficiently with the help of a template class provided by spring
framework called as JdbcTemplate.
46) How JdbcTemplate can be used?
With use of Spring JDBC framework the burden of resource management and error handling
is reduced a lot. So it leaves developers to write the statements and queries to get the data
to and from the database.

JdbcTemplate template = new JdbcTemplate(myDataSource);

A simple DAO class looks like this.

public class StudentDaoJdbc implements StudentDao {


private JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {


this.jdbcTemplate = jdbcTemplate;
}
more..
}

The configuration is shown below.

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">


<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>
<bean id="studentDao" class="StudentDaoJdbc">
<property name="jdbcTemplate">
<ref bean="jdbcTemplate"/>
</property>
</bean>
<bean id="courseDao" class="CourseDaoJdbc">
<property name="jdbcTemplate">
<ref bean="jdbcTemplate"/>
</property>
</bean>

47) How do you write data to backend in spring using


JdbcTemplate?
The JdbcTemplate uses several of these callbacks when writing data to the database. The
usefulness you will find in each of these interfaces will vary. There are two simple
interfaces. One is PreparedStatementCreator and the other interface is
BatchPreparedStatementSetter.

48) Explain about PreparedStatementCreator?


PreparedStatementCreator is one of the most common used interfaces for writing data to
database. The interface has one method createPreparedStatement().
PreparedStatement createPreparedStatement(Connection conn)
throws SQLException;

When this interface is implemented, we should create and return a PreparedStatement from
the Connection argument, and the exception handling is automatically taken care off. When
this interface is implemented, another interface SqlProvider is also implemented which has
a method called getSql() which is used to provide sql strings to JdbcTemplate.

49) Explain about BatchPreparedStatementSetter?


If the user what to update more than one row at a shot then he can go for
BatchPreparedStatementSetter. This interface provides two methods

setValues(PreparedStatement ps, int i) throws SQLException;

int getBatchSize();

The getBatchSize() tells the JdbcTemplate class how many statements to create. And this
also determines how many times setValues() will be called.

50) Explain about RowCallbackHandler and why it is used?


In order to navigate through the records we generally go for ResultSet. But spring provides
an interface that handles this entire burden and leaves the user to decide what to do with
each row. The interface provided by spring is RowCallbackHandler. There is a method
processRow() which needs to be implemented so that it is applicable for each and everyrow.

void processRow(java.sql.ResultSet rs);


Hibernate Interview Questions
1) What is Hibernate?
Hibernate is a powerful, high performance object/relational persistence and query service.
This lets the users to develop persistent classes following object-oriented principles such as
association, inheritance, polymorphism, composition, and collections.

2) What is ORM?
ORM stands for Object/Relational mapping. It is the programmed and translucent
perseverance of objects in a Java application in to the tables of a relational database using
the metadata that describes the mapping between the objects and the database. It works
by transforming the data from one representation to another.

3) What does an ORM solution comprises of?


• It should have an API for performing basic CRUD (Create, Read, Update, Delete)
operations on objects of persistent classes
• Should have a language or an API for specifying queries that refer to the classes
and the properties of classes
• An ability for specifying mapping metadata
• It should have a technique for ORM implementation to interact with transactional
objects to perform dirty checking, lazy association fetching, and other optimization
functions

4) What are the different levels of ORM quality?


There are four levels defined for ORM quality.
i. Pure relational
ii. Light object mapping
iii. Medium object mapping
iv. Full object mapping

5) What is a pure relational ORM?


The entire application, including the user interface, is designed around the relational model
and SQL-based relational operations.

6) What is a meant by light object mapping?


The entities are represented as classes that are mapped manually to the relational tables.
The code is hidden from the business logic using specific design patterns. This approach is
successful for applications with a less number of entities, or applications with common,
metadata-driven data models. This approach is most known to all.
7) What is a meant by medium object mapping?
The application is designed around an object model. The SQL code is generated at build
time. And the associations between objects are supported by the persistence mechanism,
and queries are specified using an object-oriented expression language. This is best suited
for medium-sized applications with some complex transactions. Used when the mapping
exceeds 25 different database products at a time.

8) What is meant by full object mapping?


Full object mapping supports sophisticated object modeling: composition, inheritance,
polymorphism and persistence. The persistence layer implements transparent persistence;
persistent classes do not inherit any special base class or have to implement a special
interface. Efficient fetching strategies and caching strategies are implemented transparently
to the application.

9) What are the benefits of ORM and Hibernate?


There are many benefits from these. Out of which the following are the most important one.
i. Productivity – Hibernate reduces the burden of developer by providing much of
the functionality and let the developer to concentrate on business logic.
Maintainability – As hibernate provides most of the functionality, the LOC for the
application will be reduced and it is easy to maintain. By automated object/
relational persistence it even reduces the LOC. Performance – Hand-coded
persistence provided greater performance than automated one. But this is not true
all the times. But in hibernate, it provides more optimization that works all the time
there by increasing the performance. If it is automated persistence then it still
increases the performance. Vendor independence – Irrespective of the different
types of databases that are there, hibernate provides a much easier way to develop
a cross platform application.

10) How does hibernate code looks like?


Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
MyPersistanceClass mpc = new MyPersistanceClass ("Sample App");
session.save(mpc);
tx.commit();
session.close();

The Session and Transaction are the interfaces provided by hibernate. There are many other
interfaces besides this.

11) What is a hibernate xml mapping document and how


does it look like?
In order to make most of the things work in hibernate, usually the information is provided in
an xml document. This document is called as xml mapping document. The document
defines, among other things, how properties of the user defined persistence classes’ map to
the columns of the relative tables in database.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "http://hibernate.sourceforge.net/hibernate-map

<hibernate-mapping>
<class name="sample.MyPersistanceClass" table="MyPersitaceTable">
<id name="id" column="MyPerId">
<generator class="increment"/>
</id>
<property name="text" column="Persistance_message"/>
<many-to-one name="nxtPer" cascade="all" column="NxtPerId"/>
</class>
</hibernate-mapping>

Everything should be included under tag. This is the main tag for an xml mapping
document.

12) Show Hibernate overview?

13) What the Core interfaces are of hibernate framework?


There are many benefits from these. Out of which the following are the most important one.
i. Session Interface – This is the primary interface used by hibernate applications.
The instances of this interface are lightweight and are inexpensive to create and
destroy. Hibernate sessions are not thread safe.
ii. SessionFactory Interface – This is a factory that delivers the session objects to
hibernate application. Generally there will be a single SessionFactory for the whole
application and it will be shared among all the application threads.
iii. Configuration Interface – This interface is used to configure and bootstrap
hibernate. The instance of this interface is used by the application in order to specify
the location of hibernate specific mapping documents.
iv. Transaction Interface – This is an optional interface but the above three
interfaces are mandatory in each and every application. This interface abstracts the
code from any kind of transaction implementations such as JDBC transaction, JTA
transaction.
v. Query and Criteria Interface – This interface allows the user to perform queries
and also control the flow of the query execution.

14) What are Callback interfaces?


These interfaces are used in the application to receive a notification when some object
events occur. Like when an object is loaded, saved or deleted. There is no need to
implement callbacks in hibernate applications, but they’re useful for implementing certain
kinds of generic functionality.
15) What are Extension interfaces?
When the built-in functionalities provided by hibernate is not sufficient enough, it provides a
way so that user can include other interfaces and implement those interfaces for user desire
functionality. These interfaces are called as Extension interfaces.

16) What are the Extension interfaces that are there in


hibernate?
There are many extension interfaces provided by hibernate.
• ProxyFactory interface - used to create proxies
• ConnectionProvider interface – used for JDBC connection management
• TransactionFactory interface – Used for transaction management
• Transaction interface – Used for transaction management
• TransactionManagementLookup interface – Used in transaction management.
• Cahce interface – provides caching techniques and strategies
• CacheProvider interface – same as Cache interface
• ClassPersister interface – provides ORM strategies
• IdentifierGenerator interface – used for primary key generation
• Dialect abstract class – provides SQL support

17) What are different environments to configure


hibernate?
There are mainly two types of environments in which the configuration of hibernate
application differs.
i. Managed environment – In this kind of environment everything from database
connections, transaction boundaries, security levels and all are defined. An example
of this kind of environment is environment provided by application servers such as
JBoss, Weblogic and WebSphere.
ii. Non-managed environment – This kind of environment provides a basic
configuration template. Tomcat is one of the best examples that provide this kind of
environment.

18) What is the file extension you use for hibernate


mapping file?
The name of the file should be like this : filenam.hbm.xml
The filename varies here. The extension of these files should be “.hbm.xml”.
This is just a convention and it’s not mandatory. But this is the best practice to follow this
extension.

19) What do you create a SessionFactory?


Configuration cfg = new Configuration();
cfg.addResource("myinstance/MyConfig.hbm.xml");
cfg.setProperties( System.getProperties() );
SessionFactory sessions = cfg.buildSessionFactory();
First, we need to create an instance of Configuration and use that instance to refer to the
location of the configuration file. After configuring this instance is used to create the
SessionFactory by calling the method buildSessionFactory().

20) What is meant by Method chaining?


Method chaining is a programming technique that is supported by many hibernate
interfaces. This is less readable when compared to actual java code. And it is not mandatory
to use this format. Look how a SessionFactory is created when we use method chaining.

SessionFactory sessions = new Configuration()


.addResource("myinstance/MyConfig.hbm.xml")
.setProperties( System.getProperties() )
.buildSessionFactory();

21) What does hibernate.properties file consist of?


This is a property file that should be placed in application class path. So when the
Configuration object is created, hibernate is first initialized. At this moment the application
will automatically detect and read this hibernate.properties file.

hibernate.connection.datasource = java:/comp/env/jdbc/AuctionDB
hibernate.transaction.factory_class = net.sf.hibernate.transaction.JTATransactionF
hibernate.transaction.manager_lookup_class = net.sf.hibernate.transaction.JBossTra
hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect

22) What should SessionFactory be placed so that it can be


easily accessed?
As far as it is compared to J2EE environment, if the SessionFactory is placed in JNDI then it
can be easily accessed and shared between different threads and various components that
are hibernate aware. You can set the SessionFactory to a JNDI by configuring a property
hibernate.session_factory_name in the hibernate.properties file.

23) What are POJOs?


POJO stands for plain old java objects. These are just basic JavaBeans that have defined
setter and getter methods for all the properties that are there in that bean. Besides they
can also have some business logic related to that property. Hibernate applications works
efficiently with POJOs rather then simple java classes.

24) What is object/relational mapping metadata?


ORM tools require a metadata format for the application to specify the mapping between
classes and tables, properties and columns, associations and foreign keys, Java types and
SQL types. This information is called the object/relational mapping metadata. It defines the
transformation between the different data type systems and relationship representations.
25) What is HQL?
HQL stands for Hibernate Query Language. Hibernate allows the user to express queries in
its own portable SQL extension and this is called as HQL. It also allows the user to express
in native SQL.

26) What are the different types of property and class


mappings?
• Typical and most common property mapping

<property name="description" column="DESCRIPTION" type="string"/>


Or
<property name="description" type="string">
<column name="DESCRIPTION"/>
</property>

• Derived properties

<property name="averageBidAmount" formula="( select AVG(b.AMOUNT) from BID b

• Typical and most common property mapping

<property name="description" column="DESCRIPTION" type="string"/>

• Controlling inserts and updates

<property name="name" column="NAME" type="string" insert="false" update="fal

27) What is Attribute Oriented Programming?


XDoclet has brought the concept of attribute-oriented programming to Java. Until JDK 1.5,
the Java language had no support for annotations; now XDoclet uses the Javadoc tag
format (@attribute) to specify class-, field-, or method-level metadata attributes. These
attributes are used to generate hibernate mapping file automatically when the application is
built. This kind of programming that works on attributes is called as Attribute Oriented
Programming.

28) What are the different methods of identifying an


object?
There are three methods by which an object can be identified.
i. Object identity – Objects are identical if they reside in the same memory location
in the JVM. This can be checked by using the = = operator.
ii. Object equality – Objects are equal if they have the same value, as defined by the
equals( ) method. Classes that don’t explicitly override this method inherit the
implementation defined by java.lang.Object, which compares object identity.
iii. Database identity – Objects stored in a relational database are identical if they
represent the same row or, equivalently, share the same table and primary key
value.
29) What are the different approaches to represent an
inheritance hierarchy?
i. Table per concrete class.
ii. Table per class hierarchy.
iii. Table per subclass.

30) What are managed associations and hibernate


associations?
Associations that are related to container management persistence are called managed
associations. These are bi-directional associations. Coming to hibernate associations, these
are unidirectional.
Design Patterns Interview Questions
1) What is a software design pattern?
A design pattern is a solution to a general software problem within a particular context.
• Context : A recurring set of situations where the pattern applies.
• Problem : A system of forces (goals and constraints) that occur repeatedly in this
context.
• Solution : A description of communicating objects and classes (collaboration) that
can be applied to resolve those forces.
Design patterns capture solutions that have evolved over time as developers strive for
greater flexibility in their software. Whereas class libraries are reusable source code, and
components are reusable packaged objects, patterns are generic, reusable design
descriptions that are customized to solve a specific problem. The study of design patterns
provides a common vocabulary for communication and documentation, and it provides a
framework for evolution and improvement of existing patterns.

2) Why is the study of patterns important?


As initial software designs are implemented and deployed, programmers often discover
improvements which make the designs more adaptable to change. Design patterns capture
solutions that have evolved over time as developers strive for greater flexibility in their
software, and they document the solutions in a way which facilitates their reuse in other,
possibly unrelated systems. Design patterns allow us to reuse the knowledge of experienced
software designers.
Moreover, the study of design patterns provides a common vocabulary for communication
and documentation, and it provides a framework for evolution and improvement of existing
patterns. As an analogy, consider that during a discussion among programmers, the words
“stack” and “tree” can be used freely without explanation. Software developers understand
fundamental data structures such as a “stack” because these data structures are well-
documented in textbooks and are taught in computer science courses. The study of design
patterns will have a similar (but more profound) effect by allowing designers to say
“composite pattern” or “observer pattern” in a particular design context, without having to
describe all classes, relationships, and collaborations which make up the pattern. Patterns
raise the level of abstraction when discussing and documenting software designs.

3) How do I document a design pattern?


A pattern description must address the following major points:
• Pattern Name and Classification : A short, meaningful name for the pattern,
usually only one or two words. Names provide a vocabulary for patterns, and they
have implied semantics – choose names carefully. Following the GoF book, we can
also group patterns into higher level classifications such as creational, structural,
and behavioral patterns.
• Problem : A general description of the problem context and the goals and
constraints that occur repeatedly in that context. A concrete motivational scenario
can be used to help describe the problem. The problem description should provide
guidance to assist others in recognizing situations where the pattern can be applied.
• Solution : The classes and/or objects that participate in the design pattern, their
structure (e.g., in terms of a UML class diagram), their responsibilities, and their
collaborations. The solution provides an abstract description that can be applied in
many different situations. Sample Code in an object-oriented language can be used
to illustrate a concrete realization of the pattern.
• Consequences : A discussion of the results and tradeoffs of applying the pattern.
Variations and language-dependent alternatives should also be addressed.
• Known Uses : Examples of the pattern in real systems. Look for applications of the
pattern in language libraries and frameworks, published system descriptions, text
books, etc. Not every good solution represents a pattern. A general rule of thumb is
that a candidate pattern (also called a “proto-pattern”) should be discovered in a
minimum of three existing systems before it can rightfully be called a pattern.
The following quote by Robert Martin highlights the importance of providing pattern
descriptions: “The revolutionary concept of the GoF book is not the fact that there are
patterns; it is the way in which those patterns are documented. ... Prior to the GoF book,
the only good way to learn patterns was to discover them in design documentation, or
(more probably) code.”

4) Where can I learn more about design patterns?


The best place to start is the seminal work by Erich Gamma, Richard Helm, Ralph Johnson,
and John Vlissides (collectively known as the “Gang of Four” or simply “GoF”) entitled
Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley, 1995).
Warning: This book is not light reading. From the Preface: “Don't worry if you don't
understand this book completely on the first reading. We didn't understand it all on the first
writing.”
It is, however, a book which wears well over time, and it is definitely worth the effort
required to work through it.
Beyond the GoF book, consider the list of references in the Design Patterns section of this
bibliography on object technology, plus the following web links:
• Design Patterns Home Page
• Huston Design Patterns
• Brad Appleton's Software Patterns Links
• Cetus Patterns Links

5) What is an example of a design pattern?


Following the lead of the “Gang of Four” (GoF), design pattern descriptions usually contain
multiple sections including
• Intent
• Motivation
• Applicability
• Structure
• Participants
• Collaborations
• Consequences
• Implementation
• Sample Code
• Known Uses
• Related Patterns
A complete discussion of even a small pattern is beyond the scope of a simple FAQ entry,
but it is possible to get the idea by examining an abbreviated discussion of one of the
simplest and most easily understood patterns. Consider the Singleton pattern, whose intent
reads as follows:
Intent: Ensure that a class has one instance, and provide a global point of access to it.
Almost every programmer has encountered this problem and formulated an approach for
solving it in a general way – some solutions are better than others. The solution offered by
the GoF would look something like the following when coded in Java.

public class Singleton


{
private static Singleton instance = null;
public static Singleton getInstance()
{
if (instance == null)
instance = new Singleton();
return instance;
}

protected Singleton() { ... }


// possibly another constructor form

public void someMethod() { ... }

//... other methods


}

The programmer would access the single instance of this class by writing something similar
to

Singleton.getInstance().someMethod()

or similar to

Singleton s = Singleton.getInstance();
s.method1();
...
s.method2();
...

For a more complete discussion of the Singleton pattern, see the chapter “Singleton” in the
book Design Patterns: Elements of Reusable Object-Oriented Software by the “Gang of
Four” (Addison-Wesley, 1995), or the chapter “Singleton” in the book Patterns in Java,
Volume 1 by Mark Grand (John Wiley & Sons, 1998). For information about variations on
the Singleton Pattern, see the chapter entitled “To Kill a Singleton” in the book Pattern
Hatching: Design Patterns Applied by John Vlissides or the article “Implementing the
Singleton Pattern in Java” by Rod Waldhoff.
6) Calendar is an abstract class. The getInstance() method
tries to instantiate GregorianCalendar() i.e., parent
instantiating a derived class. This looks Non-OO? Ex:
Calendar a=Calendar.getInstance(); Can somebody explain
why is it so?
The Calender class is an abstact class, true, however,the point you missed is that the
getInstance() returns the " Calendar using the default timezone and locale. " , in your case,
the GregorianCalender a class that IS a Calender (a Suzuki IS a car, a 747 IS a plane..the
standard OO terminology. So what you get is a class that does some specialized work based
on the default locale. Other methods

public static synchronized Calendar getInstance(TimeZone zone,Locale aLocale)


public static synchronized Calendar getInstance(TimeZone zone)

return Calenders for specific timezones and locales. The closest parallel is possibly the
Factory Method design pattern.

7) What major patterns do the Java APIs utilize?


Design patterns are used and supported extensively throughout the Java APIs. Here are
some examples:
• The Model-View-Controller design pattern is used extensively throughout the Swing
API.
• The getInstance() method in java.util.Calendar is an example of a simple form of
the Factory Method design pattern.
• The classes java.lang.System and java.sql.DriverManager are examples of the
Singleton pattern, although they are not implemented using the approach
recommended in the GoF book but with static methods.
• The Prototype pattern is supported in Java through the clone() method defined in
class Object and the use of java.lang.Cloneable interface to grant permission for
cloning.
• The Java Swing classes support the Command pattern by providing an Action
interface and an AbstractAction class.
• The Java 1.1 event model is based on the observer pattern. In addition, the
interface java.util.Observable and the class java.util.Observer provide support for
this pattern.
• The Adapter pattern is used extensively by the adapter classes in java.awt.event.
• The Proxy pattern is used extensively in the implementation of Java's Remote
Method Invocation (RMI) and Interface Definition Language (IDL) features.
• The structure of Component and Container classes in java.awt provide a good
example of the Composite pattern.
• The Bridge pattern can be found in the separation of the components in java.awt
(e.g., Button and List), and their counterparts in java.awt.peer.
8) How can I make sure at most one instance of my class
is ever created?
This is an instance where the Singleton design pattern would be used. You need to make
the constructor private (so nobody can create an instance) and provide a static method to
get the sole instance, where the first time the instance is retrieved it is created:

public class Mine {


private static Mine singleton;
private Mine() {
}
public static synchronized Mine getInstance() {
if (singleton == null) {
singleton = new Mine();
}
return singleton;
}
// other stuff...
}

9) When would I use the delegation pattern instead of


inheritence to extend a class's behavior?
Both delegation and inheritance are important concepts in object-oriented software design,
but not everyone would label them as patterns. In particular, the seminal book on design
patterns by the “Gang of Four” contains a discussion of inheritance and delegation, but the
authors do not treat these topics as specific patterns. It is reasonable to think of them as
design concepts which are more general than specific design patterns.
Inheritance is a relationship between two classes where one class, called a subclass in this
context, inherits the attributes and operations of another class, called its superclass.
Inheritance can be a powerful design/reuse technique, especially when it is used in the
context of the Liskov Substitution Principle. (The article by Robert Martin at
http://www.objectmentor.com/publications/lsp.pdf provides an excellent explanation of the
ideas behind Barbara Liskov’s original paper on using inheritance correctly.) The primary
advantages of inheritance are
1. it is directly supported by object-oriented languages, and
2. it provides the context for polymorphism in strongly-typed object-oriented
languages such as C++ and Java.
But since the inheritance relationship is defined at compile-time, a class can’t change its
superclass dynamically during program execution. Moreover, modifications to a superclass
automatically propagate to the subclass, providing a two-edged sword for software
maintenance and reuse. In summary, inheritance creates a strong, static coupling between
a superclass and its subclasses.
Delegation can be viewed as a relationship between objects where one object forwards
certain method calls to another object, called its delegate. Delegation can also a powerful
design/reuse technique. The primary advantage of delegation is run-time flexibility – the
delegate can easily be changed at run-time. But unlike inheritance, delegation is not directly
supported by most popular object-oriented languages, and it doesn’t facilitate dynamic
polymorphism.
As a simple example, consider the relationship between a Rectangle class and a Window
class. With inheritance, a Window class would inherit its rectangular properties from class
Rectangle. With delegation, a Window object would maintain a reference or pointer to a
Rectangle object, and calls to rectangle-like methods of the Window object would be
delegated to corresponding methods of the Rectangle object.
Now let’s consider a slightly more complex example. Suppose employees can classified
based on how they are paid; e.g., hourly or salaried. Using inheritance, we might design
three classes: an Employee class which encapsulates the functionality common to all
employees, and two subclasses HourlyEmployee and SalariedEmployee which encapsulates
pay-specific details. While this design might be suitable for some applications, we would
encounter problems in a scenario where a person changes, say from hourly to salaried. The
class of an object and the inheritance relationship are both static, and objects can’t change
their class easily (but see the State pattern for tips on how to fake it).
A more flexible design would involve delegation – an Employee object could delegate pay-
related method calls to an object whose responsibilities focused solely on how the employee
is paid. In fact, we might still use inheritance here in a slightly different manner by creating
an abstract class (or interface) called PayClassification with two subclasses
HourlyPayClassification and SalariedPayClassification which implement classification-specific
computations. Using delegation as shown, it would be much easier to change the pay
classification of an existing Employee object.
This second example illustrates an important point: In implementing delegation, we often
want the capability to replace the delegate with another object, possibly of a different class.
Therefore delegation will often use inheritance and polymorphism, with classes of potential
delegates being subclasses of an abstract class which encapsulates general delegate
responsibilities.
One final point. Sometimes, the choice between delegation and inheritance is driven by
external factors such as programming language support for multiple inheritance or design
constraints requiring polymorphism. Consider threads in Java. You can associate a class
with a thread in one of two ways: either by extending (inheriting) directly from class
Thread, or by implementing the Runnable interface and then delegating to a Thread object.
Often the approach taken is based on the restriction in Java that a class can only extend
one class (i.e., Java does not support multiple inheritance). If the class you want to
associate with a thread already extends some other class in the design, then you would
have to use delegation; otherwise, extending class Thread would usually be the simpler
approach.

10) Which patterns were used by Sun in designing the


Enterprise JavaBeans model?
Many design patterns were used in EJB, and some of them are clearly identifiable by their
naming convention. Here are several:
1. Factory Method: Define a interface for creating classes, let a subclass (or a helper
class) decide which class to instantiate.
This is used in EJB creation model. EJBHome defines an interface for creating the
EJBObject implementations. They are actually created by a generated container
class. See InitialContextFactory interface that returns an InitialContext based on a
properties hashtable.
2. Singleton: Ensure a class has only one instance, and provide a global point of
access to it.
There are many such classes. One example is javax.naming.NamingManager
3. Abstract Factory: Provide an interface for creating families of relegated or
dependent objects without specifying their concrete classes.
We have interfaces called InitialContext, InitialContextFactory. InitialContextFactory
has methods to get InitialContext.
4. Builder: Separate the construction of a complex factory from its representation so
that the same construction process can create different representations.
InitialContextFactoryBuilder can create a InitialContextFactory.
5. Adapter: Convert the interface of a class into another interface clients expect.
In the EJB implementation model, we implement an EJB in a class that extends
SessionBean or a EntityBean. We don't directly implement the EJBObject/home
interfaces. EJB container generates a class that adapts the EJBObject interface by
forwarding the calls to the enterprise bean class and provides declarative
transaction, persistence support.
6. Proxy: Provide a surrogate for other object to control access to it.
We have remote RMI-CORBA proxies for the EJB's.
7. Memento: Without violating encapsulation, capture and externalize an object's
internal state so that the object can be restored to this state later.
Certainly this pattern is used in activating/passivating the enterprise beans by the
container/server.

11) What is an analysis pattern?


An analysis pattern is a software pattern not related to a language or implementation
problem, but to a business domain, such as accounting or health care. For example, in
health care, the patient visit activity would be subject to a number of patterns.
There is a good overview from an OOPSLA '96 presentation at
http://www.jeffsutherland.org/oopsla96/fowler.html
A good text would be: Martin Fowler's Martin Analysis Patterns : Reusable Object Models,
ISBN: 0201895420, published by Addison-Wesley.
In summary, analysis patterns are useful for discovering and capturing business processes.

12) What are the differences between analysis patterns


and design patterns?
Analysis pattern are for domain architecture, and design pattern are for implementation
mechanism for some aspect of the domain architecture. In brief, analysis pattern are more
high level and more (end-user) functional oriented.

13) How does "Extreme Programming" (XP) fit with


patterns?
Extreme Programming has a large emphasis on the concept of refactoring: Writing code
once and only once.
Patterns, particularly the structural patterns mentioned by the Gang of Four, can give good
pointers about how to acheive that goal.
(XP states when and where factoring should happen, patterns can show you how.)
14) What is the disadvantage of using the Singleton
pattern? It is enticing to use this pattern for all the classes
as it makes it easy to get the reference of the singleton
object.
The intent of the Singleton pattern is to ensure a class has only one instance and to provide
a global point of access to it. True, the second part about providing a global point of access
is enticing, but the primary disadvantage of using the Singleton pattern for all classes is
related to the first part of the intent; i.e., that it allows only one instance of the class. For
most classes in an application, you will need to create multiple instances. What purpose
would a Customer class serve if you could create only one Customer object?

15) How do you write a Thread-Safe Singleton?


I have written plenty of non-thread-safe Singletons but it wasn't until recently when I
tracked it down that I realized that thread-safety could be a big problem.
The problem is that in the typical Singleton implementation (at least the ones I've seen)
there is the ability to create multiple versions of the single instance...I know, "But How?".
Well, in the getInstance() call the instance is checked for null, and then immediately
constructed if it is null, and then the instance is returned.
The problem is that the thread (Ta) making the call could swap-out immediately after
checking for a null. A subsequent thread (Tb) could then make a call to get the instance and
construct an instance of the Singleton. When the original thread (Ta) is then swapped back
in, it would construct and return a completely separate object. BAD KITTY!
The following code snippet shows an example of a thread-safe Singleton.

package com.jgk.patterns.singleton;
public class JGKSingleton {

/* Here is the instance of the Singleton */


private static JGKSingleton instance_;
/* Need the following object to synchronize */
/* a block */
private static Object syncObject_;
/* Prevent direct access to the constructor
private JGKSingleton() {
super();
}

public static JGKSingleton getInstance() {


/* in a non-thread-safe version of a Singleton */
/* the following line could be executed, and the */
/* thread could be immediately swapped out */
if (instance_ == null) {
synchronized(syncObject_) {
if (instance_ == null) {
instance_ = new JGKSingleton();
}
}
}
return instance_;
}
}

NOTE: The 2nd check for if (instance_ == null) is needed to avoid making another unnecessary
construct.
Don't let this byte you! ;-)

16) What is the Reactor pattern?


The new book "Pattern-oriented Software Architecture Volume 2" ISBN 0471606952 has a
chapter on the Reactor pattern. It falls under the general category of "Event Handling
Patterns". To quote the leading bit of the chapter,
"The Reactor architectural pattern allows event-driven applications to demultiplex and
dispatch service requests that are delivered to an application from one or more clients"
It is used in a synchronous manner, so that if the callback you delegate the event to takes a
while to complete you will run into problems with scalability.

17) What are Process Patterns?


Basically process patterns define a collection of best practices, techniques, methods for
developing object-oriented software.
A good reference site is by Scott Ambler. He also has two books on the topic plus a white
paper on the subject you can download.
http://www.ambysoft.com/processPatternsPage.html.

18) How and where did the concept of design patterns get
started?
Work on patterns has been influenced by the works of Christopher Alexander who published
on topics related to urban planning and building architecture in the late 1970s. The history
of patterns for software design began in the late 1980s and reached an important milestone
with the publishing of the first book fully dedicated to this subject by the "Gang of Four",
Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Design Patterns - Elements
of Reusable Object-Oriented Software). In conjunction, the emergence of object-oriented
software development fostered the work on other topics related to design patterns such as
application frameworks, analysis patterns, language idioms, and so on.

19) Where can I find good examples of the Prototype


pattern?
The prototype pattern is actually quite simple to implement in Java.
Recall that the idea of prototype is that you are passed an object and use that object as a
template to create a new object. Because you might not know the implementation details of
the object, you cannot create a new instance of the object and copy all of its data. (Some of
the data may not be accessible via methods). So you ask the object itself to give you a copy
of itself.
Java provides a simple interface named Cloneable that provides an implementation of the
Prototype pattern. If you have an object that is Cloneable, you can call its clone() method to
create a new instance of the object with the same values.
The trick here is that you must override the clone() method to increase its visibility, and just
call super.clone(). This is because the implementation of clone(), defined in
java.lang.object, is protected. For example:

public class CopyMe implements Cloneable {


public Object clone() {
return super.clone();
}
}

Note that Cloneable is an empty interface! It merely acts as a tag to state that you really
want instance of the class to be cloned. If you don't implement Cloneable, the super.clone()
implementation will throw a CloneNotSupportedException.
The Object implementation of clone() performs a shallow copy of the object in question.
That is, it copies the values of the fields in the object, but not any actual objects that may
be pointed to. In other words, the new object will point to the same objects the old object
pointed to.
As an example of using the cloning:

CopyMe thing = new Copyme();


CopyMe anotherThing = (Copyme)thing.clone();

This example is pretty trivial, but the real power comes when you don't know what you're
actually cloning.
For example, suppose you define an interface that represents a customer:

public interface Customer extends Cloneable {


public Object clone(); // require making it public!
public String getName();
public void setName(String name);
...
}

You might have several different implementations of this interface, possibly storing data in a
file, database, or using EJB Entity beans. If a shallow copy of the data is sufficient to
represent a copy of the object, Java's clone() method works great.
You might have a method that needs to make a copy of the data to store it in a Hashtable,
for example:

public void storeCustomer(Customer customer) {


Customer copy = (Customer)customer.clone();
dataStore.put(copy);
}

Note that this method knows nothing about what type of customer we're getting. This
pattern will work for any actual type of Customer, no matter how the data is stored. For
example:

FileBasedCustomer c1 = new FileBasedCustomer(...);


RDBMSBasedCustomer c2 = new RDBMSBasedCustomer(...);
EJBBasedCustomer c3 = new EJBBasedCustomer(...);

manager.storeCustomer(c1);
manager.storeCustomer(c2);
manager.storeCustomer(c3);

20) What are Anti-Patterns?


There isn't really a "clean-cut" definition out there just yet, unlike Design Patterns.
Basically, as Design Patterns (and more particularly, Process Patterns) try to codify a
standard vocabulary for working solutions to problems that reappear frequently, Anti-
Patterns represent an effort to define and classify reoccuring non-solutions, i.e., things that
lots of projects do that fail to yield a solution, or actually prevent a project from working or
being finished.
The most basic example I can think of is "The Hammer", inspired by the old addage, "If
your only tool is a hammer, everything looks like a nail" (or the variation, "If your only tool
is a hammer, everything looks like your left thumb." Hammer describes a regular,
reoccuring problem in inexperienced engineers (particularly those who've only used one
language for the bulk of their carreer so far), that of trying to force-feed all problems into
the solutions they already know.
http://www.antipatterns.com/ has more information.

21) What patterns are particularly useful in building


networked applications?
I suggest starting with Pattern-Oriented Software Architecture: Patterns for Concurrent and
Networked Objects (POSA2). POSA2 specifically brings together 17 interrelated patterns
addressing Service Access and Configuration, Event Handling, Synchronization, and
Concurrency.
The patterns and many of the examples in POSA2 come primarily from the design and
implementation of the ACE framework.

22) Are there any good Java-specific patterns books


available?
The Java-specific patterns books are:
• Java Design Patterns: A Tutorial
• Patterns in Java, Volume 1
• Patterns in Java, Volume 2
• Concurrent Programming in Java , Second Edition: Design Principles and Patterns
• SanFrancisco Design Patterns
As far as the good part of the question.... Doug Lea's Concurrent Programming book is
probably the best of the bunch. However, its patterns are specific to concurrent
programming. Many people don't like the quality of Mark Grand's two Patterns in Java
books. [They are rated 3 and 2 stars at Amazon, respectively]. The first printing of the
Cooper tutorial book was riddled with errors. If you get that, be sure to get at least the
second printing. [Look on last line of page before TOC.] The SanFrancisco book is definitely
good, but I'm not sure how good if you aren't using SF.
23) What are Collaboration Patterns?
Collaboration Patterns are repeatable techniques used by teams of people to help them
work together (collaborate). Ellen Gottesdiener of EBG Consulting has created these
patterns in order to help facilitate good teamwork. These patterns really have nothing to do
with object-oriented development or Java, besides the fact that they can help with
requirements gathering or CRC design sessions. In a nutshell, Collaboration Patterns are
techniques to help make meetings useful.

24) Is it correct from a design point of view to make an


object both an Observer and Observable at the same time?
Yes, and this can be the preferred pattern in some cases.
For example, suppose you were writing a supply chain management system for a retail
chain. Each store object in your system generates item-sold events; when the chain
generates enough of these for a particular product, a buyer object generates a purchase
order for more of the product. However, the buyer object has no particular interest in
individual item sold events. Instead, the buyer (Observer) registers to receive out-of-stock
events from the warehouse (Observable); the warehouse, as Observer, registers with the
individual stores (Observables) to receive item-sold events. Thus, the warehouse is both
Observer and Observable. (Please note that this is a synthetic example, and probably not
the way to organize a supply chain.)
Another reason to use one or more central Observer-Observable object in between ultimate
Observers and Observables is to fully decouple the two. In some cases, Observer and
Observable may exist on different machines, and may rely on the central Observer-
Observable to hide this complication.
A good source for more details is the Publisher-Subscriber section of Buschmann et al.,
Pattern-Oriented Software Architecture: A System of Patterns.

25) How can I maintain a single instance of an object in an


applet?
In start(), instead of always creating a new object, return the existing one if it exists or
create a new one if it doesn't.

26) What is the best way to generate a universally unique


object ID? Do I need to use an external resource like a file
or database, or can I do it all in memory?
I need to generate unique id's that will be used for node 'ID' attribute values within XML
documents. This id must be unique system-wide. The generator must be available to a
number of servlets that add various node structures to my XML docs as a service. What is
the best way to tackle this? The 'possible' ways I can see:
• Keep the maximum ID value in a flat-file where the service would read it upon start-
up and increment it. Upon shutdown or failure, it would write the latest max id to
the file.
• Calculate the max id by searching the XML itself. This will be tougher since XML
requires an alpha-numeric value (not strictly numeric).
• Use a database (MySQL) with a two-field table where one field is the incremental
counter.
I just have this feeling that none of the above are the most efficient ways of doing this.
Regards, -Andy]
There is an additional way to do that that doesn't rely on an external file (or database) like
the one you have presentred. If has been presented in the EJB Design Patterns book,
written by Floyd Marinescu, and available in a pdf format for free from the given link.
The suggested solution is based on the UUID for EJB pattern, that comes out from this
question:
How can universally unique primary keys can be generated in menory without requiring a
database or a singleton?
Without enetring in the specifics (you can fully check out the pattern by reading the
appropriate chapter), the solution is to generate a 32 digit key, encoded in hexadecimal
composed as follows:
1. Unique down to the millisecond. Digits 1-8 are are the hex encoded lower 32 bits of
the System.currentTimeMillis() call.
2. Unique across a cluster. Digits 9-16 are the encoded representation of the 32 bit
integer of the underlying IP address.
3. Unique down to the object in a JVM. Digits 17-24 are the hex representation of the
call to System.identityHashCode(), which is guaranteed to return distinct integers for
distinct objects within a JVM.
4. Unique within an object within a millisecond. Finally digits 25-32 represent a
random 32 bit integer generated on every method call using the cryptographically
strong java.security.SecureRandom class.

27) Is there some kind of Design pattern which would


make it possible to use the Same code base in EJB and non
EJB context?
A good suggestion would be using Delegation

class PieceOfCode {
public Object myMethod() {}
}
class EJBImpl ... {
PieceOfCode poc = new PieceOfCode();
public Object myMethod() {
return poc.myMethod();
}
}

This should not be a violation of EJB specs, since EJBs can use simple java classes for their
use. Think about Dependant Objects and so on.

28) What is session facade?


Session facade is one design pattern that is often used while developing enterprise
applications.
It is implemented as a higher level component (i.e.: Session EJB), and it contains all the
iteractions between low level components (i.e.: Entity EJB). It then provides a single
interface for the functionality of an application or part of it, and it decouples lower level
components simplifying the design.
Think of a bank situation, where you have someone that would like to transfer money from
one account to another.
In this type of scenario, the client has to check that the user is authorized, get the status of
the two accounts, check that there are enough money on the first one, and then call the
transfer. The entire transfer has to be done in a single transaction otherwise is something
goes south, the situation has to be restored.
As you can see, multiple server-side objects need to be accessed and possibly modified.
Multiple fine-grained invocations of Entity (or even Session) Beans add the overhead of
network calls, even multiple transaction. In other words, the risk is to have a solution that
has a high network overhead, high coupling, poor reusability and mantainability.
The best solution is then to wrap all the calls inside a Session Bean, so the clients will have
a single point to access (that is the session bean) that will take care of handling all the rest.
Obviously you need to be very careful when writing Session Facades, to avoid the abusing
of it (often called "God-Bean").
For a detailed description of this pattern, check this page: Core J2EE Patterns - Session
Facade or get Floyd Marinescu's EJB Design Patterns, in PDF format.

29) How is JDO different from VO ?


JDO is a persistence technology that competes against entity beans in enterprise application
development. It allows you to create POJOs (plain old java objects) and persist them to the
database - letting JDO take care of the storage.
Value objects, on the other hand, represent an abstract design pattern used in conjuction
with entity beans, jdbc, and possibly even JDO to overcome commonly found isolation and
transactional problems in enterprise apps. Value objects alone do not allow you to persist
objects - they are simple data holders used to transfer data from the database to the client
and back to the database.
Side note: I know that many books out there still refer to these data holders as value
objects but the correct term is DTO: data transfer objects. Value objects refer to objects
that hold a value. A good example of this java.lang.Integer object which holds an int.

30) How can I implement the MVC design pattern using


JSP?
The MVC (Model View Controller) design pattern is a pattern/architecture that can be used
by GUI's. It seperates the application's data, user interface and control logic into three
separate entities. This ensures the system will be more maintainable in the future as
changes to one component will not have an affect on the others.
The MVC pattern also conforms with the JSP Model 2 architecture.
The MVC pattern can be easily implemented in web applications using JSTL core, JSP,
Servlets and JavaBeans.
JSTL makes it easy for HTML designers to use dynamic data in their pages without having to
learn in depth java. The tags are in a recognizable HTML like format meaning a smaller
learning curve than taking on the JSP specification after taking on the Java specification.
JSTL also makes it easy for web developers who are developing all aspects of the application
in helping you keep the content separate from the display by keeping your JSP clean from
any Java code. Since JSTL and its EL (expression Language) are really only suited for
accessing data, it forces you to use a MVC pattern so long as you keep all JSP and Java
syntax/code out of the JSP pages.
A common scenario might look like this, a user sends a request to a server. The request is
handled by a Servlet (the controller) which will initialize any JavaBeans (the model) required
to fulfill the user's request. The Servlet (the controller) will then forward the request, which
contains the JavaBeans (the model), to a JSP (the view) page which contains only HTML and
JSTL syntax. The JSTL will format the data into a human readable format before being sent
back to the user. Thus completing the full MVC process.
JSTL also has a tag library for XML processing, this could be used in an MVC environment as
you could replace the JavaBeans with an XML document to describe your data, so long as
the XML is still constructed in a controller such as a Servlet before being passed to the JSP
(the view).
JSTL also has a tag library for database access, using this in your JSP (the view) pages
would NOT comply to the MVC pattern as there will be no separation between the model and
the view.
RMI Interview Questions
1)Explain RMI Architecture?
RMI uses a layered architecture, each of the layers could be enhanced or replaced without
affecting the rest of the system. The details of layers can be summarised as follows:
• Application Layer: The client and server program
• Stub & Skeleton Layer: Intercepts method calls made by the client/redirects these
calls to a remote RMI service.
• Remote Reference Layer: Understands how to interpret and manage references
made from clients to the remote service objects.
• Transport layer: Based on TCP/IP connections between machines in a network. It
provides basic connectivity, as well as some firewall penetration strategies.

2)What is the difference between RMI & Corba?


The most significant difference between RMI and CORBA is that CORBA was made
specifically for interoperability across programming languages. That is CORBA fosters the
notion that programs can be built to interact in multiple languages. The server could be
written in C++, the business logic in Python, and the front-end written in COBOL in theory.
RMI, on the other hand is a total Java solution, the interfaces, the implementations and the
clients--all are written in Java.
RMI allows dynamic loading of classes at runtime. In a multi-language CORBA environment,
dynamic class loading is not possible. The important advantage to dynamic class loading is
that it allows arguments to be passed in remote invocations that are subtypes of the
declared types. In CORBA, all types have to be known in advance. RMI (as well as RMI/
IIOP) provides support for polymorphic parameter passing, whereas strict CORBA does not.
CORBA does have support for multiple languages which is good for some applications, but
RMI has the advantage of being dynamic, which is good for other applications.

3)What are the services in RMI ?


An RMI "service" could well be any Java method that can be invoked remotely. The other
service is the JRMP RMI naming service which is a lookup service.

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

5)How many types of protocol implementations does RMI


have?
RMI has at least three protocol implementations: Java Remote Method Protocol(JRMP),
Internet Inter ORB Protocol(IIOP), and Jini Extensible Remote Invocation(JERI). These are
alternatives, not part of the same thing, All three are indeed layer 6 protocols for those who
are still speaking OSI reference model.

6)Does RMI-IIOP support dynamic downloading of


classes?
No, RMI-IIOP doesn't support dynamic downloading of the classes as it is done with CORBA
in DII (Dynamic Interface Invocation).Actually RMI-IIOP combines the usability of Java
Remote Method Invocation (RMI) with the interoperability of the Internet Inter-ORB Protocol
(IIOP).So in order to attain this interoperability between RMI and CORBA,some of the
features that are supported by RMI but not CORBA and vice versa are eliminated from the
RMI-IIOP specification.

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

8)Can RMI and Corba based applications interact ?


Yes they can. RMI is available with IIOP as the transport protocol instead of JRMP.
EJB Interview Questions
1. What is EJB?
EJB stands for Enterprise JavaBeans and is widely-adopted server side component
architecture for J2EE. It enables rapid development of ission-critical application that are
versatile, reusable and portable across middleware while protecting IT investment and
preventing vendor lock-in.

2. What is session Facade?


Session Facade is a design pattern to access the Entity bean through local interface than
accessing directly. It increases the performance over the network. In this case we call
session bean which on turn call entity bean.

3. What is EJB role in J2EE?


EJB technology is the core of J2EE. It enables developers to write reusable and portable
server-side business logic for the J2EE platform.

4. What is the difference between EJB and Java beans?


EJB is a specification for J2EE server, not a product; Java beans may be a graphical
component in IDE.

5. What are the key features of the EJB technology?


1. EJB components are server-side components written entirely in the Java
programming language
2. EJB components contain business logic only - no system-level programming &
services, such as transactions, security, life-cycle, threading, persistence, etc. are
automatically managed for the EJB component by the EJB server.
3. EJB architecture is inherently transactional, distributed, portable multi-tier, scalable
and secure.
4. EJB components are fully portable across any EJB server and any OS.
5. EJB architecture is wire-protocol neutral--any protocol can be utilized like IIOP,
JRMP, HTTP, DCOM, etc.

6. What are the key benefits of the EJB technology?


1. Rapid application development
2. Broad industry adoption
3. Application portability
4. Protection of IT investment
7. How many enterprise beans?
There are three kinds of enterprise beans:
1. session beans,
2. entity beans, and
3. message-driven beans.

8. What is message-driven bean?


A message-driven bean combines features of a session bean and a Java Message Service
(JMS) message listener, allowing a business component to receive JMS. A message-driven
bean enables asynchronous clients to access the business logic in the EJB tier.

9. What are Entity Bean and Session Bean?


Entity Bean is a Java class which implements an Enterprise Bean interface and provides the
implementation of the business methods. There are two types: Container Managed
Persistence (CMP) and Bean-Managed Persistence (BMP).
Session Bean is used to represent a workflow on behalf of a client. There are two types:
Stateless and Stateful. Stateless bean is the simplest bean. It doesn't maintain any
conversational state with clients between method invocations. Stateful bean maintains state
between invocations.

10. How EJB Invocation happens?


Retrieve Home Object reference from Naming Service via JNDI. Return Home Object
reference to the client. Create me a new EJB Object through Home Object interface. Create
EJB Object from the Ejb Object. Return EJB Object reference to the client. Invoke business
method using EJB Object reference. Delegate request to Bean (Enterprise Bean).

11. 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 considering 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 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 EJBs 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.
12. 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 referring the EJB Object classes
the container creates a separate instance for each client request. The instance pool
maintenance 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.

13. Can the primary key in the entity bean be a Java


primitive type such as int?
The primary key can’t be a primitive type. Use the primitive wrapper classes, instead. For
example, you can use java.lang.Integer as the primary key class, but not int (it has to be a
class, not a primitive).

14. Can you control when passivation occurs?


The developer, according to the specification, cannot directly control when passivation
occurs. Although for Stateful Session Beans, the container cannot passivate an instance that
is inside a transaction. So using transactions can be a strategy to control passivation. The
ejbPassivate() method is called during passivation, so the developer has control over what
to do during this exercise and can implement the require optimized logic. Some EJB
containers, such as BEA Weblogic, provide the ability to tune the container to minimize
passivation calls. Taken from the Weblogic 6.0 DTD -The passivation-strategy can be either
default or transaction. With the default setting the container will attempt to keep a working
set of beans in the cache. With the transaction setting, the container will passivate the bean
after every transaction (or method call for a non-transactional invocation).

15. What is the advantage of using Entity bean for


database operations, over directly using JDBC API to do
database operations? When would I use one over the
other?
Entity Beans actually represents the data in a database. It is not that Entity Beans replaces
JDBC API. There are two types of Entity Beans Container Managed and Bean Managed. In
Container Managed Entity Bean - Whenever the instance of the bean is created the
container automatically retrieves the data from the DB/Persistence storage and assigns to
the object variables in bean for user to manipulate or use them. For this the developer
needs to map the fields in the database to the variables in deployment descriptor files
(which varies for each vendor). In the Bean Managed Entity Bean - The developer has to
specifically make connection, retrieve values, assign them to the objects in the ejbLoad()
which will be called by the container when it instantiates a bean object. Similarly in the
ejbStore() the container saves the object values back the persistence storage. ejbLoad and
ejbStore are callback methods and can be only invoked by the container. Apart from this,
when you use Entity beans you don’t need to worry about database transaction handling,
database connection pooling etc. which are taken care by the ejb container.

16. What is EJB QL?


EJB QL is a Query Language provided for navigation across a network of enterprise beans
and dependent objects defined by means of container managed persistence. EJB QL is
introduced in the EJB 2.0 specification. The EJB QL query language defines finder methods
for entity beans with container managed persistence and is portable across containers and
persistence managers. EJB QL is used for queries of two types of finder methods: Finder
methods that are defined in the home interface of an entity bean and which return entity
objects. Select methods, which are not exposed to the client, but which are used by the
Bean Provider to select persistent values that are maintained by the Persistence Manager or
to select entity objects that are related to the entity bean on which the query is defined.

17. Brief description about local interfaces?


EEJB was originally designed around remote invocation using the Java Remote Method
Invocation (RMI) mechanism, and later extended to support to standard CORBA transport
for these calls using RMI/IIOP. This design allowed for maximum flexibility in developing
applications without consideration for the deployment scenario, and was a strong feature in
support of a goal of component reuse in J2EE. Many developers are using EJBs locally, that
is, some or all of their EJB calls are between beans in a single container. With this feedback
in mind, the EJB 2.0 expert group has created a local interface mechanism. The local
interface may be defined for a bean during development, to allow streamlined calls to the
bean if a caller is in the same container. This does not involve the overhead involved with
RMI like marshalling etc. This facility will thus improve the performance of applications in
which co-location is planned. Local interfaces also provide the foundation for container-
managed relationships among entity beans with container-managed persistence.

18. What are the special design cares that must be taken
when you work with local interfaces?
It is important to understand that the calling semantics of local interfaces are different from
those of remote interfaces. For example, remote interfaces pass parameters using call-by-
value semantics, while local interfaces use call-by-reference. This means that in order to
use local interfaces safely, application developers need to carefully consider potential
deployment scenarios up front, then decide which interfaces can be local and which remote,
and finally, develop the application code with these choices in mind. While EJB 2.0 local
interfaces are extremely useful in some situations, the long-term costs of these choices,
especially when changing requirements and component reuse are taken into account, need
to be factored into the design decision.
19. What happens if remove( ) is never invoked on a
session bean?
In case of a stateless session bean it may not matter if we call or not as in both cases
nothing is done. The number of beans in cache is managed by the container. In case of
Stateful session bean, the bean may be kept in cache till either the session times out, in
which case the bean is removed or when there is a requirement for memory in which case
the data is cached and the bean is sent to free pool.

20. What is the difference between Message Driven Beans


and Stateless Session beans?
In several ways, the dynamic creation and allocation of message-driven bean instances
mimics the behavior of stateless session EJB instances, which exist only for the duration of a
particular method call. However, message-driven beans are different from stateless session
EJBs (and other types of EJBs) in several significant ways: Message-driven beans process
multiple JMS messages asynchronously, rather than processing a serialized sequence of
method calls. Message-driven beans have no home or remote interface, and therefore
cannot be directly accessed by internal or external clients. Clients interact with message-
driven beans only indirectly, by sending a message to a JMS Queue or Topic. Only the
container directly interacts with a message-driven bean by creating bean instances and
passing JMS messages to those instances as necessary. The Container maintains the entire
lifecycle of a message-driven bean; instances cannot be created or removed as a result of
client requests or other API calls.

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

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

23. Is it 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.
24. 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.

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

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

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

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

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

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

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

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

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

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

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

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

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

39. 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 supports the dynamic class loading. The EJB container implements the
EJBHome and EJBObject classes. For every request from a unique client,

40. 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 referring the EJB Object classes
the container creates a separate instance for each client request. The instance pool
maintenance 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.

41. 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.
42. What is the need of Remote and Home interface. Why
can’t it be in one?
The main reason is because there is a clear division of roles and responsibilities between the
two interfaces. The home interface is your way to communicate with the container, that is
that is responsible of creating, locating even removing one or more beans. The remote
interface is your link to the bean that will allow you to remotely access to all its methods
and members. As you can see there are two distinct elements (the container and the beans)
and you need two different interfaces for accessing to both of them.

43. Can I develop an Entity Bean without implementing the


create() method in the home interface?
As per the specifications, there can be 'ZERO' or 'MORE' create() methods defined in an
Entity Bean. In cases where create() method is not provided, the only way to access the
bean is by knowing its primary key, and by acquiring a handle to it by using its
corresponding finder method. In those cases, you can create an instance of a bean based on
the data present in the table. All one needs to know is the primary key of that table. I.e. a
set a columns that uniquely identify a single row in that table. Once this is known, one can
use the 'getPrimaryKey()' to get a remote reference to that bean, which can further be used
to invoke business methods.
What is the difference between Context, InitialContext and Session Context? How they are
used? javax.naming.Context is an interface that provides methods for binding a name to an
object. It's much like the RMI Naming.bind() method.
javax.naming.InitialContext is a Context and provides implementation for methods available
in the Context interface.
Where as SessionContext is an EJBContext objects that is provided by the EJB container to a
SessionBean in order for the SessionBean to access the information and/or services or the
container.
There is EntityContext too which is also and EJBContext object that'll be provided to an
EntityBean for the purpose of the EntityBean accessing the container details. In general, the
EJBContext (SessionContext and EntityContext), AppletContext and ServletContext help the
corresponding Java objects in knowing about its 'context' [environment in which they run],
and to access particular information and/or service. Whereas, the javax.naming.Context is
for the purpose of 'NAMING' [by the way of referring to] an object.

44. Why an onMessage call in Message-driven bean is


always a separate transaction?
EJB 2.0 specification: "An onMessage call is always a separate transaction, because there is
never a transaction in progress when the method is called." When a message arrives, it is
passed to the Message Driven Bean through the onMessage() method, that is where the
business logic goes. Since there is no guarantee when the method is called and when the
message will be processed, is the container that is responsible of managing the
environment, including transactions.
45. Why are ejbActivate() and ejbPassivate() included for
stateless session bean even though they are never
required as it is a no conversational bean?
To have a consistent interface, so that there is no different interface that you need to
implement for Stateful Session Bean and Stateless Session Bean. Both Stateless and
Stateful Session Bean implement javax.ejb.SessionBean and this would not be possible if
stateless session bean is to remove ejbActivate and ejbPassivate from the interface.

46. Static variables in EJB should not be relied upon as


they may break in clusters. Why?
Static variables are only ok if they are final. If they are not final, they will break the cluster.
What that means is that if you cluster your application server (spread it across several
machines) each part of the cluster will run in its own JVM.
Say a method on the EJB is invoked on cluster 1 (we will have two clusters - 1 and 2) that
causes value of the static variable to be increased to 101. On the subsequent call to the
same EJB from the same client, a cluster 2 may be invoked to handle the request. A value
of the static variable in cluster 2 is still 100 because it was not increased yet and therefore
your application ceases to be consistent. Therefore, static non-final variables are strongly
discouraged in EJBs.

47. 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?
EJB Transaction is automatically rolled back only when a SystemException (or a subtype of
it) is thrown. Your ApplicationException can extend from javax.ejb.EJBException, which is a
sub class of RuntimeException. When an EJBException is encountered the container rolls
back the transaction. EJB Specification does not mention anything about Application
exceptions being sub-classes of EJBException. You can tell container to rollback the
transaction, by using setRollBackOnly on SessionContext/EJBContext object as per type of
bean you are using.

48. Does Stateful Session bean support instance pooling?


Stateful Session Bean conceptually doesn't have instance pooling.

49. Can I map more than one table in a CMP?


No, you cannot map more than one table to a single CMP Entity Bean. CMP has been, in
fact, designed to map a single table.
50. Can I invoke Runtime.gc() in an EJB?
You shouldn't. What will happen depends on the implementation, but the call will most likely
be ignored.

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

52. How to implement an entity bean which the


PrimaryKey is an auto numeric field?
The EJB 2 Spec (10.8.3 - Special case: Unknown primary key class) says that in cases
where the Primary Keys are generated automatically by the underlying database, the bean
provider must declare the findByPrimaryKey method to return java.lang.Object and specify
the Primary Key Class as java.lang.Object in the Deployment Descriptor.

53. When defining the Primary Key for the Enterprise


Bean, the Deployer using the Container Provider's tools
will typically add additional container-managed fields to
the concrete subclass of the entity bean class.
In this case, the Container must generate the Primary Key value when the entity bean
instance is created (and before ejbPostCreate is invoked on the instance.)

54. What is clustering?


Clustering is grouping machines together to transparently provide enterprise services.
Clustering is an essential piece to solving the needs for today's large websites.
The client does not know the difference between approaching one server and approaching a
cluster of servers.

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

56. 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)?
If your session bean is using bean-managed transactions, you can ensure that the calls are
handled in the same transaction by :

javax.transaction.UserTransaction tran= null;


try{
tran=ctx.getUserTransaction();
tran.begin();
myBeanHome1.create(....);
myBeanHome2.create(...);
tran.commit();
}catch(...){}

You may want to check if you're already running in a transaction by calling tran.getStatus().

57. When should I adopt BMP and when I should use CMP?
You can use CMP and BMP beans in the same application... obviously, a bean can be BMP or
CMP, not both at the same time (they are mutually exclusive).
There is a common approach that is normally used and considered a good one. You should
start developing CMP beans, unless you require some kind of special bean, like multi-tables,
that cannot be completely realized with a single bean. Then, when you realize that you need
something more or that you would prefer handling the persistence (performance issue are
the most common reason), you can change the bean from a CMP to a BMP.

58. What's different in Enterprise JavaBeans 1.1?


The most significant changes are listed below:
• Entity bean support, both container- and bean-managed persistence, is required.
• Java RMI-IIOP argument and reference types must be supported, but any protocol
can still be used including IIOP, JRMP, HTTP, or a proprietary protocol. In other
words, the client API must support the Java RMI-IIOP programming model for
portability, but the underlying protocol can be anything.
• The javax.ejb.depoyment package has been dropped in favor of a XML based
deployment descriptor
• Declarative security authorization (access control) has changed to be more role
driven. Also the runAs declarations have been eliminated.
• Declarative isolation levels are no longer available. Isolation levels are now
managed explicitly through JDBC (BMP), the database or other vendor specific
mechanisms.
• The bean-container contract as been enhanced to include a default JNDI context for
accessing properties, resources, (JDBC, JMS, etc), and other beans.
• The basic EJB roles have been expanded and redefined to better separate
responsibilities involved in the development, deployment, and hosting of enterprise
beans.

59. What is Enterprise JavaBeans?


Enterprise JavaBeans (EJB) is Sun Microsystems' specification for a distributed object
system similar to CORBA and Microsoft Transaction Server, but based on the Java platform.
EJB specifies how developers should build components that can be accessed remotely and
how EJB vendors should support those components. EJB components, called enterprise
beans, automatically handle transactions, persistence, and authorization security, so that
the developer can focus on the business logic.

60. What is an enterprise bean?


An enterprise bean is a server-side component -- defined in the Java technology -- which
adheres to the Enterprise JavaBeans server-side component model. A server-side
component is business object that can be accessed remotely. Many server-side component
models exist: CORBA specifies CORBA objects; Microsoft Transaction Server (MTS) defines
COM/DCOM; and EJB specifies enterprise beans.
Enterprise beans can be developed to represent business concepts like Employee, Order,
Travel Agent, etc. Enterprise beans can be assembled into applications that solve enterprise
business problems.
EJB has two basic types of enterprise beans: Session and Entity. Depending on the type of
enterprise bean used, features like persistence, transactions, security, and multiple
concurrent access can be managed automatically.

61. Are Enterprise JavaBeans and JavaBeans the same


thing?
Enterprise JavaBeans and JavaBeans are not the same thing; nor is one an extension of the
other. They are both component models, based on Java, and created by Sun Microsystems,
but their purpose and packages (base types and interfaces) are completely different.
JavaBeans
The original JavaBeans specification is based on the java.beans package which is a standard
package in the JDK. Components built on the JavaBeans specification are intraprocess
components that live in one address space and are typically used for Graphical User
Interface (GUI) as visual widgets like buttons, tables, HTML viewers, etc.
Enterprise JavaBeans
The EJB specification is based on the javax.ejb package, which is a standard extension
package. Components built on the EJB specification are intraprocess components that live
in multiple address spaces as distributed object. These components are used as
transactional business objects that are accessed as remote objects.

62. How does passivation work in stateful session beans?


Unlike entity beans and stateless session beans, stateful session bean are usually evicted
from memory when they are passivated. This is not true of all vendors but this view serves
as good model for understanding the concepts of passivation in session beans.
When a stateful bean experiences a lull in use -- between client invocations and transactions
-- the container may choose to passivate the stateful bean instance. To conserve resources
the bean instance is evicted from memory (dereferenced and garbage collected). When the
EJB object receives a new client request, a new stateful instance is instantiated and
associate with the EJB object to handle the request.
Stateful beans maintain a conversational state, which must be preserved before the bean
instance is evicted from memory. To accomplish this, the container will write the
conversational state of the bean instance to a secondary storage (usually disk). Only the
non-transient serializable instance fields are preserved. When the bean is activated the new
instance is populated with the preserved state. References to live resources like the
EJBContext, DataSource, JNDI ENC, and other beans must also be maintained somehow --
usually in memory -- by the container.
The javax.ejb.SessionBean interface provides two callback methods that notify the bean
instance it is about to passivated or was just activated. The ejbPassivate( ) method notifies
the bean instance that it is about have its conversational state written to disk and be
evicted from memory. Within this method the bean developer can perform operations just
prior to passivation like closing open resources. The ejbActivate( ) method is executed just
after a new bean instance has been instantiated and populated with conversational state
from disk. The bean developer can use the ejbActivate( ) method to perform operations just
prior to servicing client request, like opening resources.

63. How does a client application create a transaction


object?
How you gain access to UserTransaction objects varies depending on the type of client.
Enterprise JavaBeans provides two types of transaction management:
• Container-managed transactions. As the name implies, the EJB container makes the
decisions (based on the deployment descriptor's trans-attribute setting) regarding
how to bundle operations into transactions and then works with the transaction
manager, which manages the transaction processing.
• Bean-managed transactions. In this case, a session bean obtains the
UserTransaction object via the EJBContext using the getUserTransaction() method.
JMS clients can bundle several messages in a transaction simply by using a transactional
session--a UserTransaction object is not required. To create a transactional session, use
either QueueConnection.createQueueSession() or TopicConnection.createTopicSession()
with true as the first argument. (Some JMS implementations support JTA, so that it's also
possible to obtain a UserTransaction object from the JMS server.)
In other environments, for example, a web server that supports servlets and/or JavaServer
Pages (JSP), a JMS server, and others, you obtain a UserTransaction object via JNDI. Of
course, for a servlet to obtain a UserTransaction object, there must be a JTS-capable server
to deliver the object.
Typically, the server provides the JNDI look-up name either directly or via a system or
server property. For example, with the WebLogic server, you would use a code segment
similar to the following:

...
Context c = new InitialContext();
UserTransaction ut = (UserTransaction)
c.lookup("javax.jts.UserTransaction");
ut.begin();
// perform multiple operations...
ut.commit()
...

With J2EE implementations, you obtain the UserTransaction object with a code segment
similar to the following:

...
Context c = new InitialContext();
UserTransaction ut = (UserTransaction)
c.lookup("java:comp/UserTransaction");
ut.begin();
// perform multiple operations...
ut.commit()
...

If the environment provides the UserTransaction object via a system property, you would
use a code segment similar to the following:

...
String transName = System.getProperty("jta.UserTransaction");
Context c = new InitialContext();
UserTransaction ut = (UserTransaction) c.lookup(transName);
ut.begin();
// perform multiple operations...
ut.commit()
...

JNDI remote look-up names and property names vary, of course, across servers/
environment.

64. Do JTS implementations support nested transactions?


A JTS transaction manager must support flat transactions; support of nested transactions is
optional. If a client begins a transaction, and within that transaction begins another
transaction, the latter operation will throw a NotSupportedException if the JTS
implementation does not support nested transactions.
Keep in mind that even if the JTS implementation supports nested transactions, this
transaction manager-level support does not guarantee support for nested transactions in an
application. For example, the EJB 1.1 specification does not support nested transactions.

65. Why would a client application use JTA transactions?


One possible example would be a scenario in which a client needs to employ two (or more)
session beans, where each session bean is deployed on a different EJB server and each
bean performs operations against external resources (for example, a database) and/or is
managing one or more entity beans. In this scenario, the client's logic could required an all-
or-nothing guarantee for the operations performed by the session beans; hence, the session
bean usage could be bundled together with a JTA UserTransaction object.
In the previous scenario, however, the client application developer should address the
question of whether or not it would be better to encapsulate these operations in yet another
session bean, and allow the session bean to handle the transactions via the EJB container.
In general, lightweight clients are easier to maintain than heavyweight clients. Also, EJB
environments are ideally suited for transaction management.

66. How does a session bean obtain a JTA UserTransaction


object?
If it's necessary to engage in explicit transaction management, a session bean can be
designed for bean-managed transactions and obtain a UserTransaction object via the
EJBContext using the getUserTransaction() method. (It may also use JNDI directly, but it's
simpler to use this convenience method.)

67. Why would a session bean use bean-managed


transactions?
In some situations, it's necessary for a (stateful) session bean to selectively control which
methods participate in transactions, and then take over the bundling of operations that form
a logical unit of work.

68. How does an enterprise bean that uses container-


managed transactions obtain a JTA UserTransaction
object?
It doesn't! By definition, container-managed transaction processing implies that the EJB
container is responsible for transaction processing. The session bean has only limited control
of transaction handling via the transaction attribute.

69. Is it possible for a stateless session bean to employ a


JTA UserTransaction object?
Yes, but with restrictions. By definition, a stateless session bean has no state; hence, each
method invocation must be independent. (The bean can be "swapped out" between method
invocations.) Thus, a stateless session bean can obtain a UserTransaction object via the
EJBContext using the getUserTransaction() method, but it must start and finish each
transaction within the scope of a method invocation.

70. How do you configure a session bean for bean-


managed transactions?
You must set transaction-type in the deployment descriptor.

71. How does an entity bean obtain a JTA UserTransaction


object?
It doesn't. Entity beans do not employ JTA transactions; that is, entity beans always employ
declarative, container-managed transaction demarcation. Entity beans, by definition, are
somewhat tightly coupled (via the EJB container and server) to a datastore; hence, the EJB
container is in the best position to manage transaction processing.

72. Is it necessary for an entity bean to protect itself


against concurrent access from multiple transactions?
No. One of the motivations for using a distributed component architecture such as
Enterprise JavaBeans is to free the business logic programmer from the burdens that arise
in multiprogramming scenarios.

73. What are the constraints or drawbacks of container


managed EJB's?
CMP in beans depends a lot on the EJB vendor implementation and utilities. With some
implementations container-managed entity beans can only by mapped to one table, while
other implemenations offer Multiple table mappings to a single bean. The bottom line,It
depends on the container provider being used.

74. Is entity data persisted at the end of a transaction or


at any time?
Depends on what you mean by "persisted". Data that is part of a transaction like database
rows are persisted depending on the success of the transaction. If the transaction manager
determines that the transaction was successful or there were no problems during any of the
steps invoved in it, the data is committed, or otherwise rolled back.
The container, on the other hand, invokes certain state transition lifecycle methods to
conserve resources. This involves passivation and activation of the bean or instance
swapping. This happens independent of the transaction since the client never interacts
directly with the bean instance but with the server's implementation of the EJBObject.

75. How do enterprise beans access native libraries?


In short, they don't.
The EJB 1.1 Specification, section 18.1.2 (Programming Restrictions) lists some things that
enterprise beans cannot do. In particular:

· The enterprise bean must not attempt to load a native library.


This function is reserved for the EJB Container. Allowing the enterprise bean to l

76. How do I implement a logging system in my beans?


Using java.io is prohibited
Using the java.io package from within a bean is prohibited. The EJB 1.1 Specificat
(Programming Restrictions) states the following:

ï‚· An enterprise bean must not use the java.io package to attempt to access files
directories in the file system.
The file system APIs are not well-suited for business components to access data. B
components should use a resource manager API, such as JDBC API, to store data.
Alternative Solutions
To perform logging operations you must you a resource connection supported by the
EJB servers may support several resource connection options, which can be used to
below:

· JDBC (javax.sql.DataSource) : Write log events in to a relational database.


· URL (java.net.URL) : Write log events to a custom logging server or post them t
· JavaMail (javax.mail.Session) : E-mail log events to a special account
· JMS (javax.jms.QueueConnectionFactory | javax.jms.TopicConnectionFactory) : Sen

77. What is a container?


Enterprise beans are software components that run in a special environment called an EJB
container. The container hosts and manages an enterprise bean in the same manner that a
Java WebServer hosts a Servlet or an HTML browser hosts a Java applet. An enterprise bean
cannot function outside of an EJB container. The EJB container manages every aspect of an
enterprise bean at run time including remote access to the bean, security, persistence,
transactions, concurrency, and access to and pooling of resources.
The container isolates the enterprise bean from direct access by client applications. When a
client application invokes a remote method on an enterprise bean, the container first
intercepts the invocation to ensure persistence, transactions, and security are applied
properly to every operation a client performs on the bean. The container manages security,
transactions, and persistence automatically for the bean, so the bean developer doesn't
have to write this type of logic into the bean code itself. The enterprise bean can focus on
encapsulating business rules, while the container takes care of everything else.

Containers will manage many beans simultaneously in the same fashion that a Java
WebServer manages many Servlets. To reduce memory consumption and processing,
containers pool resources and manage the lifecycles of all the beans very carefully. When a
bean is not being used a container will place it in a pool to be reused by another client, or
possibly evict it from memory and only bring it back when its needed. Because client
applications don't have direct access to the beans -- the container lies between the client
and bean -- the client application is completely unaware of the containers resource
management activities. A bean that is not in use, for example, might be evicted from
memory on the server, while its remote reference on the client remains intact. When the
client invokes a method on the remote reference, the container simply re-incarnates the
bean to service the request. The client application is unaware of the entire process.
An enterprise bean depends on the container for everything it needs. If an enterprise bean
needs to access a JDBC connection or another enterprise bean, it does so through the
container; if an enterprise bean needs to access the identity of its caller, obtain a reference
to itself, or access properties it does so through the container. The enterprise bean interacts
with its container through one of three mechanisms: callback methods, the EJBContext
interface, or JNDI.
• Callback Methods: Every bean implements a subtype of the EnterpriseBean
interface which defines several methods, called callback methods. Each callback
method alerts the bean of a different event in its lifecycle and the container will
invoke these methods to notify the bean when it's about to pool the bean, persist its
state to the database, end a transaction, remove the bean from memory, etc. The
callback methods give the bean a chance to do some housework immediately before
or after some event. Callback methods are discussed in more detail in other
sections.
• EJBContext: Every bean obtains an EJBContext object, which is a reference directly
to the container. The EJBContext interface provides methods for interacting with the
container so that that bean can request information about its environment like the
identity of its client, the status of a transaction, or to obtain remote references to
itself.
• JNDI: Java Naming and Directory Interface is a Java extension API for accessing
naming systems like LDAP, NetWare, file systems, etc. Every bean automatically has
access to a special naming system called the Environment Naming Context (ENC).
The ENC is managed by the container and accessed by beans using JNDI. The JNDI
ENC allows a bean to access resources like JDBC connections, other enterprise
beans, and properties specific to that bean.
The EJB specification defines a bean-container contract, which includes the mechanisms
(callbacks, EJBContext, JNDI ENC) described above as well as a strict set of rules that
describe how enterprise beans and their containers will behave at runtime, how security
access is checked, transactions are managed, persistence is applied, etc. The bean-
container contract is designed to make enterprise beans portable between EJB containers so
that enterprise beans can be developed once then run in any EJB container. Vendors like
BEA, IBM, and Gemstone sell application servers that include EJB containers. Ideally, any
enterprise bean that conforms to the specification should be able to run in any conformant
EJB container.
Portability is central to the value that EJB brings to the table. Portability ensures that a bean
developed for one container can be migrated to another if another brand offers more
performance, features, or savings. Portability also means that the bean developer's skills
can be leveraged across several EJB container brands, providing organizations and
developers with better opportunities.
In addition to portability, the simplicity of the EJB programming model makes EJB valuable.
Because the container takes care of managing complex tasks like security, transactions,
persistence, concurrency and resource management the bean developer is free to focus
attention on business rules and a very simple programming model. A simple programming
model means that beans can be developed faster without requiring a Ph.D. in distributed
objects, transactions and other enterprise systems. EJB brings transaction processing and
disributed objects development into the mainstream.

78. What makes a Java class an enterprise bean?


An enterprise bean is composed of many parts, not just a single class. Essentially, an
enterprise bean is constructed with a bean class, remote interface, home interface and
deployment descriptor. These constituents are discussed below.
• ï‚· A bean class is the implementation class of the bean that defines its business,
persistence, and passivation logic. The bean class implements either the
javax.ejb.EntityBean or javax.ejb.SessionBean interface and runs inside the EJB
container. Instances of the bean class service client request indirectly; instances of
the bean class are not visible to the client.
• ï‚· The remote interface defines the business methods that will be visible to the
client's that use the enterprise bean. The remote interface extends the
javax.ejb.EJBObject interface and is implemented by a remote (distributed object)
reference. Client applications interact with the enterprise bean through its remote
interface.
• ï‚· The home interface defines the create, delete (remove), and query methods for
an enterprise bean type. The home interface extends the javax.ejb.EJBHome
interface and is implemented by a remote (distributed object) reference. The client
application will use the home interface to create beans, find existing beans, and
remove specific beans.
• ï‚· The deployment descriptor is used to describe the enterprise bean's runtime
behavior to the container. Among other things the deployment descriptor allows the
transaction, persistence, and authorization security behavior of a bean to be defined
using declarative attributes. This greatly simplifies the programming model when
developing beans.
An enterprise bean represents the sum of all these parts (remote, home, bean class, and
deployment descriptor) as one component. An enterprise bean is not an enterprise bean if
any one of these parts is missing. A change to anyone of these parts -- changing even one
attribute in the deployment descriptor for example -- creates an entirely new enterprise
bean.

79. While deploying CMP entity beans, which fields in the


bean are container-managed and how are they identified?
Container-managed fields may be specified in the bean's deployment descriptor. An entity
bean, for example, has an XML deployment descriptor containing elements similar to the
following:<br/>

<enterprise-beans>
<entity>
<description>This entity bean models an audio compact disc.</description>
<ejb-name>MusicCDBean</ejb-name>
<home>musicstore.MusicCDHome</home>
<remote>musicstore.MusicCD</remote>
<ejb-class>musicstore.MusicCDBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>musicstore.MusicCDPK</prim-key-class>
<reentrant>False</reentrant>

<cmp-field><field-name>upc</field-name></cmp-field>
<cmp-field><field-name>title</field-name></cmp-field>
<cmp-field><field-name>artist</field-name></cmp-field>
<cmp-field><field-name>type</field-name></cmp-field>
<cmp-field><field-name>price</field-name></cmp-field>
</entity>
</enterprise-beans>

In the above deployment descriptor, the container-managed fields are specified to be upc,
title, artist, type, and price.
While the deployment descriptor provides information about the container-managed fields
for use during deployment, the details of how these fields are mapped into the database (or
other persistent storage mechanism) are controlled by the container-specific deployment
process itself. To learn more about the container-specific deployment process, you will need
to consult your container vendor's documentation.

80. Does the EJB programming model support inheritance?


Inheritance is supported in EJB in a limited fashion. Enterprise beans are made up of several
parts including: a remote interface; a home interface, a bean class (implementation); and a
deployment descriptor
The remote interface, which extends javax.ejb.EJBObject can be a subtype or a super-type
of remote interfaces of other beans. This is also true of the home interface, which extends
javax.ejb.EJBHome. The bean class, which implements either javax.ejb.EntityBean or
javax.ejb.SessionBean can also be a subtype or super-type of the bean class used by
another enterprise bean. Deployment descriptors are XML files, so there is no Object-
Oriented (OO) inheritance in the deployment descriptor.
Because an enterprise bean is not one object -- its the composition of several parts --
traditional OO inheritance is not possible. The constituent Java parts (remote, home, bean
class) of an enterprise bean may themselves subtype or serve as super-type, but the bean
as a whole (the sum of its parts) doesn't support inheritance.

81. How should complex find operations be implemented?


In bean-managed persistence (BMP) complex find operations are not difficult to implement,
because you have complete control over how a find operation works through the ejbFind
methods in the bean class. ejbFind methods in BMP entities can span multiple tables and
even different data sources to locate the right entity beans.
With container-managed persistence (CMP) its more difficult because you are dependent on
the versatility of the EJB vendor. In other words, if the vendor does not support
sophisticated find operations or syntax, its more difficult to declare complex find operations
at deployment time. With CMP you have a couple options:
• · Convert the CMP bean to a BMP bean and hand code the ejbFind methods
yourself. This is a classic scenario for using BMP over CMP; when the EJB vendor is
not sophisticated enough to support a bean's data access needs.
• · Use a session bean to obtain the data you need. When a search operation
becomes to complex to implement in a single bean its a good indication that the
search operation is not appropriate for a find method. Search operations that span
the data encapsulated by several different entity beans should be placed in a
session bean with the emphasis on returning only the data needed, not necessarily
bean references. Data can be returned in tabular format instead of bean references.
NOTE:
A common design error is to implement search operations that filter results of multi-entity
find requests implemented by other entity beans. This should be avoided. If you can not
find the entity beans in one find request, then you should use a search method in a session
bean.

82. Can I use Threads in a enterprise bean?


No. The thread management is done by the container for you. As a bean developer you are
not allowed to use threads.
Section 18.1.2 of the EJB 1.1 specification states:
• · The enterprise bean must not attempt to manage threads. The enterprise bean
must not attempt to start, stop, suspend, or resume a thread; or to change a
thread’s priority or name. The enter-prise bean must not attempt to manage
thread groups.
These functions are reserved for the EJB Container. Allowing the enterprise bean to manage
threads would decrease the Container’s ability to properly manage the runtime
environment.
83. Why are beans not allowed to create their own
threads?
Enterprise beans exist inside a container at run time. The container is responsible for
managing every aspect of the enterprise bean's life including: transactions, access control,
persistence, resource pooling, etc. In order for the container to manage the runtime
environment of a bean, it must have complete control over the threads that access and run
within a bean. This means that beans can not start or manage their own threads. Containers
deny enterprise beans the privilege to manage threads for three basic reasons: Resource
management, security, and thread-sensitive storage.
Resource Management
Containers manage every aspect of the runtime environment used by enterprise beans
including transactions, access control, life cycle, resource connections, VM security, class
loading, and threads. This allows the container to conserve as many resources as possible,
which is important when there are hundreds of enterprise beans servicing thousands of
clients. Without strict management of resources like memory and threads, EJB systems
might consume to many resources (memory and cycles), which would result in a slow
system, a prospect that is untenable in a high-transaction environment. Threads started and
managed by enterprise beans would not be managed by the container, which would make it
difficult to conserve resources.
Security
There is no way for a container system to know in advance that a bean's use of threads is
benign. While intentions may be sincere it is possible -- probably inevitable -- that
developers would create malignant beans that spawn so many threads that the entire
system slows down. One bean instance's misuse of threads or the commutative effect of
many instances could cause a system slowdown. This is an insurgent denial of service,
where the beans themselves sabotage a system's ability to respond to client requests.
Security is a very good reason for denying bean's the privilege of starting and managing
their own threads.
Thread-Specific Storage
Thread-Specific Storage (TSS) is an established and common technique employed by
vendors to propagate and track client requests through the container system. It involves
associating data with a thread. The data may be information about the client's identity, the
transaction context, and other information, which can be accessed by any part of the
container without having to pass the data explicitly. This is especially useful when enterprise
beans invoke other enterprise beans or access resources, because it provides a convenient
and transparent mechanism for transferring information about the who is making the
request and under what circumstances. Each vendor will use the TSS technique differently
according to the mechanics of their server. Threads started and managed by the enterprise
bean explicitly would not have the proper TSS -- that would require intimate knowledge and
access to the vendors container system. Without the right TSS the enterprise bean's threads
can not operate within the container system properly. This is another reason why bean are
not allowed to start and manage their own threads, it would short-circuit the vendor's use of
TSS.

84. How does EJB support polymorphism?


Because an EJB consists of multiple "parts", inheritance is achievable in a rather limited
fashion (see FAQ answer on inheritance here). There have been noteworthy suggestions on
using multiple inheritance of the remote interface to achieve polymorphism, but the problem
of how to share method signatures across whole EJBs remains to be addressed. The
following is one solution to achieving polymorphism with Session Beans. It has been tried
and tested on WebLogic Apps Server 4.50 with no problems so far.
We will use an example to show how it's done. Say, there are 2 session beans, Tiger and
Lion, that share some method signatures but provide different implementations of the
methods.
• · AnimalHome and Animal are the home and remote interfaces. The signatures of
the polymorphic methods are in Animal.
• · AnimalBean is the base implementation bean.
• · TigerBean and LionBean extend from AnimalBean. They may override the
methods of AnimalBean, implementing different behaviors.
• · Deploy Tiger and Lion beans, specifying AnimalHome and Animal as their home
and remote interfaces. Note that Tiger and Lion should have different JNDI lookup
names.

85. What classes does a client application need to access


EJB?
It is worthwhile to note that the client never directly interacts with the bean object but
interacts with distributed object stubs or proxies that provide a network connection to the
EJB container system.
The mechanhism is as follows.
1. The client uses the JNDI context to get a remote reference (stub) to the home
object ( the EJBHome).
2. It uses the home to get a remote reference (stub) to the EJBs remote object (the
EJBObject)
3. It then invokes business methods on this remote object.
The client needs the remote interface, the home interface, the primary key( if it is an entity
bean).
In addition to these, the client would need the JNDI factory implementation, and the remote
and home stubs. In some EJB servers the Factory and/or stubs can be dynamically loaded
at run time. In other EJB servers they must be in the classpath of the client application.

86. What is an EJB primary key? How is it implemented


when the database doesn't have a primary key?
A primary key is an object that uniquely identifies the entity bean. According to the
specification, the primary key must be unique for each entity bean within a container. Hence
the bean's primary key usually maps to the PK in the database (provided its persisted to a
database).
You may need to create a primary key in the database for the sake of referential integrity.
This does not, however, mean you NEED a primary key in the database. As long as the
bean's primary key (which maps to a column or set of columns) can uniquely identify the
bean it should work.

87. What's an .ear file?


An .ear file is an "Enterprise Archive" file. The file has the same format as a regular .jar file
(which is the same as ZIP, incidentally). The .ear file contains everything necessary to
deploy an enterprise application on an application server. It contains both the .war (Web
Archive) file containing the web component of the application as well as the .jar file. In
addition there are some deployment descriptor files in XML.

88. Can beans use stored procedures in a database?


Stored procedures can be used by session beans that access the database using JDBC and
bean-managed entity beans that use JDBC to manage their own persistence. JDBC provides
a call interface for using stored procedures. An example is provided below:

InitialContext cntx = new InitialContext( );


DataSource dataSource = (DataSource) cntx.lookup("java:comp/env/jdbc/mydatabase");
Connection con = dataSource.getConnection( );

CallableStatement storedProcedure = con.prepareCall("{? = call someprocedure [(?,?

89. Is method overloading allowed in EJB?


Yes you can overload methods.

90. How can JMS be used from EJB 1.1?


The same as any client would use JMS. At this point there is no integration, but it is planned
for a future release of the EJB spec.

91. Can primary keys contain more than one field?


Yes, a primary key can have as many fields as the developer feels is necessary, just make
sure that each field you specify as the primary key, you also specify a matching field in the
bean class. A primary key is simply one or more attributes which uniquely identify a specific
element in a database. Also, remember to account for all fields in the equals() and
hashCode() methods.

92. How does Container Managed Persistence work with


automatically generated database ID fields? Should I map
the ID field explicitly or leave it unspecified?
In the Deployment Descriptor, map the normal fields appropriately, but don't specify the
auto-id field as one of the container managed fields.
93. Let's assume I use a JavaBean as a go-between a JSP
and an EJB, and have, say, 50 concurrent clients that need
to access the EJB functionality. Will the JSP container
actually instantiate 50 instances of the bean, or can it
reuse a single instance to access the EJB?
• It depends on the scope you associate with the JavaBean. If you assign the bean
with page (which is the default) scope or request scope, a new bean will be
instantiated for each incoming request.
• If you assign the bean with session scope, you will still have 50 instances loaded in
memory (assuming each incoming request is triggered by a distinct client), although
some may have been instantiated from an earlier request from the same client.
However, you may not want to use the session scope for a high-volume site as
these beans will continue to reside in memory, long after the request has been
serviced, consuming valuable resources until they are invalidated either explicitly or
due to a session timeout.
• You can also assign the bean with application scope, in which case it is instantiated
just once before being placed into the servlet context of the container. It can then
be accessed at a later time, as long as the server is up and running. Although this
may sound like an attractive proposition, do note that you will have to contend with
significant multithreading issues. For instance, you'll have to ensure that the bean is
accessed in a thread-safe manner from each of the JSP files. While you can do this
using explicit synchronization from within the JSP file, do note that your application
may take a significant performance hit because of this - especially if you expect tens
or hundreds of concurrent clients accessing your pages.
• So, in short, your best bet may be to assign the bean with request scope.

94. What happens when two users access an Entity Bean


concurrently?
Taken from Enterprise JavaBeans by Richard Monson-Haefel, "EJB, by default, prohibits
concurrent access to bean instances. In other words, several clients can be connected to
one EJB object, but only one client thread can access the bean instance at a time. If, for
example, one of the clients invokes a method on the EJB object, no other client can access
that bean instance until the method invocation is complete."
So, to answer your question, two users will never access an Entity Bean concurrently.

95. What's the reason for having two interfaces --


EJBHome for creating, finding & removing and EJBObject
for implementing business methods. Why not have an
single interface which supports both areas of
functionality?
This design reflects the common "Factory" Design pattern. The EJBHome interface is the
Factory that creates EJBObjects. EJBObject instances are the product of the factory. The
reason for having two interfaces is because they are both responsible for different tasks.
The EJBHome is responsible for creating and finding EJBObjects, whilst the EJBObject is
responsible for the functionality of the EJB.

96. Which fields in beans should be public?


All Container Managed Fields in an Entity Bean must be public.
Ejb 1.1 spec section 9.4.1 - "The fields must be defined in the entity bean class as public,
and must not be defined as transient."

97. How do you implement callbacks in EJB?


If your client is an EJB, it can pass a reference to itself to the method of the bean that it is
calling. The EJB can then call methods directly on that interface.
If your client is a Java client, your client requires some sort of object that will "listen" for
call-backs. This could be either a CORBA or RMI object. Again, you could pass references to
these objects to the EJB, which could then invoke methods on the references.

98. When should I use bean-managed transactions instead


of specifying transaction information in the deployment
descriptor?
The Sun J2EE EJB Guide says like this:
• Although beans with container-managed transactions require less coding, they have
one limitation: When a method is executing, it can be associated with either a single
transaction or no transaction at all. If this limitation will make coding your session
bean difficult, you should consider using bean-managed transactions.
• The following pseudo-code illustrates the kind of fine-grained control you can obtain
with bean-managed transactions. By checking various conditions, the pseudo-code
decides whether to start and stop different transactions within the business method.

begin transaction
...
update table-a
...
if (condition-x)
commit transaction
else if (condition-y)
update table-b
commit transaction
else
rollback transaction
begin transaction
update table-c
commit transaction
...

I think what it means is there are some limitations in j2ee transaction support. In a
container managed situation, nested or multiple transactions are not allowed within a
method. if a biz method needs those features you need to go for bean managed
transactions.
99. How do I automatically generate primary keys?
A common way to do it is to use a stateless session bean to retrieve the ID that you wish to
use as the primary key. This stateless session bean can then execute an Oracle sequencer
or procedure etc. to retrieve the ID value used as the primary key.

100. How is the passivation of Entity beans Managed?


The passivation of Entity beans is managed by the container. To passivate an instance, the
container first invokes the ejbStore() method for synchronizing the database with the bean
instance, then the container invokes the ejbPassivate() method. It will then return the bean
instance back to the pooled state. (Every bean has an instance pool.)
There are two ways for transitioning an entity bean from the ready to the pooled state, by
using the ejbPassivate() or ejbRemove() method. The container uses ejbPassivate() to
disassociate the bean instance from the entity object identity, and uses ejbRemove() to
remove the entity object.
When the instance is put back into the pool, it is no longer associated with an entity object
identity. The container can now assign the instance to any entity object within the same
entity bean home.
A bean instance in the pool can be removed by using unsetEntityContext().

101. To complete a transaction, which Transaction


Attributes or Isolation Level should be used for a stateless
session bean?
[For example, I have a method transfer which transfers funds from one account to another
account.]
Vague question. Is the Session bean doing the DB work? I'll assume no.
Let's say AtmEJB is a Session bean with the transfer method. Let's say AccountEJB is an
Entity bean.
Step 1:
When the client invokes the transfer method you want that to be the transaction; i.e. "the
transfer transaction". therefore you need to set the tx attribute of transfer to something
that will make the container start a tx at the beginning of transfer and terminate it at the
end of transfer. RequiresNew might be a good choice but you need to look at all your use
cases not just this one.
Step 2:
The AccountEJB methods invoked from the transfer method need to have a tx attribute that
allows them to be part of an ongoing tx. That means that deposit and withdraw cannot be
RequiresNew! (that would suspend the transfer tx and run in its own tx). Look at the spec
for these: there are 3 that meets the criteria for deposit and withdraw in the transfer use
case. Which one to use? What are the other use cases in which deposit and withdraw will be
called? Find one that works for each one.

102. Explain the different Transaction Attributes and


Isolation Levels with reference to a scenario.
The Enterprise JavaBeans model supports six different transaction rules:
• TX_BEAN_MANAGED. The TX_BEAN_MANAGED setting indicates that the enterprise
bean manually manages its own transaction control. EJB supports manual
transaction demarcation using the Java Transaction API. This is very tricky and
should not be attempted without a really good reason.
• TX_NOT_SUPPORTED. The TX_NOT_SUPPORTED setting indicates that the
enterprise bean cannot execute within the context of a transaction. If a client (i.e.,
whatever called the method-either a remote client or another enterprise bean) has a
transaction when it calls the enterprise bean, the container suspends the transaction
for the duration of the method call.
• TX_SUPPORTS. The TX_SUPPORTS setting indicates that the enterprise bean can
run with or without a transaction context. If a client has a transaction when it calls
the enterprise bean, the method will join the client's transaction context. If the
client does not have a transaction, the method will run without a transaction.
• TX_REQUIRED. The TX_REQUIRED setting indicates that the enterprise bean must
execute within the context of a transaction. If a client has a transaction when it calls
the enterprise bean, the method will join the client's transaction context. If the
client does not have a transaction, the container automatically starts a new
transaction for the method. Attributes
• TX_REQUIRES_NEW. The TX_REQUIRES_NEW setting indicates that the enterprise
bean must execute within the context of a new transaction. The container always
starts a new transaction for the method. If the client has a transaction when it calls
the enterprise bean, the container suspends the client's transaction for the duration
of the method call.
TX_MANDATORY. The TX_MANDATORY setting indicates that the enterprise bean must
always execute within the context of the client's transaction. If the client does not have a
transaction when it calls the enterprise bean, the container throws the TransactionRequired
exception and the request fails.

103. What is the most efficient approach for integrating


EJB with JSP? Should the EJBs be invoked directly from
within JSP scriptlets? Should the access take place from
within Java beans? Or is it best to use custom tags for this
purpose?
JSP scriptlet code should be minimal. Invoking EJB code directly on a JSP page results in
many lines of code on your JSP page, including try...catch blocks to catch naming and
finding exceptions.
Using a standard JavaBean as an intermediary between the JSP page and EJB server cuts
down on the amount of code needed to add to a JSP page, and promotes reuse. The
JavaBean should be a simple wrapper around the EJB you are accessing.
If you use a standard JavaBean you could also use the jsp:useBean tag to setup EJB
parameters, such as the server URL and server security parameters.
Custom tags are also an option. However, they require a lot more coding than a simple
JavaBean wrapper. The point should be to rewrite as little code as possible while at the
same time keeping the JSP scriptlet content as light as possible.
104. How do you get a JDBC database registered with a
JNDI name so that it can be accessed from an EJB?
The short answer is that it depends on which container you're using to some extent. The
one thing that (should be) common in EJB 1.1 containers is that the ejb-jar.xml file's entry
for that bean needs to contain a 'resource-ref' stanza, like so:

<resource-ref>
<res-ref-name>jdbc/LocalDB2<res-ref-name>
<res-type>javax.sql.DataSource<res-type>
<res-auth>Container<res-auth>
<resource-ref>

The res-ref-name is the most interesting part. This is the JNDI name relative to the
java:comp/env namespace. Hence, to get this connection you'd do (in your bean):

Context context = new InitialContext();


DataSource source = context.lookup("java:comp/env/jdbc/LocalDB2");

which gives you a DataSource that you can call getConnection on.
The other half of this is container specific and done at deployment time by a 'Deployer' or
'Assembler' (to use the rolenames specified by the EJB spec.) This can work very differently
from one container to the next, but here are a couple of (abbreviated) examples.
With Weblogic 5.1, you must define a connection pool in weblogic.properties, then edit the
weblogic specific deployment descriptor (using the EJB Deployment tool) to associate the
resource-ref specified in ejb-jar.xml with that connection pool.
With Inprise Application Server 4.0, all of the parameters for the connection (JDBC driver,
connection URL, etc.) are specified in the inprise specific deployment descriptor (also
editable via their deployment tool).
Other servers will have other ways of associating the resource-ref with a pre-defined
connection pool.

105. How to manage fields that can have null values in a


container-managed Entity bean?
First of all, let's just set up a typical scenario:
You are developing a product which allows a bank to sign up new customers online. You
have done analysis and design and settled on having two tables: 'users' and 'account' (let's
keep it simple). Each "user" will have a corresponding "account". The foreign key between
the two will be the "account number".
So, for the 'users' table, you have the following fields: firstName, lastName, userId,
password, and acctNum. When this table is created in the database, it is empty. Now you
must relate your EJB code to this table for persistence. For simplicity sake I will leave out
the Session bean (which I would use to talk to my Entity bean), the Entity bean primary key
class, and the home and remote interfaces.
We have the UserBean:

public class UserBean implements javax.ejb.EntityBean {


public String firstName = null;
public String lastName = null;
public String userId = null;
public String password = null;
public long acctNum = -1;

/**
* Called by the container after the UserHome.create() is called
*/
public void ejbCreate(String userId, String password, long acctNum) {
this.userId = userId;
this.password = password;
this.acctNum = acctNum;
}
...
...

public void setUserData(UserData data) throws RemoteExeption, UserDataException {


this.firstName = data.getFirstName();
this.lastName = data.getLastName();
}
...
...
}

Now, assuming you have the User (remote interface class), UserHome (home interface
class), UserPK (primary key class) already done, you need to create the bean's deployment
descriptor. Inside the deployment descriptor, you must specify the database table, 'users',
which this bean will map to. Also, you must specify which fields from your bean map to
which fields in the 'users' database table. (This is how the container knows which fields to
persist between your bean and the database table.) Now assuming all code compiles and
you have an EJB server up and running and you have deployed your bean, all you need to
do is write a client (I would use a client to access a session bean, say 'CustomerSession',
which would talk to my entity bean) to create a new user and pass in the userId, password
and acctNum values, which will create the new user in the database.
Notice the fields in the UserBean will now be set, but the firstName and lastName fields will
still be set to null. These fields will still be empty in the database and will not change until
these fields are set in the bean, since it is persisted. Now, call the setUserData(UserData
data) method for setting the firstName and lastName, and these fields will now be set in the
database and no longer be null. The container will handle the persistence of any fields which
are set to null, just as it will handle any fields which are set to some meaningful value.

106. How can I debug my EJB applications?


This depends upon which EJB Container you are using.
Borland's JBuilder 3.5, Foundation Edition allows you to debug any Java 2 application,
including the Inprise Application Server, WebLogic Server and J2EE Reference
implementation. You can download it free from www.borland.com/jbuilder.
There are other IDE's out there including NetBeans/Forte www.sun.com/forte/ffj/ce/ that
can also debug EJB.
107. How can an applet talk directly with EJB?
An applet must use the same procedure as any other Java class: it must use JNDI to locate
the EJB Home Interface, then use RMI to talk with the Home Interface as well as the EJB
itself.
This means that the J2EE and/or JNDI and/or RMI classes need to be present in the applet's
Java Virtual Machine. The easiest way to assure this is to use the latest Java Plug-in.
Netscape 6, aka Mozilla, ships with the Java Plug-in. Other browsers have various problems
with RMI and JNDI classes that are beyond the scope of this answer.
Note, however, that it is not recommended to use EJB directly from applets, in part due to
compatibility issues. Instead, you can use Servlets inside the application server to provide
an HTML front-end that is assured to work on a much larger base of clients.

108. What is the best way of implementing a web


application that uses JSP, servlet and EJB technologies all
together following a Model View Controller (MVC)
architecture?
[See the Sun J2EE Blueprints for "an integrated set of documentation and examples that
describe and illustrate 'best practices' for developing and deploying component-based
enterprise applications using the J2EE platform" including some good architecture
whitepapers and source code. -Alex]
Hmm, 'Best Way' is a bit rough - there are several 'good' ways, and the usual set of trade-
offs between them. (I'm a consultant - I have to start any answer with "It depends...",
otherwise they revoke my whiteboard privileges)
The main thing you need to keep in mind as you design this sort of a system is that you
want the interface into the EJB's to be rather narrow: in any flow, the ideal is to call one EJB
method (hopefully on a stateless session bean), and let it make calls to entities on your
behalf, then hand back the data you need to display.
How you display it depends: you can either embed beans on your JSPs and let the beans
make that hopefully-one EJB call, or you can post to a servlet, let that make the call, then
forward to the JSP for display. The second of these is more flexible and gives you more
leverage to hide, change, and enforce your site's structure. The first, however, will be easier
for developers new to this web thing to follow.
Essentially, I'm saying that Entity beans are your model, your controller is Session beans
(maybe with a bit of help from servlets or beans), and your JSPs, beans and servlets are
your View.
One thing to note here: this discussion strongly implies that your EJBs are capable of
externalizing their state as some number of very simple 'value objects' (not EJBs
themselves, just something we can pass back and forth). These value objects are probably
tuned tightly to a workflow, and will be produced by that session bean. This way the traffic
between the EJB (server) and the JSP/Servlet (client) is tuned to what the client needs,
while the transaction load on the server is minimized.
109. When does the container call my bean's ejbCreate /
ejbPostCreate / ejbStore / ejbPassivate / ejbActivate /
ejbLoad / ejbPassivate method? And what should I do
inside it?
The lifecycle of an enterprise bean is the heart of the EJB system. Your bean is basically
implemented as a set of callback methods. There are a lot of these methods, which can be
confusing; however, the implementation of each one is actually quite straightforward. Most
of the time you can get away with implementing only a few of them.
Using Bean-Managed Persistence, each callback method ejbX means the obvious thing
(usually "you must do X").
Using Container-Managed Persistence,
• ejbCreate means "fill in your defaults"
• ejbPostCreate means "your primary key is now valid; keep initializing"
• ejbStore means "I'm about to store your data into the DB"
• ejbPassivate means "I just stored your data, and I'm about to passivate you"
• ejbActivate means "I just activated you, and I'm about to load in your data"
• ejbLoad means "I just loaded your data from the DB"

110. What's the difference between EJBHome, EJB Home,


EJB Object, EJBObject and EJB (not to mention Home
Interface and Remote Interface)?
The EJB spec is all about really bad naming decisions.
First, an Enterprise JavaBean is not a JavaBean (but you already knew that).
The "Home Interface" is actually a Factory Object. It is responsible for locating or creating
instances of the desired bean, and returning remote references.
When you write the source code for the EJB Home Interface, you must extend the interface
EJBHome, and provide method signatures for all the desired create() and find() methods.
An object that implements the Home Interface is automatically generated by the EJB Server
tools.
The "EJB Object", or Remote Object, is actually a Wrapper. It sits somewhere inside the
container, between the client and your code. It is responsible for performing all the setup
and shutdown tasks (like opening transactions, or restoring data state) immediately before
and after your enterprise bean is called.
The "EJB Object" is generated by the EJB Server tools -- you don't have to write any part of
it. However, you do have to write another interface, called the "Remote Interface" or the
"EJBObject Interface," that extends interface EJBObject, and provides method
signatures for all the business methods. The server automatically generates a Java class
that implements the Remote Interface; it is this object that is registered with RMI, and a
reference to it is returned by the Home Interface (which we now know is actually a Factory
Object).
The "EJB," or Enterprise Bean, ironically, is not the EJB Object (even though it is an EJB
and it is an object). It doesn't even implement the EJBObject interface, nor does it
implement the Remote Interface. Instead, it implements either the EntityBean interface or
the SessionBean interface. It also must implement all the methods defined in the Remote
Interface -- but it doesn't actually implement the interface (in the Java sense). This is
unfortunate, since we cannot rely on the Java compiler to make sure we've implemented all
the right methods. It must also implement one ejbCreate() method for each create()
method in the Home Interface (as well as ejbFind()/find()).
111. Is there a difference between container managed and
bean managed persistence in terms of performance?
[Short answer: with bean-managed persistence, you can optimize your queries and improve
performance over the generalized container-managed heuristics. But container-managed
persistence is very convenient, and vendors will be working to improve its performance as
time goes on. -Alex]
There is of course a difference as many CMPs use O-R mapping using metadata, which is
slower than hardcoded queries (except vendors like GemStone that use a OODB which is
slow anyway!) As always, a lot depends on the database schema. Given that CMP is still
evolving, complex relationships (e.g.inheritance) and distributed transactions are not even
supported by most EJB server vendors, leave alone performance.
Having said that however, it does not seem right to compare BMP and CMP on performance
because the motivation of CMP is precisely to relieve bean providers from thinking about
this! In (J2EE) theory, a good CMP implementation should perform well in a production
environment; in practice, except for a couple of vendors who have traditionally been strong
in persistent storage space (e.g. Persistence Software, GemStone) you will not find great
CMP support at this very moment.
BMP offers a tactical approach while CMP is more strategic. Which implies that if you can
work-around some (perhaps severe) limitations for near-term, there may be much to gain
with CMP as the vendor offering matures.

112. Given that RMI-IIOP does not support distributed


garbage collection (unlike RMI-JRMP), do I need to do
something explicitly to GC beans, or is it magically handled
by the EJB framework?
It is the Containers' responsibility to handle distributed garbage collection. This is how EJB's
were designed.

113. OK, so EJB doesn't support user-created threads. So


how do I perform tasks asynchronously?
If your EJB does not need to know about the results of the aynch calls, then you can use
JMS to send an asynch. message to another part of the system.
Another alternative is to place the multithreaded code inside a CORBA or RMI server and call
this from your EJB. Always keep site of the big picture, RMI and CORBA are part of J2EE and
can be used as part of a 'J2EE' solution.
There are some things that these technologies can do that EJB at this present time cannot.

114. 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 EJB Context 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.
115. Can I deploy a new EJB without restarting my server?
(I'm using Weblogic.)
Sure. WebLogic Server4.5 includes "hot deploy" feature that allow you to deploy, redeploy
or undeploy EJBs while the Server is running, from the Weblogic Console. Deployment of
EJBs made through the console are however lost when you restart the WebLogic Server.

116. How to setup access control in an EJB such that


different application clients have different rights to invoke
different methods in one EJB?
1. Set up the different users/groups and the methods each can have access to in your
deployment descriptor. Note: You don't have to specify different methods for each
user, you could also just specify different users to your entire bean - for example if
you only wanted another component of your application talking to your bean.
2. Inside your client code, whenever you make your connection to the EJB server (to
look up the bean) you need to specify the user and password, in order to set the
Identity of the client:

...
Properties p = new Properties();
..
p.put(Context.SECURITY_PRINCIPAL, "user");
p.put(Context.SECURITY_CREDENTIALS, "password");
...

3. Inside your bean, you can do "extra" security checks (if you used 'Role'-based
security): (Assuming you have a 'manager' role defined in your deployment
descriptor and a user assigned to this role)

public int getAccountBalance(accountId) {


if (ejbContext.isCallerInRole("manager"))
return balance;
}

You could also enforce security to your EJB server. Using Weblogic, you could add
the following to your weblogic.properties file:

...
weblogic.password.user=password
...

where "user" is the username you grant access for and "password" (after '=') is the
password for this username.

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

118. Can the primary key in the entity bean be a Java


primitive type such as int?
The primary key can't be a primitive type--use the primitive wrapper classes, instead. For
example, you can use java.lang.Integer as the primary key class, but not int (it has to be a
class, not a primitive).

119. How do I map a Date/Time field to an Oracle


database with CMP?
[Question continues: (I have written a wrapper class with the help of
java.util.GregorianCalendar but it doesn't store time in Oracle database, whereas it stores
Date without any problem.)]
Use the java.sql.Timestamp field to store your Date/Time in your entity bean, and then
declare the corresponding field as 'Date' type in the Oracle database and it will work fine.
You will have the "date" value and the "time" value preserved.

120. What is the difference between a Server, a Container,


and a Connector?
To keep things (very) simple:
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.
(Note: The EJB 1.1 specification makes it clear that it does not architect the interface
between the EJB container and EJB server, which it says it left up to the vendor on how to
split the implementation of the required functionality between the two. Thus there is no
clear distinction between server and container.)
A Connector provides the ability for any Enterprise Information System (EIS) to plug into
any EJB server which supports the Connector architecture.
121. What is "clustering" in EJB?
Clustering refers to the ability of multiple load-balanced web servers to share session and
entity data. It is a major feature of web application servers. Standardized support for
clustering was one of the primary motivations behind the EJB spec.
Clustering also applies to Servlet containers sharing HttpSession data (similar to EJB
Session Beans).

122. What is "hot deployment" in WebLogic?


"Hot Deployment" in weblogic is the act of deploying, re-depolying, and un-deploying EJBs
while the server is still running (you don't have to shutdown the server to deploy an EJB).

123. Can I specify specific WHERE clauses for a find


method in a CMP Entity Bean?
The EJB query language is totally vendor specific in EJB1.1. It is being standardized in 1.2.
Yes, you can specify the where clause for a find method. This is the example for EJB's
deployed on weblogic:

findBigAccounts(double balanceGreaterThan): "(> balance $balanceGreaterThan)"

where balance maps to some field in the table.

124. When using a stateful session bean with an idle


timeout set, how can the bean receive notification from the
container that it is being removed due to timeout?
[Question continues: ? (Through some tests, it looks like none of the standard EJB callback
methods are called when a stateful session bean is removed due to idle-timeout.)]
According to the spec, ejbRemove need not (or must not) be called in this case.
ejbPassivate is simply the Wrong Thing to be called (the bean is transitioning to the 'does
not exist' state, not the 'passive' state).
The EJB 1.1. spec says in section 6.6.3 Missed ejbRemove Calls:
• The application using the session bean should provide some clean up mechanism to
periodically clean up the unreleased resources.
• For example, if a shopping cart component is implemented as a session bean, and
the session bean stores the shopping cart content in a database, the application
should provide a program that runs periodically and removes “abandoned” shopping
carts from the database.

Probably not the answer you're looking for, especially if you allocate some other resource (a
Message Queue, for example) that you need to release. Although, if you're using a resource,
you really should be getting it when you need it (via JNDI) and returning it back to the pool
right away.
125. I have created a remote reference to an EJB in
FirstServlet. Can I put the reference in a servlet session
and use that in SecondServlet?
Yes.
The EJB client (in this case your servlet) acquires a remote reference to an EJB from the
Home Interface; that reference is serializable and can be passed from servlet to servlet.
If it is a session bean, then the EJB server will consider your web client's servlet session to
correspond to a single EJB session, which is usually (but not always) what you want.

126. What is the difference between a Component


Transaction Monitor (CTM) and an Application Server?
A Component Transaction Monitor (CTM) is an application server that uses a server-side
component model. Since a CTM is a Transaction Processing monitor (TP), it is expected to
provide services for managing transactions, security, and concurrency. In addition, CTMs
also facilitate distributed object architectures and provide facilities for object persistence. In
short, a CTM is a specific type of application server.

127. How can I call one EJB from inside of another EJB?
Just do it!
EJBs can be clients of other EJBs. It just works. Really. Use JNDI to locate the Home
Interface of the other bean, then acquire an instance reference, and so forth.

128. When using Primary Keys, why do I have to


implement the hashCode() and equals() method in my
bean?
Implementing the hashCode() and equals() functions ensure that the primary key object
works properly when used with hash tables. Hash tables are the preferred way EJB servers
use to store and quickly retrieve instantiated entity beans.
If session #1 uses widget "A" (which is an entity bean) then the server needs to do some
work to instantiate and initialize the object. If session #2 then requests the same widget
"A", the EJB server will look in its hash table of existing entity beans of type widget to see if
widget "A" has already been instantiated.

129. Can I deploy two beans in a single jar file? If so, how?
Yes, multiple EJBs can be deployed in a single jar file. The deployment is somewhat
different between EJB 1.0 and EJB 1.1.
In EJB 1.1 and in the draft EJB 2.0 specification, instead of a manifest and serialized
deployment descriptors there is a single shared XML deployment descriptor named META-
INF/ejb-jar.xml. Within ejb-jar.xml there must be either a <session> or <entity> element
for each bean in the jar file. For example, the following XML fragment is for a jar file that
contains one entity and one session bean:
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>MySessionBean</ejb-name>
... other xml elements describing the bean's deployment properties ...
</session>
<entity>
<ejb-name>MyEntityBean</ejb-name>
... other xml elements describing the bean's deployment properties ...
</entity>
</enterprise-beans>
</ejb-jar>

The EJB 2.0 draft specification for deployment descriptors differs from EJB 1.1 only in the
addition of XML elements for describing additional bean properties.

130. Why use EJB when we can do the same thing with
servlets?
Actually, servlets/JSPs and EJB are complementary, not competing technologies: Servlets
provide support for writing web based applications whereas EJBs provide support for writing
transactional objects. In larger web systems that require scalability, servlet and JSP or XML/
XSL technologies provide support for the front end (UI, client) code, where EJB provides
support for the back end (database connection pooling, declaritive transactions, declaritive
security, standardized parameterization...)
The most significant difference between a web application using only servlets and one using
servlets with EJBs is that the EJB model mandates a separation between display and
business logic. This is generally considered a Good Thing in non-trivial applications because
it allows for internal reuse, allows flexibility by providing a separation of concerns, gives a
logical separation for work, and allows the business logic to be tested separately from the
UI (among others).
Some of the hings that servlets and JSPs can do that EJBs cannot are:
• Respond to http/https protocol requests.
• (With JSP) provide an easy way to format HTML output.
• Easily associate a web user with session information
Some of the things that EJBs enable you to do that servlets/JSPs do not are:
• Declaritively manage transactions. In EJB, you merely specify whether a bean's
methods require, disallow, or can be used in the context of a transaction. The EJB
container will manage your transaction boundaries appropriately. In a purely servlet
architecture, you'll have to write code to manage the transaction, which is difficult if
a logical transaction must access multiple datasources.
• Declaritively manage security. The EJB model allows you to indicate a security role
that the user must be assigned to in order to invoke a method on a bean. In
Servlets/JSPs you must write code to do this. Note, however that the security model
in EJB is sufficient for only 90% to 95% of application code - there are always
security scenarios that require reference to values of an entity, etc.

131. What restrictions are imposed on an EJB? That is,


what can't an EJB do?
From the spec:
• An enterprise Bean must not use read/write static fields. Using read-only static
fields is allowed. Therefore, it is recommended that all static fields in the enterprise
bean class be declared as final.
• An enterprise Bean must not use thread synchronization primitives to synchronize
execution of multiple instances.
• An enterprise Bean must not use the AWT functionality to attempt to output
information to a display, or to input information from a keyboard.
• An enterprise bean must not use the java.io package to attempt to access files and
directories in the file system.
• An enterprise bean must not attempt to listen on a socket, accept connections on a
socket, or use a socket for multicast.
• 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. The enterprise bean must not
attempt to use the Reflection API to access information that the security rules of the
Java programming language make unavailable.
• The enterprise bean must not attempt to create a class loader; obtain the current
class loader; set the context class loader; set security manager; create a new
security manager; stop the JVM; or change the input, output, and error streams.
• The enterprise bean must not attempt to set the socket factory used by
ServerSocket, Socket, or the stream handler factory used by URL.
• The enterprise bean must not attempt to manage threads. The enterprise bean
must not attempt to start, stop, suspend, or resume a thread; or to change a
thread's priority or name. The enterprise bean must not attempt to manage thread
groups.
• The enterprise bean must not attempt to directly read or write a file descriptor.
• The enterprise bean must not attempt to obtain the security policy information for a
particular code source.
• The enterprise bean must not attempt to load a native library.
• The enterprise bean must not attempt to gain access to packages and classes that
the usual rules of the Java programming language make unavailable to the
enterprise bean.
• The enterprise bean must not attempt to define a class in a package.
• The enterprise bean must not attempt to access or modify the security configuration
objects (Policy, Security, Provider, Signer, and Identity).
• The enterprise bean must not attempt to use the subclass and object substitution
features of the Java Serialization Protocol.
The enterprise bean must not attempt to pass this as an argument or method result. The
enterprise bean must pass the result of SessionContext.getEJBObject() or EntityContext.
getEJBObject() instead.

132. 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 statefull) to inform the
container of your loss of interest in this bean.
133. Why is it that business methods should not be
declared final?
I believe that the basic reason is that mandating non-final business methods allows
container developers to implement their EJB container via inheritence. They can generate a
class that extends your bean, with methods that perform transactional housekeeping, then
call the inherited method (which is the one you wrote in your bean), then perform more
housekeeping.
That said, I know of no major container that does things this way (although some of the
OODBMS vendors may)

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

135. How can I pass init parameters to enterprise beans?


You can specify Environment Entries that are accesssible by your EJB's. Inside your ejb-
jar.xml you define the environment entries.

<env-entry>
<env-entry-name>theParameter</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>theValue</env-entry-value>
</env-entry>

You can access the variable inside your EJB using the Environment Naming Context (in EJB
1.1)

Context ctx = new InitialContext();


String val = (String)ctx.lookup("java:comp/env/theParameter");

136. Should I use CMP or BMP for an application with


complex data manipulation & relations?
Generally, you should use CMP unless you're forced to use BMP due to limitations of the
mapping tools. Also, "complex" is relative; some relatively complex data models can be
captured with mapping tools, but some cannot.
137. For session beans, we can use the
SessionSynchronization interface. For entity beans, how do
we have control over a transaction?
The SessionSynchronization interface is used by the Session beans to Synchronize the
Instance variables after a rollback or after a commit operation, because container does not
have any other way to inform the bean of these operations.
With Entity beans, this is not a problem as the Container automatically calls the ejbLoad
method that refreshed the values from the database.
JMS Interview Questions
1) What is JMS?
Java Message Service is the new standard for interclient communication. It allows J2EE
application components to create, send, receive, and read messages. It enables distributed
communication that is loosely coupled, reliable, and asynchronous.

2) What type messaging is provided by JMS


Both synchronous and asynchronous

3) How may messaging models do JMS provide for and


what are they?
JMS provides for two messaging models, publish-and-subscribe and point-to-point queuing.

4) What are the types of messaging?


There are two kinds of Messaging:
• Synchronous messaging involves a client that waits for the server to respond to a
message.
• Asynchronous messaging involves a client that does not wait for a message from
the server. An event is used to trigger a message from a server.

5) What is publish/subscribe messaging?


With publish/subscribe message passing the sending application/client establishes a named
topic in the JMS broker/server and publishes messages to this queue. The receiving clients
register (specifically, subscribe) via the broker to messages by topic; every subscriber to a
topic receives each message published to that topic. There is a one-to-many relationship
between the publishing client and the subscribing clients.

6) Why doesn’t the JMS API provide end-to-end


synchronous message delivery and notification of delivery?
Some messaging systems provide synchronous delivery to destinations as a mechanism for
implementing reliable applications. Some systems provide clients with various forms of
delivery notification so that the clients can detect dropped or ignored messages. This is not
the model defined by the JMS API. JMS API messaging provides guaranteed delivery via the
once-and-only-once delivery semantics of PERSISTENT messages. In addition, message
consumers can insure reliable processing of messages by using either
CLIENT_ACKNOWLEDGE mode or transacted sessions. This achieves reliable delivery with
minimum synchronization and is the enterprise messaging model most vendors and
developers prefer. The JMS API does not define a schema of systems messages (such as
delivery notifications). If an application requires acknowledgment of message receipt, it can
define an application-level acknowledgment message.

7) What are the core JMS-related objects required for each


JMS-enabled application?
Each JMS-enabled client must establish the following:
• A connection object provided by the JMS server (the message broker)
• Within a connection, one or more sessions, which provide a context for message
sending and receiving
• Within a session, either a queue or topic object representing the destination (the
message staging area) within the message broker
• Within a session, the appropriate sender or publisher or receiver or subscriber
object (depending on whether the client is a message producer or consumer and
uses a point-to-point or publish/subscribe strategy, respectively). Within a session,
a message object (to send or to receive)

8) What is the Role of the JMS Provider?


The JMS provider handles security of the messages, data conversion and the client
triggering. The JMS provider specifies the level of encryption and the security level of the
message, the best data type for the non-JMS client.

9) How does a typical client perform the communication?


1. Use JNDI to locate administrative objects.
2. Locate a single ConnectionFactory object.
3. Locate one or more Destination objects.
4. Use the ConnectionFactory to create a JMS Connection.
5. Use the Connection to create one or more Session(s).
6. Use a Session and the Destinations to create the MessageProducers and
MessageConsumers needed.
7. Perform your communication.

10) Give an example of using the point-to-point model.


The point-to-point model is used when the information is specific to a single client. For
example, a client can send a message for a print out, and the server can send information
back to this client after completion of the print job.

11) Does Tomcat support JMS (Java Messaging Service)?


Tomcat is just a servlet container, not an EJB container nor an application server, so it does
not contains any JMS basic support. However, there's nothing stopping you from using
another JMS provider.
12) Is it possible to send email messages using JMS?
JMS has no inherent support for email operations.

13)How do I communicate between two clients that are on


different machines on a network using JMS? I want to use
a standalone application for communicating between the
machine and I want to pass the message using JMS.
You can make two JMS client applications, say AppA and AppB. Make AppA listen to topic
‘forA’. Make AppB listen to topic ‘forB’.
If AppA sends a message to topic ‘forB’, AppB will receive it. If AppB sends a message to
topic ‘forA’, AppA will receive it.
For sample code etc, try downloading SonicMQ (as a JMS server) and go through the
samples.

14)Is there any relationship between javax.jms.Message


and javax.mail.Message?
There is no direct relationship between javax.mail.Message and javax.jms.Message. If your
requirement is to map (correlate) them, here is what you can do:
1. From JMS domain to JavaMail domain (a javax.jms.Message is received):
1. A JMS topic/queue can be associated with one or many e-mail id(s).
2. The JMS Message Header can be mapped to ‘custom’ JavaMail Message
Header.
3. The JMS Message Body can be associated with the JavaMail Message body.
4. A JavaMail client application should be able to process these ‘custom’
headers and the content of the message body.
2. From JavaMail domain to JMS domain (a javax.mail.Message is received):
1. An e-mail id can be associated with one or more JMS topics/queues.
2. The JavaMail Message Header can be mapped to ‘custom’ JMS Message
Header.
3. The JavaMail Message Body can be associated with the JMS Message body.
4. The JMS client application should be able to process these ‘custom’ headers
and the content of the message body.
In a simple application that I tried, I removed the ‘custom’ header scenario and just
forwarded the contents of the message (text message), which worked without any
problems.Try using SonicMQ bridges, which already has something like that.

15) Is it possible to acknowledge individual messages on a


queue without affecting previously received, but as yet
unacknowledged, messages?
If you acknowledge a message, all previously received messages will also be acknowledged.
From the javax.jms.Message Javadoc, the acknowledge method will "Acknowledge this and
all previous messages received."
So the answer to your question is no, if what you meant by "affecting" is not-yet
acknowledged.
I suggest an alternative. You should look at javax.jms.QueueBrowser to review queued
messages. QueueBrowser has getEnumeration, which "Gets an enumeration for browsing
the current queue messages in the order they would be received".

16) What encryption options are there for sending


messages through JMS?
Encryption is not handled by the JMS specification. It is left to the JMS provider to
implement and provide encryption and decryption of messages. These days, Progress
Software’s SonicMQ is a leading JMS provider and they have a robust encryption mechanism
called Quality of Protection. They also provide an SSL-related feature, which also has build
in encryption.

17) How does the Application server handle the JMS


Connection?
1. Application server creates the server session and stores them in a pool.
2. Connection consumer uses the server session to put messages in the session of the
JMS.
3. Server session is the one that spawns the JMS session.
4. Applications written by Application programmers creates the message listener.
J2EE Interview Questions
1) 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 multi tiered, and web-based
applications.

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

3) 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.
TM TM
• Java Servlets and Java Server Pages (JSP ) technology components are web
components.
TM TM
• Enterprise JavaBeans (EJB ) components (enterprise beans) are business
components.
• Resource adapter components provided by EIS and tool vendors.

4) What are the four types of J2EE modules?


1. Application client module
2. Web module
3. Enterprise JavaBeans module
4. Resource adapter module

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

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

8) How many development roles are involved in J2EE


application?
There are at least 5 roles involved:
1. 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
2. Web Component Developer
◦ Writes and compiles Servlets 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
3. 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
4. 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
5. 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.
9) 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) plug ability. 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.
10) 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.

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

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

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

14) What is the web container?


Servlet and JSP containers are collectively referred to as Web containers.

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

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

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

19) What are JTA and JTS?


JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Java
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 EJBs 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.

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

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

22) What is JAAP?


The Java Authentication and Authorization Service (JAAS) provide 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.

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

24) What is Model 2?


Using JSP and Servlet together to develop Web page. Model 2 applications are easier to
maintain and extend, because views do not refer to each other directly.

25) What is Struts?


A Web page development framework. Struts combine 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.

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

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

28) Is J2EE a super set of J2SE?


Yes

29) 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.
30) 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 Servlets 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 Processing(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)
JavaServer Faces Interview Questions
1) What is JSF?
JSF stands for Java Server Faces. JSF has set of pre-assembled User Interface (UI). By this
it means complex components are pre-coded and can be used with ease. It is event-driven
programming model. By that it means that JSF has all necessary code for event handling
and component organization. Application programmers can concentrate on application logic
rather sending effort on these issues. It has component model that enables third-party
components to be added like AJAX.

2) What is required for JSF to get started?


Following things required for JSF:
• JDK (Java SE Development Kit)
• JSF 1.2
• Application Server (Tomcat or any standard application server)
• Integrated Development Environment (IDE) Ex. Netbeans 5.5, Eclipse 3.2.x, etc.
Once JDK and Application Server is downloaded and configured, one can copy the JSF jar
files to JSF project and could just start coding. :-)
If IDE is used, it will make things very smooth and will save your time.

3) What is JSF architecture?


JSF was developed using MVC (a.k.a Model View Controller) design pattern so that
applications can be scaled better with greater maintainability. It is driven by Java
Community Process (JCP) and has become a standard. The advantage of JSF is that it’s
both a Java Web user – interface and a framework that fits well with the MVC. It provides
clean separation between presentation and behavior. UI (a.k.a User Interface) can be
created by page author using reusable UI components and business logic part can be
implemented using managed beans.

4) How JSF different from conventional JSP / Servlet


Model?
JSF much more plumbing that JSP developers have to implement by hand, such as page
navigation and validation. One can think of JSP and servlets as the “assembly
language� under the hood of the high-level JSF framework.

5) How the components of JSF are rendered? An Example


In an application add the JSF libraries. Further in the .jsp page one has to add the tag
library like:

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>


<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
Or one can try XML style as well:

<?xml version="1.0"?>
<jsp:root version="2.0" xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">

Once this is done, one can access the JSF components using the prefix attached. If working
with an IDE (a.k.a Integrated Development Environment) one can easily add JSF but when
working without them one also has to update/make the faces-config.xml and have to
populate the file with classes i.e. Managed Beans between

<faces-config> </faces-config> tags

6) How to declare the Navigation Rules for JSF?


Navigation rules tells JSF implementation which page to send back to the browser after a
form has been submitted. For ex. for a login page, after the login gets successful, it should
go to Main page, else to return on the same login page, for that we have to code as:

<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-outcome>login</from-outcome>
<to-view-id>/main.jsp<to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>fail</from-outcome>
<to-view-id>/login.jsp<to-view-id>
</navigation-case>
</navigation-rule>

from-outcome to be match with action attribute of the command button of the login.jsp as:

<h:commandbutton value="Login" action="login"/>

Secondly, it should also match with the navigation rule in face-config.xml as

<managed-bean>
<managed-bean-name>user</managed-bean-name>
<managed-bean-class>core.jsf.LoginBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>

In the UI component, to be declared / used as:

<h:inputText value="#{user.name}"/>

value attribute refers to name property of the user bean.


7) How do I configure the configuration file?
The configuration file used is our old web.xml, if we use some IDE it will be pretty simple to
generate but the contents will be something like below:

<?xml version=&quote;1.0&quote; encoding=&quote;UTF-8&quote;?>

<web-app version=&quote;2.4&quote; xmlns=&quote;http://java.sun.com/xml/ns/j2ee&qu


xmlns:xsi=&quote;http://www.w3.org/2001/XMLSchema-instance&quote;
xsi:schemaLocation=&quote;http://java.sun.com/xml/ns/j2ee http://java.sun.
<context-param>
<param-name>com.sun.faces.verifyObjects</param-name>
<param-value>false</param-value>
</context-param>

<context-param>
<param-name>com.sun.faces.validateXml</param-name>
<param-value>true</param-value>
</context-param>

<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>

<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>

<session-config>
<session-timeout>
30
</session-timeout>
</session-config>

<welcome-file-list>
<welcome-file>
index.jsp
</welcome-file>
</welcome-file-list>
</web-app>

The unique thing about this file is ?servlet mapping?. JSF pages are processed by a servlet
known to be part of JSF implementation code. In the example above, it has extension of
.faces. It would be wrong to point your browser to http://localhost:8080/MyJSF/login.jsp,
but it has to be http://localhost:8080/MyJSF/login.faces. If you want that your pages to be
with .jsf, it can be done with small modification :-),

<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>

<servlet-mapping>

8) What is JSF framework?


JSF framework can be explained with the following diagram:

As can be seen in Figure 1, JSF interacts with Client Devices which ties together with
presentation, navigation and event handling and business logic of web tier model. Hence
JSF is limited to presentation logic / tier. For Database tier i.e. Database and Web services
one has to rely on other services.

9) How does JSF depict the MVC (a.k.a Model View


Controller) model?
The data that is manipulated in form or the other is done by model. The data presented to
user in one form or the other is done by view. JSF is connects the view and the model. View
can be depicted as shown by:

<h:inputText value="#{user.name}"/>

JSF acts as controller by way of action processing done by the user or triggering of an
event. For ex.

<h:commandbutton value="Login" action="login"/>

, this button event will triggered by the user on Button press, which will invoke the login
Bean as stated in the faces-config.xml file. Hence, it could be summarized as below: User
Button Click -> form submission to server -> invocation of Bean class -> result thrown by
Bean class caught be navigation rule -> navigation rule based on action directs to specific
page.

10) What does it mean by rendering of page in JSF?


Every JSF page as described has various components made with the help of JSF library. JSF
may contain h:form, h:inputText, h:commandButton, etc. Each of these are rendered
(translated) to HTML output. This process is called encoding. The encoding procedure also
assigns each component with a unique ID assigned by framework. The ID generated is
random.
11) What is JavaServer Faces?
JavaServer Faces (JSF) is a user interface (UI) framework for Java web applications. It is
designed to significantly ease the burden of writing and maintaining applications that run on
a Java application server and render their UIs back to a target client. JSF provides ease-of-
use in the following ways:
• Makes it easy to construct a UI from a set of reusable UI components
• Simplifies migration of application data to and from the UI
• Helps manage UI state across server requests
• Provides a simple model for wiring client-generated events to server-side application
code
• Allows custom UI components to be easily built and re-used
Most importantly, JSF establishes standards which are designed to be leveraged by tools to
provide a developer experience which is accessible to a wide variety of developer types,
ranging from corporate developers to systems programmers. A "corporate developer" is
characterized as an individual who is proficient in writing procedural code and business
logic, but is not necessarily skilled in object-oriented programming. A "systems
programmer" understands object-oriented fundamentals, including abstraction and
designing for re-use. A corporate developer typically relies on tools for development, while a
system programmer may define his or her tool as a text editor for writing code. Therefore,
JSF is designed to be tooled, but also exposes the framework and programming model as
APIs so that it can be used outside of tools, as is sometimes required by systems
programmers.

12) How to pass a parameter to the JSF application using


the URL string?
if you have the following URL: http://your_server/your_app/product.jsf?id=777, you access
the passing parameter id with the following lines of java code:

FacesContext fc = FacesContext.getCurrentInstance();
String id = (String) fc.getExternalContext().getRequestParameterMap().get("id");

From the page, you can access the same parameter using the predefined variable with
name param. For example,

<h:outputText value="#{param['id']}" />

Note: You have to call the jsf page directly and using the servlet mapping.

13) How to add context path to URL for outputLink?


Current JSF implementation does not add the context path for outputLink if the defined path
starts with '/'. To correct this problem use
#{facesContext.externalContext.requestContextPath} prefix at the beginning of the
outputLink value attribute. For example:

<h:outputLink value="#{facesContext.externalContext.requestContextPath}/myPage.fac
14) How to get current page URL from backing bean?
You can get a reference to the HTTP request object via FacesContext like this:

FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getReque

and then use the normal request methods to obtain path information. Alternatively,

context.getViewRoot().getViewId();

will return you the name of the current JSP (JSF view IDs are basically just JSP path
names).

15) How to access web.xml init parameters from java


code?
You can get it using externalContext getInitParameter method. For example, if you have:

<context-param>
<param-name>connectionString</param-name>
<param-value>jdbc:oracle:thin:scott/tiger@cartman:1521:O901DB</param-value>
</context-param>

You can access this connection string with:

FacesContext fc = FacesContext.getCurrentInstance();
String connection = fc.getExternalContext().getInitParameter("connectionString");

16) How to access web.xml init parameters from jsp page?


You can get it using initParam pre-defined JSF EL valiable.
For example, if you have:

<context-param>
<param-name>productId</param-name>
<param-value>2004Q4</param-value>
</context-param>

You can access this parameter with #{initParam['productId']} . For example:

Product Id: <h:outputText value="#{initParam['productId']}"/>

17) How to terminate the session?


In order to terminate the session you can use session invalidate method.
This is an example how to terminate the session from the action method of a backing bean:

public String logout() {


FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
session.invalidate();
return "login_page";
}

The following code snippet allows to terminate the session from the jsp page:

<% session.invalidate(); %> <c:redirect url="loginPage.jsf" />

18) How to implement "Please, Wait..." page?


The client-side solution might be very simple. You can wrap the jsp page (or part of it you
want to hide) into the DIV, then you can add one more DIV that appears when user clicks
the submit button. This DIV can contain the animated gif you speak about or any other
content.
Scenario: when user clicks the button, the JavaScript function is called. This function hides
the page and shows the "Wait" DIV. You can customize the look-n-fill with CSS if you like.
This is a working example:

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>


<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="demo.bundle.Messages" var="Message"/>

<html>
<head>
<title>Input Name Page</title>
<script>
function gowait() {
document.getElementById("main").style.visibility="hidden";
document.getElementById("wait").style.visibility="visible";
}
</script>
</head>

<body bgcolor="white">
<f:view>
<div id="main">
<h1><h:outputText value="#{Message.inputname_header}"/></h1>
<h:messages style="color: red"/>
<h:form id="helloForm">
<h:outputText value="#{Message.prompt}"/>
<h:inputText id="userName" value="#{GetNameBean.userName}" required="true
<f:validateLength minimum="2" maximum="20"/>
</h:inputText>
<h:commandButton onclick="gowait()" id="submit" action="#{GetNameBean.act
</h:form>
</div>
<div id="wait" style="visibility:hidden; position: absolute; top: 0; left: 0">
<table width="100%" height ="300px">
<tr>
<td align="center" valign="middle">
<h2>Please, wait...</h2>
</td>
</tr>
</table>
</div>
</f:view>
</body>
</html>

If you want to have an animated gif of the "Wait" Page, the gif should be reloaded after the
form is just submitted. So, assign the id for your image and then add reload code that will
be called after some short delay. For the example above, it might be:

<script>
function gowait() {
document.getElementById("main").style.visibility="hidden";
document.getElementById("wait").style.visibility="visible";
window.setTimeout('showProgress()', 500);
}
function showProgress(){
var wg = document.getElementById("waitgif");
wg.src=wg.src;
}
</script>
....
....
....

<img id="waitgif" src="animated.gif">

19) How to reload the page after ValueChangeListener is


invoked?
At the end of the ValueChangeListener, call
FacesContext.getCurrentInstance().renderResponse()

20) How to download PDF file with JSF?


This is an code example how it can be done with action listener of the backing bean.
Add the following method to the backing bean:

public void viewPdf(ActionEvent event) {


String filename = "filename.pdf";

// use your own method that reads file to the byte array
byte[] pdf = getTheContentOfTheFile(filename);

FacesContext faces = FacesContext.getCurrentInstance();


HttpServletResponse response = (HttpServletResponse) faces.getExternalContext()
response.setContentType("application/pdf");
response.setContentLength(pdf.length);
response.setHeader( "Content-disposition", "inline; filename=\""+fileName+"\"")
try {
ServletOutputStream out;
out = response.getOutputStream();
out.write(pdf);
} catch (IOException e) {
e.printStackTrace();
}
faces.responseComplete();
}

This is a jsp file snippet:

<h:commandButton immediate="true" actionListener="#{backingBean.viewPdf}" value="R

21) How to show Confirmation Dialog when user Click the


Command Link?
h:commandLink assign the onclick attribute for internal use. So, you cannot use it to write
your own code. This problem will fixed in the JSF 1.2. For the current JSF version you can
use onmousedown event that occurs before onclick. <script language="javascript">
function ConfirmDelete(link) { var delete = confirm('Do you want to Delete?'); if (delete ==
true) { link.onclick(); } } </script> . . . . <h:commandLink action="delete"
onmousedown="return ConfirmDelete(this);"> <h:outputText value="delete it"/>
</h:commandLink>

22) What is the different between


getRequestParameterMap() and
getRequestParameterValuesMap()
getRequestParameterValuesMap() similar to getRequestParameterMap(), but contains
multiple values for for the parameters with the same name. It is important if you one of the
components such as <h:selectMany>.

23) Is it possible to have more than one Faces


Configuration file?
Yes. You can define the list of the configuration files in the web.xml.
This is an example:

<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config-navigation.xml,/WEB-INF/faces-beans.xml</par
</context-param>

Note: Do not register /WEB-INF/faces-config.xml file in the web.xml . Otherwise, the JSF
implementation will process it twice.
Hi there, I guess the Note: column should have been meant or intended for "faces-
config.xml" file as thats the default configuration file for JSF (which is similar to struts-
config.xml for Struts!!). faces-context.xml file sounds like the user defined config file similar
to the aforementioned two xml files.
24) How to mask actual URL to the JSF page?
You'll need to implement your own version of javax.faces.ViewHandler which does what you
need. Then, you register your own view handler in faces-config.xml.
Here's a simple abstract ViewHandler you can extend and then implement the 3 abstract
methods for. The abstract methods you override here are where you'll do your conversions
to/from URI to physical paths on the file system. This information is just passed right along
to the default ViewHandler for JSF to deal with in the usual way. For example, you could
override these methods to add and remove the file extension of an incoming view id (like in
your example), for extension-less view URIs.

import java.io.IOException;
import java.util.Locale;

import javax.faces.FacesException;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* A facade view handler which maps URIs into actual physical views that the
* underlying implementation can deal with regularly.
* Therefore, all internal references to view ids, for example in faces-config,
* will use the path to the physical files. Everything publicized, however, will
* see a "converted" / facade url.
*/
public abstract class SimpleConverterViewHandler extends ViewHandler {
private static final Log LOG = LogFactory.getLog(SimpleConverterViewHandler.cla

private final ViewHandler base;

public SimpleConverterViewHandler(ViewHandler base) {


this.base = base;
}

/**
* Distinguishes a URI from a physical file view.
* Tests if a view id is in the expected format -- the format corresponding
* to the physical file views, as opposed to the URIs.
* This test is necessary because JSF takes the view ID from the
* faces-config navigation, and calls renderView() on it, etc.
*/
public abstract boolean isViewFormat(FacesContext context, String viewId);

/**
* Convert a private file path (view id) into a public URI.
*/
public abstract String convertViewToURI(FacesContext context, String viewId);

/**
* Convert a public URI into a private file path (view id)
* note: uri always starts with "/";
*/
public abstract String convertURIToView(FacesContext context, String uri);

public String getActionURL(FacesContext context, String viewId) {


// NOTE: this is used for FORM actions.

String newViewId = convertViewToURI(context, viewId);


LOG.debug("getViewIdPath: " + viewId + "->" + newViewId);
return base.getActionURL(context, newViewId);
}

private String doConvertURIToView(FacesContext context, String requestURI) {


if (isViewFormat(context, requestURI)) {
return requestURI;
} else {
return convertURIToView(context, requestURI);
}
}

public void renderView(FacesContext context, UIViewRoot viewToRender)


throws IOException, FacesException {
if (null == context || null == viewToRender)
throw new NullPointerException("null context or view");

String requestURI = viewToRender.getViewId();


String newViewId = doConvertURIToView(context, requestURI);
LOG.debug("renderView: " + requestURI + "->" + newViewId);
viewToRender.setViewId(newViewId);

base.renderView(context, viewToRender);
}

public UIViewRoot restoreView(FacesContext context, String viewId) {


String newViewId = doConvertURIToView(context, viewId);
LOG.debug("restoreView: " + viewId + "->" + newViewId);
return base.restoreView(context, newViewId);
}

public Locale calculateLocale(FacesContext arg0) {


return base.calculateLocale(arg0);
}

public String calculateRenderKitId(FacesContext arg0) {


return base.calculateRenderKitId(arg0);
}

public UIViewRoot createView(FacesContext arg0, String arg1) {


return base.createView(arg0, arg1);
}

public String getResourceURL(FacesContext arg0, String arg1) {


return base.getResourceURL(arg0, arg1);
}

public void writeState(FacesContext arg0) throws IOException {


base.writeState(arg0);
}

25) How to print out html markup with h:outputText?


The h:outputText has attribute escape that allows to escape the html markup. By default, it
equals to "true". It means all the special symbols will be replaced with '&' codes. If you set
it to "false", the text will be printed out without ecsaping.

For example, <h:outputText value="<b>This is a text</b>"/>

will be printed out like:

<b>This is a text</b>

In case of <h:outputText escape="false" value="<b>This is a text</b>"/>

you will get:

This is a text

26) h:inputSecret field becomes empty when page is


reloaded. How to fix this?
Set redisplay=true, it is false by default.
Jboss Seam Interview Questions
1) What version of JBoss AS do I need to run Seam?
• For Seam 1.3: Seam was developed against JBoss 4.2. Seam can still be run
against JBoss 4.0. The seam documentation contains instructions for configuring
JBoss 4.0.
• For Seam 1.2: Since Seam requires the latest edition of EJB3, you need to install
JBoss AS from the latest JEMS installer. Make sure that you select the "ejb3" or
"ejb3+clustering" profile to include EJB3 support. Also, the jboss-seam.jar library
file from the Seam distribution must be included in each Seam application you
deploy. Refer to examples in Seam distribution (inside the examples directory) to
see how to build and package Seam applications.

2) Can I run Seam outside of JBoss AS?


Yes, you can run Seam applications in plain Tomcat 5.5+ or in the Sun GlassFish application
server. To run Seam application in Tomcat, you need a number of additional library files and
a few configuration files to bootstrap the JBoss EJB3 inside Tomcat. Please refer to the
deploy.tomcat ANT build target for the Seam booking example (in the examples/booking
directory of the Seam distribution) for more on how to build a Tomcat WAR for Seam
applications. Refer to this blog post on how to run Seam in Sun's Glassfish application
server.

3) Can I run Seam in a J2EE environment?


Yes, as of Seam 1.1, you can use Seam in any J2EE application server, with one caveat: you
will not be able to use EJB 3.0 session beans. However, you can use either Hibernate or JPA
for persistence, and you can use Seam JavaBean components instead of session beans.

4) Can I run Seam with JDK 1.4 and earlier?


No, Seam only works on JDK 5.0 and above. It uses annotations and other JDK 5.0
features.

5) Where can I find Seam examples and documentation?


The source code and build script of all Seam example applications are included in the
examples directory of the Seam distribution. Seam documentation is available here.

6) Where can I ask questions and make suggestions about


Seam?
Please use the Seam User's discussion forum for user questions.
7) Are there books about Seam?
Yes, Prentice Hall's "JBoss Seam: Simplicity and Power Beyond Java EE 5.0" is a
comprehensive guide for Seam written by JBoss insiders.

8) Is it true that Seam only works with JSF?


Seam only supports JSF as a view framework at this time. We plan to support other web
frameworks in the future. We like JSF because it is a component-based UI framework, which
fits really well with Seam's component-based approach to business objects and persistence
objects. Seam made a major improvement to JSF by eliminating almost all XML
configuration for backing beans -- you can now define back beans from POJOs or EJB3
components using simple annotations. We recommend you use Facelets, instead of JSP,
with JSF. Facelets provide a powerful templating framework, better appplication
performance, and allows us to write much simpler JSF pages. Please see the Seam booking
example application for an example on how to use Facelets.

9) Can I use AJAX with Seam?


Yes, Seam provides excellent support for AJAX. First, Seam supports the ICEfaces and
Ajax4JSF Ajax component libraries for JSF. If you prefer a more "old fashioned" approach,
Seam provides a complete JavaScript remoting framework which lets you call Seam
components and subscribe to JMS topics directly from the client. Please refer to the Seam
remoting example application on how to use AJAX remoting to implement a chat room.
Finally, Seam's concurrency model is designed especially for use with Ajax.

10) Can I unit test Seam applications without starting the


Application Server?
Yes, Seam provides its own integration test framework based on TestNG. You can easily
mock all Seam services using those facilities without ever loading an application server or a
database. Refer to the testexample ANT target in the Seam booking example application for
more details.

11) What's so special about Seam's "state management"?


Most other web frameworks store all application state in the HTTP session, which is
inflexible, difficult to manage and a major source of memory leak. Seam can manage
business and persistence components in several stateful scopes: components that only need
to live across several pages are placed in the conversation scope; components that need to
live with the current user session are placed in the session scope; components that require
interactions from multiple users and last extended period of time (i.e., survive server
reboots) are placed in the business process scope. The advanced state management
facilities allow us to develop web application features that are previously not possible, or
very difficult, to implement.
12) Does Seam support multiple browser windows or tabs?
Yes. Seam supports fine-grained user state management beyond the simple HTTP session.
It isolates and manages user state associated with individual browser window or tab (in
contrast, HTTP session is shared across all windows of the same browser). So, in a Seam
application, each browser window / tab can become a separate workspace that has
independent history and context. Multiple user "conversations" can be supported for the
same browser. This behavior is similar to that in rich client applications. To see this feature
in action, just run the booking example application and try to book several hotels via
several browser tabs in parallel -- you can see that each tabs retains its own progress in the
booking conversation.

13) Can Seam handle back-button navigation?


Seam's nested conversation model makes it really easy to build complex, stateful
applications that tolerate use of the back button.

14) Does Seam support REST style bookmarkable URLs?


Yes, it is very easy to expose REST style bookmarkable URLs in a Seam application. In
addition, the Seam application can initialize all the necessary backend business logic and
persistence components when the user loads that URL. This way, the RESTful URL is not
only an information endpoint but also an application interaction start point.

15) I heard Seam conversations are propagated through


JSF POST request. Can I do redirect-after-post or even GET
in the same conversation?
Yes, on both accounts! To use redirect-after-post, you just need to enable the
SeamRedirectFilter in web.xml. To propagate a conversation through a GET request, pass
the conversation id in a request parameter named conversationId. By default, GET (non-
faces) requests always occur in a new conversation.

16) Can I use Seam in a portal?


Seam 1.0 features full integration with JSR-168 compliant portals such as JBoss Portal.

17) Does Seam have something like the Ruby on Rails


"flash" object?
No, Seam has something much more powerful: a conversation context. The Seam
conversation context is propagated across redirects (even when no long-running
conversation is in progress), so you can use the conversation context to store success
messages and the like.
18) Does Seam have continuations?
A jBPM "wait state" is a continuation. Each node in a pageflow definition or node in a
business process definition is a jBPM wait state. Speaking more approximately, you might
like to think of the conversation state as a continuation. (We do not usually talk in this kind
of language because it is too mysterious-sounding and obfuscates simple concepts to make
them seem more impressive.)

19) Does Seam support internationalization?


Seam includes several extensions to JSF that make it super-easy and super-elegant to
create internationalized user interfaces.

20) Are there any development tools that support Seam?


Seam 1.1 includes a Ruby on Rails style command line tool that makes it easy to set up a
new Seam project, create some simple actions, and even reverse engineer a data driven
application from an existing database.
IDE integration is also a major focus for us. JBoss Eclipse IDE provides a sophisticated,
template-driven database reverse engineering tool which can generate an entire Seam
application in minutes and a graphical jPDL editor for editing Seam pageflows and workflow
definitions. More to come, stay tuned.

You might also like