You are on page 1of 158

Question What is the difference between an Applet and an Application?

(Applets)
The differences between an applet and an application are as follows:

1. Applets can be embedded in HTML pages and downloaded over the


Internet whereas
Applications have no special support in HTML for embedding or
downloading.

2. Applets can only be executed inside a java compatible container, such as


a browser
or appletviewer whereas Applications are executed at command line by
java.exe or jview.exe.
Answer
3. Applets execute under strict security limitations that disallow certain
operations
(sandbox model security) whereas Applications have no inherent security
restrictions.

4. Applets don't have the main() method as in applications. Instead they


operate on an
entirely different mechanism where they are initialized by init(),started by
start(),stopped
by stop() or destroyed by destroy().

Question What are the Applet's Life Cycle methods? Explain them? (Applets)

Following are methods in the life cycle of an Applet:

init() method - called when an applet is first loaded. This method is called
only once in the entire cycle of an applet. This method usually intialize
the variables to be used in the applet

start() method - called each time an applet is started


Answer
paint() method - called when the applet is minimized or refreshed. This
method is used for drawing different strings, figures, and images on the
applet
window

stop() method - called when the browser moves off the applet’s page

destroy() method - called when the browser is finished with the applet

Question What is the sequence for calling the methods by AWT for applets? (Applets)
Answer When an applet begins, the AWT calls the following methods, in this
sequence:
init()

start()

paint()
When an applet is terminated, the following sequence of method calls
takes place

stop()

destroy()

Question How are the differences between Applets and Applications? (Applets)

Application:

-Applications are Stand Alone and do not need web-browser.


-Execution starts with main().
-May or may not be a GUI.

Answer
Applets

-Needs no explicit installation on local machine. Can be transferred through


Internet on to the local machine and may run as part of web-browser.
-Execution starts with init() method. Must run within a GUI (Using AWT /
Swing)

Question How do we pass a parameter from HTML page to Applet? (Applets)


[html]
[applet code="Launch.class" archive="bak.jar" width=740 height=460]
[param name="lang" value="English"]
[/applet]
Answer [/html]

And within the init() of your applet, Use the following line to get the value.

String langs = getParameter("lang");

When an user wants to send an int from HTML what does he needs to
Question
do? (Applets)
Either the user wants to send an int or a String, it will be the same. Here
are steps he might do to get an int

[html]
[applet code="Launch.class" archive="bak.jar" width=740 height=460]
[param name="mynum" value="098765"]
Answer [/applet]
[/html]

And within the init() of your applet, Use the following line to get the value.

String mynum = getParameter("mynum");


int x = Integer.parseInt(mynum);
How can I arrange for different applets on a web page to communicate
Question
with each other? (Applets)
Name your applets inside the Applet tag and invoke AppletContext’s
getApplet() method in your applet code to obtain references to the other
Answer
applets
on the page

Question How do I go from my applet to another JSP or HTML page? (Applets)


Use AppletContext and invoke showDocument() on that context object.
Below is sample code

URL targetURL;
String URLString = "http://localhost:8080/mypage.jsp";
AppletContext context = getAppletContext();
try
Answer {
targetURL = new URL(URLString);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
context.showDocument(targetURL);

Question How do I determine the width and height of my application? (Applets)


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

Dimension dim = getSize();


int appletwidth = dim.width();
int appletheight = dim.height();

Question Which classes and interfaces does Applet class consist? (Applets)
Applet class consists of a single class, the Applet class and three
Answer
interfaces: AppletContext, AppletStub, and AudioClip

Question What is AppletStub Interface? (Applets)


The applet stub interface provides the means by which an applet and the
Answer
browser communicate. Your code will not typically implement this interface

What tags are mandatory when creating HTML to display an


Question
applet? (Applets)
Answer code, height, width

Question What are the methods to retrive information about an applet? (Applets)
getAppletInfo() : Returns a string describing the applet, its author,
copyright information, etc.
Answer
getParameterInfo( ) method: Returns an array of string describing the
applet’s parameters

Question If you need to display a String on the applet, what would you do? (Applets)
drawString() is used to output a String to an applet. This method is
Answer
included in the paint() of the Applet

Question
How do you play audio clips without using applet class? (Applets)
You can do this using Java Media Framework. I dont have much context
Answer
on this API.

Question which containers use a border Layout as their default layout? (AWT)
The window, Frame and Dialog classes use a border layout as their
Answer
default layout

Question What is the preferred size of a component? (AWT)


The preferred size of a component is the minimum component size that
Answer
will allow the component to display normally

Question Which containers use a FlowLayout as their default layout? (AWT)


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

Question What is the immediate superclass of the Applet class? (AWT)

Answer Panel

Question Name three Component subclasses that support painting (AWT)


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

Question What is the immediate superclass of the Dialog class? (AWT)

Answer Window

Question What is clipping? (AWT)


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

What is the difference between a MenuItem and a


Question
CheckboxMenuItem? (AWT)
The CheckboxMenuItem class extends the MenuItem class to support a
Answer
menu item that may be checked or unchecked

Question What class is the top of the AWT event hierarchy? (AWT)
The java.awt.AWTEvent class is the highest-level class in the AWT event-
Answer
class hierarchy

In which package are most of the AWT events that support the event-
Question
delegation model defined? (AWT)
Most of the AWT-related events of the event-delegation model are
Answer defined in the java.awt.event package. The AWTEvent class is defined in
the java.awt package.

Which class is the immediate superclass of the MenuComponent


Question
class (AWT)
Answer Object

Question Which containers may have a MenuBar? (AWT)

Answer Frame

What is the relationship between the Canvas class and the Graphics
Question
class? (AWT)
A Canvas object provides access to a Graphics object via its paint()
Answer
method.

Question How are the elements of a BorderLayout organized? (AWT)


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

Question What is the difference between a Window and a Frame? (AWT)


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

Question What is the difference between the Font and FontMetrics classes? (AWT)
The FontMetrics class is used to define implementation-specific properties,
Answer
such as ascent and descent, of a Font object.

Question How are the elements of a CardLayout organized? (AWT)


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

Question What is the relationship between clipping and repainting? (AWT)


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

What is the relationship between an event-listener interface and an


Question
event-adapter class? (AWT)
Answer 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.

Question How can a GUI component handle its own events? (AWT)
A component can handle its own events by implementing the required
Answer
event-listener interface and adding itself as its own event listener.

Question How are the elements of a GridBagLayout organized? (AWT)


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

What advantage do Java's layout managers provide over traditional


Question
windowing systems? (AWT)
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
Answer
absolute sizing and positioning, they are able to accomodate platform-
specific differences among windowing systems.

Question What is the difference between the paint() and repaint() methods? (AWT)
The paint() method supports painting via a Graphics object. The repaint()
Answer
method is used to cause paint() to be invoked by the AWT painting thread.

Question How can the Checkbox class be used to create a radio button? (AWT)

Answer By associating Checkbox objects with a CheckboxGroup

Question What is the difference between a Choice and a List? (AWT)


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

Question What interface is extended by AWT event listeners? (AWT)


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

Question What is a layout manager? (AWT)


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

Question Which Component subclass is used for drawing and painting? (AWT)

Answer Canvas

What are the problems faced by Java programmers who dont use layout
Question
managers? (AWT)
Answer 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

Why variables/objects in java bean classes are declared as private?


Question
Question by Rajesh (Beans)
Since you do not want users to access these objects directly and wanted
Answer users to get access to these objects
using getter and setter methods.

Question Can there be an abstract class with no abstract methods in it? (CoreJava)

Answer Yes

Question Can an Interface be final? (CoreJava)

Answer No

Question Can an Interface have an inner class? (CoreJava)


Yes public interface abc { static int i=0; void dd(); class a1 { a1() { int j;
Answer System.out.println("in interfia"); }; public static void main(String a1[])
{ System.out.println("in interfia"); } } }

Can we define private and protected modifiers for variables in


Question
interfaces? (CoreJava)
Answer No

Question What is Externalizable? (CoreJava)


Externalizable is an Interface that extends Serializable Interface. And
Answer sends data into Streams in Compressed Format. It has two methods,
writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

Question What modifiers are allowed for methods in an Interface? (CoreJava)


Answer Only public and abstract modifiers are allowed for methods in interfaces.

Question What is a local, member and a class variable? (CoreJava)


Variables declared within a method are "local" variables.
Variables declared within the class i.e not within any methods are
Answer "member" variables (global variables).
Variables declared within the class i.e not within any methods and are
defined as "static" are class variables

I made my class Cloneable but I still get 'Can't access protected method
Question
clone. Why? (CoreJava)
Answer Yeah, some of the Java books, in particular "The Java Programming
Language", imply that all you have to do in order to have your class
support clone() is implement the Cloneable interface. Not so. Perhaps that
was the intent at some point, but that's not the way it works currently. As
it stands, you have to implement your own public clone() method, even if
it doesn't do anything special and just calls super.clone().

Question What are the different identifier states of a Thread? (CoreJava)

The different identifiers of a Thread are:


R - Running or runnable thread
S - Suspended thread
Answer
CW - Thread waiting on a condition variable
MW - Thread waiting on a monitor lock
MS - Thread suspended waiting on a monitor lock

Question Can we overload main method in java? (CoreJava)


Yes. But the main method with String args[] is called when you call the
programme (java Test1) Have a look at this demo. public class Test1
{
public static void main(String[] args)
{
System.out.println("in main method");
Answer }

public static void main(String args[],String arg)


{
System.out.println("in overload method");
}
}

Question What are some alternatives to inheritance? (CoreJava)


Delegation is an alternative to inheritance. Delegation means that you
include an instance of another class as an instance variable, and forward
messages to the instance. It is often safer than inheritance because it
forces you to think about each message you forward, because the instance
Answer
is of a known class, rather than a new class, and because it doesn't force
you to accept all the methods of the super class: you can provide only the
methods that really make sense. On the other hand, it makes you write
more code, and it is harder to re-use (because it is not a subclass).

Question Why isn't there operator overloading? (CoreJava)


Because C++ has proven by example that operator overloading makes
code almost impossible to maintain. In fact there very nearly wasn't even
method overloading in Java, but it was thought that this was too useful for
Answer
some very basic methods like print(). Note that some of the classes like
DataOutputStream have unoverloaded methods like writeInt() and
writeByte().

Question What does it mean that a method or field is "static"? (CoreJava)


Answer Static variables and methods are instantiated only once per class. In
other words they are class variables, not instance variables. If you change
the value of a static variable in a particular object, the value of that
variable changes for all instances of that class.
Static methods can be referenced with the name of the class rather than
the name of a particular object of the class (though that works too). That's
how library methods like System.out.println() work. out is a static field in
the java.lang.System class.

Question Diffrence between JRE And JVM AND JDK (CoreJava)


JVM - Java Virtual Machine. This is where all java classes gets executed.
JVM converts byte code to machine understandable code.
JRE - Java Runtime Environment - Contains all core API class files that are
Answer
needed to execute a java application
JDK - Java Development Kit - Contains tools to use java, e.g. javac, java,
javaw, keytool, etc... and JRE (See above for description of JRE)

Question Why do threads block on I/O? (CoreJava)


Threads block on i/o (that is enters the waiting state) so that other
Answer
threads may execute while the i/o Operation is performed.

Question What is synchronization and why is it important? (CoreJava)


With respect to multithreading, synchronization is the capability to control
the access of multiple threads to shared resources. Without
Answer 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.

Question Is null a keyword? (CoreJava)


Answer The null value is not a keyword.

Which characters may be used as the second character of an


Question
identifier,but not as the first character of an identifier? (CoreJava)
The digits 0 through 9 may not be used as the first character of an
Answer
identifier but they may be used after the first character of an identifier.

What modifiers may be used with an inner class that is a member of an


Question
outer class? (CoreJava)
A (non-local) inner class may be declared as public, protected, private,
Answer
static, final, or abstract.

How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8
Question
characters? (CoreJava)
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
Answer
represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit
and larger bit patterns.

Question What are wrapped classes? (CoreJava)


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

What restrictions are placed on the location of a package statement


Question
within a source code file? (CoreJava)
A package statement must appear as the first line in a source code file
Answer
(excluding blank lines and comments).

What is the difference between preemptive scheduling and time


Question
slicing? (CoreJava)
Under preemptive scheduling, the highest priority task executes until it
enters the waiting or dead states or a higher priority task comes into
Answer 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.

Question What is a native method? (CoreJava)


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

What are order of precedence and associativity, and how are they
Question
used? (CoreJava)
Order of precedence determines the order in which operators are
Answer evaluated in expressions. Associatity determines whether an expression is
evaluated left-to-right or right-to-left

Question What is the catch or declare rule for method declarations? (CoreJava)
If a checked exception may be thrown within the body of a method, the
Answer
method must either catch the exception or declare it in its throws clause.

Can an anonymous class be declared as implementing an interface and


Question
extending a class? (CoreJava)
An anonymous class may implement an interface or extend a superclass,
Answer
but may not be declared to do both.

Question What is the range of the char type? (CoreJava)


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

Question What is the purpose of finalization? (CoreJava)


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

Question What is the difference between the Boolean & operator and the &&
operator? (CoreJava)
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
Answer operand is evaluated. If the first operand returns a value of true then the
second operand is evaluated. The && operator is then applied to the first
and second operands. If the first operand evaluates to false, the evaluation
of the second operand is skipped.

How many times may an object's finalize() method be invoked by the


Question
garbage collector? (CoreJava)
An object's finalize() method may only be invoked once by the garbage
Answer
collector.

What is the purpose of the finally clause of a try-catch-finally


Question
statement? (CoreJava)
The finally clause is used to provide the capability to execute code no
Answer
matter whether or not an exception is thrown or caught.

Question What is the argument type of a program's main() method? (CoreJava)


Answer A program's main() method takes an argument of the String[] type.

Question Which Java operator is right associative? (CoreJava)

Answer The = operator is right associative.

Question Can a double value be cast to a byte? (CoreJava)


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

What is the difference between a break statement and a continue


Question
statement? (CoreJava)
A break statement results in the termination of the statement to which it
Answer applies (switch, for, do, or while). A continue statement is used to end the
current loop iteration and return control to the loop statement.

Question What must a class do to implement an interface? (CoreJava)


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

What is the advantage of the event-delegation model over the earlier


Question
event-inheritance model? (CoreJava)
Answer The event-delegation model has two advantages over the event-
inheritance model. First, it enables event handling to be handled by objects
other than the ones that generate the events (or their containers). This
allows a clean separation between a component's design and its use. The
other advantage of the event-delegation model is that it performs much
better in applications where many events are generated. This performance
improvement is due to the fact that the event-delegation model does not
have to repeatedly process unhandled events, as is the case of the event-
inheritance model.

How are commas used in the intialization and iteration parts of a for
Question
statement? (CoreJava)
Commas are used to separate multiple statements within the initialization
Answer
and iteration parts of a for statement.

Question What is an abstract method? (CoreJava)


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

What value does read() return when it has reached the end of a
Question
file? (CoreJava)
Answer The read() method returns -1 when it has reached the end of a file.

Question Can a Byte object be cast to a double value? (CoreJava)


Answer No, an object cannot be cast to a primitive value.

What is the difference between a static and a non-static inner


Question
class? (CoreJava)
A non-static inner class may have object instances that are associated
Answer with instances of the class's outer class. A static inner class does not have
any object instances.

If a variable is declared as private, where may the variable be


Question
accessed? (CoreJava)
A private variable may only be accessed within the class in which it is
Answer
declared.

Question What is an object's lock and which object's have locks? (CoreJava)
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
Answer 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.

Question What is the % operator? (CoreJava)


It is referred to as the modulo or remainder operator. It returns the
Answer
remainder of dividing the first operand by the second operand.

Question When can an object reference be cast to an interface reference? (CoreJava)


An object reference be cast to an interface reference when the object
Answer
implements the referenced interface.
Question Which class is extended by all other classes? (CoreJava)
Answer The Object class is extended by all other classes.

Question Can an object be garbage collected while it is still reachable? (CoreJava)


A reachable object cannot be garbage collected. Only unreachable objects
Answer
may be garbage collected.

Question Is the ternary operator written x : y ? z or x ? y : z ? (CoreJava)

Answer It is written x ? y : z.

Question How is rounding performed under integer division? (CoreJava)


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

What is the difference between the Reader/Writer class hierarchy and the
Question
InputStream/OutputStream class hierarchy? (CoreJava)
The Reader/Writer class hierarchy is character-oriented, and the
Answer
InputStream/OutputStream class hierarchy is byte-oriented.

Question What classes of exceptions may be caught by a catch clause? (CoreJava)


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

If a class is declared without any access modifiers, where may the class
Question
be accessed? (CoreJava)
A class that is declared without any access modifiers is said to have
Answer package access. This means that the class can only be accessed by other
classes and interfaces that are defined within the same package.

Question Does a class inherit the constructors of its superclass? (CoreJava)


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

Question What is the purpose of the System class? (CoreJava)


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

Question Name the eight primitive Java types. (CoreJava)


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

Which class should you use to obtain design information about an


Question
object? (CoreJava)
Answer The Class class is used to obtain information about an object's design.
Question Is "abc" a primitive value? (CoreJava)
Answer The String literal "abc" is not a primitive value. It is a String object.

What restrictions are placed on the values of each case of a switch


Question
statement? (CoreJava)
During compilation, the values of each case of a switch statement must
Answer
evaluate to a value that can be promoted to an int value.

Question What modifiers may be used with an interface declaration? (CoreJava)

Answer An interface may be declared as public or abstract.

Question Is a class a subclass of itself? (CoreJava)

Answer A class is a subclass of itself.

What is the difference between a while statement and a do


Question
statement? (CoreJava)
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
Answer
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.

Question What modifiers can be used with a local inner class? (CoreJava)

Answer A local inner class may be final or abstract.

Question What is the purpose of the File class? (CoreJava)


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

Question Can an exception be rethrown? (CoreJava)


Answer Yes, an exception can be rethrown.

Question When does the compiler supply a default constructor for a class? (CoreJava)

The compiler supplies a default constructor for a class if no other


Answer
constructors are provided.

If a method is declared as protected, where may the method be


Question
accessed? (CoreJava)
A protected method may only be accessed by classes or interfaces of the
Answer
same package or by subclasses of the class in which it is declared.

Which non-Unicode letter characters may be used as the first character of


Question
an identifier? (CoreJava)
The non-Unicode letter characters $ and _ may appear as the first
Answer
character of an identifier
Question What restrictions are placed on method overloading? (CoreJava)
Two methods may not have the same name and argument list but
Answer
different return types.

Question What is casting? (CoreJava)


There are two types of casting, casting between primitive numeric types
and casting between object references. Casting between numeric types is
Answer 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.

Question What is the return type of a program's main() method? (CoreJava)

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

What class of exceptions are generated by the Java run-time


Question
system? (CoreJava)
The Java runtime system generates RuntimeException and Error
Answer
exceptions.

Question What class allows you to read objects directly from a stream? (CoreJava)
The ObjectInputStream class supports the reading of objects from input
Answer
streams.

What is the difference between a field variable and a local


Question
variable? (CoreJava)
A field variable is a variable that is declared as a member of a class. A
Answer
local variable is a variable that is declared local to a method.

Question How are this() and super() used with constructors? (CoreJava) Discuss in Detail
this() is used to invoke a constructor of the same class. super() is used to
Answer
invoke a superclass constructor.

What is the relationship between a method's throws clause and the


Question
exceptions that can be thrown during the method's execution? (CoreJava)
A method's throws clause must declare any checked exceptions that are
Answer
not caught within the body of the method.

Question Why are the methods of the Math class static? (CoreJava)
Answer So they can be invoked as if they are a mathematical code library.

Question What are the legal operands of the instanceof operator? (CoreJava)
The left operand is an object reference or null value and the right
Answer
operand is a class, interface, or array type.
Question What an I/O filter? (CoreJava)
An I/O filter is an object that reads from one stream and writes to
Answer another, usually altering the data in some way as it is passed from one
stream to another.

Question If an object is garbage collected, can it become reachable again? (CoreJava)


Once an object is garbage collected, it ceases to exist. It can no longer
Answer
become reachable again.

Question What are E and PI? (CoreJava)


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

Question Are true and false keywords? (CoreJava)


Answer The values true and false are not keywords.

What is the difference between the File and RandomAccessFile


Question
classes? (CoreJava)
The File class encapsulates the files and directories of the local file
Answer system. The RandomAccessFile class provides the methods needed to
directly access data contained in any part of a file.

Question What happens when you add a double value to a String? (CoreJava)

Answer The result is a String object.

Question What is your platform's default character encoding? (CoreJava)


If you are running Java on English Windows platforms, it is probably
Answer Cp1252. If you are running Java on English Solaris platforms, it is most
likely 8859_1.

Question Which package is always imported by default? (CoreJava)


Answer The java.lang package is always imported by default.

What interface must an object implement before it can be written to a


Question
stream as an object? (CoreJava)
An object must implement the Serializable or Externalizable interface
Answer
before it can be written to a stream as an object.

Question Whats the difference between notify() and notifyAll()? (CoreJava)


notify() is used to unblock one waiting thread; notifyAll() is used to
unblock all of them. Using notify() is preferable (for efficiency) when only
one blocked thread can benefit from the change (for example, when
Answer
freeing a buffer back into a pool). notifyAll() is necessary (for correctness)
if multiple threads should resume (for example, when releasing a "writer"
lock on a file might permit all "readers" to resume).
Why can't I say just abs() or sin() instead of Math.abs() and
Question
Math.sin()? (CoreJava)
The import statement does not bring methods into your local name
space. It lets you abbreviate class names, but not get rid of them
altogether. That's just the way it works, you'll get used to it. It's really a
lot safer this way. <br> However, there is actually a little trick you can use
in some cases that gets you what you want. If your top-level class doesn't
Answer
need to inherit from anything else, make it inherit from java.lang.Math.
That *does* bring all the methods into your local name space. But you
can't use this trick in an applet, because you have to inherit from
java.awt.Applet. And actually, you can't use it on java.lang.Math at all,
because Math is a "final" class which means it can't be extended.

Question Wha is the output from System.out.println("Hello"+null); (CoreJava)

Answer Hellonull

Question Why are there no global variables in Java? (CoreJava)


Global variables are considered bad form for a variety of reasons:
· Adding state variables breaks referential transparency (you no longer can
understand a statement or expression on its own: you need to understand
it in the context of the settings of the global variables).
· State variables lessen the cohesion of a program: you need to know more
to understand how something works. A major point of Object-Oriented
Answer
programming is to break up global state into more easily understood
collections of local state.
· When you add one variable, you limit the use of your program to one
instance. What you thought was global, someone else might think of as
local: they may want to run two copies of your program at once.
For these reasons, Java decided to ban global variables.

Question What does it mean that a class or member is final? (CoreJava)


A final class can no longer be subclassed. Mostly this is done for security
reasons with basic classes like String and Integer. It also allows the
compiler to make some optimizations, and makes thread safety a little
easier to achieve.
Methods may be declared final as well. This means they may not be
overridden in a subclass.
Answer Fields can be declared final, too. However, this has a completely different
meaning. A final field cannot be changed after it's initialized, and it must
include an initializer statement where it's declared. For example,
public final double c = 2.998;
It's also possible to make a static field final to get the effect of C++'s const
statement or some uses of C's #define, e.g.
public static final double c = 2.998;

Question What does it mean that a method or class is abstract? (CoreJava)


Answer An abstract class cannot be instantiated. Only its subclasses can be
instantiated. You indicate that a class is abstract with the abstract keyword
like this:
public abstract class Container extends Component {
Abstract classes may contain abstract methods. A method declared
abstract is not actually implemented in the current class. It exists only to
be overridden in subclasses. It has no body. For example,
public abstract float price();
Abstract methods may only be included in abstract classes. However, an
abstract class is not required to have any abstract methods, though most
of them do.
Each subclass of an abstract class must override the abstract methods of
its superclasses or itself be declared abstract.

Question what is a transient variable? (CoreJava)


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

Question How are Observer and Observable used? (CoreJava)


Objects that subclass the Observable class maintain a list of observers.
When an Observable object is updated it invokes the update() method of
Answer each of its observers to notify the observers that it has changed state. The
Observer interface is implemented by objects that observe Observable
objects.

Question Can a lock be acquired on a class? (CoreJava)


Yes, a lock can be acquired on a class. This lock is acquired on the class's
Answer
Class object.

What state does a thread enter when it terminates its


Question
processing? (CoreJava)
Answer When a thread terminates its processing, it enters the dead state.

Question How does Java handle integer overflows and underflows? (CoreJava)
It uses those low order bytes of the result that can fit into the size of the
Answer
type allowed by the operation.

Question What is the difference between the >> and >>> operators? (CoreJava)
The >> operator carries the sign bit when shifting right. The >>> zero-
Answer
fills bits that have been shifted out.

Question Is sizeof a keyword? (CoreJava)


Answer The sizeof operator is not a keyword.

Does garbage collection guarantee that a program will not run out of
Question
memory? (CoreJava)
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
Answer
than they are garbage collected. It is also possible for programs to create
objects that are not subject to garbage collection
Can an object's finalize() method be invoked while it is
Question
reachable? (CoreJava)
An object's finalize() method cannot be invoked by the garbage collector
Answer while the object is still reachable. However, an object's finalize() method
may be invoked by other objects.

What value does readLine() return when it has reached the end of a
Question
file? (CoreJava)
Answer The readLine() method returns null when it has reached the end of a file.

Question Can a for statement loop indefinitely? (CoreJava)


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

To what value is a variable of the String type automatically


Question
initialized? (CoreJava)
Answer The default value of an String type is null.

Question What is a task's priority and how is it used in scheduling? (CoreJava)


A task's priority is an integer value that identifies the relative order in
Answer which it should be executed with respect to other tasks. The scheduler
attempts to schedule higher priority tasks before lower priority tasks.

Question What is the range of the short type? (CoreJava)


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

Question What is the purpose of garbage collection? (CoreJava)


The purpose of garbage collection is to identify and discard objects that
Answer are no longer needed by a program so that their resources may be
reclaimed and reused.

Question What do you understand by private, protected and public? (CoreJava)


These are accessibility modifiers. Private is the most restrictive, while
public is the least restrictive. There is no real difference between protected
Answer and the default type (also known as package protected) within the context
of the same package, however the protected keyword allows visibility to a
derived class in a different package.

Question What is Downcasting ? (CoreJava)


Downcasting is the casting from a general to a more specific type, i.e.
Answer
casting down the hierarchy

Can a method be overloaded based on different return type but same


Question
argument type ? (CoreJava)
No, because the methods can be called without using their return type in
Answer
which case there is ambiquity for the compiler

What happens to a static var that is defined within a method of a


Question
class ? (CoreJava)
Answer Can't do it. You'll get a compilation error

Question How many static init can you have ? (CoreJava)


As many as you want, but the static initializers and class variable
initializers are executed in textual order and may not refer to class
Answer
variables declared in the class whose declarations appear textually after
the use, even though these class variables are in scope.

What is the difference amongst JVM Spec, JVM Implementation, JVM


Question
Runtime ? (CoreJava)
The JVM spec is the blueprint for the JVM generated and owned by Sun.
The JVM implementation is the actual implementation of the spec by a
Answer
vendor and the JVM runtime is the actual running instance of a JVM
implementation

Question Describe what happens when an object is created in Java? (CoreJava)


Several things happen in a particular order to ensure the object is
constructed properly:
1. Memory is allocated from heap to hold all instance variables and
implementation-specific data of the object and its superclasses.
Implemenation-specific data includes pointers to class and method data.
2. The instance variables of the objects are initialized to their default
values.
Answer 3. The constructor for the most derived class is invoked. The first thing a
constructor does is call the consctructor for its superclasses. This process
continues until the constrcutor for java.lang.Object is called, as
java.lang.Object is the base class for all objects in java.
4. Before the body of the constructor is executed, all instance variable
initializers and initialization blocks are executed. Then the body of the
constructor is executed. Thus, the constructor for the base class completes
first and constructor for the most derived class completes last.

What does the "final" keyword mean in front of a variable? A method? A


Question
class? (CoreJava)
FINAL for a variable : value is constant
Answer FINAL for a method : cannot be overridden
FINAL for a class : cannot be derived

Question What is the difference between instanceof and isInstance? (CoreJava)


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

Question Why is not recommended to have instance variables in Interface (CoreJava)


By Default, All data members and methods in an Interface are public.
Answer Having public variables in a class that will be implementing it will be
violation of the Encapsulation principles

Question What is the diffrence between inner class and nested class? (CoreJava)
When a class is defined within a scope od another class, then it becomes
inner class.
Answer
If the access modifier of the inner class is static, then it becomes nested
class.

How the private constructor is called in the main java


Question
programme? (CoreJava)
Have a look at this demo. public class Test2
{
private Test2()
{
System.out.println("Test2class");
}

class Subclass extends Test2


{
public Subclass()
{
Answer
System.out.println("Subclass");
}
}

public static void main(String[] args)


{
Subclass s = new Test2().new Subclass();
}
}
This works because an inner class is allowed to access private members of
its enclosing instance, including the private constructor.

Which is garbage collected first: Normal variables or static


Question
variables? (CoreJava)
Answer Normal variables will be collected first. Lets take a simple example:
Class A is having a static variable s which is used by obj1, obj2 and obj3 of
Class B. Each object of class B is having instance variables a and b (normal
variables). Lets say if obj1 is not being in use since long time, then
automatically the garbage collector will collect the space occupied by obj1.
It will not destroy the static variable S as it is being used by the other two
objects obj2 and obj3. Therefore only normal variables will be destroyed
first.
We can say it in a simple statement that "Variables having less scope will
be destroyed first"

Question Diffrence between JRE And JVM AND JDK (CoreJava) (CoreJava)
The "JDK" is the Java Development Kit. I.e., the JDK is bundle of software
that you can use to develop Java based software. The "JRE" is the Java
Runtime Environment. I.e., the JRE is an implementation of the Java
Answer Virtual Machine which actually executes Java programs. Typically, each
JDK contains one (or more) JRE's along with the various development tools
like the Java source compilers, bundling and deployment tools, debuggers,
development libraries, etc.

is it necessary to initialize a final variable at the time of


Question
declaretion ? (CoreJava)
NO, it's not necessary.
Many text books say like this but thats not true. Value of a final variable
can be instance specific also, but in this case we have to initialise the
variable in all the constructors.
If we want to have a common final value of a variable for all the instances
Answer then there are two ways.
1. Initialise the variable at class level (at the time of declaration) or 2. just
declare variable at class level and initialise it in any one of the instance
blocks i.e.
A. class A { final int a; {a=5;}}
B. class A { final int a = 5;}

Question What is a compilation unit? (CoreJava)


Answer A compilation unit is a Java source code file.

Question What restrictions are placed on method overriding? (CoreJava)


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.
Answer
The overriding method may not throw any exceptions that may not be
thrown by the overridden method.

Question How can a dead thread be restarted? (CoreJava)

Answer A dead thread cannot be restarted.

Question What happens if an exception is not caught? (CoreJava)


An uncaught exception results in the uncaughtException() method of the
Answer thread's ThreadGroup being invoked, which eventually results in the
termination of the program in which it is thrown.
Which arithmetic operations can result in the throwing of an
Question
ArithmeticException? (CoreJava)
Answer Integer / and % can result in the throwing of an ArithmeticException

Question Can an abstract class be final? (CoreJava)


Answer An abstract class may not be declared as final

What happens if a try-catch-finally statement does not have a catch


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

Question What is numeric promotion? (CoreJava)


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

Question What is the difference between a public and a non-public class? (CoreJava)
A public class may be accessed outside of its package. A non-public class
Answer
may not be accessed outside of its package.

To what value is a variable of the boolean type automatically


Question
initialized? (CoreJava)
Answer The default value of the boolean type is false

Question Can try statements be nested? (CoreJava)

Answer Yes

What is the difference between the prefix and postfix forms of the ++
Question
operator? (CoreJava)
The prefix form performs the increment operation and returns the value
of the increment operation. The postfix form returns the current value all
Answer
of the expression and then performs the increment operation on that
value.

Question What is the purpose of a statement block? (CoreJava)


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

Question What is a Java package and how is it used? (CoreJava)


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

Question What modifiers may be used with a top-level class? (CoreJava)

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

Question What are the Object and Class classes used for? (CoreJava)
The Object class is the highest-level class in the Java class hierarchy. The
Answer Class class is used to represent the classes and interfaces that are loaded
by a Java program.

How does a try statement determine which catch clause should be used
Question
to handle an exception? (CoreJava)
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
Answer
appear. The first catch clause that is capable of handling the exception is
executed. The remaining catch clauses are ignored.

Question What are synchronized methods and synchronized statements? (CoreJava)


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

What is the difference between an if statement and a switch


Question
statement? (CoreJava)
The if statement is used to select among two alternatives. It uses a
boolean expression to decide which alternative should be executed. The
Answer
switch statement is used to select among multiple alternatives. It uses an
int expression to determine which alternative should be executed.

Question What gives java it's "write once and run anywhere" nature? (CoreJava)
Java is compiled to be a byte code which is the intermediate language
between source code and machine code. This byte code is not platorm
specific and hence can be fed to any platform. After being fed to the JVM,
Answer
which is specific to a particular operating system, the code platform
specific machine code is generated thus making java platform
independent.

Question What are the four corner stones of OOP ? (CoreJava)


Answer Abstraction, Encapsulation, Polymorphism and Inheritance

Question Difference between a Class and an Object ? (CoreJava)


A class is a definition or prototype whereas an object is an instance or
Answer
living representation of the prototype

What is the difference between method overriding and


Question
overloading? (CoreJava)
Overriding is a method with the same name and arguments as in a
Answer parent, whereas overloading is the same method name but different
arguments

Question What is a "stateless" protocol ? (CoreJava)


Without getting into lengthy debates, it is generally accepted that
Answer protocols like HTTP are stateless i.e. there is no retention of state between
a transaction which is a single request response combination

Question What is constructor chaining and how is it achieved in Java ? (CoreJava)


A child object constructor always first needs to construct its parent (which
Answer in turn calls its parent constructor.). In Java it is done via an implicit call to
the no-args constructor as the first statement.

Question What is passed by ref and what by value ? (CoreJava)


All Java method arguments are passed by value. However, Java does
Answer manipulate objects by reference, and all object variables themselves are
references

You can create a String object as String str = "abc"; Why cant a button
Question
object be created as Button bt = "abc";? Explain (CoreJava)
The main reason you cannot create a button by Button bt1= "abc"; is
because "abc" is a literal string (something slightly different than a String
object, by-the-way) and bt1 is a Button object. The only object in Java that
Answer
can be assigned a literal String is java.lang.String. Important to note that
you are NOT calling a java.lang.String constuctor when you type String s =
"abc";

What does the "abstract" keyword mean in front of a method? A


Question
class? (CoreJava)
Abstract keyword declares either a method or a class. If a method has a
abstract keyword in front of it,it is called abstract method.Abstract method
hs no body.It has only arguments and return type.Abstract methods act as
Answer placeholder methods that are implemented in the subclasses.
Abstract classes can't be instantiated.If a class is declared as abstract,no
objects of that class can be created.If a class contains any abstract method
it must be declared as abstract

How many methods do u implement if implement the Serializable


Question
Interface? (CoreJava)
Answer The Serializable interface is just a "marker" interface, with no methods of
its own to implement. Other 'marker' interfaces are
java.rmi.Remote
java.util.EventListener

What are the practical benefits, if any, of importing a specific class rather
Question than an entire package (e.g. import java.net.* versus import
java.net.Socket)? (CoreJava)
It makes no difference in the generated class files since only the classes
that are actually used are referenced by the generated class file. There is
another practical benefit to importing single classes, and this arises when
two (or more) packages have classes with the same name. Take
java.util.Timer and javax.swing.Timer, for example. If I import java.util.*
and javax.swing.* and then try to use "Timer", I get an error while
Answer compiling (the class name is ambiguous between both packages). Let's say
what you really wanted was the javax.swing.Timer class, and the only
classes you plan on using in java.util are Collection and HashMap. In this
case, some people will prefer to import java.util.Collection and import
java.util.HashMap instead of importing java.util.*. This will now allow them
to use Timer, Collection, HashMap, and other javax.swing classes without
using fully qualified class names in.

What is the difference between logical data independence and physical


Question
data independence? (CoreJava)
Logical Data Independence - meaning immunity of external schemas to
Answer changeds in conceptual schema. Physical Data Independence - meaning
immunity of conceptual schema to changes in the internal schema.

Question What is user defined exception ? (CoreJava)


Apart from the exceptions already defined in Java package libraries, user
Answer
can define his own exception classes by extending Exception class.

Question Difference Between Abstraction and Encapsulation (CoreJava)


Abstraction is removing some distinctions between objects, so as to show
their commonalities.
Answer
Encapsulation is hiding the details of the implementation of an object so
that there are no external dependencies on the particular implementation.

Question What are Checked and Un-Checked Exceptions? Explain. (CoreJava)


Answer Throwable extends Object (checked)
Exception extends Throwable (checked)
RuntimeException extends Exception (un-checked)
Error extends Throwable (un-checked)
So anything that extends Throwable or Exception (except
RuntimeException) will be checked. Anything that extends Error or
RuntimeException will be un-checked
Checked exceptions are problems that arise in correct code and may be
due to technical problems such as IO problems or user mistakes such as
opening a socket when the remote machine does not exist. Because these
problems can occur at anytime, say due to network outage, you must have
code that can handle and recover from these. In fact, the Java compiler
checks that you have trapped them, hence checked exceptions.
Runtime exceptions are typically bugs in the program. Errors are severe
problems such as out of memory and sufficiently rare, that you are not
required to handle them as they are usually unrecoverable.

Question Can we sort an Hashtable? (CoreJava)


Yes. Here is an example
Answer
http://www.javagalaxy.com:8080/CoreJava/View.jsp?slno=90&tbl=0

What is the exact difference between Abstract classes and


Question
Interfaces? (CoreJava)
Interfaces provide a form of multiple inheritance -- any number of
interfaces can be implemented A class can extend only one other class.
Answer Interfaces are limited to public methods and constants with no
implementation. Abstract classes can have a partial implementation,
protected parts, static methods, etc.

Question Garbage collector thread belongs to which priority? (CoreJava)


Answer Garbage collector thread belongs to low priority (MIN_PRIORITY)

Can you throw (and re-throw) an exception inside a catch{}


Question
clause? (CoreJava)
Yes, It will cause the exception to be passed to the handlers at the next-
Answer
higher level. All further catch clauses are ignored in the current try block.

Question What is the difference between ArrayList and Vector (CoreJava)

Answer Methods in Vectors are synchronized

Question Can we have inner class in the interface ? (CoreJava)


Answer Yes.We can have inner class in the interface.

Question How to get values from a Vector (CoreJava)


Answer Vector v = new Vector(10,2) v.add(3); v.add(4); int i= v.get(1);

What is meant by Instance Variables and Class Variables (CoreJava)


Question

instance variables Any item of data that is associated with a particular


object. Each instance of a class has its own copy of the instance variables
defined in the class. Also called a field. class variables A data item
Answer
associated with a particular class as a whole--not with particular instances
of the class. Class variables are defined in class definitions. Also called a
static field

Question What is difference between jsp and Servlet? (CoreJava)


Answer THe main diff between jsp and servlet is code and content presentation in
jsp, it is not possible in servlet.

Does the code in finally block get executed if there is an exception and a
Question
return statement in a catch block? (CoreJava)
If an exception occurs and there is a return statement in catch block, the
finally block is still executed. The finally block will not be executed when
Answer the System.exit(1) statement is executed earlier or the system shut down
earlier or the memory is used up earlier before the thread goes to finally
block.

Question What are the Object and Class classes used for? (CoreJava)
The Object class is the highest-level class in the Java class hierarchy. The
Answer Class class is used to represent the classes and interfaces that are loaded
by a Java program.

What interface must an object implement before it can be written to a


Question
stream as an object? (CoreJava)
An object must implement the Serializable or Externalizable interface
Answer
before it can be written to a stream as an object.

Question What is an I/O filter? (CoreJava)


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

Question What class allows you to read objects directly from a stream? (CoreJava)
The ObjectInputStream class supports the reading of objects from input
Answer
streams.

If a class is declared without any access modifiers, where may the class
Question
be accessed? (CoreJava)
A class that is declared without any access modifiers is said to have
Answer package or friendly access. This means that the class can only be accessed
by other classes and interfaces that are defined within the same package.

If class A does not implement Serializable but a subclass B implements


Question Serializable, will the fields of class A be serialized when B is
serialized? (CoreJava)
Only the fields of Serializable objects are written out and restored. The
object may be restored only if it has a no-arg constructor that will initialize
Answer the fields of non-serializable supertypes. If the subclass has access to the
state of the superclass it can implement writeObject and readObject to
save and restore that state.

Question When a Serializable object is written with writeObject, then modified and
written a second time, why is the modification missing when the stream is
deserialized? (CoreJava)
The ObjectOutputStream class keeps track of each object it serializes and
sends only the handle if the object is written into the stream a subsequent
time. This is the way it deals with graphs of objects. The corresponding
ObjectInputStream keeps track of all of the objects it has created and their
handles so when the handle is seen again it can return the same object.
Answer
Both output and input streams keep this state until they are freed.

Alternatively, the ObjectOutputStream class implements a reset method


that discards the memory of having sent an objecct, so sending an object
again will make a copy.

Question How do I get the serialVersionUID of a class? (CoreJava)


Run the serialver tool, supplying the name of the class, as shown in the
example that follows:
Answer
serialver java.lang.String

The object serialization classes are stream oriented. How do I write


Question
objects to a random access file? (CoreJava)
Currently there is no direct way to write objects to a random access file.

You can use the ByteArray I/O streams as an intermediate place to write
and read bytes to/from the random access file and create Object I/O
streams from the byte streams to write/read the objects. You just have to
make sure that you have the entire object in the byte stream or
Answer
reading/writing the object will fail.

For example, java.io.ByteArrayOutputStream can be used to receive the


bytes of ObjectOutputStream. From it you can get a byte[] of the result
which, in turn, can be used with ByteArrayInputStream as input to
ObjectInput.

Can I compress the serial representation of my objects using my own zip/


Question
unzip methods? (CoreJava)
ObjectOutputStream produces an OutputStream. If your zip object
Answer
extends the OutputStream class, there is no problem compressing it.

When a local object is serialized and passed as a parameter in an RMI


call, are the byte codes for the local object's methods also passed? What
Question
about object coherency, if the remote VM application "keeps" the object
handle? (CoreJava)
Answer The bytecodes for a local object's methods are not passed directly in the
ObjectOutputStream, but the object's class may need to be loaded by the
receiver if the class is not already available locally. (The class files
themselves are not serialized, just the names of the classes.) All classes
must be able to be loaded during deserialization using the normal class
loading mechanisms. For applets this means they are loaded by the
AppletClassLoader.
There are no conherency guarantees for local objects passed to a remote
VM, since such objects are passed by copying their contents (a true pass-
by-value).

Question Explain about Singleton Class (CoreJava)


In general, you use a singleton to enforce the notion that there will be
only one instance of a given class. Singletons should be used in situations
where creating more than one of something would be a logical error.

For example, a ConnectionPool would be a good place to use a singleton. If


clients could arbitrarily create ConnectionPools without regard to what
already exists, you would have a waste of resources. So you limit the
possible number of connection pools to 1 (per JVM), and you then know
that all clients are getting their connections from a single source.

Answer Another example of Singleton use is for Object Factories. Say you have a
class called FooFactory that is responsible for fetching/saving Foo objects
to/from a database. You want to ensure that for each Foo record in the db,
there is only one corresponding Foo object floating around your
application. By centralizing all the creation logic in a single class, and
making that class a Singleton, you eliminate the possibility fo duplicate
objects.

The code that uses a connection obtained from the connection pool is
another matter. If all it does is do a getData() type operation, there is no
harm in having more than one of them.

Strings are immutable, How are we able to perform concatination on


Question
String object? (CoreJava)
Yes. Strings are immutable. Thats why while concatenating, it always
returns a new string object.
If we take this example :
String s1 = "psn";
s1 = s1.concat("prasad"); // Here you are reassigning the new object to
the older reference s1
System.out.println(s1);
Answer
String s1 = "psn";
String s2 = s1.concat("prasad");
System.out.println(s1); // will remain same . no change. it prints "psn"
only
System.out.println(s2); // as you have assigned the newly created object
to s2

Question It is valid to declare an inherited method as abstract? (CoreJava)


Yes,It is valid. However, there is no way to get to behaviour which is
Answer located above the abstract method in the hierarchy. In effect, you will
block access to parent methods further up the hierarchy.
Question what is j2EE? (CoreJava)
J2EE menas Java 2 Enterprise Edition.. it follows certain rules and
regulations to develop web technologies. and certain technologies are
Answer
under comes i this category like EJB/JSP/Servlets/JMS/Web Servers/App
Servers/Struts and Oracle-9.0i

Question Can an Interface have an inner class? (CoreJava)


Yes. Interface can have an inner class. The possible use of this is to
provide multiple inheritance in java. A class "abc1" can extend normal
Answer class "abc2" and can implement an Interface "abc" having an inner class
"abc3". This way class "abc1" can get the functionality of both "abc2" and
"abc3" classes.

Question what is tunnelling? (CoreJava)


Tunnelling is a route to somewhere. For example, RMI tunnelling is a way
Answer to make RMI application get through firewall. In CS world, tunnelling means
a way to transfer data.

What is the difference between the File and RandomAccessFile


Question
classes? (CoreJava)
The File class encapsulates the files and directories of the local file
Answer system. The RandomAccessFile class provides the methods needed to
directly access data contained in any part of a file.

Question How are this() and super() used with constructors? (CoreJava)
this() is used to invoke a constructor of the same class. super() is used to
Answer
invoke a superclass constructor

Question What is casting? (CoreJava)


There are two types of casting, casting between primitive numeric types
and casting between object references. Casting between numeric types is
Answer 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.

Question What is the purpose of the Runtime class? (CoreJava)


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

Question Does object serialization support encryption? (CoreJava)


Object serialization does not contain any encryption/decryption in itself. It
writes to and reads from Java Streams, so it can be coupled with any
Answer available encryption technology. Object serialization can be used in many
different ways from simple persistence, writing and read to/from files, or
for RMI to communicate across hosts.
Why is OutOfMemoryError thrown after writing a large number of objects
Question
into an ObjectOutputStream? (CoreJava)
The ObjectOutputStream maintains a table mapping objects written into
the stream to a handle. The first time an object is written to a stream, its
contents are written into the stream; subsequent writes of the object result
in a handle to the object being written into the stream. This table
Answer maintains references to objects that might otherwise be unreachable by an
application, thus, resulting in an unexpected situation of running out of
memory. A call to the ObjectOutputStream.reset() method resets the
object/handle table to its initial state, allowing all previously written
objects to be elgible for garbage collection.

Why is UTFDataFormatException thrown by DataOutputStream.writeUTF()


Question
when serializing a String? (CoreJava)
DataOutputStream.writeUTF() does not support writing out strings larger
than 64K. The first two bytes of a UTF string in the stream are the length
Answer of the string. If a java.lang.String can be larger than 64K, it needs to be
stored in the stream by an alternative method rather than depending on
the default method of storing a String in the stream, writeUTF.

How can I create an ObjectInputStream from an ObjectOutputStream


Question
without a file in between? (CoreJava)
ObjectOutputStream and ObjectInputStream work to/from any stream
object. You could use a ByteArrayOutputStream and then get the array
and insert it into a ByteArrayInputStream. You could also use the piped
stream classes as well. Any java.io class that extends the OutputStream
Answer and InputStream classes can be used.

Alternatively, the ObjectOutputStream> class implements a reset method


that discards the memory of having sent an object, so sending an object
again will make a copy.

Why can't a file that contains multiple appended ObjectOutputStreams be


Question
deserialized by one ObjectInputStream? (CoreJava)
Using the default implementation of serialization, there must be a one-to-
one mapping between ObjectOutputStream construction and
ObjectInputStream construction. ObjectOutputStream constructor writes a
stream header andObjectInputStream reads this stream header. A
Answer workaround is to subclass ObjectOutputStream and override
writeStreamHeader(). The overriding writeStreamHeader() should call the
super writeStreamHeader method if it is the first write to the file and it
should call ObjectOutputStream.reset() if it is appending to a pre-existing
ObjectOutputStream within the file.

Question What is the difference between Shallow Copy and Deep Copy? (CoreJava)
Answer Shallow Copy:
If a shallow copy is performed on an object, then it gets copied but its
contained objects are not copied. Also any changes made in the cloned
object is automatically reflected in the shallowed copy object as well. An
example

class Student implements Cloneable


{
public String name;
public String age;
public Student(String name,String address)
{
this.name = name;
this.age = age;
}
public Object clone() throws java.lang.CloneNotSupportedException
{
return this;
}
}

public class ShallowCloneClient


{
public ShallowCloneClient() throws java.lang.CloneNotSupportedException
{
Student st1 = new Student("guddu","22,nagar road");
Student st2 = (Student)st1.clone();
st2.name="new name";
System.out.println(st1.name);
}
public static void main(String args[]) throws
java.lang.CloneNotSupportedException
{
new ShallowCloneClient();
}
}

When you execute the programme, the output will be "new name", this
shows that both st1 and st2 instances are the same, changing one changes
other too.

Deep Copy:

A deep copy occurs when an object is copied along with the objects to
which it refers to are also copied. This occurs only when every object in the
tree is serializable. An example

import java.io.*;

class Student1 implements Cloneable,Serializable


{
public String name;
public String age;
public Student1(String name,String address)
{
this.name = name;
this.age = age;
}
public Object clone() throws java.lang.CloneNotSupportedException
{
try{
ByteArrayOutputStream byteArr = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(byteArr);
objOut.writeObject(this);
ByteArrayInputStream byteArrIn = new
ByteArrayInputStream(byteArr.toByteArray());
ObjectInputStream objIn = new ObjectInputStream(byteArrIn);
return objIn.readObject();
}catch(Exception ex){
ex.printStackTrace();
return null;
}
}
}

public class ShallowCloneClient1


{
public ShallowCloneClient1() throws java.lang.CloneNotSupportedException
{
Student1 st1 = new Student1("guddu","22,nagar road");
Student1 st2 = (Student1)st1.clone();
st2.name="new name";
System.out.println(st1.name);
}
public static void main(String args[]) throws
java.lang.CloneNotSupportedException
{
new ShallowCloneClient1();
}
}

When you execute the programme, the output will be "guddu", this shows
that st1 and st2 instances are different.

Question Can an abstract class have final method? (CoreJava)

Answer Yes

Question Can an abstract class have only final methods? (CoreJava)

Answer Yes

Question Can a final class have abstract method? (CoreJava)


Answer No. It gives compile time error saying that the class is not abstract.

Question Can you compare if null is equal to null? i.e.


String str = null;
String str1 = null;

if(str == str1)
SOP("true");
(CoreJava)

Yes, And its going to be true as the objects have not been allocated any
Answer
memory location.

Post-increment or Post-Decrement? Which would give better


performance?
e.g. for(int x=0; x < 10000; x++)
SOP("JG");
Question
for(int y>0; y < 10000; y--)
SOP("JG");
(CoreJava)

Post-Decrement would give better performance. This is due to the binary


Answer subtraction
(1's complement/ 2's complement)

Question What's the difference between a queue and a stack? (CoreJava)


Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO
Answer
rule.

Can an inner class declared inside of a method access local variables of


Question
this method? (CoreJava)
Answer It's possible if these variables are final.

What are the different ways in which polymorphism can be achieved in


Question
java? (CoreJava)
Polymorphism can be acheived two ways
overloading - static binding/early binding
overriding - dynamic binding/late binding

Answer In case of overloading the method to be called is decided at the compile


time based on the method signature.

In case of overriding the method to be called is decided at run time and


NOT at compile time. This is runtime polymorphism.

Question What's the difference between constructors and other methods? (CoreJava)
Constructors must have the same name as the class and can not return a
Answer value. They are only called once while
regular methods could be called many times.

Question It is valid to declare an inherited method as abstract? (CoreJava)


Answer Yes its valid to declare an inherited method abstract. But it would be of
no use as you need to define the class
abstract again.

e.g.

abstract class AbsTest


{
abstract void setName(String name);
}

public class AbsTest1 extends AbsTest //compile error is thrown as there is


an abstract method, declare the class abstract
{
abstract void setName(String name){} // error, abstract method
cannot have body
}

What would you use to compare two String variables - the operator ==
Question
or the method equals()? (CoreJava)
I'd use the method equals() to compare the values of the Strings and the
Answer == to check if two variables point at the
same instance of a String object.

Question How do you know if an explicit object casting is needed? (CoreJava)


If you assign a superclass object to a variable of a subclass's data type,
you need to do explicit casting. For example:
Object a; Customer b; b = (Customer) a;
Answer
When you assign a subclass to a variable having a supeclass type, the
casting is performed automatically.

Question What will the output of the following programme be? Look at the
programme carefully, we have an instance method and
static method (class method) defined in both Animal class and Cat class.

public class Animal {


public static void hide() {
System.out.format("The hide method in Animal.%n");
}
public void override() {
System.out.format("The override method in Animal.%n");
}
}

public class Cat extends Animal {


public static void hide() {
System.out.format("The hide method in Cat.%n");
}
public void override() {
System.out.format("The override method in Cat.%n");
}

public static void main(String[] args) {


Cat myCat = new Cat();
Animal myAnimal = myCat;
//myAnimal.hide(); //BAD STYLE
Animal.hide(); //Better!
myAnimal.override();
}
}
(CoreJava)

The output of the programme will be..

The hide method in Animal.


The override method in Cat.

For class methods, the runtime system invokes the method defined in the
compile-time type of the reference on which the
method is called. In the example, the compile-time type of myAnimal is
Answer
Animal. Thus, the runtime system invokes the hide
method defined in Animal. For instance methods, the runtime system
invokes the method defined in the runtime type of the
reference on which the method is called. In the example, the runtime type
of myAnimal is Cat. Thus, the runtime system
invokes the override method defined in Cat.

An instance method cannot override a static method, and a static method


cannot hide an instance method.

Have a look at the following code.


How do I execute the method d() in class B without creating another
instance in the main method.

class A {
void c() {
System.out.println("In A class");
}
}
Question public class B extends A {
void d() {
System.out.println("In B class");
}

public static void main(String args[]) {


A a = new B();
}
}
(CoreJava)
Answer you will need to typecast the object to ((B)a).d();

Why do we require public static void main(String args[]) method in Java


Question
programme? (CoreJava)
Following are few reasons why there is public static void main(String
args[])

a. public: The method can be accessed outside the class / package


b. static: You need not have an instance of the class to access the method
c. void: Your application need not return a value, as the JVM launcher
would return the value when it exits
d. main(): This is the entry point for the application

Answer
If the main() was not static, you would require an instance of the class in
order to execute the method.
If this is the case, what would create the instance of the class? What if
your class did not have a public constructor?

java Test

would get converted to Test.main() there by invoking the main()

Assume you have an ArrayList with 7 objects in it. And there is an int[] as

int[] intArray = new int[3];


intArray[0] = 2;
Question
intArray[1] = 4;
intArray[2] = 6;

How do you go about deleting objects from ArrayList based on the values
present in int[]? (CoreJava)
Answer This looks to be very simple question as we can make a for loop and
remove objects from
ArrayList. But remember that for the first time when you try to remove an
object at index 2 from ArrayList,
you would end up with an ArrayList size reduced from 7 to 6.

And your code would be throwing ArrayIndexOutOfBoundsException. Have


a look at this piece of code

public void testArrayList()


{
int[] intArray = new int[3];
intArray[0] = 2;
intArray[1] = 4;
intArray[2] = 6;

ArrayList al = new ArrayList();


for(int i=0; i < 7; i++)
{
al.add("test "+i);
}
System.out.println(al);

for(int x=0; x < intArray.length; x++)


{
System.out.println(al.remove(intArray[x]));
}
}

The above code doesn't work as the ArrayList size would shrink when you
try to remove the first element.

Have a look at this working code below

public void testArrayList()


{
int[] intArray = new int[3];
intArray[0] = 2;
intArray[1] = 4;
intArray[2] = 6;

ArrayList al = new ArrayList();


for(int i=0; i < 7; i++)
{
al.add("test "+i);
}
System.out.println(al);

for(int x = intArray.length-1; (x != -1); x--)


{
System.out.println(al.remove(intArray[x]));
}
}

You should try to delete from the bottom of the ArrayList. So that the size
of the ArrayList doesn't effect the index of the objects
that we are trying to delete.

How does a try statement determine which catch clause should be used
Question
to handle an exception? (CoreJava)
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
Answer appear.
The first catch clause that is capable of handling the exceptionis executed.
The remaining catch clauses are ignored

Question What is Tight Encapsulation? (CoreJava)


Answer Encapsulation is for member variables in a classes that may not be
accessed by any other classes. Below are few examples

Example 1:
class Test {
private String name;
}

This class is tightly encapsulated as you can't access the member "name".

Example 2:

class Test2 {
private String name;

public void setName(String name) {


if(name.equals("test2") {
this.name = name;
}
else {
//throw user exception
}
}
public String getName() {
return name;
}
}

The standard way to protect the data is to make it private, so that no other
class can get direct access to it, and
then write public methods to get the data and set the data. The method
that sets the data should carry out appropriate
checks to make sure the incoming data is valid.

In Example 2 we are validating the incoming data with "test2". If its test2
we are allowing the data to be set, else
we are throwing an exception.

Tight encapsulation will not only protect direct access to data members,
but will also prevent those members from being
set to improper values.

Question What is the maximum size of Integer wrapper class? (CoreJava)


2 TO THE POWER OF 31 - 1 or 2147483647 int value. Its little hard to
Answer
remember all these stuff :(

Can main() of one java program be invoked in another java program's


Question
main()? (CoreJava)
Answer Yes, This is possible. Have a look at the below code
package corejava;

public class A
{
public static void main(String args[])
{
System.out.println("in A");
}
}

package corejava;

public class B
{
public static void main(String args[])
{
System.out.println("in B");
String str = "one,two";
String[] strArray = str.split(str);
A.main(strArray);
}
}

Question Can we write a static keyword before the main class? (CoreJava)

Answer No

int[] array = new int[5];


int[] array1 = {1,2,3,4,5};
Question
Why not new is used in second statement?
(CoreJava)

In the first line we are creating an int array with size 5 but in the second
line we are creating an int array with 5 elements in it.
Answer
In short you are initializing an int array in line one and you are creating an
int array with elements in line two.

Question Can an exception be re-thrown? (CoreJava)


Yes, the exception can be rethrown. And it will be rethrown to the caller
method to handle the exception. This process
continues till a method that handles this exception is called.
Answer
Its better to handle the exception using "Exception" class as its the parent
class that is being extended by all other
exception classes.

Question What are the different inner classes available in java? Explain each inner
class with an example. (CoreJava)
Answer There are four types of inner classes in java

1. Member class
2. Static member class
3. Local class
4. Anonymous class

1. Member class

A member class is defined as a member of a class. The member class is


instance specific and has access to any and all
methods and members, even the parent's "this" reference. All public,
protected, default, and private members are visible
to instances of member class.

You must provide an instance of the enclosing class when you create a new
instance of member class.

public class EnclosingClass {


private int instVar = 1;

public class MemberClass {


public void innerMethod () {
instVar++;
}
}

public MemberClass createMember () {


return this.new MemberClass ();
}
}

If you need to create an instance of member class outside of the scope of


the enclosing class, you need to use an
instance of the enclosing class to create the member instance:

EnclosingClass ec = new EnclosingClass ();


EnclosingClass.MemberClass mc = ec.new MemberClass ();

or

EnclosingClass.MemberClass mc = new EnclosingClass ().new


MemberClass ();

member classes can be declared as abstract and final. The access


specifiers, public, protected, default and private
can be used within the class.
2. Static member class
A static member class is a static member of a class. Like any other static
method, a static member class has access to
all static methods of the parent, or top-level, class. These classes can use
instance variables and methods only
through an object reference. Only public, final, and static are permitted as
modifier inside a static member class.

E.g.
public class EnclosingClass {
private static int static_var = 0; // Has got access
public int instance_var = 0; // Has got no access

public static class StaticInnerClass {


}
}

Because the inner class is static, it can access only the static_var variable,
even though it is private
It cannot access the instance_var variable because it is not static,
regardless of the fact that it is public

The fully qualified class name for the inner class is


EnclosingClass.StaticInnerClass

These classes can be declared as public, abstract and final.

public class Outer {


public String name = "Outer";

public static void main (String argv[]) {


Inner i = new Inner ();

i.showName ();
} //End of main

private static class Inner {


String name = new String ("Inner");
void showName () {
System.out.println (name);
}
} //End of Inner class
}

3. Local class
Local classes are declared within a block of code and are visible only within
that block, just as any other method
variable. Local classes are good way to maintain Encapsulation.
Local classes, like local variables, cannot be declared public, protected,
private, or static.
Local classes cannot have static members.
Local classes can only access final local variables and method arguments of
the enclosing method.
Local inner classes can be declared as abstract and final.

Example

public class AnyClass {


void localClassDemo() { // a function
class LocalClass { // a class inside a function definition
void func() {
System.out.println( “in Local class”);
}
}
LocalClass local = new LocalClass();
local.func() ;
}
}

4. Anonymous class

An anonymous class is a local class that has no name. An anonymous class


is implicitly final.
Anonymous classes cannot be public, protected, private, or static. The
syntax for anonymous inner classes does not
allow for any modifiers to be used. An anonymous inner class can extend a
superclass or it can implement an interface.
But not both.

Example

public class SomeGUI extends JFrame


{
protected void buildGUI()
{
button1 = new JButton();
button2 = new JButton();
button1.addActionListener(
new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent e)
{
// do something
}
});
}
}

Question What is the disadvantage of using an inner class? (CoreJava)


Java bytecode has no concept of inner classes, so the compiler translates
inner classes into ordinary classes that are
accessible to any code in the same package. An inner class gets access to
the fields of the enclosing outer class-even if
these fields are declared private and the inner class is translated into a
Answer separate class. To let this separate class
access the fields of the outer class, the compiler silently changes these
fields' scope from private to package. As a
result, when you use inner classes, you not only have the inner class
exposed, but you also have the compiler silently
overruling your decision to make some fields private.

Question Does java support pointers? (CoreJava)


Strictly speaking, in Java, a pointer is a reference that is guaranteed not
to be null. However, when people use the
term pointer, they usually mean C++ style direct hardware address
pointers.
Answer
How can you write serious code without pointers? Java does not have raw
pointers like C or C++. It has something almost
as powerful, but many times safer called references (Java refers to them
as pointers in one place, the NullPointerException).
They are like pointers, except that the dangerous features are removed.

Question Does java support global variables? (CoreJava)


Though java doesn't support global variables, you can achieve this by
creating variables public and static.

Example

public class Global {


public static int x = 37;
public static String s = "test";
}
Answer
Such members can be accessed by saying:

public class test {


public static void main(String args[])
{
Global.x = Global.x + 100;
Global.s = "bbb";
}
}
Can an interface have variables defined in it? How do you use
Question
them? (CoreJava)
Yes we can have variables defined in an Interface. Have a look at the
class below to
know how to use those variables

public interface MyInterface


{
String STR1 = "STR1";
String STR2 = "STR2";
Answer }

public class MyTestClass implements MyInterface


{
public static void main(String args[])
{
System.out.println(STR1);
}
}

In a scenario, where you have to write an application which navigates


between different pre-defined states of the
Question
application, what should I be using, an Abstract class or an
Interface? (CoreJava)
I would suggest Abstract class as your application is navigating through
pre-defined states of the application.
Answer

Question What is the differences between inheritance and composition? (CoreJava)

Answer Inheritance:

Inheritance is the ability to derive one class from another; the derived class
(also called the subclass) inherits all
of the methods and data members of its superclass.

class Fruit {
//...
}
class Apple extends Fruit {
//...
}

In the above example, class Apple is related to class Fruit by inheritance,


because Apple extends Fruit. In this
example Fruit is superclass and Apple is subclass.

Composition:

Composition (called "has-a") is a relationship between classes where one


class has a data member that is an instance of
the other class.

class Fruit {
//...
}
class Apple {
private Fruit fruit = new Fruit();
//...
}

In the example above, class Apple is related to class Fruit by composition,


because Apple has an instance variable that
holds a reference to Fruit object.

In this example, Apple is what I will call front-end class and Fruit is what I
will call back-end class.
In a composition relationship, the front-end class holds a reference in one
of its instance variables to a back-end class.

Question What is meant by upcasting? (CoreJava)


Upcasting is where a derived object reference is cast to one of its base
objects reference.

class Base
{
public void show()
{
System.out.println("In Base class");
}
}

class Derived extends Base


{
public void show()
Answer {
System.out.println("In Derived class");
}

public static void main(String args[])


{
//upcasting
Base base = new Derived();
base.show();
}
}

When an object is upcast it becomes a base object for the purpose of the
cast, therefore any new fields and methods
declared in the derived class are not accessible.
Why Java is not complete Object Oriented Programming
Question
language? (CoreJava)
I am not sure what the interviewer has in his mind, but I can think of
only one reason,
Answer
"Java doesn't support multiple inheritance".

Do you guys have anthing to add?

Write a program in java to get in output as follows.


1
12
123
1 2 3 4.
Question
Write the program in java to get in output as follows.
1
23
456
7 8 9 10

Provide a solution (CoreJava)


Answer Below is the sample programme that gives you this output.

public class A
{
public static void main(String args[]) throws Exception
{
/**
* outputs the following format
*1
*23
*345
*4567
*/
for (int i = 1; i <= 4; i++) {
for (int j = 0; j < i; j++) {
System.out.print(i + j +" ");
}
System.out.println("");
}

System.out.println("*****************");

/**
* outputs the following format
*1
*12
*123
*1234
*/
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j +" ");
}
System.out.println("");
}

System.out.println("*****************");

/**
* outputs the following format
*1
*23
*456
* 7 8 9 10
*/
int k=1;
int y = 1;
for (int i = 1; i <= 4; i++) {
for (int j = 0; j < k; j++) {
System.out.print(y++ +" ");
}
k++;
System.out.println("");
}
}
}

What is the difference between break, continue and return


Question
statements? (CoreJava)
Answer

break: breaks the current loop and moves the cursor to next line after the
loop

e.g.
for(int i=0; i < 10; i++)
{
System.out.println("i"+i);
if(i == 5) break;
}

continue: Use continue when you have to skip few lines of code in a loop
when a condition is satisfied

e.g.

for(int i=0; i < 10; i++)


{
System.out.println("i:"+i);
if(i == 5) continue;
System.out.println("ii:"+i);
}

return: When a condition is satisfied you may want to return from the
method itself.

e.g.
public int getValue() {
int retValue = 0;
for(int i=0; i < 10; i++)
{
retValue = i;
System.out.println("i:"+i);
if(i == 5) return retValue;
System.out.println("ii:"+i);
}
return retValue;
}

Question What are dynamic class loaders? (CoreJava)


This is a mechanism of loading classes at runtime. They have following
characteristics,

a. lazyloading - load classes only when they are required. This helps in
memory management.

b. type safety linkate - Dynamic loading of a class should not require


additional run-time checks in order to
guarantee type safety. Adds link-time checks by replacing run-time checks.
They are performed only once.

c. User defined class loaders - Programmers have the control to load


classes in their applications. A user can
Answer define a class loader to load classes from remote location.

d. Multiple namespaces - Class loaders provide separate namespaces for


different software components. For
example an applet running in a browser loads classes from different jar
files. Assume that the classes loaded
from different jar files have same name but they are treated as distinct
types by JVM

E.g.

Class cla = Class.forName( "com.javagalaxy.util.MyClass" );


MyClass tCla = (MyClass)cla.newInstance( );
tCla.doSomething();

What is the difference between local inner class and non-local inner
Question
class? (CoreJava)
Answer Local inner classes may only access the local variables or method
parameters of the code block in which
they are defined. Local inner classes may only access final variables which
have been assigned a value.
A non-local inner class has access to all variables declared within the
encapsulating class

What is meant by Virtual function in Java? Does Java supports Virtual


Question
function? (CoreJava)
Java supports Virtual functions, all functions in Java are virtual by default.
Virtual functions or virtual methods are functions or methods that will be
redefined in derived classes.

Pure Virtual functions from C++ could be abstract functions without body.

Make your class abstract, define the pure virtual methods you want
subclasseses to provide implementation for
(using the abstract keyword in their definition) and you should be good.

public abstract class MyClass {


Answer public void concreteInitThing() {
// your code here
}

public abstract void specificImplementation(); //Virtual method


}

public class ConcreteImplementationOfMyClass extends MyClass {


public void specificImplementation() {
// Your code here
}
}

Question Why does main() in java taking String[] as argument? (CoreJava)


Since main(String[]) is the starting point for an application if you need to
Answer pass any arguments to
application at the startup time, we can send the parameters as Strings

Question Why java is called as PLATFORM independent? (CoreJava)


Answer Java applications consist of byte-code which may be interpreted by a
virtual engine. Thus, the
applications are able to run on any hardware for which a virtual engine
exists. Interpretation by a
virtual engine means a lower processing speed, compared to compiled
software. To counter this
disadvantage, improvements have been developed, like just-in-time
compilation (JIT), which
translates program instructions of the virtual engine into instructions for
the physical machine.
The result in this case is an aligned program in memory, which can be
executed rapidly without
interpretation. Aditional analysis of the runtime behavior with Hotspot-
technology results in
additional improvements.

Since Object class is the super class of every class in java and suppose if I
Question write class x extends y and this class x also extending Object,
Is this multiple Inheritance ? (CoreJava)
When you write "public class x" which doesn't extend any other class by
default x is extending Object.

Answer When you write "public class x extends y" x is extending y and y is
extending Object class

Your class can extend only one class.

How do you uniquely identify one instance of a class among 10 instances


Question
of the same class? (CoreJava)
Answer One way would be to check an objects hashCode.

What is the difference between inheritance and decorator design


Question
pattern? (DesignPatterns)
Decorators represent a powerful alternative to inheritance. Inheritance
lets you add functionality to classes
at compile time, decorators let you add functionality to objects at runtime.

For example
1. FileReader frdr = new FileReader(filename);
2. LineNumberReader lrdr = new LineNumberReader(frdr);

Answer Line 1 creates a file reader (frdr), and line 2 adds line-number tracking.

At runtime, decorators forward method calls to the objects they decorate.


For example, in the code above, the line
number reader, lrdr, forwards method calls to the file reader, frdr.
Decorators add functionality either before or
after forwarding to the object they decorate; for example, our line number
reader tracks the current line number as
it reads from an input stream.

What are the difference between DAO (Data Access Object ) and DAC
Question
(Data Access Component)? (DesignPatterns)
Answer The advantage of using data access objects is that any business object
(which contains application or operation specific details)
does not require direct knowledge of the final destination for the
information it manipulates. As a result, if it is
necessary to change where or how that data is stored that modification can
be made without needing to change the main application.
Data Access Objects can be used in Java to insulate an application from
the underlying Java persistence technology, which could
be JDBC, JDO, EJB, Hibernate, or any one of a range of technologies. Using
Data Access Objects means the underlying technology
can be upgraded or swapped without changing other parts of the
application.

Question Are enterprise beans allowed to use Thread.sleep()? (EJB)


Enterprise beans make use of the services provided by the EJB container,
such as life-cycle management. To avoid conflicts with these services,
Answer
enterprise beans are restricted from performing certain operations:
Managing or synchronizing threads

Is it possible to write two EJB's that share the same Remote and Home
Question interfaces, and have different bean classes? if so, what are the
advantages/disadvantages? (EJB)
It's certainly possible. In fact, there's an example that ships with the
Inprise Application Server of an Account interface with separate
Answer
implementations for CheckingAccount and SavingsAccount, one of which
was CMP and one of which was BMP.

Is it possible to specify multiple JNDI names when deploying an


Question
EJB? (EJB)
No. To achieve this you have to deploy your EJB multiple times each
Answer
specifying a different JNDI name.

Is there any way to force an Entity Bean to store itself to the db? I don't
Question wanna wait for the container to update the db, I want to do it NOW! Is it
possible? (EJB)
Specify the transaction attribute of the bean as RequiresNew. Then as per
section 11.6.2.4 of the EJB v 1.1 spec EJB container automatically starts a
Answer
new transaction before the method call. The container also performs the
commit protocol before the method result is sent to the client.

I am developing a BMP Entity bean. I have noticed that whenever the


create method is invoked, the ejbLoad() and the ejbStore() methods are
Question also invoked. I feel that once my database insert is done, having to do a
select and update SQL queries is major overhead. is this behavior typical of
all EJB containers? Is there any way to suppress these invocations? (EJB)
This is the default behaviour for EJB. The specification states that
ejbLoad() will be called before every transaction and ejbStore() after every
Answer
transaction. Each Vendor has optimizations, which are proprietary for this
scenario.

Question Can an EJB send asynchronous notifications to its clients? (EJB)


Answer Asynchronous notification is a known hole in the first versions of the EJB
spec. The recommended solution to this is to use JMS, which is becoming
available in J2EE-compliant servers. The other option, of course, is to use
client-side threads and polling. This is not an ideal solution, but it's
workable for many scenarios.

Question How can I access EJB from ASP? (EJB)


You can use the Java 2 Platform, Enterprise Edition Client Access Services
Answer (J2EETM CAS) COM Bridge 1.0, currently downloadable from
http://developer.java.sun.com/developer/earlyAccess/j2eecas/

Question Is there a guarantee of uniqueness for entity beans? (EJB)


There is no such guarantee. The server (or servers) can instantiate as
many instances of the same underlying Entity Bean (with the same PK) as
it wants. However, each instance is guaranteed to have up-to-date data
Answer
values, and be transactionally consistent, so uniqueness is not required.
This allows the server to scale the system to support multiple threads,
multiple concurrent requests, and multiple hosts.

How do the six transaction attributes map to isolation levels like "dirty
Question read"? Will an attribute like "Required" lock out other readers until I'm
finished updating? (EJB)
The Transaction Attributes in EJB do not map to the Transaction Isolation
levels used in JDBC. This is a common misconception. Transaction
Attributes specify to the container when a Transaction should be started,
Answer
suspended(paused) and committed between method invocations on
Enterprise JavaBeans. For more details and a summary of Transaction
Attributes refer to section 11.6 of the EJB 1.1 specification.

I have created a remote reference to an EJB in FirstServlet. Can I put the


Question
reference in a servlet session and use that in SecondServlet? (EJB)
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
Answer 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.

Can the primary key in the entity bean be a Java primitive type such as
Question
int? (EJB)
The primary key can't be a primitive type--use the primitive wrapper
Answer 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)

Question What's new in the EJB 2.0 specification? (EJB)


Following are the main features supported in EJB 2.0 * Integration of EJB
with JMS * Message Driven Beans * Implement additional Business
Answer
methods in Home interface which are not specific for bean instance. * EJB
QL.

Question What is the need of Remote and Home interface. Why cant it be in
one? (EJB)
In a few words, I would say that 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
who is responsible of creating, locating even removing one or more beans.
Answer
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.

Question What is the difference between Java Beans and EJB?s? (EJB)
Java Beans are client-side objects and EJBs are server side object, and
Answer
they have completely different development, lifecycle, purpose.

Question With regard to Entity Beans, what happens if both my EJB


Question Server and Database crash, what will happen to unsaved changes? Is there
any transactional log file used? (EJB)
Actually, if your EJB server crashes, you will not even be able to make a
connection to the server to perform a bean lookup, as the server will no
longer be listening on the port for incoming JNDI lookup requests. You will
lose any data that wasn't committed prior to the crash. This is where you
should start looking into clustering your EJB server.
Another Answer
Hi, Any unsaved and uncommited changes are lost the moment your EJB
Server crashes. If your database also crashes, then all the saved changes
Answer
are also lost unless you have some backup or some recovery mechanism
to retrieve the data. So consider database replication and EJB Clustering
for such scenarios, though the occurence of such a thing is very very rare.
Thx, Uma All databse have the concept of log files(for exampe oracle have
redo log files concept). So if data bases crashes then on starting up they
fill look up the log files to perform all pending jobs. But is EJB crashes, It
depend upon the container how frequenlty it passivates or how frequesntly
it refreshes the data with Database.

Question Question Can you control when passivation occurs? (EJB)


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 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.
Answer 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)."
Does EJB 1.1 support mandate the support for RMI-IIOP ? What is the
Question meaning of "the client API must support the Java RMI-IIOP programming
model for portability, but the underlying protocol can be anything" ? (EJB)
EJB1.1 does mandate the support of RMI-IIOP.
OK, to answer the second question:
There are 2 types of implementations that an EJB Server might provide:
CORBA-based EJB Servers and Proprietry EJB Servers. Both support the
RMI-IIOP API but how that API is implemented is a different story. (NB: By
API we mean the interface provided to the client by the stub or proxy).
A CORBA-based EJB Server actually implements its EJB Objects as CORBA
Answer
Objects (it therefore encorporates an ORB and this means that EJB's can
be contacted by CORBA clients (as well as RMI-IIOP clients)
A proprietry EJB still implements the RMI-IIOP API (in the client's stub) but
the underlying protocol can be anything. Therefore your EJB's CANNOT be
contacted by CORBA clients. The difference is that in both cases, your
clients see the same API (hence, your client portability) BUT how the stubs
communicate with the server is different.

The EJB specification says that we cannot use Bean Managed Transaction
Question
in Entity Beans. Why? (EJB)
The short, practical answer is... because it makes your entity beans
useless as a reusable component. Also, transaction management is best
left to the application server - that's what they're there for. It's all about
Answer atomic operations on your data. If an operation updates more than one
entity then you want the whole thing to succeed or the whole thing to fail,
nothing in between. If you put commits in the entity beans then it's very
difficult to rollback if an error occurs at some point late in the operation.

Question Can I invoke Runtime.gc() in an EJB? (EJB)


You shouldn't.
What will happen depends on the implementation, but the call will most
Answer likely be ignored. You should leave system level management like garbage
collection for the container to deal with. After all, that's part of the benefit
of using EJBs, you don't have to manage resources yourself.

What is clustering? What are the different algorithms used for


Question
clustering? (EJB)
Clustering is grouping machines together to transparantly provide
enterprise services.The client does not now the difference between
Answer approaching one server or approaching a cluster of servers.Clusters
provide two benefits: scalability and high availability. Further information
can be found in the JavaWorld article J2EE Clustering.

What is the advantage of using Entity bean for database operations, over
Question directly using JDBC API to do database operations? When would I use one
over the other? (EJB)
Answer 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 Mananged. In Container Managed Entity
Bean - Whenever the instance of the bean is created the container
automatically retrieves the data from the DB/Persistance 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, retrive values, assign them to the objects in the ejbLoad()
which will be called by the container when it instatiates a bean object.
Similarly in the ejbStore() the container saves the object values back the
the persistance storage. ejbLoad and ejbStore are callback methods and
can be only invoked by the container. Apart from this, when you use Entity
beans you dont need to worry about database transaction handling,
database connection pooling etc. which are taken care by the ejb
container. But in case of JDBC you have to explicitly do the above features.
what suresh told is exactly perfect. ofcourse, this comes under the
database transations, but i want to add this. the great thing about the
entity beans of container managed, whenever the connection is failed
during the transaction processing, the database consistancy is mantained
automatically. the container writes the data stored at persistant storage of
the entity beans to the database again to provide the database
consistancy. where as in jdbc api, we, developers has to do manually.

Question What is the role of serialization in EJB? (EJB)


A big part of EJB is that it is a framework for underlying RMI: remote
method invocation. You're invoking methods remotely from JVM space 'A'
on objects which are in JVM space 'B' -- possibly running on another
machine on the network.
To make this happen, all arguments of each method call must have their
current state plucked out of JVM 'A' memory, flattened into a byte stream
Answer which can be sent over a TCP/IP network connection, and then deserialized
for reincarnation on the other end in JVM 'B' where the actual method call
takes place.
If the method has a return value, it is serialized up for streaming back to
JVM A. Thus the requirement that all EJB methods arguments and return
values must be serializable. The easiest way to do this is to make sure all
your classes implement java.io.Serializable.

Question What is EJB QL? (EJB)


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 persistenceand is portable across containers and
persistence managers. EJB QL is used for queries of two types of finder
Answer
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.
Is is possible for an EJB client to marshall an object of class
Question
java.lang.Class to an EJB? (EJB)
Technically yes, spec. compliant NO! - The enterprise bean must not
attempt to query a class to obtain information about the declared members
Answer
that are not otherwise accessible to the enterprise bean because of the
security rules of the Java language.

Question Is it legal to have static initializer blocks in EJB? (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
Answer
initialize static fields - which may be illegal in EJB if they are read/write -
In EJB this can be achieved by including the code in either the ejbCreate(),
setSessionContext() or setEntityContext() methods.

Is it possible to stop the execution of a method before completion in a


Question
SessionBean? (EJB)
Stopping the execution of a method inside a Session Bean is not possible
Answer without writing code inside the Session Bean. This is because you are not
allowed to access Threads inside an EJB.

Question What is the default transaction attribute for an EJB? (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
Answer
attribute for those methods having container managed transaction. In
weblogic, the default transaction attribute for EJB is SUPPORTS.

What is the difference between session and entity beans? When should I
Question
use one or the other? (EJB)
An entity bean represents persistent global data from the database; a
session bean represents transient user-specific data that will die when the
Answer user disconnects (ends his session). Generally, the session beans
implement business methods (e.g. Bank.transferFunds) that call entity
beans (e.g. Account.deposit, Account.withdraw)

Is there any default cache management system with Entity beans ? In


Question other words whether a cache of the data in database will be maintained in
EJB ? (EJB)
Caching data from a database inside the Application Server are what
Entity EJB's are used for.The ejbLoad() and ejbStore() methods are used
to synchronize the Entity Bean state with the persistent storage(database).
Transactions also play an important role in this scenario. If data is
Answer
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 transcation
rolled back.
Question Why is ejbFindByPrimaryKey mandatory? (EJB)
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
Answer
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.

Question Why do we have a remove method in both EJBHome and EJBObject? (EJB)
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
Answer 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.

Question How can I call one EJB from inside of another EJB? (EJB)
EJBs can be clients of other EJBs. It just works. Use JNDI to locate the
Answer Home Interface of the other bean, then acquire an instance reference, and
so forth.

What is the difference between a Server, a Container, and a


Question
Connector? (EJB)
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
Answer 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 http://java.sun.com/j2ee/connector/ for more indepth
information on Connectors.

Question How is persistence implemented in enterprise beans? (EJB)


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

Question What is an EJB Context? (EJB)


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

Question Is method overloading allowed in EJB? (EJB)

Answer Yes you can overload methods

Question Should synchronization primitives be used on bean methods? (EJB)


No. The EJB specification specifically states that the enterprise bean is
Answer not allowed to use thread primitives. The container is responsible for
managing concurrent access to beans at runtime

Question Are we allowed to change the transaction isolation property in


Question
middle of a transaction? (EJB)
No. You cannot change the transaction isolation level in the middle of
Answer
transaction.

Question For Entity Beans, What happens to an instance field not mapped
Question
to any persistent storage,when the bean is passivated? (EJB)
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
Answer
instance gets logically disassociated from it's remote object.
Be careful here, as the functionality of passivation/activation for Stateless
Session, Stateful Session and Entity beans is completely different. For
entity beans the ejbPassivate method notifies the entity bean that it is
being disassociated with a particular entity prior to reuse or for dereferenc.

Question What is a Message Driven Bean, What functions does a message


Question
driven bean have and how do they work in collaboration with JMS? (EJB)
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.
Answer
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.

The EJB container implements the EJBHome and EJBObject classes. For
Question every request from a unique client, does the container create a separate
instance of the generated EJBHome and EJBObject classes? (EJB)
The EJB container maintains an instance pool. The container uses these
instances for the EJB Home reference irrespective of the client request.
while refering the EJB Object classes the container creates a separate
instance for each client request.
Another Answer
Answer The instance pool maintainence is up to the implementation of the
container. If the container provides one, it is available otherwise it is not
mandatory for the provider to implement it. Having said that, yes most of
the container providers implement the pooling functionality to increase the
performance of the app server. How it is implemented, it is again up to the
implementer.

What is the advantage of putting an Entity Bean instance from the "Ready
Question
State" to "Pooled state"? (EJB)
Answer 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".

Question Can a Session Bean be defined without ejbCreate() method? (EJB)


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.
Answer
Stateful Session Beans can have arguments (more than one create
method) stateful beans can contain multiple ejbCreate() as long as they
match with the home interface definition
You need a reference to your EJBObject to startwith. For that Sun insists
on putting a method for creating that reference (create method in the
home interface). The EJBObject does matter here. Not the actual bean.

Is it possible to share an HttpSession between a JSP and EJB? What


Question happens when I change a value in the HttpSession from inside an
EJB? (EJB)
You can pass the HttpSession as parameter to an EJB method, only if all
objects in session are serializable.This has to be consider as "passed-by-
value", that means that it's read-only in the EJB. If anything is altered
from inside the EJB, it won't be reflected back to the HttpSession of the
Servlet Container.The "pass-by-reference" can be used between EJBs
Remote Interfaces, as they are remote references. While it IS possible to
pass an HttpSession as a parameter to an EJB object, it is considered to be
"bad practice (1)" in terms of object oriented design. This is because you
Answer
are creating an unnecessary coupling between back-end objects (ejbs) and
front-end objects (HttpSession). Create a higher-level of abstraction for
your ejb's api. Rather than passing the whole, fat, HttpSession (which
carries with it a bunch of http semantics), create a class that acts as a
value object (or structure) that holds all the data you need to pass back
and forth between front-end/back-end. Consider the case where your ejb
needs to support a non-http-based client. This higher level of abstraction
will be flexible enough to support it. (1) Core J2EE design patterns (2001)

Question Is there any way to read values from an entity bean without locking it for
the rest of the transaction (e.g. read-only transactions)? We have a key-
value map bean which deadlocks during some concurrent reads. Isolation
levels seem to affect the database only, and we need to work within a
transaction. (EJB)
The only thing that comes to (my) mind is that you could write a 'group
accessor' - a method that returns a single object containing all of your
entity bean's attributes (or all interesting attributes). This method could
then be placed in a 'Requires New' transaction. This way, the current
Answer transaction would be suspended for the duration of the call to the entity
bean and the entity bean's fetch/operate/commit cycle will be in a separate
transaction and any locks should be released immediately. Depending on
the granularity of what you need to pull out of the map, the group accessor
might be overkill.

What is the difference between a "Coarse Grained" Entity Bean and a


Question
"Fine Grained" Entity Bean? (EJB)
A 'fine grained' entity bean is pretty much directly mapped to one
relational table, in third normal form.
A 'coarse grained' entity bean is larger and more complex, either because
its attributes include values or lists from other tables, or because it 'owns'
one or more sets of dependent objects. Note that the coarse grained bean
might be mapped to a single table or flat file, but that single table is going
to be pretty ugly, with data copied from other tables, repeated field groups,
columns that are dependent on non-key fields, etc.
Answer Fine grained entities are generally considered a liability in large systems
because they will tend to increase the load on several of the EJB server's
subsystems (there will be more objects exported through the distribution
layer, more objects participating in transactions, more skeletons in
memory, more EJB Objects in memory, etc.) The other side of the coin is
that the 1.1 spec doesn't mandate CMP Error! No index entries
found.support for dependent objects (or even indicate how they should be
supported), which makes it more difficult to do coarse grained objects with
CMP. The EJB 2.0 specification improves this in a huge way.

Question What is EJBDoclet? (EJB)


EJBDoclet is an open source JavaDoc doclet that generates a lot of the
Answer EJB related source files from custom JavaDoc comments tags embedded in
the EJB source file.

Question What are the main benefits of J2EE? (EJB)


Answer J2EE provides the following:
Faster solutions delivery time to market. J2EE uses "containers" to simplify
development. J2EE containers provide for the separation of business logic
from resource and lifecycle management, which means that developers can
focus on writing business logic -- their value add -- rather than writing
enterprise infrastructure. For example, the Enterprise JavaBeansTM
(EJBTM) container (implemented by J2EE technology vendors) handles
distributed communication, threading, scaling, transaction management,
etc. Similarly, Java Servlets simplify web development by providing
infrastructure for component, communication, and session management in
a web container that is integrated with a web server.
Freedom of choice. J2EE technology is a set of standards that many
vendors can implement. The vendors are free to compete on
implementations but not on standards or APIs. Sun supplies a
comprehensive J2EE Compatibility Test Suite (CTS) to J2EE licensees. The
J2EE CTS helps ensure compatibility among the application vendors which
helps ensure portability for the applications and components written for
J2EE. J2EE brings Write Once, Run AnywhereTM (WORATM) to the server.
Simplified connectivity. J2EE technology makes it easier to connect the
applications and systems you already have and bring those capabilities to
the web, to cell phones, and to devices. J2EE offers Java Message Service
for integrating diverse applications in a loosely coupled, asynchronous way.
J2EE also offers CORBA support for tightly linking systems through remote
method calls. In addition, J2EE 1.3 adds J2EE Connectors for linking to
enterprise information systems such as ERP systems, packaged financial
applications, and CRM applications.
By offering one platform with faster solution delivery time to market,
freedom of choice, and simplified connectivity, J2EE helps IT by reducing
TCO and simultaneously avoiding single-source for their enterprise
software needs.

Question Name a few Design Patterns used in J2ee applications (EJB)


Answer MVC, Front Controller, Session Facade, Data Access Object

What is the deployment order for the deployed server components in


Question
WebLogic server? (EJB)
§ JDBC Connection Pools
§ JDBC Multi Pools
§ JDCB Data Sources
§ JDBC Tx Data Sources
§ JMS Connection Factories
Answer
§ JMS Servers
§ Connector Components
§ EJB Components
§ Web App Components
--- An examination of the log file .,.,

Why do the create() or find() method return the remote reference or a


Question
primary key only? (EJB)
The EJB Specification prohibits this behavior, and the weblogic.ejbc
compiler checks for this behavior and prohibits any polymorphic type of
response from a create() or find() method.
The reason the create() and find() methods cannot return any object or
primitive type is similar to the reason that regular constructors can be cast
Answer
into the class itself or any of it?s super classes.
For example
A a = new A() or
A b = new B() where B is a child of A.
You cannot do, for example Vector v = new A();

Question Which XML parser comes with WebLogic Server 6.1? (EJB)
Answer We bundle a parser, based on Apache's Xerces 1.3.1 parser, in WebLogic
Server 6.1. In addition, we include a WebLogic proprietary high-
performance non-validating parser that you can use for small to medium
sized XML documents. The WebLogic XML Registry allows you to configure
the parser you want to use for specific document types.

Can I use the getAttribute() and setAttribute() methods of Version 2.2 of


Question
the Java Servlet API to parse XML documents? (EJB)
Yes. Use the setAttribute() method for SAX mode parsing and the
getAttribute() method for DOM mode parsing. Using these methods in a
Answer Servlet, however, is a WebLogic-specific feature. This means that the
Servlet may not be fully portable to other Servlet engines, so use the
feature with caution.

How can I run multiple instances of the same servlet class in the same
Question
WebLogic Server instance? (EJB)
If you want to run multiple instances, your servlet will have to implement
the SingleThreadModel interface. An instance of a class that implements
the SingleThreadModel interface is guaranteed not to be invoked by
multiple threads simultaneously. Multiple instances of a SingleThreadModel
interface are used to service simultaneous requests, each running in a
single thread.
Answer
When designing your servlet, consider how you use shared resources
outside of the servlet class such as file and database access. Because there
are multiple instances of servlets that are identical, and may use exactly
the same resources, there are still synchronization and sharing issues that
must be resolved, even if you do implement the SingleThreadModel
interface.

Question What technologies are included in J2EE? (EJB)


The primary technologies in J2EE are: Enterprise JavaBeansTM (EJBsTM),
JavaServer PagesTM (JSPsTM), Java Servlets, the Java Naming and
Answer
Directory InterfaceTM (JNDITM), the Java Transaction API (JTA), CORBA,
and the JDBCTM data access API.

What is the Java Authentication and Authorization Service (JAAS)


Question
1.0? (EJB)
The Java Authentication and Authorization Service (JAAS) provides a way
for a J2EE application to authenticate and authorize a specific user or group
of users to run it. JAAS is a Java programing language version of the
Answer
standard Pluggable Authentication Module (PAM) framework that extends
the Java 2 platform security architecture to support user-based
authorization.

Must my bean-managed persistence mechanism use the WebLogic JTS


Question
driver? (EJB)
BEA recommend that you use the TxDataSource for bean-managed
Answer
persistence.
Question Must EJBs be homogeneously deployed across a cluster? Why? (EJB)
Yes. Beginning with WebLogic Server version 6.0, EJBs must be
homogeneously deployed across a cluster for the following reasons:
n To keep clustering EJBs simple
n To avoid cross server calls which results in more efficiency. If EJBs are
not deployed on all servers, cross server calls are much more likely.
n To ensure that every EJB is available locally
Answer
n To ensure that all classes are loaded in an undeployable way
Every server must have access to each EJB's classes so that it can be
bound into the local JNDI tree. If only a subset of the servers deploys the
bean, the other servers will have to load the bean's classes in their
respective system classpaths which makes it impossible to undeploy the
beans.

Question Is an XSLT processor bundled in WebLogic Server? (EJB)


Yes, we bundle an XSLT processor, based on Apache's Xalan 2.0.1
Answer
processor, in WebLogic Server 6.1.

I plugged in a version of Apache Xalan that I downloaded from the


Question Apache Web site, and now I get errors when I try to transform documents.
What is the problem? (EJB)
You must ensure that the version of Apache Xalan you download from the
Apache Web site is compatible with Apache Xerces version 1.3.1. Because
you cannot plug in a different version of Apache Xerces (see the preceding
question), the only version of Apache Xerces that is compatible with
Answer
WebLogic Server 6.1 is 1.3.1.
The built-in parser (based on version 1.3.1 of Apache Xerces) and
transformer (based on version 2.0.1 of Apache Xalan) have been modified
by BEA to be compatible with each other.

Question How do I increase WebLogic Server memory? (EJB)


Increase the allocation of Java heap memory for WebLogic Server. (Set
the minimum and the maximum to the same size.) Start WebLogic Server
with the -ms32m option to increase the allocation, as in this example:
Answer $ java ... -ms32m -mx32m ...
This allocates 32 megabytes of Java heap memory to WebLogic Server,
which improves performance and allows WebLogic Server to handle more
simultaneous connections. You can increase this value if necessary.

Question What causes Java.io exceptions in the log file of WebLogic Server? (EJB)
Answer You may see messages like these in the log file:
(Windows NT)
java.io.IOException Connection Reset by Peer
java.io.EOFException Connection Reset by Peer
(Solaris)
java.io.Exception: Broken pipe
These messages occur when you are using servlets. A client initiates an
HTTP request, and then performs a series of actions on the browser:
1. Click Stop or enter equivalent command or keystrokes
2. Click Refresh or enter equivalent command or keystrokes
3. Send a new HTTP request.
The messages indicate that WebLogic Server has detected and recovered
from an interrupted HTTP request.

Question What is the function of T3 in WebLogic Server? (EJB)


T3 provides a framework for WebLogic Server messages that support for
enhancements. These enhancements include abbreviations and features,
such as object replacement, that work in the context of WebLogic Server
clusters and HTTP and other product tunneling.
T3 predates Java Object Serialization and RMI, while closely tracking and
leveraging these specifications. T3 is a superset of Java Object.
Serialization or RMI; anything you can do in Java Object Serialization and
Answer RMI can be done over T3.
T3 is mandated between WebLogic Servers and between programmatic
clients and a WebLogic Server cluster. HTTP and IIOP are optional
protocols that can be used to communicate between other processes and
WebLogic Server. It depends on what you want to do. For example, when
you want to communicate between
n A browser and WebLogic Server-use HTTP
n An ORB and WebLogic Server-IIOP.

What are the enhancements in EJB 2.0 specification with respect to


Question
Asynchronous communication? (EJB)
EJB 2.0 mandates integration between JMS and EJB.
We have specified the integration of Enterprise JavaBeans with the Java
Message Service, and have introduced message-driven beans. A message-
driven bean is a stateless component that is invoked by the container as a
Answer result of the arrival of a JMS message. The goal of the message-driven
bean model is to make developing an enterprise bean that is
asynchronously invoked to handle the processing of incoming JMS
messages as simple as developing the same functionality in any other JMS
MessageListener.

Question What are the enhancements in EJB 2.0 with respect to CMP? (EJB)
EJB 2.0 extends CMP to include far more robust modeling capability, with
support for declarative management of relationships between entity EJBs.
Developers no longer need to re-establish relationships between the
various beans that make up their application -- the container will restore
the connections automatically as beans are loaded, allowing bean
Answer developers to navigate between beans much as they would between any
standard Java objects.
EJB 2.0 also introduces for the first time a portable query language, based
on the abstract schema, not on the more complex database schema. This
provides a database and vendor-independent way to find entity beans at
run time, based on a wide variety of search criteria.

Question Can you briefly describe about local interfaces? (EJB)


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

What are the special design care that must be taken when you work with
Question
local interfaces? (EJB)
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
Answer
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.

Question What happens if remove( ) is never invoked on a session bean? (EJB)


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

What is the difference between creating a distributed application using


Question
RMI and using a EJB architecture? (EJB)
Answer It is possible to create the same application using RMI and EJB. But in
case of EJB the container provides the requisite services to the component
if we use the proper syntax. It thus helps in easier development and lesser
error and use of proven code and methodology. But the investment on
application server is mandatory in that case. But this investment is
warranted because it results in less complex and maintainable code to the
client, which is what the end client wants. Almost all the leading
application servers provide load balancing and performance tuning
techniques. In case of RMI we have to code the services and include in the
program the way to invoke these services.

Can the bean class implement the EJBObject class directly? If not
Question
why? (EJB)
It is better not to do it will make the Bean class a remote object and its
methods can be accessed without the containers? security, and transaction
Answer
implementations if our code by mistake passed it in one of its parameters.
Its just a good design practice.

What does isIdentical() method return in case of different type of


Question
beans? (EJB)
Stateless ? true always
Stateful ? depends whether the references point to the same session object
Answer
Entity ? Depends whether the primary key is the same and the home is
same

Question How should you type cast a remote object? Why? (EJB)
A client program that is intended to be interoperable with all compliant
EJB Container implementations must use the
javax.rmi.PortableRemoteObject.narrow(...) method to perform type-
Answer narrowing of the client-side representations of the remote home and
remote interfaces. Programs using the cast operator for narrowing the
remote and remote home interfaces are likely to fail if the Container
implementation uses RMI-IIOP as the underlying communication transport.

Question What should you do in a passivate method? (EJB)


You try to make all nontransient variables, which are not one of the
following to null. For the given list the container takes care of serializing
and restoring the object when activated.
Serializable objects, null, UserTransaction, SessionContext, JNDI contexts
Answer in the beans context, reference to other beans, references to connection
pools.
Things that must be handled explicitly are like a open database connection
etc. These must be closed and set to null and retrieved back in the activate
method.

What is the relationship between local interfaces and container-managed


Question
relationships? (EJB)
Entity beans that have container-managed relationships with other entity
beans, must be accessed in the same local scope as those related beans,
Answer and therefore typically provide a local client view. In order to be the target
of a container-managed relationship, an entity bean with container-
managed persistence must provide a local interface.

Question What does a remove method do for different cases of beans? (EJB)
Answer Stateless Session : Does not do anything to the bean as moving the bean
from free pool to cache are managed by the container depending on load.
Stateful Session: Removes the bean from the cache.
Entity Bean: Deletes the bean (data) from persistent storage

Question How does a container-managed relationship work? (EJB)


An entity bean accesses related entity beans by means of the accessor
methods for its container-managed relationship fields, which are specified
by the cmr-field elements of its abstract persistence schema defined in the
deployment descriptor. Entity bean relationships are defined in terms of
Answer
the local interfaces of the related beans, and the view an entity bean
presents to its related beans is defined by its local home and local
interfaces. Thus, an entity bean can be the target of a relationship from
another entity bean only if it has a local interface.

What is the new basic requirement for a CMP entity bean class in 2.0
Question
from that of ejb 1.1? (EJB)
It must be abstract class. The container extends it and implements
Answer
methods which are required for managing the relationships

Question What are the basic classes required in the client for invoking an EJB? (EJB)
The home and the remote interfaces, the implementation of the Naming
Context Factory, the stubs and skeletons.
Answer
In some App servers the stubs and the skeletons can be dynamically
downloaded from the server

What is the difference between Message Driven Beans and Stateless


Question
Session beans? (EJB)
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
Answer 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.
Note: 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.

Question What is the need for Clustering? (EJB)


To scale the application so that it
Answer 1. Is Highly Available
2. Has High Throughput.
Question What are the benefits of Clustering (Workload Management)? (EJB)
They are
1. It balances client processing requests, allowing incoming work requests
to be distributed according to a configured Workload Management selection
policy.
2. It provides fail over capability by redirecting client requests to a running
server when one or more servers are unavailable. This improves the
Answer availability of applications and administrative services.
3. It enables systems to be scaled up to serve a higher client load than
provided by the basic configuration. With server groups and clones
additional instances of servers can easily be added to the configuration.
4. It enables servers to be transparently maintained and upgraded while
applications remain available for users.
5. It centralizes administration of application servers and other objects.

Question What are the types of Scaling? (EJB)

There are two types of scaling


Answer 1. Vertical Scaling
2. Horizontal Scaling.

Question What is Vertical Scaling? (EJB)


When multiple server clones of an application server are defined on the
Answer same physical m/c, it is called Vertical Scaling. The objective is to use the
processing power of that m/c more efficiently.

Question What is Horizontal Scaling? (EJB)


When Clones of an application server are defined on multiple physical
Answer m/c, it is called Horizontal Scaling. The objective is to use more than one
less powerful m/c more efficiently.

Question What is a Server Group? (EJB)


A server group is a template of an Application Server(and its contents)
i.e, it is a logical representation of the application server. It has the same
Answer structure and attributes as the real Application Server, but it is not
associated with any node, and does not correspond to any real server
process running on any node.

Question What is a Clone? (EJB)


The copies of a server group are called Clones. But unlike a Server Group
Answer Clones are associated with a node and are real server process running in
that node.

Question What is Ripple Effect? (EJB)


The process of propagating the changes in the properties of a server
Answer
group during runtime to all the associated clones is called Ripple Effect.
Question What level of Load Balancing is possible with EJBs? (EJB)
The workload management service provides load balancing for the
following types of enterprise beans
Answer 1. Homes of entity or session beans
2. Instances of entity beans
3. Instances of stateless session beans

What is the basic requirement for in-memory replication in


Question
Weblogic? (EJB)
1. The data in session should consist only of Serialized objects.
Answer
2. Only setAttribute function should be used to set objects in session

Question How JDBC services can be used in clustered environment? (EJB)


Identical DataSource has to be created in each clustered server instances
Answer
and configure to use different connection pools.

What are the services that should not be used in a Clustered


Question
Environment? (EJB)
Non-clustered services:
1. File Services
Answer 2. Time services
3. Weblogic events
4. Weblogic Workspaces (In WebLogic 5.1)

Question Mention some tools to cluster Web Servers? (EJB)

Web Servers can be clustered using


Answer 1. Edge Server.
2. DNS

Question What is in-memory replication? (EJB)


The process by which the contents in the memory of one physical m/c are
Answer
replicated in all the m/c in the cluster is called in-memory replication.

Question What cannot be or is recommended not to be done using EJB? (EJB)


Answer · 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
enterprise bean class be declared as final.
· Enterprise Bean must not use thread synchronization primitives to
synchronize execution of multiple instances.
· Enterprise bean must not attempt to manage threads. 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.
· Enterprise Bean must not use the AWT functionality to attempt to output
information to a display, or to input information from a keyboard.
· Enterprise bean must not use java.io package to attempt to access files
and directories in file system.
· Enterprise bean must not attempt to directly read or write a file
descriptor.
· Enterprise bean must not attempt to listen on a socket, accept
connections on a socket, or use a socket for multicast.
· Enterprise bean must not attempt to set the socket factory used by
ServerSocket, Socket, or the stream handler factory used by URL.
· 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.
· 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.
· 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.
· Enterprise bean must not attempt to define a class in a package.
· Enterprise bean must not attempt to use the subclass and object
substitution features of the Java Serialization Protocol.
· Enterprise bean must not attempt to obtain the security policy
information for a particular code source.
· Enterprise bean must not attempt to access or modify the security
configuration objects (Policy, Security, Provider, Signer, and Identity).
· 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.
Enterprise bean must not attempt to load a native library.

Question What is t3 protocol in weblogic? (EJB)


T3 is a physical layer (layer 1) protocol, and definitely you don't expect
Answer any browser to recognize it (e.g. TCP is a layer 4 protocol, and HTTP is
running on top of TCP port 80). It's main use is for EJB's communicating.

Question What design pattern would you use to reduce JNDI lookups? (EJB)
Answer Use ServiceLocator/EJBHomeFactory Pattern to reduce expensive JNDI
lookup process.
How it works is to cache those service objects when the client performs
JNDI lookup first
time and reuse that service object from the cache second time onwards for
other clients.
This technique maintains a cache of service objects and looks up the JNDI
only first time
for a service object. This technique reduces redundant and expensive JNDI
lookup process
thus increasing performance significantly.

Service Locator Pattern implements this technique by having a class to


cache service objects,
methods for JNDI lookup and methods for getting service objects from the
cache.

ServiceLocator acts as interceptor between client and JNDI.

Question What are the different XML files used in J2EE? (EJB)
While working with an .ear deployment, you would generally be having

web.xml - (part of .war file)


Answer
ejb-jar.xml - (part of .jar file)
application.xml - (part of .ear file)
weblogic-ejb-jar.xml - (part of .jar file and while using weblogic server)

Question What is a design pattern? (General)


A design pattern systematically names, motivates, and explains a general
Answer
design that addresses a recurring design problem.

Question Describe the visitor design pattern (General)


Represents an operation to be performed on the elements of an object
structure. Visitor lets you define a new operation without changing the
classes of the elements on which it operates.
Answer The root of a class hierarchy defines an abstract method to accept a
visitor. Subclasses implement this method with visitor.visit(this). The
Visitor interface has visit methods for all subclasses of the baseclass in the
hierarchy.

What is the difference between Internationalization and


Question
Localization? (General)
Internationalization (i18n) is the up front work of building a system in
such a way that it can be adapted to multiple
locales. Internationalization involves writing and designing an application
so that it can be used with different
languages, date, time, currency and other values without software
modification.
Answer
Localization (l10n) is the process of actually adapting internationalized
software to the needs of users in a particular
geographical or cultural area. Localization involves writing and designing
an application capable of dealing with a
specific region, country or language.

What is the difference between a Portal server and an Application


Question
server? (General)
Answer Before understanding portal server, we will have to understand portal. As
we know, portal in nothing but a web
application. In simple words, a portal server is an application having a
portal and its management capabilities.
In traditional web application, we have a separate management section for
managing the web application. Portal server
provides the application as well as that management section. In other
words, a portal server is an application deployed
inside application server.

Whereas, an application server is a system that provides the execution


environment that is at the core of network
computing or web-based architectures, providing a full set of services.

What are the basic configurations that needs to be taken care before an
Question
application is deployed in weblogic server 8.1? (General)
I remember of the following configurations

- Setting up connection pool


Answer - Setting up Datasource
- Setting up a new server instance
- Clustering (if required)
- JMS Queue's and Topics (if required)

Question What is the Collections API? (JavaUtil)


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

Question What is the List interface? (JavaUtil)


Answer The List interface provides support for ordered collections of objects.

Question What is the Vector class? (JavaUtil)


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

Question What is an Iterator interface? (JavaUtil)


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

Question Which java.util classes and interfaces support event handling? (JavaUtil)
The EventObject class and the EventListener interface support event
Answer
processing

Question What is the GregorianCalendar class? (JavaUtil)


Answer The GregorianCalendar provides support for traditional Western calendars

Question What is the Locale class? (JavaUtil)


The Locale class is used to tailor program output to the conventions of a
Answer
particular geographic, political, or cultural region
Question What is the SimpleTimeZone class? (JavaUtil)
Answer The SimpleTimeZone class provides support for a Gregorian calendar

Question What is the Map interface? (JavaUtil)


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

What is the highest-level event class of the event-delegation


Question
model? (JavaUtil)
The java.util.EventObject class is the highest-level class in the event-
Answer
delegation class hierarchy

Question What is the Collection interface? (JavaUtil)


The Collection interface provides support for the implementation of a
Answer mathematical bag - an unordered collection of objects that may contain
duplicates

Question What is the Set interface? (JavaUtil)


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

Question What is the purpose of the enableEvents() method? (JavaUtil)


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
Answer
for a particular event. The enableEvents() method is used by objects that
handle events by overriding their event-dispatch methods.

Question What is the ResourceBundle class? (JavaUtil)


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

Question What is the default size of the vector? (JavaUtil)


Vector v = new Vector();
Answer Constructs an empty vector so that its internal data array has size 10 and
its standard capacity increment is zero.

Question How does an included file in jsp look in the compiled .java file? (JavaUtil)
Answer If you are using jsp action include as <jsp:include page="a.jsp"/> then
you see the following line of code in the service method of the .java file
(servlet)
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response,
"a.jsp", out, false);

If you are using directive include as *lt;%@ include file="a.jsp" %> then
you see the following line of code within the static block as
static {
_jspx_dependants = new java.util.Vector(1);
_jspx_dependants.add("/a.jsp");
}

Question What is the Properties class? (JavaUtil)


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

Question What is the difference between ArrayList and Vector? (JavaUtil)


a.Internally, both the ArrayList and Vector hold onto their contents using
an Array. A Vector defaults to doubling the size of its array, while the
ArrayList increases its array size by 50 percent.
Answer b.ArrayList doesn't have a constructor for specifying the incremental
capacity, where as Vector has a constructor to specify the initial capacity
and incremental capacity.
c.Vector is synchronized where as ArrayList is not synchronized

Question What is the difference between Iterator and Enumeration? (JavaUtil)


Iterator takes the place of Enumeration in the Java collections framework.
Iterators differ from enumerations in two ways: Iterators allow the caller to
Answer
remove elements from the underlying collection during the iteration with
well-defined semantics. Method names have been improved.

Question What is the ResourceBundle class? (JavaUtil)


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

How would you guarantee sorting of objects in a class that implements


Question
Map interface? (JavaUtil)
TreeMap class implements SortedMap interface and provides the
guarantee of sorted objects in ascending key order.

TreeMap treeMap = new TreeMap();


Answer
treeMap.put("abc", "xyz");
treeMap.put("xyz", "abc");
treeMap.put("def","xyz");
System.out.println("treeMap::"+treeMap);

How can u avoid the conflict between java.util.Date and


Question
java.sql.Date? (JavaUtil)
Answer If your code has to use both java.util.Date and java.sql.Date in the same
class,

Depending on number of times you are using these classes you can import
any one of the
package. e.g. Assume you are using java.util.Date for 5 times in your code
and you are
using java.sql.Date only for one time then import java.util.* and for using
java.sql.Date

use java.sql.Date sDate = new java.sql.Date();

Question What is the difference b/w HashSet & LinkedHashSet? (JavaUtil)


Comment from Gyula, From the javadoc the LinkedHashSet differs from
HashSet in that it maintains a doubly-linked list running through all of its
Answer entries. By this it preservs the order of elements when somebody iterates
over them (the elements will be retrieved in a predictable order - the order
of inserting).

What is the query used to display all tables names in SQL Server (Query
Question
analyzer)? (JDBC)
Answer select * from information_schema.tables

Question How many types of JDBC Drivers are present and what are they? (JDBC)

There are 4 types of JDBC Drivers


Type 1: JDBC-ODBC Bridge Driver
Answer Type 2: Native API Partly Java Driver
Type 3: Network protocol Driver
Type 4: JDBC Net pure Java Driver

Question What is the fastest type of JDBC driver? (JDBC)


JDBC driver performance will depend on a number of issues:
(a) the quality of the driver code,
(b) the size of the driver code,
(c) the database server and its load,
(d) network topology,
Answer (e) the number of times your request is translated to a different API.
In general, all things being equal, you can assume that the more your
request and response change hands, the slower it will be. This means that
Type 1 and Type 3 drivers will be slower than Type 2 drivers (the database
calls are make at least three translations versus two), and Type 4 drivers
are the fastest (only one translation).

Question What Class.forName will do while loading drivers? (JDBC)


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

Question How to Retrieve Warnings? (JDBC)


Answer SQLWarning objects are a subclass of SQLException that deal with
database access warnings. Warnings do not stop the execution of an
application, as exceptions do; they simply alert the user that something
did not happen as planned. A warning can be reported on a Connection
object, a Statement object (including PreparedStatement and
CallableStatement objects), or a ResultSet object. Each of these classes
has a getWarnings method, which you must invoke in order to see the first
warning reported on the calling object
E.g.
SQLWarning warning = stmt.getWarnings();
if (warning != null) {
while (warning != null) {
System.out.println("Message: " + warning.getMessage());
System.out.println("SQLState: " + warning.getSQLState());
System.out.print("Vendor error code: ");
System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}

Question what are stored procedures? How is it useful? (JDBC)


A stored procedure is a set of statements/commands which reside in the
database. The stored procedure is precompiled and saves the database the
effort of parsing and compiling sql statements everytime a query is run.
Each Database has it's own stored procedure language, usually a variant of
C with a SQL preproceesor. Newer versions of db's support writing stored
procs in Java and Perl too.
Answer Before the advent of 3-tier/n-tier architecture it was pretty common for
stored procs to implement the business logic( A lot of systems still do it).
The biggest advantage is of course speed. Also certain kind of data
manipulations are not achieved in SQL. Stored procs provide a mechanism
to do these manipulations. Stored procs are also useful when you want to
do Batch updates/exports/houseKeeping kind of stuff on the db. The
overhead of a JDBC Connection may be significant in these cases.

Question How to call a Stored Procedure from JDBC? (JDBC)


The first step is to create a CallableStatement object. As with Statement
an and PreparedStatement objects, this is done with an open Connection
object. A CallableStatement object contains a call to a stored procedure.
Answer
E.g.
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();

Question Is the JDBC-ODBC Bridge multi-threaded? (JDBC)


No. The JDBC-ODBC Bridge does not support concurrent access from
different threads. The JDBC-ODBC Bridge uses synchronized methods to
Answer serialize all of the calls that it makes to ODBC. Multi-threaded Java
programs may use the Bridge, but they won't get the advantages of multi-
threading.

Does the JDBC-ODBC Bridge support multiple concurrent open


Question
statements per connection? (JDBC)
No. You can open only one Statement object per connection when you
Answer
are using the JDBC-ODBC Bridge.

Question What is cold backup, hot backup, warm backup recovery? (JDBC)
a. cold backup - All these files must be backed up at the same time,
before the databaseis restarted.
Answer b. hot backup - official name is 'online backup' ? is a backup taken of each
tablespace while the database is running and is being accessed by the
users.

Question When we will Denormalize data? (JDBC)


Data denormalization is reverse procedure, carried out purely for reasons
Answer of improving performance.It maybe efficient for a high-throughput system
to replicate data for certain data.

Question What is the advantage of using PreparedStatement? (JDBC)


If we are using PreparedStatement the execution time will be less.The
PreparedStatement object contains not just an SQL statement,but the SQL
Answer statement that has been precompiled.This means that when the
PreparedStatement is executed,the RDBMS can just run the
PreparedStatement's Sql statement without having to compile it first.

Question What is a "dirty read"? (JDBC)


Quite often in database processing, we come across the situation wherein
one transaction can change a value, and a second transaction can read this
value before the original change has been committed or rolled back. This is
known as a dirty read scenario because there is always the possibility that
Answer the first transaction may rollback the change, resulting in the second
transaction having read an invalid value. While you can easily command a
database to disallow dirty reads, this usually degrades the performance of
your application due to the increased locking overhead. Disallowing dirty
reads also leads to decreased system concurrency.

Question What is Metadata and why should I use it? (JDBC)


Metadata ('data about data') is information about one of two things:
Database information (java.sql.DatabaseMetaData), or Information about a
specific ResultSet (java.sql.ResultSetMetaData).
Answer
Use DatabaseMetaData to find information about your database, such as
its capabilities and structure. Use ResultSetMetaData to find information
about the results of an SQL query, such as size and types of columns

Question Different types of Transaction Isolation Levels? (JDBC)


Answer The isolation level describes the degree to which the data being updated
is visible to other transactions. This is important when two transactions are
trying to read the same row of a table. Imagine two transactions A & B.
Three types of inconsistencies can occur:
· Dirty-read: A has changed a row, but has not committed the changes. B
reads the uncommitted data but his view of the data may be wrong if A
rolls back his changes and updates his own changes to the database.
· Non-repeatable read: B performs a read, but A modifies or deletes that
data later. If B reads the same row again, he will get different data.
· Phantoms: A does a query on a set of rows to perform an operation. B
modifies the table such that a query of A would have given a different
result. The table may be inconsistent.
TRANSACTION_READ_UNCOMMITTED : DIRTY READS, NON-REPEATABLE
READ AND PHANTOMS CAN OCCUR.
TRANSACTION_READ_COMMITTED : DIRTY READS ARE PREVENTED, NON-
REPEATABLE READ AND PHANTOMS CAN OCCUR.
TRANSACTION_REPEATABLE_READ : DIRTY READS , NON-REPEATABLE
READ ARE PREVENTED AND PHANTOMS CAN OCCUR.
TRANSACTION_SERIALIZABLE : DIRTY READS, NON-REPEATABLE READ
AND PHANTOMS ARE PREVENTED.

Question What is 2 phase commit? (JDBC)


A 2-phase commit is an algorithm used to ensure the integrity of a
committing transactionIn Phase 1, the transaction coordinator contacts
potential participants in the transaction. The participants all agree to make
the results of the transaction permanent but do not do so immediately. The
participants log information to disk to ensure they can complete Phase 2. If
Answer
all the participants agree to commit, the coordinator logs that agreement
and the outcome is decided. The recording of this agreement in the log
ends Phase
In Phase 2, the coordinator informs each participant of the decision, and
they permanently update their resources.

Question How do you handle your own transaction ? (JDBC)


Connection Object has a method called setAutocommit ( Boolean istrue)
Answer - Default is true
Set the Parameter to false , and begin your transaction

What is the normal procedure followed by a java client to access the


Question
db.? (JDBC)
The database connection is created in 3 steps:
1.Find a proper database URL (see FAQ on JDBC URL)
2.Load the database driver
3.Ask the Java DriverManager class to open a connection to your database
In java code, the steps are realized in code as follows:
Answer 1.Create a properly formatted JDBR URL for your database. (See FAQ on
JDBC URL for more information). A JDBC URL has the form
jdbc:someSubProtocol://myDatabaseServer/theDatabaseName 2.
Class.forName("my.database.driver");
3 . Connection conn = DriverManager.getConnection("a.JDBC.URL",
"databaseLogin","databasePassword");

Question What is a data source? (JDBC)


Answer A DataSource class brings another level of abstraction than directly using
a connection object. Data source can be referenced by JNDI. Data Source
may point to RDBMS, file System , any DBMS etc.

Question What are collection pools? What are the advantages? (JDBC)
A connection pool is a cache of database connections that is maintained in
Answer
memory, so that the connections may be reused

How do you get Column names only for a table (SQL Server)? Write the
Question
Query. (JDBC)
select name from syscolumns where id=(select id from sysobjects where
Answer
name='user_hdr') order by colid --user_hdr is the table name

What is the difference between cached rowset, jdbrowset and


Question
webrowset? (JDBC)
A CachedRowSet is a disconnected, serializable, scrollable container for
tabular data. A primary purpose of the CachedRowSet class is to provide a
representation of a JDBC ResultSet that can be passed between different
components of a distributed application. For example, a CachedResultSet
can be used to send the result of a query executed by an Enterprise
JavaBeans component running in a server environment over a network to a
client running in a web browser. A second use for CachedRowSets is to
provide scrolling and updating for ResultSets that don't provide these
capabilities themselves. A CachedRowSet can be used to augment the
capabilities of a JDBC driver that doesn't have full support for scrolling and
updating. Finally, a CachedRowSet can be used to provide Java
Answer
applications with access to tabular data in an environment such as a thin
client or PDA, where it would be inappropriate to use a JDBC driver due to
resource limitations or security considerations. The CachedRowSet class
provides a means to "get rows in" and "get changed rows out" without the
need to implement the full JDBC API.
A JdbcRowSet is a connected rowset that wraps a ResultSet object. The
main use of JdbcRowSet is to wrap a ResultSet and make it appear as a
JavaBeans(tm) component.
The WebRowSet class extends CachedRowSet with the ability to write out
the state of the the RowSet as an XML document. The format of the XML
document is described by the DTD 'RowSet.dtd'.

Question Is thin driver provided by Oracle a type 4 driver? (JDBC)

Answer YES

What are different types of isolation levels in JDBC and explain where you
Question
can use them? (JDBC)
Answer If the application needs only committed records, then
TRANSACTION_READ_COMMITED isolation is the good choice.
If the application needs to read a row exclusively till you finish your work,
then TRANSACTION_REPEATABLE_READ is the best choice.
If the application needs to control all of the transaction problems(dirty
read, phantom read and unrepeatable read), you can choose
TRANSACTION_SERIALIZABLE for maximum safety. Performance issues
have to be taken care with this. E.g Banking applications.
If the application don't have to deal with concurrent transactions, then the
best choice is TRANSACTION_NONE to improve performance.
If the application is searching for records from the database then you can
easily choose TRANSACTION_READ_UNCOMMITED because you need not
worry about other programmes that are inserting records at the same
time. It improves performance.

What is the difference between Statement, PreparedStatement and


Question
CallableStatemen? (JDBC)
Statement is used for static SQL statement with no input and output
parameters, PreparedStatement is used for dynamic SQL statement with
input parameters and CallableStatement is used for dynamic SQL satement
with both input and output parameters, but PreparedStatement and
CallableStatement can be used for static SQL statements as well.
CallableStatement is mainly meant for stored procedures.

PreparedStatement gives better performance when compared to Statement


because it is pre-parsed and pre-compiled by the database once for the
first time and then onwards it reuses the parsed and compiled statement.
Answer Because of this feature, it significantly improves performance when a
statement executes repeatedly, It reduces the overload incurred by parsing
and compiling.

CallableStatement gives better performance when compared to


PreparedStatement and Statement when there is a requirement for single
request to process multiple complex statements. It parses and stores the
stored procedures in the database and does all the work at database itself
that in turn improves performance. But we loose java portability and we
have to depend up on database specific stored procedures.

Who implements the methods of JDBC (java.sql.*) interfaces?


e.g.resultSet.next() is a method in ResultSet interface and Sun doesn't
Question provide any
implementation for this method. Who actually provides the
implementation. (JDBC)
Its the JDBC Driver vendor. Java provides the specifications for the
Answer interfaces
and its the vendor who has to implement those methods.

Consider the following code:

Class.forName("mypackage.MyClass");
Connection con = DriverManager.getConnection("some connection
Question
string");

What Exceptions can be thrown in the above statements?


(JDBC)

Answer The above statements can throw any or all of the following exceptions
LinkageError - if the linkage fails
ExceptionInInitializerError - if the initialization provoked by this method
fails
ClassNotFoundException - if the class cannot be located
SQLException - if a database access error occurs

What actually does Class.forName("mypackage.MyDriver"); method


Question
do? (JDBC)
Class.forName("..."); initializes the provided class and returns the Class
object associated with the class or interface with the given string name.

For example, the following code fragment returns the runtime Class
Answer
descriptor for the class
named java.lang.Thread:

Class t = Class.forName("java.lang.Thread")

If your SQL gets truncated in the process of execution, How would you
Question know how much of data is trnasfered
and how much of data is left over? (JDBC)
This can be known using the class DataTruncation. DataTruncation is an
exception that reports a DataTruncation
warning (on reads) or throws a DataTruncation exception (on writes) when
JDBC unexpectedly truncates (meaning
that less information was read or written than requested) a data value. So
all we should do is write our code
Answer using the getDataSize() and getTransferSize() methods of this class in our
catch block trapping this SQLException.

The getDataSize() returns the number of bytes of data that should have
been transferred while the getTransferSize()
method returns the number of bytes of data actually transferred. The
SQLstate for a DataTruncation is 01004.

Question What is the difference between different JDBC drivers? (JDBC)


Answer Type 1:
A JDBC-ODBC bridge provides JDBC API access via one or more ODBC
drivers. Note that some ODBC native code and in many
cases native database client code must be loaded on each client machine
that uses this type of driver. Hence, this kind
of driver is generally most appropriate when automatic installation and
downloading of a Java technology application is
not important.

Type 2:
A native-API partly Java technology-enabled driver converts JDBC calls into
calls on the client API for Oracle, Sybase,
Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of
driver requires that some binary code be
loaded on each client machine.

Type 3:
A net-protocol fully Java technology-enabled driver translates JDBC API
calls into a DBMS-independent net protocol which
is then translated to a DBMS protocol by a server. This net server
middleware is able to connect all of its Java
technology-based clients to many different databases. The specific protocol
used depends on the vendor. In general,
this is the most flexible JDBC API alternative. It is likely that all vendors of
this solution will provide products
suitable for Intranet use. In order for these products to also support
Internet access they must handle the additional
requirements for security, access through firewalls, etc., that the Web
imposes. Several vendors are adding JDBC
technology-based drivers to their existing database middleware products.

Type 4:
A native-protocol fully Java technology-enabled driver converts JDBC
technology calls into the network protocol used by
DBMSs directly. This allows a direct call from the client machine to the
DBMS server and is a practical solution for
Intranet access. Since many of these protocols are proprietary the database
vendors themselves will be the primary
source for this style of driver. Several database vendors have these in
progress.

Question How may messaging models do JMS provide for and what are they? (JMS)
JMS provide for two messaging models, publish-and-subscribe and point-
Answer
to-point queuing

Question What is messaging? (JMS)


Messaging is a mechanism by which data can be passed from one
Answer
application to another application.

Question What is point-to-point messaging? (JMS)


With point-to-point message passing the sending application/client
establishes a named message queue in the JMS broker/server and sends
Answer messages to this queue. The receiving client registers with the broker to
receive messages posted to this queue. There is a one-to-one relationship
between the sending and receiving clients.

Can two different JMS services talk to each other? For instance, if A and B
are two different JMS providers, can Provider A send messages directly to
Question
Provider B? If not, then can a subscriber to Provider A act as a publisher to
Provider B? (JMS)
Answer The answers are no to the first question and yes to the second. The JMS
specification does not require that one JMS provider be able to send
messages directly to another provider. However, the specification does
require that a JMS client must be able to accept a message created by a
different JMS provider, so a message received by a subscriber to Provider
A can then be published to Provider B. One caveat is that the publisher to
Provider B is not required to handle a JMSReplyTo header that refers to a
destination that is specific to Provider A.

What is the advantage of persistent message delivery compared to


Question
nonpersistent delivery? (JMS)
If the JMS server experiences a failure, for example, a power outage, any
message that it is holding in primary storage potentially could be lost. With
persistent storage, the JMS server logs every message to secondary
Answer storage. (The logging occurs on the front end, that is, as part of handling
the send operation from the message producing client.) The logged
message is removed from secondary storage only after it has been
successfully delivered to all consuming clients

Question How is a java object message delivered to a non-java Client? (JMS)


It is according to the specification that the message sent should be
received in the same format. A non-java client cannot receive a message in
Answer
the form of java object. The provider in between handles the conversion of
the data type and the message is transferred to the other end.

Question What is MDB and What is the special feature of that? (JMS)
MDB is Message driven bean, which very much resembles the Stateless
session bean. The incoming and out going messages can be handled by the
Answer
Message driven bean. The ability to communicate asynchronously is the
special feature about the Message driven bean.

Question Give an example of using the publish/subscribe model. (JMS)


JMS can be used to broadcast shutdown messages to clients connected to
the Weblogic server on a module wise basis. If an application has six
Answer
modules, each module behaves like a subscriber to a named topic on the
server.

Question What is the difference between the Mailing and Messaging? (JMS)
Java Mailing is the set of APIs that primarily concerns with the sending of
Mail messages through the standard mail protocols. Messaging is the way
Answer of communicating to the remote machines using Message Oriented
Middlewares. Message Oriented Middlewares do not use mailing internally
for communication. They create their own channels for communication.

Question What are the types of messaging? (JMS)


Answer There are two kinds of Messaging.
Synchronous Messaging:
Synchronous messaging involves a client that waits for the server to
respond to a message.
Asynchronous Messaging:
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.

Question What is publish/subscribe messaging? (JMS)


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

Why doesn't the JMS API provide end-to-end synchronous message


Question
delivery and notification of delivery? (JMS)
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
Answer 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.

What are the core JMS-related objects required for each JMS-enabled
Question
application? (JMS)
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
Answer 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)

Question What are the various message types supported by JMS? (JMS)

Answer Stream Messages ? Group of Java Primitives


Map Messages ? Name Value Pairs.
Name being a string
Value being a java primitive
Text Messages ? String messages (since being widely used a separate
messaging Type has been supported)
Object Messages ? Group of serialize able java object
Bytes Message ? Stream of uninterrupted bytes

Question What is the Role of the JMS Provider? (JMS)


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

Question How does a typical client perform the communication? (JMS)


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

Question Give an example of using the point-to-point model. (JMS)


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
Answer
the server can send information back to this client after completion of the
print job.

Question How does the Application server handle the JMS Connection? (JMS)
- App server creates the server session and stores them in a pool
- Connection consumer uses the server session to put messages in the
session of the JMS.
Answer
- Server session is the one that spawns the JMS session.
- Applications written by Application programmers creates the message
listener

Question What protocols does JNDI provide an interface to? (JNDI)


JNDI itself is independent of any specific directory access protocol.
Individual service providers determine the protocols to support. JNDI
supports popular protocols, such as LDAP (Light weight Directory Access
Answer
Protocol) , NDS(Netscape Directory Service), DNS(Domain Naming
Service), and NIS(Network Information Service), supplied by different
vendors.

Question What is Context and InitialContext? (JNDI)


Answer A context represents a set of bindings within a naming service. A Context
object provides the methods for binding names to objects and unbinding
names from objects, for renaming objects, and for listing the bindings.
JNDI performs all naming operations relative to a context.
The JNDI specification defines an InitialContext class. This class is
instantiated with properties that define the type of naming service in use
(such as provider URL, security, ID and password to use when connecting).

What's the difference between JNDI lookup(), list(), listBindings(), and


Question
search()? (JNDI)
lookup() attempts to find the specified object in the given context. I.e., it
looks for a single, specific object and either finds it in the current context
or it fails.
list() attempts to return an enumeration of all of the NameClassPair's of all
of the objects in the current context. I.e., it's a listing of all of the objects
in the current context but only returns the object's name and the name of
the class to which the object belongs.
listBindings() attempts to return an enumeration of the Binding's of all of
Answer
the objects in the current context. I.e., it's a listing of all of the objects in
the current context with the object's name, its class name, and a reference
to the object itself.
search() attempts to return an enumeration of all of the objects matching
a given set of search criteria. It can search across multiple contexts (or
not). It can return whatever attributes of the objects that you desire. Etc.
It's by far the most complex and powerful of these options but is also the
most expensive.

Question Components of JNDI (JNDI)


Naming Interface- The naming interface organizes information
hierarchically and maps human-friendly names to addresses or objects that
are machine-friendly. It allows access to named objects through multiple
namespaces.
Answer Directory Interface- JNDI includes a directory service interface that
provides access to directory objects, which can contain attributes, thereby
providing attribute-based searching and schema support
Service Provider Interface- JNDI comes with the SPI, which supports the
protocols provided by third parties.

Question Is JNDI a protocol? Where is it used? (JNDI)


Yes.HotJava Views 1.1 is using JNDI to access LDAP. Enterprise APIs such
as Enterprise JavaBeans, Java Message Service, JDBC 2.0 make use of
Answer
JNDI to for their naming and directory needs. RMI over IIOP applications
can use JNDI to access the CORBA (COS) naming service.

Question What are native methods? How do you use them? (JNI)
Native methods are methods written in other languages like C, C++, or
Answer even assembly language.
You can call native methods from Java using JNI

Question Can we implement an interface in a JSP? (JSP)

Answer No
Question What is the difference between ServletContext and PageContext? (JSP)

ServletContext: Gives the information about the container


Answer
PageContext: Gives the information about the Request

What is the difference in using request.getRequestDispatcher() and


Question
context.getRequestDispatcher()? (JSP)
request.getRequestDispatcher(path): In order to create it we need to
give the relative path of the resource
Answer
context.getRequestDispatcher(path): In order to create it we need to give
the absolute path of the resource.

Question How to pass information from JSP to included JSP? (JSP)

Answer Using <%jsp:param> tag.

Question What is the difference between directive include and jsp include? (JSP)
<%@ include> : Used to include static resources during translation time.
Answer
: Used to include dynamic content or static content during runtime.

Question What is the difference between RequestDispatcher and sendRedirect? (JSP)


RequestDispatcher: server-side redirect with request and response
Answer objects.
sendRedirect : Client-side redirect with new request and response objects.

Question How does JSP handle runtime exceptions? (JSP)


Using errorPage attribute of page directive and also we need to specify
Answer isErrorPage=true if the current page is intended to URL redirecting of a
JSP.

Question How do you delete a Cookie within a JSP? (JSP)

Cookie mycook = new Cookie("name","value");


response.addCookie(mycook);
Answer Cookie killmycook = new Cookie("mycook","value");
killmycook.setMaxAge(0);
killmycook.setPath("/");
killmycook.addCookie(killmycook);

Question How do I mix JSP and SSI #include? (JSP)


Answer If you're just including raw HTML, use the #include directive as usual
inside your .jsp file.
<!--#include file="data.inc"-->
But it's a little trickier if you want the server to evaluate any JSP code
that's inside the included file. Ronel Sumibcay
(ronel@LIVESOFTWARE.COM) says: If your data.inc file contains jsp code
you will have to use
<%@ vinclude="data.inc" %>
The <!--#include file="data.inc"--> is used for including non-JSP files.

Question What is the difference between Model 1 and Model 2 architecture? (JSP)
Answer In Model 1 there is no Controller and in Model 2 there is a Controller

How can my application get to know when a HttpSession is


Question
removed? (JSP)
Define a Class HttpSessionNotifier which implements
HttpSessionBindingListener and implement the functionality what you need
Answer
in valueUnbound() method.
Create an instance of that class and put that instance in HttpSession.

Question How can I implement a thread-safe JSP page? (JSP)


You can make your JSPs thread-safe by having them implement the
Answer SingleThreadModel interface. This is done by adding the directive <%@
page isThreadSafe="false" % > within your JSP page.

Question How many JSP scripting elements are there and what are they? (JSP)

There are three scripting language elements:


declarations
Answer
scriptlets
expressions

In the Servlet 2.4 specification SingleThreadModel has been deprecates,


Question
why? (JSP)
Because it is not practical to have such model. Whether you set
isThreadSafe to true or false, you should take care of concurrent client
Answer
requests to the JSP page by synchronizing access to any shared objects
defined at the page level.

Question How do I include static files within a JSP page? (JSP)


Static resources should always be included using the JSP include
directive. This way, the inclusion is performed just once during the
translation phase. The following example shows the syntax: Do note that
Answer
you should always supply a relative URL for the file attribute. Although you
can also include static resources using the action, this is not advisable as
the inclusion is then performed for each and every request.

Question How do I mix JSP and SSI #include? (JSP)


If you're just including raw HTML, use the #include directive as usual
inside your .jsp file.
<!--#include file="data.inc"-->
But it's a little trickier if you want the server to evaluate any JSP code that's
Answer
inside the included file. If your data.inc file contains jsp code you will have
to use
<%@ vinclude="data.inc" %>
The <!--#include file="data.inc"--> is used for including non-JSP files.
Question Can a JSP page process HTML FORM data? (JSP)
Yes. However, unlike servlets, you are not required to implement HTTP-
protocol specific methods like doGet() or doPost() within your JSP page.
You can obtain the data for the FORM input elements via the request
implicit object within a scriptlet or expression as:
<%
Answer
String item = request.getParameter("item");
int howMany = new Integer(request.getParameter("units")).intValue();
%>
or
<%= request.getParameter("item") %>

Question What JSP lifecycle methods can I override? (JSP)


You cannot override the _jspService() method within a JSP page. You can
however, override the jspInit() and jspDestroy() methods within a JSP
page. jspInit() can be useful for allocating resources like database
connections, network connections, and so forth for the JSP page. It is good
programming practice to free any allocated resources within jspDestroy().
The jspInit() and jspDestroy() methods are each executed just once during
the lifecycle of a JSP page and are typically declared as JSP declarations:
<%!
public void jspInit() {
Answer
...
}
%>

<%!
public void jspDestroy() {
...
}
%>

Question How do I include static files within a JSP page? (JSP)


Static resources should always be included using the JSP include
directive. This way, the inclusion is performed just once during the
translation phase. The following example shows the syntax:
Answer <%@ include file="copyright.html" %>
Do note that you should always supply a relative URL for the file attribute.
Although you can also include static resources using the action, this is not
advisable as the inclusion is then performed for each and every request.

Question How do I perform browser redirection from a JSP page? (JSP)


Answer You can use the response implicit object to redirect the browser to a
different resource, as:
response.sendRedirect("http://www.foo.com/path/error.html");
You can also physically alter the Location HTTP header attribute, as shown
below:
<%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
String newLocn = "/newpath/index.html";
response.setHeader("Location",newLocn);
%>
You can also use the: <jsp:forward page="/newpage.jsp" /> Also note
that you can only use this before any output has been sent to the client. I
beleve this is the case with the response.sendRedirect() method as well.
If you want to pass any paramateres then you can pass using <jsp:forward
page="/servlet/login"> <jsp:param name="username" value="jsmith" />
</jsp:forward>>

Question Can a JSP page instantiate a serialized bean? (JSP)


No problem! The useBean action specifies the beanName attribute, which
can be used for indicating a serialized bean. For example:
<jsp:useBean id="shop" type="shopping.CD" beanName="CD" />
<jsp:getProperty name="shop" property="album" />
Answer A couple of important points to note. Although you would have to name
your serialized file "filename.ser", you only indicate "filename" as the value
for the beanName attribute. Also, you will have to place your serialized file
within the WEB-INF\jsp\beans directory for it to be located by the JSP
engine.

Can you make use of a ServletOutputStream object from within a JSP


Question
page? (JSP)
No. You are supposed to make use of only a JSPWriter object (given to
you in the form of the implicit object out) for replying to clients. A
JSPWriter can be viewed as a buffered version of the stream object
Answer returned by response.getWriter(), although from an implementational
perspective, it is not. A page author can always disable the default
buffering for any page using a page directive as:
<%@ page buffer="none" %>

What's a better approach for enabling thread-safe servlets and JSPs?


Question
SingleThreadModel Interface or Synchronization? (JSP)
Although the SingleThreadModel technique is easy to use, and works well
for low volume sites, it does not scale well. If you anticipate your users to
increase in the future, you may be better off implementing explicit
synchronization for your shared data. The key however, is to effectively
minimize the amount of code that is synchronzied so that you take
maximum advantage of multithreading.
Answer Also, note that SingleThreadModel is pretty resource intensive from the
server's perspective. The most serious issue however is when the number
of concurrent requests exhaust the servlet instance pool. In that case, all
the unserviced requests are queued until something becomes free - which
results in poor performance. Since the usage is non-deterministic, it may
not help much even if you did add more memory and increased the size of
the instance pool.

Question Can I stop JSP execution while in the midst of processing a request? (JSP)
Answer Yes. Preemptive termination of request processing on an error condition
is a good way to maximize the throughput of a high-volume JSP engine.
The trick (asuming Java is your scripting language) is to use the return
statement when you want to terminate further processing. For example,
consider:
<% if (request.getParameter("foo") != null) {
// generate some html or update bean property
} else {
/* output some error message or provide redirection back to the input
form after creating a memento bean updated with the 'valid' form
elements that were input. this bean can now be used by the previous form
to initialize the input elements that were valid then, return from the body
of the _jspService() method to terminate further processing */
return;
}
%>

How can I get to view any compilation/parsing errors at the client while
Question
developing JSP pages? (JSP)
With JSWDK 1.0, set the following servlet initialization property within the
\WEB-INF\servlets.properties file for your application:
Answer jsp.initparams=sendErrToClient=true
This will cause any compilation/parsing errors to be sent as part of the
response to the client.

Question Is there a way to reference the "this" variable within a JSP page? (JSP)
Yes, there is. Under JSP 1.0, the page implicit object is equivalent to
Answer
"this", and returns a reference to the servlet generated by the JSP page.

How do I instantiate a bean whose constructor accepts parameters using


Question
the useBean tag? (JSP)
Answer Consider the following bean: package bar;
public class FooBean {
public FooBean(SomeObj arg) {
...
}
//getters and setters here
}
The only way you can instantiate this bean within your JSP page is to use a
scriptlet. For example, the following snippet creates the bean with session
scope:
&l;% SomeObj x = new SomeObj(...);
bar.FooBean foobar = new FooBean(x);
session.putValue("foobar",foobar);
%> You can now access this bean within any other page that is part of the
same session as: &l;%
bar.FooBean foobar = session.getValue("foobar");
%>
To give the bean "application scope", you will have to place it within the
ServletContext as:
&l;%
application.setAttribute("foobar",foobar);
%>
To give the bean "request scope", you will have to place it within the
request object as:
&l;%
request.setAttribute("foobar",foobar);
%>
If you do not place the bean within the request, session or application
scope, the bean can be accessed only within the current JSP page (page
scope).
Once the bean is instantiated, it can be accessed in the usual way:
jsp:getProperty name="foobar" property="someProperty"/ jsp:setProperty
name="foobar" property="someProperty" value="someValue"/

Question Can I invoke a JSP error page from a servlet? (JSP)


Yes, you can invoke the JSP error page and pass the exception object to
it from within a servlet. The trick is to create a request dispatcher for the
JSP error page, and pass the exception object as a
javax.servlet.jsp.jspException request attribute. However, note that you
can do this from only within controller servlets. If your servlet opens an
OutputStream or PrintWriter, the JSP engine will throw the following
translation error:
java.lang.IllegalStateException: Cannot forward as OutputStream or Writer
has already been obtained
The following code snippet demonstrates the invocation of a JSP error page
from within a controller servlet:
protected void sendErrorRedirect(HttpServletRequest request,
HttpServletResponse response, String errorPageURL, Throwable e) throws
ServletException, IOException {
request.setAttribute ("javax.servlet.jsp.jspException", e);
Answer
getServletConfig().getServletContext().
getRequestDispatcher(errorPageURL).forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse
response) {
try {
// do something
} catch (Exception ex) {
try {
sendErrorRedirect(request,response,"/jsp/MyErrorPage.jsp",ex);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Question How can you store international / Unicode characters into a cookie? (JSP)

One way is, before storing the cookie URLEncode it.


Answer URLEnocder.encoder(str);
And use URLDecoder.decode(str) when you get the stored cookie.
Question What are the implicit objects? (JSP)
Implicit objects are objects that are created by the web container and
contain information related to a particular request, page, or application.
They are:
request
response
pageContext
Answer
session
application
out
config
page
exception

Question Is JSP technology extensible? (JSP)


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

How can I implement a thread-safe JSP page? What are the advantages
Question
and Disadvantages of using it? (JSP)
You can make your JSPs thread-safe by having them implement the
SingleThreadModel interface. This is done by adding the directive
<%@ page isThreadSafe="false" %> within your JSP page.
With this, instead of a single instance of the servlet generated for your JSP
page loaded in memory, you will have N instances of the servlet loaded
and initialized, with the service method of each instance effectively
synchronized. You can typically control the number of instances (N) that
are instantiated for all servlets implementing SingleThreadModel through
Answer the admin screen for your JSP engine.
More importantly, avoid using the <%! DECLARE %> tag for variables. If
you do use this tag, then you should set isThreadSafe to true, as
mentioned above. Otherwise, all requests to that page will access those
variables, causing a nasty race condition.
SingleThreadModel is not recommended for normal use. There are many
pitfalls, including the example above of not being able to use <%! %>.
You should try really hard to make them thread-safe the old fashioned
way: by making them thread-safe

Question How does JSP handle run-time exceptions? (JSP)


Answer You can use the errorPage attribute of the page directive to have
uncaught run-time exceptions automatically forwarded to an error
processing page. For example:
<%@ page errorPage="error.jsp" %>
redirects the browser to the JSP page error.jsp if an uncaught exception is
encountered during request processing. Within error.jsp, if you indicate
that it is an error-processing page, via the directive:
<%@ page isErrorPage="true" %>
the Throwable object describing the exception may be accessed within the
error page via the exception implicit object.
Note: You must always use a relative URL as the value for the errorPage
attribute.

How do I prevent the output of my JSP or Servlet pages from being


Question
cached by the browser? (JSP)
You will need to set the appropriate HTTP header attributes to prevent
the dynamic content output by the JSP page from being cached by the
browser. Just execute the following scriptlet at the beginning of your JSP
pages to prevent them from being cached at the browser. You need both
the statements to take care of some of the older browser versions.
Answer <%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy
server
%>

Question How do I use comments within a JSP page? (JSP)


You can use "JSP-style" comments to selectively block out code while
debugging or simply to comment your scriptlets. JSP comments are not
visible at the client. For example:
<%-- the scriptlet is now commented out
<%
out.println("Hello World");
%>
--%>
You can also use HTML-style comments anywhere within your JSP page.
These comments are visible at the client. For example:
Answer
<!-- (c) 2004 javagalaxy.com -->
Of course, you can also use comments supported by your JSP scripting
language within your scriptlets. For example, assuming Java is the
scripting language, you can have:
<%
//some comment
/**
yet another comment
**/
%>

Question Response has already been commited error. What does it mean? (JSP)
Answer This error show only when you try to redirect a page after you already
have written something in your page. This happens because HTTP
specification force the header to be set up before the lay out of the page
can be shown (to make sure of how it should be displayed...content-
type="text/html" or "text/xml" or "plain-text" or "image/jpg", etc...) When
you try to send a redirect status (Number is line_status_402), your HTTP
server cannot send it right now if it hasn't finished to set up the header. If
not starter to set up the header, there are no problems, but if it 's already
begin to set up the header, then your HTTP server expects these headers to
be finished setting up and it cannot be the case if the stream of the page is
not over... In this last case it's like you have a file started with <HTML
Tag> <Some Headers> <Body> some output (like testing your
variables...) ... and before you indicate that the file is over (and before the
size of the page can be setted up in the header), you try to send a redirect
status... It s simply impossible due to the specification of HTTP 1.0 and 1.1

Question How do I use a scriptlet to initialize a newly instantiated bean? (JSP)


A jsp:useBean action may optionally have a body. If the body is specified,
its contents will be automatically invoked when the specified bean is
instantiated. Typically, the body will contain scriptlets or jsp:setProperty
tags to initialize the newly instantiated bean, although you are not
restricted to using those alone.
The following example shows the "today" property of the Foo bean
initialized to the current date when it is instantiated. Note that here, we
Answer
make use of a JSP expression within the jsp:setProperty action.
<jsp:useBean id="foo" class="com.Bar.Foo" >
<jsp:setProperty name="foo" property="today" value="<
%=java.text.DateFormat.getDateInstance().format(new java.util.Date())
%>"/ >
<%-- scriptlets calling bean setter methods go here --%>
</jsp:useBean >

How can I enable session tracking for JSP pages if the browser has
Question
disabled cookies? (JSP)
Answer We know that session tracking uses cookies by default to associate a
session identifier with a unique user. If the browser does not support
cookies, or if cookies are disabled, you can still enable session tracking
using URL rewriting.
URL rewriting essentially includes the session ID within the link itself as a
name/value pair. However, for this to be effective, you need to append the
session ID for each and every link that is part of your servlet response.
Adding the session ID to a link is greatly simplified by means of of a couple
of methods: response.encodeURL() associates a session ID with a given
URL, and if you are using redirection, response.encodeRedirectURL() can
be used by giving the redirected URL as input.
Both encodeURL() and encodeRedirectedURL() first determine whether
cookies are supported by the browser; if so, the input URL is returned
unchanged since the session ID will be persisted as a cookie.
Consider the following example, in which two JSP files, say hello1.jsp and
hello2.jsp, interact with each other. Basically, we create a new session
within hello1.jsp and place an object within this session. The user can then
traverse to hello2.jsp by clicking on the link present within the page.Within
hello2.jsp, we simply extract the object that was earlier placed in the
session and display its contents. Notice that we invoke the encodeURL()
within hello1.jsp on the link used to invoke hello2.jsp; if cookies are
disabled, the session ID is automatically appended to the URL, allowing
hello2.jsp to still retrieve the session object.
Try this example first with cookies enabled. Then disable cookie support,
restart the brower, and try again. Each time you should see the
maintenance of the session across pages.
Do note that to get this example to work with cookies disabled at the
browser, your JSP engine has to support URL rewriting.
hello1.jsp
<%@ page session="true" %>
<%
Integer num = new Integer(100);
session.putValue("num",num);
String url =response.encodeURL("hello2.jsp");
%>
<a href='<%=url%>'>hello2.jsp</a>
hello2.jsp
<%@ page session="true" %>
<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is "+i.intValue());

Question How can I declare methods within my JSP page? (JSP)


You can declare methods for use within your JSP page as declarations.
The methods can then be invoked within any other methods you declare,
or within JSP scriptlets and expressions.
Do note that you do not have direct access to any of the JSP implicit
objects like request, response, session and so forth from within JSP
methods. However, you should be able to pass any of the implicit JSP
variables as parameters to the methods you declare. For example:
<%!
public String whereFrom(HttpServletRequest req) {
HttpSession ses = req.getSession();
...
return req.getRemoteHost();
}
%>
<%
out.print("Hi there, I see that you are coming in from ");
%>
Answer
<%= whereFrom(request) %>
Another Example
file1.jsp:
<%@page contentType="text/html"%>
<%!
public void test(JspWriter writer) throws IOException{
writer.println("Hello!");
}
%>

file2.jsp
<%@include file="file1.jsp"%>
<html>
<body>
<%test(out);% >
</body>
</html>

Question Is there a way I can set the inactivity lease period on a per-session basis?
(JSP)

Typically, a default inactivity lease period for all sessions is set within
your JSP engine admin screen or associated properties file. However, if
your JSP engine supports the Servlet 2.1 API, you can manage the
inactivity lease period on a per-session basis. This is done by invoking the
HttpSession.setMaxInactiveInterval() method, right after the session has
Answer been created. For example:
<%
session.setMaxInactiveInterval(300);
%>
would reset the inactivity period for this session to 5 minutes. The
inactivity interval is set in seconds.

Question How can I set a cookie and delete a cookie from within a JSP page? (JSP)

A cookie, mycookie, can be deleted using the following scriptlet:


<%
//creating a cookie
Cookie mycookie = new Cookie("aName","aValue");
response.addCookie(mycookie);
Answer //delete a cookie
Cookie killMyCookie = new Cookie("mycookie", null);
killMyCookie.setMaxAge(0);
killMyCookie.setPath("/");
response.addCookie(killMyCookie);
%>

Question How does a servlet communicate with a JSP page? (JSP)


Answer The following code snippet shows how a servlet instantiates a bean and
initializes it with FORM data posted by a browser. The bean is then placed
into the request, and the call is then forwarded to the JSP page, Bean1.jsp,
by means of a request dispatcher for downstream processing.
public void doPost (HttpServletRequest request, HttpServletResponse
response) {
try {
govi.FormBean f = new govi.FormBean();
String id = request.getParameter("id");
f.setName(request.getParameter("name"));
f.setAddr(request.getParameter("addr"));
f.setAge(request.getParameter("age"));
//use the id to compute
//additional bean properties like info
//maybe perform a db query, etc.
// . . .
f.setPersonalizationInfo(info);
request.setAttribute("fBean",f);
getServletConfig().getServletContext().getRequestDispatcher
("/jsp/Bean1.jsp").forward(request, response);
} catch (Exception ex) {
...
}
}
The JSP page Bean1.jsp can then process fBean, after first extracting it
from the default request scope via the useBean action.
jsp:useBean id="fBean" class="govi.FormBean" scope="request"/
jsp:getProperty name="fBean" property="name" / jsp:getProperty
name="fBean" property="addr" / jsp:getProperty name="fBean"
property="age" / jsp:getProperty name="fBean"
property="personalizationInfo" /

How do I have the JSP-generated servlet subclass my own custom servlet


Question
class, instead of the default? (JSP)
One should be very careful when having JSP pages extend custom servlet
classes as opposed to the default one generated by the JSP engine. In
doing so, you may lose out on any advanced optimization that may be
provided by the JSP engine. In any case, your new superclass has to fulfill
the contract with the JSP engine by:
Implementing the HttpJspPage interface, if the protocol used is HTTP, or
implementing JspPage otherwise Ensuring that all the methods in the
Servlet interface are declared final Additionally, your servlet superclass
Answer also needs to do the following:
The service() method has to invoke the _jspService() method
The init() method has to invoke the jspInit() method
The destroy() method has to invoke jspDestroy()
If any of the above conditions are not satisfied, the JSP engine may throw
a translation error.
Once the superclass has been developed, you can have your JSP extend it
as follows:
<%@ page extends="packageName.ServletName" %<

How can I prevent the word "null" from appearing in my HTML input text
Question
fields when I populate them with a resultset that has null values? (JSP)
You could make a simple wrapper function, like
<%!
String blanknull(String s) {
return (s == null) ? "" : s;
Answer }
%>
then use it inside your JSP form, like
<input type="text" name="shoesize" value="<%=blanknull(shoesize)%
>" >

How can I get to print the stacktrace for an exception occuring within my
Question
JSP page? (JSP)
Answer By printing out the exception's stack trace, you can usually diagonse a
problem better when debugging JSP pages. By looking at a stack trace, a
programmer should be able to discern which method threw the exception
and which method called that method. However, you cannot print the
stacktrace using the JSP out implicit variable, which is of type JspWriter.
You will have to use a PrintWriter object instead. The following snippet
demonstrates how you can print a stacktrace from within a JSP error page:
<%@ page isErrorPage="true" %>
<%
out.println("
");

PrintWriter pw = response.getWriter();

exception.printStackTrace(pw);

out.println("
");
%>

Question How do you pass an InitParameter to a JSP? (JSP)


The JspPage interface defines the jspInit() and jspDestroy() method which
the page writer can use in their pages and are invoked in much the same
manner as the init() and destory() methods of a servlet. The example page
below enumerates through all the parameters and prints them to the
console.
<%@ page import="java.util.*" %>
<%!
ServletConfig cfg =null;
public void jspInit(){
Answer
ServletConfig cfg=getServletConfig();
for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();)
{
String name=(String)e.nextElement();
String value = cfg.getInitParameter(name);
System.out.println(name+"="+value);
}
}
%>

Question How can my JSP page communicate with an EJB Session Bean? (JSP)
Answer The following is a code snippet that demonstrates how a JSP page can
interact with an EJB session bean:
<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject,
foo.AccountHome, foo.Account" %>
<%!
//declare a "global" reference to an instance of the home interface of the
session bean
AccountHome accHome=null;
public void jspInit() {
//obtain an instance of the home interface
InitialContext cntxt = new InitialContext( );
Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome =
(AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
}
%>
<%
//instantiate the session bean
Account acct = accHome.create();
//invoke the remote methods
acct.doWhatever(...);
// etc etc...
%>

How do you prevent the Creation of a Session in a JSP Page and


Question
why? (JSP)
By default, a JSP page will automatically create a session for the request
if one does not exist. However, sessions consume resources and if it is not
necessary to maintain a session, one should not be created. For example,
a marketing campaign may suggest the reader visit a web page for more
information. If it is anticipated that a lot of traffic will hit that page, you
Answer may want to optimize the load on the machine by not creating useless
sessions.

The page directive is used to prevent a JSP page from automatically


creating a session:
<%@ page session="false">

Question What is the difference between page and request scopes? (JSP)
If you specify scope as Page then its life span is until page is displayed or
control is forwarded to a new page. Accessibility is current page only.
Answer But if u specify as Request, its life span is until the request has been
completely processed and the response has been sent back to the user.
Accessibility is current page and any included or for-warded pages

What is the difference between a tag handler and a tag handler


Question
class? (JSP)
The only difference between a tag handler and a tag handler class is that
Answer a tag handler is written in JSP syntax, while a tag handler class is written
in the Java language.

Question How do you precompile a jsp page? (JSP)


To precompile a JSP page, access the page with a query string of ?
jsp_precompile
Answer
http://www.javagalaxy.com:8080/RMI/index.jsp?jsp_precompile
the jsp page will not get executed by this action.

How do you print the contents of a.jsp in b.jsp. How do you include the
Question
file? (JSP)
Answer a.jsp
<%!
public int i=10;
%>

b.jsp
<%@ include file="a.jsp" %>
<%
out.println(i);
%>

do not use as this will include the file at runtime where as the above
includes (directive include) the file at compile time

a.jsp
<%!
int x = 10;
%>

b.jsp
<%@ include file="a.jsp" %>
Question
<%
int x = 20;
out.println("x:"+x);
%>

When the above programme is invoked as http://localhost:8080/b.jsp,


what is the output? (JSP)
Compiler error as x is already initialised.
When a.jsp file is included in b.jsp, all the variables of a.jsp are also
Answer
invoked
in b.jsp.

The following are the contents of test.jsp

<html>
<title>Welcome to my web page</title>
<h1>This example demonstrates the output of test.jsp</h1>
Question <%! String name=request.getParameter(``name``); %>
Name is <%=name %>
</html>

If the user types http://localhost:8080/test.jsp?name=JavaGalaxy, What


will the output be? (JSP)
Compilation error as all the implict objects (request,session,out,...) are
not available in
declarative part.Since we are trying to declare
Answer
name=request.getParameter("name")
it gives us compilation error as stating undefined variable or class name :
request

How can we access a Vector from one jsp page to another jsp page.? You
Question also need to restrict a third jsp page from having access to this
Vector. (JSP)
Answer If you use session.setAttribute("key","value"); then the object that is put
into the session is available till the session is timed out. In this case
if you need to restrict the vector in third jsp page, put it in request scope
e.g. request.setAttribute("key", "value"); By this way your object
is available till your request has been processed.

Question Why would a client application use JTA transactions? (JTA)


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
Answer 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.
...
Context c = new InitialContext(); UserTransaction ut =
(UserTransaction) c.lookup("java:comp/UserTransaction");
ut.begin(); // perform multiple operations...
ut.commit()
...

How do I convert a numeric IP address like 192.18.97.39 into a hostname


Question
like java.sun.com? (Networking)
String hostname =
Answer
InetAddress.getByName("192.18.97.39").getHostName();

Question What information is needed to create a TCP Socket? (Networking)


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

What is the difference between URL instance and URLConnection


Question
instance? (Networking)
A URL instance represents the location of a resource, and a
Answer URLConnection instance represents a link for accessing or communicating
with the resource at the location.

Question What are the two important TCP Socket classes? (Networking)
Socket and ServerSocket. ServerSocket is used for normal two-way
socket communication. Socket class allows us to read and write through
Answer
the sockets. getInputStream() and getOutputStream() are the two
methods available in Socket class.

Considering a=4 and b=10. Can you swap the values without using any
Question
temp variable? The final output should be a=10 and b=4. (Other)
a = a + b // 4 + 10 = 14
b = a - b // 14 - 10 = 4
a = a - b // 14 - 4 = 10
Answer
b=4
a = 10

Write a query for getting the second maximum marks of students from
Question
students table? (Other)
select max(marks) from students where marks <(select max(marks)
Answer
from students)

Question how to make default checkbox selecte(in struts) (Other)

Answer useing the set and get methods it can be done.

Considering a=4 and b=10. Can you swap the values without using any
Question
temp variable? The final output should be a=10 and b=4. (Other)
a = a + b // 4 + 10 = 14
b = a - b // 14 - 10 = 4
a = a - b // 14 - 4 = 10
Answer
b=4
a = 10

Question How many types of protocol implementations does RMI have? (RMI)
RMI has at least three protocol implementations: Java Remote Method
Protocol(JRMP), Internet Inter ORB Protocol(IIOP), and Jini Extensible
Answer 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.

Question Does RMI-IIOP support dynamic downloading of classes? (RMI)


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

Does RMI-IIOP support code downloading for Java objects sent by value
Question across an IIOP connection in the same way as RMI does across a JRMP
connection? (RMI)
Answer Yes. The JDK 1.2 support the dynamic class loading.

Question Can RMI and Corba based applications interact ? (RMI)


Answer Yes they can. RMI is available with IIOP as the transport protocol instead
of JRMP.

Assume an application needs security permissions granted before the


application can talk to the database. How
Question do you go about setting the permissions? Give an example of setting the
permission in Tomcat and stand alone
java programme. (Security)
In Tomcat:
Add security permission to catalina.policy file located under
<TOMCAT_HOME>/conf/ Add the following lines

grant codeBase "file:${catalina.home}/webapps/MyContext/-"


{
permission java.security.AllPermission;
};

Answer
In stand alone java application:
Create a .policy file that points to the code base where the application
resides.

grant codebase "file:c:/source/java/-"


{
permission java.security.AllPermission;
};

java -Djava.security.policy=<file name>.policy com.test.MyClass

Request parameter How to find whether a parameter exists in the request


Question
object? (Servlets)
1.boolean hasFoo = !(request.getParameter("foo") == null ||
request.getParameter("foo").equals(""));
Answer 2. boolean hasParameter =
request.getParameterMap().contains(theParameter);
(which works in Servlet 2.3+)

How can I send user authentication information while


Question
makingURLConnection? (Servlets)
You'll want to use HttpURLConnection.setRequestProperty and set all the
Answer
appropriate headers to HTTP authorization.

Question Can we use the constructor, instead of init(), to initialize servlet? (Servlets)
Answer Yes , of course you can use the constructor instead of init(). There's
nothing to stop you. But you shouldn't. The original reason for init() was
that ancient versions of Java couldn't dynamically invoke constructors with
arguments, so there was no way to give the constructur a ServletConfig.
That no longer applies, but servlet containers still will only call your no-arg
constructor. So you won't have access to a ServletConfig or
ServletContext.

How can a servlet refresh automatically if some new data has entered the
Question
database? (Servlets)
Answer You can use a client-side Refresh or Server Push

Question The code in a finally clause will never fail to execute, right? (Servlets)
Answer Using System.exit(1); in try block will not allow finally code to execute.

Question What is HttpTunneling? (Servlets)


HTTP tunneling is used to encapsulate other protocols within the HTTP or
HTTPS protocols. Normally the intra-network of an organization is blocked
by a firewall and the network is exposed to the outer world only through a
Answer
specific web server port , that listens for only HTTP requests. To use any
other protocol, that by passes the firewall, the protocol is embedded in
HTTP and send as HttpRequest.

What is Server Side Push and how is it implemented and when is it


Question
useful? (Servlets)
Server Side push is useful when data needs to change regularly on the
clients application or browser, without intervention from client. Standard
examples might include apps like Stock's Tracker, Current News etc. As
such server cannot connect to client's application automatically. The
mechanism used is, when client first connects to Server, (Either through
login etc..), then Server keeps the TCP/IP connection open.
Answer It's not always possible or feasible to keep the connection to Server open.
So another method used is, to use the standard HTTP protocols ways of
refreshing the page, which is normally supported by all browsers.
<META HTTP-EQUIV="Refresh" CONTENT="5;URL=/servlet/stockquotes/">

This will refresh the page in the browser automatically and loads the new
data every 5 seconds.

Question What are the phases in JSP? (Servlets)


a) Translation phase ? conversion of JSP to a Servlet source, and then
Compilation of servlet source into a class file. The translation phase is
Answer typically carried out by the JSP engine itself, when it receives an incoming
request for the JSP page for the first time
b) init(), service() and destroy() method as usual as Servlets.

How many cookies can one set in the response object of the servlet?
Question
Also, are there any restrictions on the size of cookies? (Servlets)
If the client is using Netscape, the browser can receive and store 300
total cookies
Answer
4 kilobytes per cookie (including name)
20 cookies per server or domain
What?s the difference between sendRedirect( ) and forward( )
Question
methods? (Servlets)
A sendRedirect method creates a new request (it?s also reflected in
browser?s URL ) where as forward method forwards the same request to
the new target(hence the chnge is NOT reflected in browser?s URL).
Answer
The previous request scope objects are no longer available after a redirect
because it results in a new request, but it?s available in forward.
SendRedirectis slower compared to forward.

Is there some sort of event that happens when a session object gets
Question
bound or unbound to the session? (Servlets)
HttpSessionBindingListener will hear the events When an object is added
and/or remove from the session object, or when the session is invalidated,
Answer
in which case the objects are first removed from the session, whether the
session is invalidated manually or automatically (timeout).

What do the differing levels of bean storage (page, session, app)


Question
mean? (Servlets)
page life time - NO storage. This is the same as declaring the variable in
a scriptlet and using it from there.
session life time - request.getSession(true).putValue "myKey", myObj);
Answer application level ?
getServletConfig().getServletContext().setAttribute("myKey ",myObj )
request level - The storage exists for the lifetime of the request, which
may be forwarded between jsp's and servlets

Is it true that servlet containers service each request by creating a new


thread? If that is true, how does a container handle a sudden dramatic
Question
surge in incoming requests without significant performance
degradation? (Servlets)
The implementation depends on the Servlet engine. For each request
generally, a new Thread is created. But to give performance boost, most
containers, create and maintain a thread pool at the server startup time.
To service a request, they simply borrow a thread from the pool and when
Answer they are done, return it to the pool.
For this thread pool, upper bound and lower bound is maintained. Upper
bound prevents the resource exhaustion problem associated with unlimited
thread allocation. The lower bound can instruct the pool not to keep too
many idle threads, freeing them if needed.

Question Can I just abort processing a JSP? (Servlets)


Yes. Because your JSP is just a servlet method, you can just put
Answer
(whereever necessary) a < % return; % >

Question What is URL Encoding and URL Decoding ? (Servlets)


Answer URL encoding is the method of replacing all the spaces and other extra characters into their
Characters and Decoding is the reverse process converting all Hex Characters back their norm
For Example consider this URL, /ServletsDirectory/Hello'servlet/
When Encoded using URLEncoder.encode("/ServletsDirectory/Hello'servlet/") the output is
http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2FTh
back using
URLDecoder.decode("http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FH

Do objects stored in a HTTP Session need to be serializable? Or can it


Question
store any object? (Servlets)
Yes, the objects need to be serializable, but only if your servlet container
supports persistent sessions. Most lightweight servlet engines (like
Answer Tomcat) do not support this. However, many EJB-enabled servlet engines
do. Even if your engine does support persistent sessions, it is usually
possible to disable this feature.

Question What is the difference between session and cookie? (Servlets)


The difference between session and a cookie is two-fold.
1) session should work regardless of the settings on the client browser.
even if users decide to forbid the cookie (through browser settings) session
still works. there is no way to disable sessions from the client browser.
2) session and cookies differ in type and amount of information they are
Answer capable of storing.
Javax.servlet.http.Cookie class has a setValue() method that accepts
Strings. javax.servlet.http.HttpSession has a setAttribute() method which
takes a String to denote the name and java.lang.Object which means that
HttpSession is capable of storing any java object. Cookie can only store
String objects.

What is the difference between ServletContext and ServletConfig?


Question (Servlets)

Both are interfaces.


The servlet engine implements the ServletConfig interface in order to pass
configuration information to a servlet. The server passes an object that
Answer implements the ServletConfig interface to the servlet's init() method.
The ServletContext interface provides information to servlets regarding the
environment in which they are running. It also provides standard way for
servlets to write events to a log file.

What are the differences between GET and POST service


Question
methods? (Servlets)
A GET request is a request to get a resource from the server. Choosing
GET as the "method" will append all of the data to the URL and it will show
up in the URL bar of your browser. The amount of information you can
send back using a GET is restricted as URLs can only be 1024 characters. A
POST request is a request to post (to send) form data to a resource on the
Answer
server. A POST on the other hand will (typically) send the information
through a socket back to the webserver and it won't show up in the URL
bar. You can send much more information to the server this way - and it's
not restricted to textual data either. It is possible to send files and even
binary data such as serialized Java objects!
Question What is the difference between GenericServlet and HttpServlet? (Servlets)
GenericServlet is for servlets that might not use HTTP, like for instance
FTP service.As of only Http is implemented completely in HttpServlet.
Answer The GenericServlet has a service() method that gets called when a client
request is made. This means that it gets called by both incoming requests
and the HTTP requests are given to the servlet as they are

What is the Max amount of information that can be saved in a Session


Question
Object ? (Servlets)
As such there is no limit on the amount of information that can be saved
in a Session Object. Only the RAM available on the server machine is the
limitation. The only limit is the Session ID length(Identifier) , which should
not exceed more than 4K. If the data to be store is very huge, then it's
Answer
preferred to save it to a temporary file onto hard disk, rather than saving it
in session. Internally if the amount of data being saved in Session exceeds
the predefined limit, most of the servers write it to a temporary cache on
Hard disk.

Question Explain the status codes of HttpResponse object. (Servlets)


100-199 ----> Informational 200-299 ----> Request was succesful
Answer 300-399 ----> Request file has moved 400-499 ----> Client error 500-599
----> Server error

Question What is Servlet chaining? (Servlets)


Answer response object from one servlet is passed as request to another Servlet.
Try this example and you will come to know what servlet chaining is all
about.
public class ServletA extends HttpServlet {
public void init(ServletConfig config) throws ServletException {}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String aValue = request.getParameter("valueA");
System.out.println("ServletA read: "+aValue);
request.setAttribute("ReadTheValue","Yes");
//do other servlet stuff...just don't open a write and output to the page....
request.getRequestDispatcher("/servletB").forward(req,resp);
}
}

public class ServletB extends HttpServlet {


public void init(ServletConfig config) throws ServletException {}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String aValue = request.getParameter("valueA");
System.out.println("ServletB also got the value: "+aValue);
System.out.println("ServletB also found attribute:
"+request.getAttribute("ReadTheValue"));
//finish the task and write to the page.
}
}
Advantages:
1) Chaining reduces the demand on a single servlet
2) Modular design
3) Enables different complex processes to be maintained by more than one
person.
4) Allows steps in a process to be modified (eg servlet 1 -> servlet 2 or
servlet 1 -> servlet 3 -> servlet 2, etc)
5) Removes the complexity in a single servlet

I am using servlets. I need to store an object NOT a string in a cookie. Is


Question that possible? The helpfile says BASE64 encoding is suggested for use with
binary values. How can I do that? (Servlets)
You could serialize the object into a ByteArrayOutputStream and then
Base64 encode the resulting byte[]. We must keep in mind the size
limitations of a cookie and the overhead of transporting it back and forth
between the browser and the server.
Limitations are:
Answer
* at most 300 cookies
* at most 4096 bytes per cookie (as measured by the characters that
comprise the cookie non-terminal in the syntax description of the Set-
Cookie2 header, and as received in the Set-Cookie2 header)
* at most 20 cookies per unique host or domain name

Suppose that Myservlet implements SingleThreadModel and there are


Local variables, Instance variables,
Question Class variables,Request attributes,Session attributes and Context
attributes. Which among
these variables would be thread safe? (Servlets)
Answer Local,Instance and request variables are thread safe.

I have the following deployed in my web.xml file.


<session-config>
<session-timeout>30</session-timeout>
</session-config>
Question
then I perform setMaxInactiveInterval(2400) for my session object.The
First one denotes
30 minutes and second one denoted 40 minutes. After how long would the
session expire? (Servlets)
40 minutes. The timeout defined in your DD is used until you redefine it
Answer with
setMaxInactiveInterval

Question The first time a Jsp page is requested which method is called? (Servlets)
The first time a jsp page is requested jspInit method is called and the
Answer request is
handled by _jspService
Assume there is a servlet which is placed inside a .jar file and the .jar file
is placed under WEB-INF/lib folder. Now you
have the same servlet class under WEB-INF/classes folder. Which servlet
Question
class do you think will be called when there is a
request to that particular servlet? i.e. the servlet in WEB-INF/lib or the
servlet in WEB-INF/classes (Servlets)
The servlet in WEB-INF/classes folder will be called. classes under WEB-
Answer
INF/classes will override the classes under WEB-INF/lib.

How do I support both GET and POST protocol from the same
Question
Servlet? (Servlets)
The easy way is, just support POST, then have your doGet() method call
your doPost() method:

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException
{
Answer
doPost(req, res);
}

Implementing the service() method is usually not what you want to do,
since HttpServlet provides its own implementation
of service() that turns around and calls doGet() and doPost()

Question What is the difference between the doGet and doPost methods? (Servlets)
doGet() is called in response to an HTTP GET request. This happens when
users click on a link, or enter a URL into the
browser's address bar. It also happens with some HTML FORMs (those with
METHOD="GET" specified in the FORM tag).

doPost() is called in response to an HTTP POST request. This happens with


Answer some HTML FORMs (those with METHOD="POST"
specified in the FORM tag).

Both methods are called by the default (superclass) implementation of


service in the HttpServlet base class. You should
override one or both to perform your servlet's actions. You probably
shouldn't override service().

How does one choose between overriding the doGet(), doPost(), and
Question
service() methods? (Servlets)
Answer The differences between the doGet() and doPost() methods are that they
are called in the HttpServlet that your servlet
extends by its service() method when it recieves a GET or a POST request
from a HTTP protocol request.

A GET request is a request to get a resource from the server. This is the
case of a browser requesting a web page. It
is also possible to specify parameters in the request, but the length of the
parameters on the whole is limited. This
is the case of a form in a web page declared this way in html: <form
method="GET"> or <form>.

A POST request is a request to post (to send) form data to a resource on


the server. This is the case of of a form in
a web page declared this way in html: <form method="POST">. In this
case the size of the parameters can be much greater.

The GenericServlet has a service() method that gets called when a client
request is made. This means that it gets called
by both incoming requests and the HTTP requests are given to the servlet
as they are (you must do the parsing yourself).

The HttpServlet instead has doGet() and doPost() methods that get called
when a client request is GET or POST. This
means that the parsing of the request is done by the servlet: you have the
appropriate method called and have
convenience methods to read the request parameters.

NOTE: the doGet() and doPost() methods (as well as other HttpServlet
methods) are called by the service() method.

What is the diffence between client side validations and server side
Question validations and under what scenerio we use these validations. Which one is
better? (Servlets)
When you say Clien side validation its Javascript validation. This
validation doesn't require a request to the server.
The validation is done within the browser itself.

Server side validation, The validation is done at the server end. You will
need to make a request to the server
and pass all the form data to the server to do the validation.

There is no rule that says use Client side validation for this and use Server
Answer side valiedation for that. It all depends on
your application.

If there are any simple validations, e.g. check if First name is entered and
entered email address is valid you can go for
Client side validation. If there are business rules that needs to validate
user input, then you will go for Server side
validation.
Server side validation has more control over your data validation and is
secure (You dont display your validation logic to the users)

Question What is the directory structure to create a web application? (Servlets)


Answer Any web application needs to have the following directory structure

Assume your web application name is javagalaxy then you would have

javagalaxy
- (put all your jsp's, java script files, css files here. You may create
different folders to segregate files)
-WEB-INF (put your web.xml file here)
-WEB-INFlib ( put all your library files here e.g. struts.jar, log4j.jar)
-WEB-INFclasses (put all your class files here e.g. servlets, struts action
class)

Question How we invoke multi threading in servlet? (Servlets)


Servlets are multi-threaded by default. If you need to make a servlet
Answer
single threaded, implement SingleThreadModel interface in the servlet

Question Is Servlet a thread or a process? (Servlets)


Answer Servlet is a thread. A process holds a collection of threads

Question What happens if a Servlet is not loaded into memory? (Servlets)


If a Servlet is not loaded in memory because it is shutting down or
starting up,
it will not be listening for requests and cannot accept connections. Any
Answer
clients that attempt to
connect to the server will normally fail after a client-specific timeout
period.

Can you please tell me how many instances of servlet will be created for a
Question
very complex 500 users system? Question by : Sonal (Servlets)
This actually depends on your configuration in web.xml

1. <load-on-startup>200</load-on-startup>

2. <load-on-startup>1</load-on-startup>

In the first point you are asking the server to create 200 instances of a
given servlet. There are Pros and Cons for this. This actually takes
much of your memory.
Answer
In the second point you are creating only one servlet instance at startup.
This is a good practice. So when the server is unable to server requests
by just this one instance, then the server would create another instance of
the servlet to handle more requests. This would continue until the
server can handle the requests.

There is no specific number of instances that can be created by a server for


a given servlet. This depends on your infrastructure.

In a single servlet program the three methods (i.e


service(),doGet(),doPost()) are available by default?
Question
Which method is initalize first? Can there be any command to invoke the
doGet() first? (Servlets)
Answer First time when a servlet is invoked init() gets called. init() is called only
once in a servlets life cycle.
service(), doGet() and doPost() gets called after init() is called. This is
where your request gets processed.

service(), doGet() and doPost() are available by default to your servlet, but
it depends on what method you
are overriding. You can have only service() or doGet() or both doGet() and
doPost(). or all of them. It all
depends on what you wanted to acheive in your servlet.

By default service() is called. If you want doGet() to be called then avoid


overriding service()

Question What is the difference between 2 tier & 3 tier architecture? (Servlets)
In 2 tier architecture client directly interacts with the database but in 3
tier
architecture there is a middle tier that connects between client and
database.
Answer
So in 3 tier when the user asks for some information from DB, middle tier
interacts
with DB and does necessary processing on the records and gives
information to user.

Question What are the Difference between Functions and Procedures? (SQL)
1. Functions are used for computations where as Procedures can be used
for performing business logic

2. Functions MUST return a value, Procedures need not be.

3) you can have DML(insert, update, delete) statements in a Function. But,


you cannot call such a function in a SQL query..

eg: suppose, if u have a function that is updating a table.. you can't


call that function in any sql query.

- select myFunction(field) from sometable;


Answer
will throw error.

4) function parameters are always IN, no OUT is possible

5) function returns 1 value only. procedure can return multiple


values(max. 1024)

6) we can select the fields from function.in the case of procdure we cannot
select the fields.

7) Function do not return the images,text whereas stored procedures


returns all
Question What is the difference between UNION and UNION ALL ? (SQL)
UNION ALL selects all records between two queries including duplicates,
whereas UNION takes the time to sort
records in order to remove duplicates. In short UNION only selects distinct
values, UNION ALL selects all values.
Answer
e.g.
SELECT Date FROM table1 UNION SELECT Date FROM table2
SELECT Date FROM table1 UNION ALL SELECT Date FROM table2

Question What is a join and explain different types of joins. (SQL)


Answer Joins are used in queries to explain how different tables are related. Joins
also let you select data from a table
depending upon data from another table.

<b> Types of joins </b> INNER JOIN, OUTER JOIN, CROSS JOIN.
OUTER JOIN is further classified as LEFT OUTER JOINS, RIGHT OUTER
JOINS and FULL OUTER JOINS.

Table details

<b> Student </b>


ID
FirstName
LastName
BirthDate

<b> Attendance </b>


ID
AttendanceDate
AttendanceCode
MinutesAbsent

<b> StudentSchedule </b>


ID
Course

<b> Cross Join </b> - A cross join merges two tables on every record in a
geometric fashion, every record of one table
is combined with every record from the other table. Two tables of 10
records each in a cross join will create a
table of 100 (10 X 10) records.

<b> Inner Join </b> - An Inner join is used to match two tables based on
values of a common field.
An inner join gets data from both tables where the specified data exists in
both tables. For E.g.

List of students in the database that were absent on December 4, 2003,


you would use an inner join between
the two tables "Student" and "Attendance"

SELECT Student.ID, Student.FirstName, Student.LastName,


Attendance.AttendanceCode, Attendance.MinutesAbsent
FROM Student INNER JOIN Attendance ON Student.ID=Attendance.ID
WHERE Attendance.AttendanceDate='12/4/2003'

<b> Outer Join </b> - An outer join gets data from the source table at all
times, and returns data from the outer
joined table ONLY if it matches the criteria. When using outer joins, fields
will be set to NULL if data does
not exist in the outer-joined table. For E.g.

SELECT Student.ID, Student.FirstName, Student.LastName,


Attendance.AttendanceCode, Attendance.MinutesAbsent
FROM Student INNER JOIN StudentSchedule ON
StudentSchedule.ID=Student.ID< br /> LEFT OUTER JOIN Attendance ON
Student.ID=Attendance.ID AND Attendance.AttendanceDate='12/4/2003'
WHERE StudentSchedule.Course='E NGLISH 9'

<i> a </i> Left Outer join - All outer joins retrieve records from both
tables, just as an inner join does. However,
an outer join retrieves all of the records from one of the tables. A column
in the result is NULL if the
corresponding input table did not contain a matching record.
<i> b </i> Right Outer join - The right outer join is similar to the left
outer join in that it retrieves all the
records from one side of the relationship, but this time it's the right table.
Only records where the condition
values match are retrieved from the left.
<i> c </i> Full Outer Join - The full outer join retrieves all records from
both the left and the right table.

For 'n' number of SQL SELECT statements connected by UNION, how


Question many times should we specify UNION
to eliminate the duplicate rows? (SQL)
Answer Only Once

Question In the WHERE clause what is BETWEEN and IN? (SQL)


Answer IN keyword helps to limit the selection criteria to one or more discrete
values, the BETWEEN keyword allows for
selecting a range. The syntax for the BETWEEN clause is as follows:

SELECT "column_name"
FROM "table_name"
WHERE "column_name" BETWEEN 'value1' AND 'value2'

This will select all rows whose column has a value between 'value1' and
'value2'.

The syntax for using the IN keyword is as follows:


SELECT "column_name"
FROM "table_name"
WHERE "column_name" IN ('value1', 'value2', ...)

The number of values in the parenthesis can be one or more, with each
values separated by comma. Values can be numerical
or characters. If there is only one value inside the parenthesis, this
commend is equivalent to

WHERE "column_name" = 'value1'

Question Is BETWEEN inclusive of the range values specified? (SQL)

Answer Yes

What is 'LIKE' used for in WHERE clause? What are the wildcard
Question
characters? (SQL)
LIKE is another keyword that is used in the WHERE clause. Basically, LIKE
allows you to do a search based on a
pattern rather than specifying exactly what is desired (as in IN) or spell out
a range (as in BETWEEN).
The syntax for is as follows:
Answer
SELECT "column_name"
FROM "table_name"
WHERE "column_name" LIKE {PATTERN}

‘%’ ( for a string of any character ) and ‘_’ (for any single character ) are
the two wild card characters.

Question When do you use a LIKE statement? (SQL)


To do partial search e.g. to search employee by name, you need not
specify
the complete name; using LIKE, you can search for partial string matches.

Answer Example SQL : SELECT EMPNO FROM EMP


WHERE EMPNAME LIKE 'RAMESH%'

% is used to represent remaining all characters in the name.


This query fetches all records contains RAMESH in six characters.

Question What is a self join and give an example. (SQL)


Joining two instances of a same table.
Sample SQL : SELECT A.EMPNAME , B.EMPNAME
Answer
FROM EMP A, EMP B
WHERE A.MGRID = B.EMPID

Question What is a transaction? (SQL)


Answer A transaction is a logicl unit of work where all steps must be commited or
rolled back.

Question What is ACID? (SQL)


ACID stands for Atomicity, Consistency, Isolation and Duralbility. These
are the properties of a transaction.

1. Atomicity - states that database modifications must follow an "all or


nothing" rule. Each transaction is said to
be "atomic." If one part of the transaction fails, the entire transaction fails.
It is critical that the database
management system maintain the atomic nature of transactions in spite of
any DBMS, operating system or hardware failure.

2. Consistency - states that only valid data will be written to the database.
If, for some reason, a transaction is
executed that violates the database’s consistency rules, the entire
transaction will be rolled back and the database
will be restored to a state consistent with those rules. On the other hand, if
a transaction successfully executes,
it will take the database from one state that is consistent with the rules to
another state that is also consistent
with the rules.
Answer
3. Isolation - requires that multiple transactions occurring at the same
time not impact each other's execution.
For example, if Joe issues a transaction against a database at the same
time that Mary issues a different transaction,
both transactions should operate on the database in an isolated manner.
The database should either perform Joe's entire
transaction before executing Mary's or vice-versa. This prevents Joe's
transaction from reading intermediate data
produced as a side effect of part of Mary’s transaction that will not
eventually be committed to the database.
Note that the isolation property does not ensure which transaction will
execute first, merely that they will not
interfere with each other.

4. Durability - ensures that any transaction committed to the database will


not be lost. Durability is ensured through
the use of database backups and transaction logs that facilitate the
restoration of committed transactions in spite of
any subsequent software or hardware failures.

Question How do you perform a search based on part of a word? (SQL)


SELECT * FROM emp WHERE dept LIKE '%war%'. The above query will
return a recordset with
Answer
records consisting 'war' in the department name. E.g.
soft<b>war</b>e(war), hard<b>war</b>e(war)

Question What is GROUP BY? (SQL)


The GROUP BY keywords have been added to SQL because aggregate
functions (like SUM) return the aggregate
of all column values every time they are called. Without the GROUP BY
functionality, finding the sum for each
individual group of column values was not possible.
Answer
The corresponding SQL syntax is,

SELECT "column_name1", SUM("column_name2")


FROM "table_name"
GROUP BY "column_name1"

What is the difference between dropping, truncating and deleting from a


Question
table. (SQL)
1. Dropping - (Table structure + Data are deleted), Invalidates the
dependent objects ,Drops the indexes
Answer 2. Truncating - (Data alone deleted), Performs auto commit and is faster
than delete
3. Delete - (Data alone deleted), Auto commit is not performed

What are cursors? Explain different types of cursors. What are the
Question disadvantages of cursors?
How can you avoid cursors? (SQL)
Cursors allow row-by-row prcessing of the resultsets.
Different Types of cursors - Static, Dynamic, Forward-only, Keyset-driven.

Disadvantages of cursors - Each time you fetch a row from the cursor, it
results in a network roundtrip, where as a
normal SELECT query makes only one rowundtrip, however large the
Answer
resultset is. Cursors are also costly because they
require more resources and temporary storage (results in more IO
operations). Furthere, there are restrictions on
the SELECT statements that can be used with some types of cursors.

Most of the times, set based operations can be used instead of cursors.

Question What are triggers? How to invoke a trigger on demand? (SQL)


Triggers are special kind of stored procedures that get executed
automatically when an INSERT, UPDATE or DELETE
operation takes place on a table.

Triggers can't be invoked on demand. They get triggered only when an


associated action (INSERT, UPDATE, DELETE) happens
Answer on the table on which they are defined.

Triggers are generally used to implement business rules, auditing. Triggers


can also be used to extend the referential
integrity checks, but wherever possible, use constraints for this purpose,
instead of triggers, as constraints are much
faster.
Question What is a tuple? (SQL)
In a table, a tuple is a row. Each row in the table represents a collection
Answer
of related data values.

What errors would arise when you try to execute a query and at the same
Question
time DB is down? (SQL)
Answer An SQLException would arise

How do you select second maximum marks from a Student table with a
Question
single statement? (SQL)
select max(marks) from Student where marks < (select max(marks)
Answer
from Student);

How to display the dept information from department table. (Oracle


Question
DB) (SQL)
Answer select * from dept;

Question How to display the details of all employees. (Oracle DB) (SQL)

Answer select * from emp;

Question How to display the name and job for all employees. (Oracle DB) (SQL)

Answer select ename, job from emp;

Question How to display name and salary for all employees. (Oracle DB) (SQL)

Answer select ename, sal from emp;

How to display employee number and total salary for each employee.
Question
(Oracle DB) (SQL)
Answer select empno, sal+comm from emp;

How to display employee name and annual salary for all employees.
Question
(Oracle DB) (SQL)
Answer select empno, empname, 12*sal+nvl(comm,0) annualsal from emp;

How to display the names of all employees who are working in department
Question
number 10. (Oracle DB) (SQL)
Answer select ename from emp where deptno=10;

How to display the names of all employees working as clerks and drawing
Question
a salary more than 3000. (Oracle DB) (SQL)
Answer select ename from emp where job='CLERK' and sal>3000;
How to display employee number and names for employees who earn
Question
commission. (Oracle DB) (SQL)
Answer select empno, ename from emp where comm is not null and comm>0;

How to display names of employees who do not earn any commission.


Question
(Oracle DB) (SQL)
Answer Select empno, ename from emp where comm is null or comm=0;

How to display the names of employees who are working as clerk,


Question salesman or analyst and drawing a salary more than 3000. (Oracle
DB) (SQL)
select ename from emp where (job='CLERK' or job='SALESMAN' or
job='ANALYST') and sal>3000;
Answer (or)
select ename from emp where job in('CLERK','SALESMAN','ANALYST') and
sal>3000;

How to display the names of employees who are working in the company
Question
for the past 5 years. (Oracle DB) (SQL)
Answer select ename from emp where sysdate-hiredate>5*365;

How to display the list of employees who have joined the company before
Question
30th June 90 sor after 31st dec 90. (Oracle DB) (SQL)
select * from emp where hiredate between '30-jun-1990' and '31-
Answer
dec-1990';

Question How to display current date. (Oracle DB) (SQL)

Answer select sysdate from dual;

How to display the list of users in your database (using log table). (Oracle
Question
DB) (SQL)
Answer select * from dba_users;

How to display the names of all tables from the current user. (Oracle
Question
DB) (SQL)
Answer select * from tab;

Question How to display the name of the current user. (Oracle DB) (SQL)

Answer show user;

How to display the names of employees working in department number


Question 10 or 20 or 40 or employees working as clerks, salesman or analyst.
(Oracle DB) (SQL)
Answer select ename from emp where deptno in (10,20,40) or job in
('CLERK','SALESMAN','ANALYST');

How to display the names of employees whose name starts with alphabet
Question
S. (Oracle DB) (SQL)
Answer select ename from emp where ename like 'S%';

How to display employee names for employees whose name ends with
Question
alphabet. (Oracle DB) (SQL)
Answer select ename from emp where ename like '%S';

How to display the names of employees whose names have second


Question
alphabet A in their names. (Oracle DB) (SQL)
Answer select ename from emp where ename like '_S%';

How to display the names of employees whose name is exactly five


Question
characters in length. (Oracle DB) (SQL)
select ename from emp where length(ename)=5;
Answer (or)
select ename from emp where ename like '_____';

How to display the names of employees who are not working as


Question
managers. (Oracle DB) (SQL)
select * from emp minus (select * from emp where empno in (select mgr
from emp));
(or)
select * from emp where empno not in (select mgr from emp where mgr is
Answer
not null);
(or)
select * from emp e where empno not in (select mgr from emp where
e.empno=mgr)

How to display the names of employees who are not working as


Question
SALESMAN or CLERK or ANALYST. (Oracle DB) (SQL)
select ename from emp where job not in
Answer
('CLERK','SALESMAN','ANALYST');

How to display all rows from EMP table. The system should wait after
Question
every screen full of information. (Oracle DB) (SQL)
Answer set pause on;

How to display the total number of employees working in the company.


Question
(Oracle DB) (SQL)
Answer select count(*) from emp;

How to display the total salary being paid to all employees. (Oracle
Question
DB) (SQL)
Answer select sum(sal)+sum(nvl(comm,0)) from emp;

Question How to display the maximum salary from emp table. (Oracle DB) (SQL)

Answer select max(sal) from emp;

Question How to display the minimum salary from emp table. (Oracle DB) (SQL)

Answer select min(sal) from emp;

Question How to display the average salary from emp table. (Oracle DB) (SQL)

Answer select avg(sal) from emp;

How to display the maximum salary being paid to CLERK. (Oracle


Question
DB) (SQL)
Answer select max(sal) from emp where job='CLERK';

How to display the maximum salary being paid in dept no 20. (Oracle
Question
DB) (SQL)
Answer select max(sal) from emp where deptno=20;

How to display the min Sal being paid to any SALESMAN. (Oracle
Question
DB) (SQL)
Answer select min(sal) from emp where job='SALESMAN';

Question How to display the average salary drawn by managers. (Oracle DB) (SQL)

Answer select avg(sal) from emp where job='MANAGER';

How to display the total salary drawn by analyst working in dept no 40.
Question
(Oracle DB) (SQL)
Answer select sum(sal)+sum(nvl(comm,0)) from emp where deptno=40;

How to display the names of employees in order of salary i.e. the name of
Question
the employee earning lowest salary should appear first. (Oracle DB) (SQL)
Answer select ename from emp order by sal;

How to display the names of employees in descending order of salary.


Question
(Oracle DB) (SQL)
Answer select ename from emp order by sal desc;

How to display the details from emp table in order of emp name. (Oracle
Question
DB) (SQL)
Answer select ename from emp order by ename;

Question How to display empno, ename, deptno, and sal. Sort the output first
based on name and within name by deptno and within deptno by Sal;
(Oracle DB) (SQL)
Answer select * from emp order by ename,deptno,sal;

How to display the name of the employee along with their annual salary
Question (Sal * 12). The name of the employee earning highest annual salary
should appear first. (Oracle DB) (SQL)
select ename, 12*(sal+nvl(comm,0)) Annual from emp order by
Answer
12*(sal+nvl(comm,0)) desc;

How to display name, Sal, hra, pf, da, total Sal for each employee. The
output should be in the order of
Question
total Sal, hra 15% of Sal, da 10% of sal, pf 5% of sal total salary will be
(sal*hra*da)-pf. (Oracle DB) (SQL)
select ename,sal,sal*15/100 HRA, sal*5/100 PF, sal*10/100
Answer
DA,sal+sal*15/100-sal*5/100+sal*10/100 TOTAL_SALARY from emp

How to display dept numbers and total number of employees within each
Question
group. (Oracle DB) (SQL)
Answer select deptno,count(*) from emp group by deptno;

How to display the various jobs and total number of employees with each
Question
job group. (Oracle DB) (SQL)
Answer select job, count(*) from emp group by job;

How to display department numbers and total salary for each


Question
department. (Oracle DB) (SQL)
Answer select deptno, sum(sal) from emp group by deptno;

How to display department numbers and maximum salary for each


Question
department. (Oracle DB) (SQL)
Answer select deptno, max(sal),min(sal) from emp group by deptno;

How to display the various jobs and total salary for each job. (Oracle
Question
DB) (SQL)
Answer select job, sum(sal) from emp group by job;

How to display each job along with minimum sal being paid in each job
Question
group. (Oracle DB) (SQL)
Answer select job, min(sal) from emp group by job;

How to display the department numbers with more than three employees
Question
in each dept. (Oracle DB) (SQL)
Answer select deptno, count(*) from emp group by deptno having count(*)>3;
How to display the various jobs along with total sal for each of the jobs
Question
where total sal is greater than 40000. (Oracle DB) (SQL)
Answer select job, sum(sal) from emp group by job having sum(sal)>40000;

How to display the various jobs along with total number of employees in
Question each job. The output should
contain only those jobs with more than three employees. (Oracle DB) (SQL)
Answer select job, count(*) from emp group by job having count(*)>3;

Question How to display the name of emp who earns highest sal. (Oracle DB) (SQL)

Answer select ename from emp where sal=(select max(sal) from emp);

How to display the employee number and name of employee working as


Question
CLERK and earning highest salary among CLERKS. (Oracle DB) (SQL)
select empno, ename from emp where job='CLERK' and sal=(select
Answer
max(sal) from emp where job='CLERK');

How to display the names of the salesman who earns a salary more than
Question
the highest salary of any clerk. (Oracle DB) (SQL)
select ename from emp where job='SALESMAN' and sal >
Answer
(select max(sal) from emp where job='CLERK');

How to display the names of clerks who earn salary more than that of
Question
James of that of sal lesser than that of Scott. (Oracle DB) (SQL)
select ename from emp where job='CLERK' and sal<(select sal from emp
Answer where ename='SCOTT') and sal>(select sal from emp where
ename='JAMES');

How to display the names of employees who earn a Sal more than that of
Question
James or that of salary greater than that of Scott. (Oracle DB) (SQL)
select ename from emp where sal <
Answer (select sal from emp where ename='SCOTT') and sal >
(select sal from emp where ename='JAMES');

How to display the names of the employees who earn highest salary in
Question
their respective departments. (Oracle DB) (SQL)
select * from emp e where sal =
Answer
(select max(sal) from emp where deptno=e.deptno)

How to display the names of employees who earn highest salaries in their
Question
respective job groups. (Oracle DB) (SQL)
select * from emp e where sal in
Answer
(select max(sal) from emp group by job having e.job=job)

Question How to display the employee names who are working in accountings
dept. (Oracle DB) (SQL)
select ename from emp where deptno =
(select deptno from dept where dname="ACCOUNTING");
Answer (or)
select ename from emp where deptno in (select deptno from dept where
dname="ACCOUNTING");

How to display the employee names who are working in Chicago. (Oracle
Question
DB) (SQL)
select ename from emp where deptno =
Answer
(select deptno from dept where loc='CHICAGO');

How to display the job groups having total salary greater then the
Question
maximum salary for managers. (Oracle DB) (SQL)
select job, sum(sal) from emp group by job having sum(sal) >
Answer
(select max(sal) from emp where job='MANAGER');

How to display the names of employees from department number 10 with


Question salary greater than that of any employee working in other departments.
(Oracle DB) (SQL)
select ename,sal,deptno from emp e where deptno=10 and sal >
Answer
any(select sal from emp where e.deptno!=deptno);

How to display the names of employee from department number 10 with


Question salary greater then that of
all employee working in other departments. (Oracle DB) (SQL)
select ename, sal, deptno from emp e where deptno=10 and sal >
Answer
any(select sal from emp where e.deptno != deptno);

Question How to display the names of employees in Upper case. (Oracle DB) (SQL)

Answer select upper(ename) from emp;

Question How to display the names of employees in lower case. (Oracle DB) (SQL)

Answer select lower(ename) from emp;

Question How to display the name of employees in proper case. (Oracle DB) (SQL)

Answer select initcap(ename) from emp;

How to find out the length of your name using appropriate function.
Question
(Oracle DB) (SQL)
Answer select length('India') from dual;

Question How to display the length of all employees' names. (Oracle DB) (SQL)

Answer select sum(length(ename)) from emp;


How to display the name of the employee concatenate with EMP no.
Question
(Oracle DB) (SQL)
select ename||empno from emp;
Answer (or)
select concat(ename,empno) from emp;

How to Use appropriate function and extract 3 characters starting from 2


Question characters from the following
string 'Oracle' i.e. the output should be 'rac'. (Oracle DB) (SQL)
Answer select substr('oracle',2,3) from dual;

How to find the first occurrence of character a from the following string
Question
'computer maintenance corporation'. (Oracle DB) (SQL)
Answer select instr('computer maintenance corporation','a',1,1) from dual;

How to Replace every occurrence of alphabet A with B in the string Allen's


Question
(user translate function). (Oracle DB) (SQL)
Answer select replace('Allens','A','b') from dual;

How to display the information from EMP table. Wherever job 'manager'
Question is found it should be displayed
as boss(replace function). (Oracle DB) (SQL)
Answer select empno, ename, replace(job, 'MANAGER', 'Boss') JOB from emp;

How to display empno, ename, deptno from EMP table. Instead of display
Question department numbers display the
related department name (use decode function). (Oracle DB) (SQL)
select e.empno, e.ename, d.dname from emp e,dept d where e.deptno =
Answer
d.deptno;

Question How to display your age in days. (Oracle DB) (SQL)


Answer select round(sysdate-to_date('15-aug-1947')) from dual;

Question How to display your age in months. (Oracle DB) (SQL)


select floor(months_between(sysdate,'15-aug-1947')) "age in months"
Answer
from dual;

How to display current date as 15th august Friday nineteen forty seven.
Question
(Oracle DB) (SQL)
Answer select to_char(sysdate,'ddth month day year') from dual;

How to display the following output for each row from EMP table as 'scott
Question has joined the company
on Wednesday 13th august nineteen ninety'. (Oracle DB) (SQL)
Answer select ename||' has joined the company on '||to_char(hiredate,'day ddth
month year') from emp;

How to find the date of nearest Saturday after current day. (Oracle
Question
DB) (SQL)
Answer select next_day(sysdate, 'SATURDAY') from dual;

Question How to display current time. (Oracle DB) (SQL)


Answer select to_char(sysdate,'hh:mi:ss') Time from dual;

How to display the date three months before the current date. (Oracle
Question
DB) (SQL)
Answer select add_months(sysdate,-3) from dual;

How to display the common jobs from department number 10 and 20.
Question
(Oracle DB) (SQL)
select job from emp where deptno=10 and job in(select job from emp
where deptno=20);
Answer (or)
select job from emp where deptno=10 intersect select job from emp where
deptno=20;

How to display the jobs found in department number 10 and 20 eliminate


Question
duplicate jobs. (Oracle DB) (SQL)
select distinct(job) from emp where deptno=10 and job in(select job from
emp where deptno=20);
Answer (or)
select job from emp where deptno=10 intersect select job from emp where
deptno=20;

Question How to display the jobs which are unique to dept no 10. (Oracle DB) (SQL)
select job from emp where deptno=10 minus select job from emp where
deptno!=10;
Answer (or)
select job from emp where deptno = 10 and job not in (select job from
emp where deptno<>10);

How to display the details of those who do not have any person working
Question
under them. (Oracle DB) (SQL)
select empno from emp where empno not in (select mgr from emp where
Answer
mgr is not null);

How to display the details of employees who are in sales dept and grade
Question
is 3. (Oracle DB) (SQL)
Answer select * from emp where sal>=(select losal from salgrade where
grade=3) and sal<=(select hisal
from salgrade where grade=3) and deptno=(select deptno from dept
where dname='SALES');

How to display those who are not managers and who are managers any
Question
one. (Oracle DB) (SQL)
select * from emp where empno in(select mgr from emp) union
Answer select * from emp where empno not in(select mgr from emp where mgr is
not null);

How to display those employees whose name contains not less than 4
Question
chars. (Oracle DB) (SQL)
Answer Select * from emp where length(ename)>4;

How to display those departments whose name start with 'S' while
Question
location name end with 'O'. (Oracle DB) (SQL)
Answer select * from dept where dname like 'S%' and loc like '%O';

How to display those employees whose manager name is JONES. (Oracle


Question
DB) (SQL)
select * from emp where mgr=(select empno from emp where
Answer
ename='JONES');

How to display those employees whose salary is more than 3000 after
Question
giving 20% increment. (Oracle DB) (SQL)
select * from emp where sal*120/100 > 3000;
Answer (or)
select * from emp where sal+sal*20/100 > 3000;

Question How to display all employees with there dept name. (Oracle DB) (SQL)
Answer select ename, dname from emp e, dept d where e.deptno = d.deptno;

Question How to display ename who are working in sales dept. (Oracle DB) (SQL)
select empno, ename from emp where deptno=(select deptno from dept
Answer
where dname='SALES');

How to display employee name, deptname, salary and comm. for those
Question Sal in between 2000 to 5000 while
location is Chicago. (Oracle DB) (SQL)
select empno,ename,deptno from emp where deptno=(select deptno
Answer from dept where loc='CHICAGO') and
sal between 2000 and 5000;

How to display those employees whose salary greater than his manager
Question
salary. (Oracle DB) (SQL)
select * from emp e where sal>(select sal from emp where
Answer
empno=e.mgr);
How to display those employees who are working in the same dept where
Question
his manager is working. (Oracle DB) (SQL)
select * from emp e where deptno = (select deptno from emp where
Answer
empno=e.mgr);

How to display those employees who are not working under any manger.
Question
(Oracle DB) (SQL)
Answer select * from emp where mgr is null or empno=mgr;

How to display grade and employees name for the dept no 10 or 30 but
Question grade is not 4, while joined the
company before 31-dec-82. (Oracle DB) (SQL)
select empno,ename,sal,deptno,hiredate,grade from emp e,salgrade s
where e.sal>=s.losal
Answer
and e.sal<=s.hisal and deptno in(10,30) and grade<>4 and hiredate<'01-
dec-1981';

How to update the salary of each employee by 10% increments that are
Question
not eligible for commission. (Oracle DB) (SQL)
Answer update emp set sal=sal+(sal*10/100) where comm is null;

How to delete those employees who joined the company before 31-
Question dec-82 while there dept location
is 'NEW YORK' or 'CHICAGO'. (Oracle DB) (SQL)
delete from emp where hiredate<'31-dec-1982' and deptno in
Answer
(select deptno from dept where loc in('NEW YORK','CHICAGO'));

How to display employee name, job, deptname, location for all who are
Question
working as managers. (Oracle DB) (SQL)
select ename,job,dname,loc from emp e, dept d where
Answer
e.deptno=d.deptno and empno in (select mgr from emp);

How to display those employees whose manager names is Jones, and


Question
also display there manager name. (Oracle DB) (SQL)
select e.empno, e.ename, m.ename MANAGER from emp e, emp m
Answer
where e.mgr=m.empno and m.ename='JONES';

How to display name and salary of ford if his Sal is equal to high Sal of
Question
his grade. (Oracle DB) (SQL)
select ename,sal from emp e where ename='FORD' and sal=(select hisal
Answer from salgrade where
grade=(select grade from salgrade where e.sal>=losal and e.sal<=hisal));

Question How to display employee name, his job, his dept name, his manager
name, his grade and make out of an
under department wise. (Oracle DB) (SQL)
break on deptno;
select d.deptno, e.ename, e.job, d.dname, m.ename, s.grade from
Answer
emp e, emp m, dept d, salgrade s where e.deptno=d.deptno and e.sal
between s.losal and s.hisal and e.mgr=m.empno order by e.deptno;

How to List out all the employees name, job, and salary grade and
department name for every one in the
Question
company except 'CLERK'. Sort on salary display the highest salary. (Oracle
DB) (SQL)
select empno, ename, sal, dname, grade from emp e, dept d, salgrade s
Answer where e.deptno=d.deptno
and e.sal between s.losal and s.hisal and e.job<>'CLERK' order by sal;

How to display employee name, his job and his manager. display also
Question
employees who are without manager. (Oracle DB) (SQL)
select e.ename, e.job, m.ename Manager from emp e,emp m where
Answer e.mgr=m.empno union select
ename,job,'no manager' from emp where mgr is null;

Question How to find out the top 5 earner of company. (Oracle DB) (SQL)
select * from emp e where 5>(select count(*) from emp where sal>e.sal)
Answer
order by sal desc;

How to display the name of those employees who are getting highest
Question
salary. (Oracle DB) (SQL)
Answer select empno,ename,sal from emp where sal=(select max(sal) from emp);

How to display those employees whose salary is equal to average of


Question
maximum and minimum. (Oracle DB) (SQL)
Answer select * from emp where sal=(select (max(sal)+min(sal))/2 from emp);

How to display count of employees in each department where count


Question
greater than 3. (Oracle DB) (SQL)
Answer select deptno, count(*) from emp group by deptno having count(*)>3;

How to display dname where at least 3 are working and display only
Question
dname. (Oracle DB) (SQL)
select dname from dept where deptno in
Answer
(select deptno from emp group by deptno having count(*)>3);

How to display name of those managers name whose salary is more than
Question
average salary of secompany. (Oracle DB) (SQL)
select ename, sal from emp where empno in(select mgr from emp) and
Answer
sal > (select avg(sal) from emp);
How to display those managers name whose salary is more than an
Question
average salary of his employees. (Oracle DB) (SQL)
select ename, sal from emp e where empno in(select mgr from emp) and
Answer
e.sal>(select avg(sal) from emp where mgr=e.empno);

How to display employee name, Sal, comm and net pay for those
employees whose net pay are greater
Question
than or equal to any other employee salary of the company? (Oracle
DB) (SQL)
select ename, sal, comm, sal+nvl(comm,0) netPay from emp where
Answer
sal+nvl(comm.,0)>=any(select sal from emp);

How to display those employees whose salary is less than his manager
Question
but more than salary of any other managers. (Oracle DB) (SQL)
select * from emp e where sal<(select sal from emp where empno =
Answer
e.mgr) and sal>any(select sal from emp where empno!=e.mgr);

How to find out the last 5(least) earner of the company? (Oracle
Question
DB) (SQL)
select * from emp e where 5>(select count(*) from emp where sal<e.sal)
Answer
order by sal;

How to find out the number of employees whose salary is greater than
Question
there manager salary? (Oracle DB) (SQL)
select count(*) from emp e where sal>(select sal from emp where
Answer
empno=e.mgr);

How to display those manager who are not working under president but
Question
they are working under any other manager? (Oracle DB) (SQL)
select * from emp e where mgr in(select empno from emp where
Answer
ename<>'KING');

How to delete those department where no employee working? (Oracle


Question
DB) (SQL)
delete from dept d where 0=(select count(*) from emp where
Answer
deptno=d.deptno);

How to delete those records from EMP table whose deptno not available
Question
in dept table? (Oracle DB) (SQL)
Answer delete from emp where deptno not in(select deptno from dept);

How to display those earners whose salary is out of the grade available in
Question
Sal grade table? (Oracle DB) (SQL)
select * from emp where sal<(select min(losal) from salgrade) or
Answer
sal>(select max(hisal) from salgrade);
How to display employee name, Sal, comm. and whose net pay is greater
Question
than any other in the company? (Oracle DB) (SQL)
Select ename, sal, comm from emp where sal+sal*15/100-sal*5/100
Answer +sal*10/100 =
(select max(sal+sal*15/100-sal*5/100+sal*10/100) from emp);

How to display name of those employees who are going to retire 31-
Question dec-99. If the maximum job is
period is 18 years? (Oracle DB) (SQL)
Answer select * from emp where (to_date('31-dec-1999')-hiredate)/365>18;

How to display those employees whose salary is ODD value? (Oracle


Question
DB) (SQL)
Answer select * from emp where mod(sal,2)=1;

How to display those employees whose salary contains at least 4 digits?


Question
(Oracle DB) (SQL)
Answer select * from emp where length(sal)>=4;

How to display those employees who joined in the company in the month
Question
of DEC? (Oracle DB) (SQL)
Answer select * from emp where upper(to_char(hiredate,'mon'))='DEC';

How to display those employees whose name contains "A"? (Oracle


Question
DB) (SQL)
Answer select * from emp where instr(ename,'A',1,1)>0;

How to display those employees whose deptno is available in salary?


Question
(Oracle DB) (SQL)
Answer select * from emp where instr(sal,deptno,1,1)>0;

How to display those employees whose first 2 characters from hire date-
Question
last 2 characters of salary? (Oracle DB) (SQL)
select substr(hiredate,0,2)||substr(sal,length(sal)-1,2) from emp;
Answer
select concat( substr(hiredate,0,2), substr(sal,length(sal)-1,2) ) from emp;

How to display those employees whose 10% of salary is equal to the year
Question
of joining? (Oracle DB) (SQL)
Answer select * from emp where to_char(hiredate,'yy')=sal*10/100;

How to display those employees who are working in sales or research?


Question
(Oracle DB) (SQL)
select * from emp where deptno in(select deptno from dept where dname
Answer
in('SALES','RESEARCH'));
Question How to display the grade of Jones? (Oracle DB) (SQL)
select grade from salgrade where losal<=(select(sal) from emp where
Answer ename='JONES') and
hisal>=(select(sal) from emp where ename='JONES');

How to display those employees who joined the company before 15th of
Question
the month? (Oracle DB) (SQL)
select empno,ename from emp where hiredate<(to_date('15-'||
Answer
to_char(hiredate,'mon')||'-'||to_char(hiredate,'yyyy')));

How to delete those records where no of employee in a particular


Question
department is less than 3? (Oracle DB) (SQL)
delete from emp where deptno in(select deptno from emp group by
Answer
deptno having count(*)>3);

How to delete those employees who joined the company 21 years back
Question
from today? (Oracle DB) (SQL)
select * from emp where round((sysdate-hiredate)/365)>21; or
Answer select * from emp where (to_char (sysdate, 'yyyy')-to_char
(hiredate ,'yyyy') )>21;

How to display the department name the no of characters of which is


Question equal to no of employees in any
other department? (Oracle DB) (SQL)
Select dname from dept where length(dname) in (select count(*) from
Answer
emp group by deptno);

How to display those employees who are working as manager? (Oracle


Question
DB) (SQL)
Answer select * from emp where empno in(select mgr from emp);

How to count the no of employees who are working as manager (use set
Question
operation)? (Oracle DB) (SQL)
Answer select count(*) from emp where empno in(select mgr from emp);

How to display the name of then dept those employees who joined the
Question
company on the same date? (Oracle DB) (SQL)
select empno,ename,hiredate,deptno from emp e where hiredate in
Answer
(select hiredate from emp where empno<>e.empno);

How to display the manager who is having maximum number of


Question
employees working under him? (Oracle DB) (SQL)
Select mgr from emp group by mgr having count(*)=(select
Answer
max(count(mgr)) from emp group by mgr);
How to list out employees name and salary increased by 15% and
Question
expressed as whole number of dollars? (Oracle DB) (SQL)
select empno,ename,lpad(concat('$',round(sal*115/100)),7) salary from
Answer
emp;

How to produce the output of the EMP table "EMPLOYEE_AND_JOB" for


Question
ename and job? (Oracle DB) (SQL)
Answer select * from EMPLOYEE_AND_JOB;

How to list all employees with hire date in the format 'June 4 1988'?
Question
(Oracle DB) (SQL)
Answer select to_char(hiredate,'month dd yyyy') from emp;

How to print a list of employees displaying 'Less Salary' if less than 1500
if exactly 1500 display
Question
as 'Exact Salary' and if greater than 1500 display 'More Salary'? (Oracle
DB) (SQL)
select empno,ename,'Less Salary '||sal from emp where sal<1500
union
Answer select empno,ename,'More Salary '||sal from emp where sal>1500
union
select empno,ename,'Exact Salary '||sal from emp where sal=1500

How to write query to calculate the length of employee has been with the
Question
company? (Oracle DB) (SQL)
Answer Select round(sysdate-hiredate) from emp;

How to display those mangers who are getting less than his employees
Question
Sal. (Oracle DB) (SQL)
Select empno from emp e where sal<any(select sal from emp where
Answer
mgr=e.empno);

How to print the details of all the employees who are sub ordinate to
Question
Blake. (Oracle DB) (SQL)
Select * from emp where mgr=(select empno from emp where
Answer
ename='BLAKE');

How to display those who working as manager using co related sub query.
Question
(Oracle DB) (SQL)
Answer Select * from emp where empno in(select mgr from emp);

How to display those employees whose manger name is Jones and also
Question
with his manager name. (Oracle DB) (SQL)
Select * from emp where mgr=(select empno from emp where
Answer ename='JONES') union select * from emp
where empno=(select mgr from emp where ename='JONES');
How to define variable representing the expressions used to calculate on
Question
employee's total annual renumaration. (Oracle DB) (SQL)
Answer define emp_ann_sal=(sal+nvl(comm,0))*12;

How to use the variable in a statement which finds all employees who can
Question
earn 30,000 a year or more. (Oracle DB) (SQL)
Answer select * from emp where &emp_ann_sal>30000;

How to find out how many mangers are there with out listing them.
Question
(Oracle DB) (SQL)
Answer Select count (*) from EMP where empno in (select mgr from EMP);

How to find out the avg sal and avg total remuneration for each job type
Question
remember salesman earn commission. (Oracle DB) (SQL)
select job,avg(sal+nvl(comm,0)),sum(sal+nvl(comm,0)) from emp group
Answer
by job;

How to check whether all employees number are indeed unique. (Oracle
Question
DB) (SQL)
select count(empno),count(distinct(empno)) from emp having
Answer
count(empno)=(count(distinct(empno)));

How to list out the lowest paid employees working for each manager,
Question exclude any groups where min sal
is less than 1000 sort the output by sal. (Oracle DB) (SQL)
select e.ename,e.mgr,e.sal from emp e where sal in(select min(sal) from
Answer
emp where mgr=e.mgr) and e.sal>1000 order by sal;

How to list ename, job, annual sal, deptno, dname and grade who earn
Question
30000 per year and who are not clerks. (Oracle DB) (SQL)
Select e.ename, e.job, (e.sal+nvl(e.comm,0))*12, e.deptno, d.dname,
s.grade from emp e, salgrade s , dept d
Answer
where e.sal between s.losal and s.hisal and e.deptno=d.deptno and
(e.sal+nvl(comm,0))*12> 30000 and e.job <> 'CLERK';

How to find out the all employees who joined the company before their
Question
manager. (Oracle DB) (SQL)
Select * from emp e where hiredate<(select hiredate from emp where
Answer
empno=e.mgr);

How to list out the all employees by name and number along with their
Question manager's name and number also
display 'No Manager' who has no manager. (Oracle DB) (SQL)
Answer select e.empno,e.ename,m.empno Manager,m.ename ManagerName from
emp e,emp m where e.mgr=m.empno
union
select empno,ename,mgr,'No Manager' from emp where mgr is null;

How to find out the employees who earned the highest Sal in each job
Question
typed sort in descending Sal order. (Oracle DB) (SQL)
select * from emp e where sal =(select max(sal) from emp where
Answer
job=e.job);

How to find out the employees who earned the min Sal for their job in
Question
ascending order. (Oracle DB) (SQL)
select * from emp e where sal =(select min(sal) from emp where
Answer
job=e.job) order by sal;

How to find out the most recently hired employees in each dept order by
Question
hire date (Oracle DB) (SQL)
Answer select * from emp order by deptno,hiredate desc;

How to display ename, sal and deptno for each employee who earn a Sal
Question greater than the avg of their
department order by deptno (Oracle DB) (SQL)
select ename,sal,deptno from emp e where sal>(select avg(sal) from
Answer
emp where deptno=e.deptno) order by deptno;

How to display the department where there are no employees (Oracle


Question
DB) (SQL)
select deptno,dname from dept where deptno not in(select
Answer
distinct(deptno) from emp);

How to display the dept no with highest annual remuneration bill as


Question
compensation. (Oracle DB) (SQL)
select deptno,sum(sal) from emp group by deptno having sum(sal) =
Answer
(select max(sum(sal)) from emp group by deptno);

How to find in which year did most people join the company. display the
Question
year and number of employees (Oracle DB) (SQL)
select count(*),to_char(hiredate,'yyyy') from emp group by
Answer
to_char(hiredate,'yyyy');

Question How to display avg sal figure for the dept (Oracle DB) (SQL)

Answer select deptno,avg(sal) from emp group by deptno;

How to write a query of display against the row of the most recently hired
Question employee. display ename hire
date and column max date showing. (Oracle DB) (SQL)
Answer select empno,hiredate from emp where hiredate=(select max (hiredate)
from emp);

How to display employees who can earn more than lowest Sal in dept no
Question
30 (Oracle DB) (SQL)
select * from emp where sal>(select min(sal) from emp where
Answer
deptno=30);

How to find employees who can earn more than every employees in dept
Question
no 30 (Oracle DB) (SQL)
select * from emp where sal>(select max(sal) from emp where
Answer deptno=30);
select * from emp where sal>all(select sal from emp where deptno=30);

Question How to select dept name dept no and sum of Sal (Oracle DB) (SQL)
break on deptno on dname;
Answer select e.deptno,d.dname,sal from emp e, dept d where e.deptno=d.deptno
order by e.deptno;

How to find all dept's which have more than 3 employees (Oracle
Question
DB) (SQL)
Answer select deptno from emp group by deptno having count(*)>3;

How to display the half of the enames in upper case and remaining lower
Question
case (Oracle DB) (SQL)
select concat ( upper ( substr ( ename, 0 , length (ename)/ 2) ),
Answer lower (substr (ename, length(ename) / 2+1, length(ename) )) ) from
emp;

Question How to create a copy of emp table. (Oracle DB) (SQL)

Answer Create table emp1 as select * from emp;

Question How to select ename if ename exists more than once. (Oracle DB) (SQL)
select distinct(ename) from emp e where ename in(select ename from
Answer
emp where e.empno<>empno);

Question How to display all enames in reverse order. (Oracle DB) (SQL)

Answer select ename from emp order by ename desc;

How to display those employee whose joining of month and grade is


Question
equal. (Oracle DB) (SQL)
select empno,ename from emp e, salgrade s where e.sal between s.losal
Answer
and s.hisal and to_char(hiredate,'mm')=grade;

How to display those employee whose joining date is available in dept no


Question
(Oracle DB) (SQL)
Answer select * from emp where to_char(hiredate,'dd')=deptno;

How to display those employees name as follows A ALLEN, B BLAKE


Question
(Oracle DB) (SQL)
Answer select substr(ename,1,1)||' '||ename from emp;

Question How to list out the employees ename, sal, PF from emp (Oracle DB) (SQL)

Answer Select ename,sal,sal*15/100 PF from emp;

Question How to create table emp with only one column empno (Oracle DB) (SQL)

Answer Create table emp (empno number(5));

How to add this column to emp table ename Varchar(20). (Oracle


Question
DB) (SQL)
Answer alter table emp add ename varchar2(20) not null;

How to add primary key constraint after the table has been created?
Question
(Oracle DB) (SQL)
Answer alter table emp add constraint emp_empno primary key (empno);

How to increase the length of ename column to 30 characters. (Oracle


Question
DB) (SQL)
Answer alter table emp modify ename varchar2(30);

Question How to add salary column to emp table. (Oracle DB) (SQL)

Answer alter table emp add sal number(7,2);

I want to give a validation saying that sal cannot be greater 10,000(note


Question
give a name to this column). How to do this? (Oracle DB) (SQL)
Answer alter table emp add constraint emp_sal_check check (sal<10000);

How to add column called as mgr to your emp table. This column should
Question be related to empno. Give a
command to add this constraint (Oracle DB) (SQL)
Alter table emp add mgr number (5);
Answer
Alter table emp add constraint emp_mgr foreign key (empno);

How to add dept no column to your emp table. This dept no column
Question should be related to deptno column of
dept table (Oracle DB) (SQL)
Alter table emp add deptno number (3);
Answer Alter table emp1 add constraint emp1_deptno foreign key(deptno)
references dept(deptno);
How to create table called as new emp. Using single command create this
Question table as well as to get data
into this table (use create table as) (Oracle DB) (SQL)
Answer create table newemp as select *from emp;

How to create table called as newemp. This table should contain only
Question
empno,ename, dname (Oracle DB) (SQL)
create table newemp as select empno,ename,dname from emp e , dept d
Answer
where e.deptno=d.deptno;

How to delete the rows of employees who are working in the company for
Question
more than 2 years. (Oracle DB) (SQL)
Answer delete from emp where floor(sysdate-hiredate)>2*365;

How to provide a commission to employees who are not earning any


Question
commission. (Oracle DB) (SQL)
Answer update emp set comm=300 where comm is null;

Write a query, If any employee has commission his commission should be


Question
incremented by 10% of his salary. (Oracle DB) (SQL)
Answer update emp set comm=comm*10/100 where comm is not null;

How to display employee name and department name for each employee.
Question
(Oracle DB) (SQL)
Answer select ename,dname from emp e, dept d where e.deptno=d.deptno;

How to display employee number, name and location of the department


Question
in which he is working. (Oracle DB) (SQL)
Answer Select empno, ename, loc from emp e, dept d where e.deptno=d.deptno;

How to display ename, dname even if there no employees working in a


Question
particular department(use outer join). (Oracle DB) (SQL)
Select ename, dname from emp e, dept d where e.deptno (+)=
Answer
d.deptno;

Question How to display employee name and his manager name. (Oracle DB) (SQL)
Answer Select e.ename, m.ename from emp e, emp m where e.mgr=m.empno;

How to display the department name along with total salary in each
Question
department. (Oracle DB) (SQL)
Answer Select deptno, sum(sal) from emp group by deptno;

How to display the department name and total number of employees in


Question
each department. (Oracle DB) (SQL)
Answer select deptno,count(*) from emp group by deptno;

Question How to display the current date and time (Oracle DB) (SQL)
Answer select to_char(sysdate,'month mon dd yy yyyy hh:mi:ss') from dual;

Question What is the advantage of DispatchAction class? (Struts)


Using DispatchAction class you can overcome writing one Action class for
one business entity.
Answer Instead you can write multiple business entities in one Action class and call
the business
method that is required by the application.

Can you write your own method in Action class other than execute() and
Question call that user method
directly? (Struts)
Answer Yes, We can create any number of methods in Action class and instruct
the action tag in
struts-config.xml file to call that user method. This is possible by using
DispatchAction class.

A sample code would look like this

public class StudentAction extends DispatchAction


{
public ActionForward create(ActionMapping mapping, ActionForm
form,
HttpServletRequest req,
HttpServletResponse res) throws Exception
{
return something;
}

public ActionForward read(ActionMapping mapping, ActionForm form,


HttpServletRequest req,
HttpServletResponse res) throws Exception
{
return something;
}

public ActionForward update(ActionMapping mapping, ActionForm


form,
HttpServletRequest req,
HttpServletResponse res) throws Exception
{
return something;
}

}
In the above Action class if the user wants to call any method, he would do
something
like this in my struts-config.xml file

<action path="/somePage"
type="StudentAction"
name="studentForm"
<b>parameter="methodToCall"</b>
scope="request"
validate="true"
input="/student.jsp">

<forward name="success" path="/success.jsp"/>


</action>

In this configuration file the value of the parameter methodToCall


determines the method in
the StudentAction class to be invoked. For example, the JSP from which
you are calling this
action, can set the methodToCall parameter to any of the methods it wants
to.

How you will enable front-end validation based on the xml in


Question
validation.xml? (Struts)
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"
Answer 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.

What happens when the user has not provided required information that
is needed by the struts
Question
validator framework? Explain how struts handles to display the validation
messages? (Struts)
When the user has not provided any required information, the validation
messages are
displayed to the user and this block of code does this job.

<logic:messagesPresent>
<bean:message key="errors.header.login"/>
Answer
<ul>
<html:messages id="error">
<li><bean:write name="error"/></li>
</html:messages>
</ul><hr />
</logic:messagesPresent>
Question Brief on how struts validation is working (Struts)
Struts uses 2 XML files to validate the user form. validator-rules.xml and
validation.xml
files. The validator-rules.xml defines a set of standard validations and
these validations
Answer are used in validation.xml file.

Generally the rules defined in validator-rules.xml file are typical java class
files that does
the validation in the backend.

Question Explain about ActionForm class (Struts)


ActionForm class defines get and set methods for information provided by
the client in the
Answer HTML form. It has reset (for reseting the defined variables to its initital
state) and
validate method for validating the user input.

Question Explain about Action Class (Struts)


The Action Class is part of the Model and is a wrapper around the
business logic. The
purpose of Action Class is to translate the HttpServletRequest to the
business logic. To
use the Action, we need to Subclass and overwrite the execute() method.
In the Action
Class all the database/business processing are done. It is advisable to
Answer perform all the
database related stuffs in the Action Class. The ActionServlet (command)
passes the
parameterize 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.

Do you write an ActionForm class for every form that you need to
Question
process? (Struts)
Answer No, I define DynaValidatorForm as this class takes care of defining
get/set methods and
doing the validation for me. And I need to define this class in struts-
config.xml file. An e.g.
would be

<form-beans>

<form-bean name="categoryForm"
type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="category" type="java.lang.String"/
>
</form-bean>
</form-beans>

Question How would struts handle "messages" required for the application? (Struts)
Messages are defined in a .properties file as name value pairs. To make
these messages
available to the application, you need to place the .properties file in WEB-
INF/classes
folder. And define the following tag in struts-config.xml file
Answer
<message-resources parameter="ApplicationResources" />

And in order to display a message in a jsp you would use

<bean:message key="title.mytitle"/>

What is the name of the XML file which handles requests and gives
Question responses? And acts
as a controller? (Struts)
Answer struts-config.xml file

Question Explain about ActionServlet in Apache Struts (Struts)


ActionServlet acts as a controller in Struts. There can be only one
ActionServlet defined
Answer
for a context. ActionServlet is defined in web.xml file of a context e.g.
WEB-INF/web.xml

Question Can I have more than one struts-config.xml file? (Struts)


Answer Yes. A sample configuration in web.xml file would look like this

<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<!-- module configurations -->
<init-param>
<param-name>config/exercise</param-name>
<param-value>/WEB-INF/exercise/struts-config.xml</param-
value>
</init-param>
<init-param>
<param-name>config/upload</param-name>
<param-value>/WEB-INF/upload/struts-config.xml</param-
value>
</init-param>
</servlet>

Question What is Struts Validator Framework? (Struts)


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
Answer
the java scripts and it can be used to 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.

Question What is the role of ActioMapping object in Struts Action class? (Struts)
An ActionMapping knows about the mapping of a particular request to an
Answer
instance of a particular Action class.

What happens internally when actionMappings.findForward("target")


Question
method is called in Action class. (Struts)
actionMappings.findForward("target") method returns ActionForward
object. An ActionForward represents a destination to
which the controller, RequestProcessor, might be directed to perform a
Answer
RequestDispatcher.forward or
HttpServletResponse.sendRedirect to, as a result of processing activities of
an Action class.

Expalin JSP,Servlet Combination VS Struts Which is better and


Question
how? (Struts)
Struts is a framework based on Model-View-Controller (MVC) design
paradigm. The Model represents the business or database code, the View
represents
the page design code, and the Controller represents the navigational code.
The Struts framework is designed to help developers create web
applications
Answer
that utilize a MVC architecture. Struts framework internally uses Servlet
Technology for processing the request and response.

Sun Microsystems has provided the JSP / Servlet API specifications, and its
the web server or application server vendor who implements the logic for
the API.

Question Explain ActionForward against JSP:forward (Struts)


jsp:forward is part of JSTL and will be used in JSP pages. It internally
uses RequestDispatcher to forward the request to new jsp or servlet page
Answer
ActionForward is part of Struts framework and is used in Action class. It
internally uses RequestDispatcher to forward the request to ActionServlet

Question How to handle multiple forms using Struts?


(Struts)

What I understand from your question is, You are having multiple forms
in different pages and needs to
process this information to server at the last form.

e.g. Form 1, 2, 3 and 4 in 4 different web pages and process the data to
server at the final web page.

It is easy to have a form that spans multiple jsp's with struts. Make sure
that your form bean is part
Answer
of the session and not the request object. Also be sure to include some
type of form validation routine
that checks to make sure all of the required information has been
submitted before you send the whole
form off to the server for processing.

You cannot have single web page with multiple forms and submit all of it at
once. When you click on submit button in a form only the form that has
submit button will be submitted to server.

Question What are the tokens available in Struts? (Struts)


Answer Any one would like like to answer this question?

Question What is the difference between Action messages & Action errors? (Struts)

Answer Any one would like like to answer this question?

Why does it take so much time to access an Applet having Swing


Question
Components the first time? (Swing)
Because behind every swing component are many Java objects and
resources. This takes time to create them in memory. JDK 1.3 from Sun
Answer
has some improvements which may lead to faster execution of Swing
applications.

Why does JComponent have add() and remove() methods but Component
Question
does not? (Swing)
because JComponent is a subclass of Container, and can contain other
Answer
components and jcomponents

Question How would you create a button with rounded edges? (Swing)
There are 2 ways. The first thing is to know that a JButton?s edges are
drawn by a Border. so you can override the Button?s
paintComponent(Graphics) method and draw a circle or rounded rectangle
Answer
(whatever), and turn off the border. Or you can create a custom border
that draws a circle or rounded rectangle around any component and set
the button?s border to it.

Question How would you detect a keypress in a JComboBox? (Swing)


Add a KeyListener to the JComboBox?s editor component instead of
Answer
adding a KeyListener to the JComboBox itself

Why should the implementation of any Swing callback (like a listener)


Question
execute quickly? (Swing)
Because callbacks are invoked by the event dispatch thread which will be
Answer blocked processing other events for as long as your method takes to
execute.

Why would you use SwingUtilities.invokeAndWait or


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

If your UI seems to freeze periodically, what might be a likely


Question
reason? (Swing)
A callback implementation like ActionListener.actionPerformed or
Answer MouseListener.mouseClicked is taking a long time to execute thereby
blocking the event dispatch thread from processing other UI events.

Question Which Swing methods are thread-safe? (Swing)


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

Why won’t the JVM terminate when I close all the application
Question
windows? (Swing)
The AWT event dispatcher thread is not a daemon thread. You must
Answer
explicitly call System.exit to terminate the JVM.

JFrame is a heavy weight component. Since it extends an awt Frame, is it


Question
Thread Safe? (Swing)
JFrame itself is, since it is just a java.awt.Frame in essence, but the root
Answer pane/content pane is not, so it effectively follows the same rules for Swing
containers and is not considered thread safe.

What is the difference between invokeAndWait() and


Question
invokeLater()? (Swing)
invokeAndWait() blocks until the Runnable task is complete; it's
synchronous.
Answer
invokeLater() posts an action event to the event queue and returns
immediately; it's asynchronous.

Question What is the difference between a Scrollbar and a ScrollPane? (Swing)


Answer 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

Question What do heavy weight components mean? (Swing)


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

Question Difference between paint() and paintComponent() (Swing)


The key point is that the paint() method invokes three methods in the
following order:
a) paintComponent()
b) paintBorder()
c) paintChildren()
Answer
As a general rule, in Swing, you should be overriding the paintComponent
method unless you know what you are doing.
paintComponent() paints only component (panel) but paint() paints
component and all its children.

What is the difference between paint(), repaint() and update() methods


Question
within an applet which contains images? (Swing)
paint : is only called when the applet is displayed for the first time, or
when part of the applet window has to be redisplayed after it was hidden.
repaint : is used to display the next image in a continuous loop by calling
the update method.
Answer update : you should be aware that, if you do not implement it yourself,
there is a standard update method that does the following :
· it will reset the applet window to the current background color (i.e. it will
erase the current image)
it will call paint to construct the new image

Question What are peerless components? (Swing)


Answer The peerless components are called light weight components

Question When should the method invokeLater()be used? (Swing)


This method is used to ensure that Swing components are updated
Answer
through the event-dispatching thread.

Question What is the difference between yielding and sleeping? (Threads)


When a task invokes its yield() method, it returns to the ready state.
Answer
When a task invokes its sleep() method, it returns to the waiting state.
Question When a thread blocks on I/O, what state does it enter? (Threads)

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

Question When a thread is created and started, what is its initial state? (Threads)
Answer A thread is in the ready state after it has been created and started.

Question What invokes a thread's run() method? (Threads)


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

What method is invoked to cause an object to begin executing as a


Question
separate thread? (Threads)
The start() method of the Thread class is invoked to cause an object to
Answer
begin executing as a separate thread.

What is the purpose of the wait(), notify(), and notifyAll()


Question
methods? (Threads)
The wait(),notify(), and notifyAll() methods are used to provide an
efficient way for threads to wait for a shared resource. When a thread
Answer 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.

Question What are the high-level thread states? (Threads)


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

Question What happens when a thread cannot acquire a lock on an object? (Threads)
If a thread attempts to execute a synchronized method or synchronized
Answer statement and is unable to acquire an object's lock, it enters the waiting
state until the lock becomes available.

How does multithreading take place on a computer with a single


Question
CPU? (Threads)
The operating system's task scheduler allocates execution time to
Answer multiple tasks. By quickly switching between executing tasks, it creates the
impression that tasks execute sequentially.

What happens when you invoke a thread's interrupt method while it is


Question
sleeping or waiting? (Threads)
When a task's interrupt() method is executed, the task enters the ready
Answer state. The next time the task enters the running state, an
InterruptedException is thrown.
Question What state is a thread in when it is executing? (Threads)

Answer An executing thread is in the running state

What are three ways in which a thread can enter the waiting
Question
state? (Threads)
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
Answer
by invoking an object's wait() method. It can also enter the waiting state by
invoking its (deprecated) suspend() method.

Question What method must be implemented by all threads? (Threads)


All tasks must implement the run() method, whether they are a subclass
Answer
of Thread or implement the Runnable interface.

What are the two basic ways in which classes that can be run as threads
Question
may be defined? (Threads)
A thread class may be declared as a subclass of Thread, or it may
Answer
implement the Runnable interface.

If there are 20 threads waiting in the waiting pool with same priority, how
Question
can you invoke 15th thread from the waiting pool? (Threads)
Its not possible do call a particular thread. The methods notify() will calls
thread from waiting pool, but there is no guaranty which thread is invoked.
Answer
The method notifyAll() method puts all the waiting threads from the
waiting pool in ready state.

Question Explain about Deadlock state of a thread (Threads)


Answer Synchronizing run() is a good example of a simple deadlock scenario,
where a thread is blocked forever, waiting for something to happen that
can't. Let's look at a few examples that are more realistic than this.

The most common deadlock scenario occurs when two threads are both
waiting for each other to do something. The following (admittedly
contrived) code snippet makes what's going on painfully obvious:

see code at: http://www.javagalaxy.com:8080/Threads/View.jsp?


slno=3&tbl=0

Now, imagine a scenario whereby one thread (call it Wilma) calls fred(),
passes through the synchronization of lock_1, and is then preempted,
allowing another thread (call it Betty) to execute. Betty calls barney(),
acquires lock_2, and tries to acquire lock_1, but can't because Wilma has
it. Betty is now blocked, waiting for lock_1 to become available, so Wilma
wakes up and tries to acquire lock_2 but can't because Betty has it. Wilma
and Betty are now deadlocked. Neither one can ever execute.

(Note that lock_1 and lock_2 have to be one-element arrays rather than
simple ints, because only objects have monitors in Java; the argument to
synchronized must be an object. An array is a first-class object in Java; a
primitive-type such as int is not. Consequently, you can synchronize on it.
Moreover, a one-element array is efficient to bring into existence compared
to a more elaborate object (like an Integer) since it's both small and does
not require a constructor call. Also, note that I can keep the reference to
the lock as a simple Object reference, since I'll never access the array
elements.

Question What is a daemon thread? (Threads)


Daemon threads are service providers for other threads running in the
same process as the daemon thread. When the only remaining threads in a
process are daemon threads, the interpreter exits. This is because when
only daemon threads remain, there is no other thread for which a daemon
Answer thread can provide a service. An example would be AWT-Event threads.
Another example would be a mail daemon. When a mail message is
recieved by a mail server it generally needs to be forwarded on to another
machine. One way to do this is to have a daemon check for mail every so
often and cause the mail to be forwarded.

Can you explain the difference between green threads and native
Question
threads? (Threads)
Green threads is thread mechanism implemented in JVM itself. It is blind
and can run on any OS, so actually all threads are run in one native thread
and scheduling is up to JVM. This is disadvantageously for SMP systems,
since only one processor can serve Java application.
Answer
Native threads is a mechanism based on OS threading mechanism. This
allows to use features of hardware and OS. For example,there is IBM's JDK
for AIX that supports native threads. The perfomance of applications can
be highly imploved by this.

I have created a program with a main method that instantiates and starts
Question three threads, the first two of which are daemons. Why daemons does die
when normal thread die? (Threads)
Because of nature of daemon threads. They are alive if exists at least one
Answer
"normal user's" thread. Otherwise they die immediately

Question When will a Thread Object be garbage collected? (Threads)


Since Thread is also an Object, it will only garbage collected when the
reference count is zero. You may think it is quite non-sense. the thread is
useless when it enter "dead" state. why not garbage collect it? That's
Answer because the thread object itself may contain some other useful information
even the thread dead , e.g. the result of the execution of the thread. Thus,
it is not sensible to do garbage collect when the reference count is not
zero.

Question What happens when you call yield() on a thread? (Threads)


Causes the currently executing thread object to temporarily pause and
Answer
allow other threads to execute
What is the difference between "green" threads and "native" threads on
Question
Linux OS? (Threads)
Native threads can switch between threads pre-emptively, switching
control from a running thread to a non-running thread
at any time. Green threads only switch when control is explicitly given up
by a thread
(Thread.yield(), Object.wait(), etc.) or a thread performs a blocking
operation (read(), etc.).

On multi-CPU machines, native threads can run more than one thread
Answer
simultaneously by assigning different threads to
different CPUs. Green threads run on only one CPU.

Native threads create the appearance that many Java processes are
running: each thread takes up its own entry in the
process table. One clue that these are all threads of the same process is
that the memory size is identical for all the
threads - they are all using the same memory.

Question What is the difference between Multitasking and Multithreading? (Threads)


Multitasking is the ability of an operating system to execute more than
one program simultaneously. Though we say so but in reality no two
programs on a single processor machine can be executed at the same
time. The CPU switches from one program to the next so quickly that
appears as if all of the programs are executing at the same time.

Multithreading is the ability of an operating system to execute the different


parts of the program, called threads,
simultaneously. The program has to be designed well so that the different
Answer
threads do not interfere with each other. This
concept helps to create scalable applications because you can add threads
as and when needed.

Individual programs are all isolated from each other in terms of their
memory and data, but individual threads are not as
they all share the same memory and data variables. Hence, implementing
multitasking is relatively easier in an operating system than implementing
multithreading.

Which UML diagrams would give a chronological perspective of a


Question
scenario? (UML)
Answer Sequence Diagram

Which UML diagram would you use to view and understand large complex
Question
systems, on a high level? (UML)
Answer Package Diagrams
Give 2 examples of non-functional requirements considered during the
Question
Design Phase? (UML)
Answer Performance and Security

What diagrams would you use in OOAD, to capture Hardware Topology,


Question
using Nodes and Links? (UML)
Answer Deployment Diagrams

Question What is the term used to describe the dependency between classes? (UML)

Answer Coupling

Question Why is XML such an important development? (XML)


It removes two constraints which were holding back Web
developments:<br> 1. § dependence on a single, inflexible document type
(HTML) which was being much abused for tasks it was never designed
for;<br> 2. the complexity of full SGML, whose syntax allows many
Answer powerful but hard-to-program options.<br> § XML allows the flexible
development of user-defined document types. It provides a robust, non-
proprietary, persistent, and verifiable file format for the storage and
transmission of text and data both on and off the Web; and it removes the
more complex options of SGML, making it easier to program for.

Is it possible to write the contents of org.w3c.dom.Document object into


Question
an .xml file? (XML)
Yes its possible. One to achieve this is by using Xerces. Xerces is an XML
parser. You would use the following code

org.apache.xml.serialize.OutputFormat format = new


Answer org.apache.xml.serialize.OutputFormat(myDocument);
org.apache.xml.serialize.XMLSerializer output = new
org.apache.xml.serialize.XMLSerializer(new FileOutputStream(new
File("test.xml")), format);
output.serialize(myDocument);

What is the difference between DOM and SAX? What would you use if an
Question
option is given? (XML)
Answer DOM parses an XML document and returns an instance of
org.w3c.dom.Document. This document object's tree must then
be "walked" in order to process the different elements. DOM parses the
ENTIRE Document into memory, and then makes it
available to you. The size of the Document you can parse is limited to the
memory available.

SAX uses an event callback mechanism requiring you to code methods to


handle events thrown by the parser as it
encounters different entities within the XML document. SAX throws events
as the Document is being parsed. Only the
current element is actually in memory, so there is no limit to the size of a
Document when using SAX.

The specific parser technology that will be used will be determined by the
requirements of your application. If you need the
entire document represented, you will most likely use DOM builder
implementation. If you only care about parts of the
XML document and/or you only need to parse the document once, you
might be better served using SAX implementation.

Question What is SOAP? (XML)


The Simple Object Access Protocol (SOAP) uses XML to define a protocol
for the exchange of information in distributed computing environments.
Answer SOAP
consists of three components: an envelope, a set of encoding rules, and a
convention for representing remote procedure calls.

Question What is DOM? (XML)


The Document Object Model (DOM) is an interface specification
maintained by the W3C DOM Workgroup that defines an application
Answer independent mechanism
to access, parse, or update XML data. In simple terms it is a hierarchical
model that allows developers to manipulate XML documents easily.

Question Can you walk us through the steps necessary to parse XML file? (XML)

DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
Answer factory.setValidating(true);
DocumentBuilder domBuilder = factory.newDocumentBuilder();
Document doc = domBuilder.parse(XMLFile);

Question Is it necessary to validate XML file against a DTD? (XML)


Although XML does not require data to be validated against a DTD, many
Answer of the benefits of using the technology are derived from being able to
validate XML documents against business or technical architecture rules.

Question What is XPath? (XML)


XPath stands for XML Path Language
XPath is a syntax for defining parts of an XML document
XPath is used to navigate through elements and attributes in an XML
document
Answer
XPath contains a library of standard functions
XPath is a major element in XSLT
XPath is designed to be used by both XSLT and XPointer
XPath is a W3C Standard

Question What is XSL? (XML)


Answer XSLT - a language for transforming XML documents
XSLT is used to transform an XML document into another XML document,
or another type of document that is recognized by a browser, like HTML
and XHTML.
Normally XSLT does this by transforming each XML element into an
(X)HTML element.

Question What is a DTD and a Schema? (XML)


The XML Document Type Declaration contains or points to markup
declarations that provide a grammar for a class of documents. This
grammar is known as a document type definition or DTD.

The DTD can point to an external subset containing markup declarations,


or can contain the markup declarations directly in an internal subset, or
can even do both.

Answer
A Schema is:

XML Schemas express shared vocabularies and allow machines to carry out
rules made by people. They provide a means for defining the structure,
content and semantics of XML documents.

Schemas are a richer and more powerful of describing information than


what is possible with DTDs.

Question What is the difference between DTD and Schema? (XML)


Answer The first, and probably most significant, difference between XML Schemas
and XML DTDs is that XML Schemas use XML document syntax. While
transforming the syntax to XML doesn’t automatically improve the quality
of the description, it does make those descriptions far more extensible
than they were in the original DTD syntax. Declarations can have richer
and more complex internal structures than declarations in DTDs, and
schema designers can take advantage of XML’s containment hierarchies to
add extra information where appropriate - even sophisticated information
like documentation. There are a few other benefits from this approach.
XML Schemas can be stored along with other XML documents in XML-
oriented data stores, referenced, and even styled,
using tools like XLink, XPointer, and XSL.

The largest addition XML Schemas provide to the functionality of the


descriptions is a vastly improved data typing system. XML Schemas
provide data-oriented data types in addition to the more document-
oriented data types XML 1.0 DTDs support, making XML more suitable for
data interchange applications.
Built-in datatypes include strings, booleans, and time values, and the XML
Schemas draft provides a mechanism for generating additional data types.
Using that system, the draft provides support for all of the XML 1.0 data
types (NMTOKENS, IDREFS, etc.) as well as data-specific types like
decimal,integer, date, and time. Using XML Schemas, developers can build
their own libraries of easily interchanged data types and use them inside
schemas or across multiple schemas.

The current draft of XML Schemas also uses a very different style for
declaring elements and attributes to DTDs. In addition to declaring
elements and attributes individually, developers can create models -
archetypes - that can be applied to multiple elements and refined if
necessary. This provides a lot of the functionality SOX had developed to
support object-oriented concepts like inheritance. Archetype development
and refinement will probably become the mark of the high-end schema
developer, much as the effective use of parameter entities was the mark of
the high-end DTD developer. Archetypes should be easier to model and
use consistently, however.

XML Schemas also support namespaces, a key feature of the W3C’s vision
for the future of XML. While it probably wouldn’t be impossible to integrate
DTDs and namespaces, the W3C has decided to move on, supporting
namespaces in its newer developments and not retrofitting XML 1.0. In
many cases, provided that namespace-prefixes don’t change or simply
aren’t used, DTD’s can work just fine with namespaces, and should be able
to interoperate with namespaces and schema processing that relies on
namespaces. There will be a few cases, however, where namespaces may
force developers to use the newer schemas rather than the older DTDs.