Sei sulla pagina 1di 127

Question: When you declare a method as abstract method ?

Answer: When i want child class to implement the behavior of the method.

Question: Can I call a abstract method from a non abstract method ?

Answer: Yes, We can call a abstract method from a Non abstract method in a Java abstract class

Question: What is the difference between an Abstract class and Interface in Java ? or can you
explain when you use Abstract classes ?

Answer: Abstract classes let you define some behaviors; they force your subclasses to provide
others. These abstract classes will provide the basic funcationality of your applicatoin, child class
which inherited this class will provide the funtionality of the abstract methods in abstract class.
When base class calls this method, Java calls the method defined by the child class.

An Interface can only declare constants and instance methods, but cannot implement
default behavior.
Interfaces provide a form of multiple inheritance. A class can extend only one other class.
Interfaces are limited to public methods and constants with no implementation. Abstract
classes can have a partial implementation, protected parts, static methods, etc.
A Class may implement several interfaces. But in case of abstract class, a class may
extend only one abstract class.
Interfaces are slow as it requires extra indirection to find corresponding method in the
actual class. Abstract classes are fast.

Question: What is user-defined exception in java ?

Answer: User-defined expections are the exceptions defined by the application developer which
are errors related to specific application. Application Developer can define the user defined
exception by inherite the Exception class as shown below. Using this class we can throw new
exceptions.

Java Example : public class noFundException extends Exception { } Throw an exception using
a throw statement: public class Fund { ... public Object getFunds() throws noFundException { if
(Empty()) throw new noFundException(); ... } } User-defined exceptions should usually be
checked.

Question: To what value is a variable of the boolean type automatically initialized?

The default value of the boolean type is false.

Question: Can try statements be nested?

Try statements may be tested.


Question: What is the difference between the prefix and postfix forms of the ++ operator?

The prefix form performs the increment operation and returns the value ofthe increment
operation. The postfix form returns the current value all of the expression and then performs the
increment operation on that value.

Question: What is the purpose of a statement block?

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

Question: What is a Java package and how is it used?

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

Question: What modifiers may be used with a top-level class?

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

Question: What are the Object and Class classes used for?

The Object class is the highest-level class in the Java class hierarchy. The Class class is used to
represent the classes and interfaces that are loaded by a Java program.

Question: How does a try statement determine which catch clause should be used to handle
an exception?

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

Question: Can an unreachable object become reachable again?

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

Question: When is an object subject to garbage collection?

Answer: An object is subject to garbage collection when it becomes unreachable to the program
in which it is used.

Question: What method must be implemented by all threads?


Answer: All tasks must implement the run() method, whether they are a subclass ofThread or
implement the Runnable interface.

Question: What methods are used to get and set the text label displayed by a Button
object?

Answer: getLabel() and setLabel()

Question: Which Component subclass is used for drawing and painting?

Answer: Canvas

Question: What are synchronized methods and synchronized statements?

Answer: Synchronized methods are methods that are used to control access to an object. A
thread only executes a synchronized method after it has acquired the lock for the method's object
or class. Synchronized statements are similar to synchronized methods. A synchronized
statement can only be executed after a thread has acquired the lock for the object or class
referenced in the synchronized statement.

Question: What are the two basic ways in which classes that can be run as threads may be
defined?

Answer: A thread class may be declared as a subclass of Thread, or it may implement the
Runnable interface.

Question: What are the problems faced by Java programmers who don't use layout
managers?

Answer: Without layout managers, Java programmers are faced with determining how their GUI
will be displayed across multiple windowing systems and finding a common sizingand
positioning that will work within the constraints imposed by each windowing system.

Question: What is the difference between an if statement and a switch statement?

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

Question: What happens when you add a double value to a String?

Answer: The result is a String object.

Question: What is the List interface?

Answer: The List interface provides support for ordered collections of objects.
Question: What is the difference between checked and Unchecked Exceptions in Java ?

Answer: All predefined exceptions in Java are either a checked exception or an unchecked
exception. Checked exceptions must be caught using try .. catch() block or we should throw the
exception using throws clause. If you dont, compilation of program will fail.

Java Exception Hierarchy +--------+ | Object | +--------+ | | +-----------+ | Throwable | +-----------


+ / \ / \ +-------+ +-----------+ | Error | | Exception | +-------+ +-----------+ / | \ / | \ \________/
\______/ \ +------------------+ unchecked checked | RuntimeException | +------------------+ / | | \
\_________________/ unchecked

Question: Explain garbage collection ?

Answer: Garbage collection is an important part of Java's security strategy. Garbage collection
is also called automatic memory management as JVM automatically removes the unused
variables/objects from the memory. The name "garbage collection" implies that objects that are
no longer needed by the program are "garbage" and can be thrown away. A more accurate and
up-to-date metaphor might be "memory recycling." When an object is no longer referenced by
the program, the heap space it occupies must be recycled so that the space is available for
subsequent new objects. The garbage collector must somehow determine which objects are no
longer referenced by the program and make available the heap space occupied by such
unreferenced objects. In the process of freeing unreferenced objects, the garbage collector must
run any finalizers of objects being freed.

Question: How you can force the garbage collection ?

Answer: Garbage collection automatic process and can't be forced. We can call garbage
collector in Java by calling System.gc() and Runtime.gc(), JVM tries to recycle the unused
objects, but there is no guarantee when all the objects will garbage collected.

Question: What are the field/method access levels (specifiers) and class access levels ?

Answer: Each field and method has an access level:

private: accessible only in this class


(package): accessible only in this package
protected: accessible only in this package and in all subclasses of this class
public: accessible everywhere this class is available

Similarly, each class has one of two possible access levels:

(package): class objects can only be declared and manipulated by code in this package
public: class objects can be declared and manipulated by code in any package

Question: What are the static fields & static Methods ?


Answer: If a field or method defined as a static, there is only one copy for entire class, rather
than one copy for each instance of class. static method cannot accecss non-static field or call
non-static method

Example Java Code

static int counter = 0;

A public static field or method can be accessed from outside the class using either the usual
notation:

Java-class-object.field-or-method-name

or using the class name instead of the name of the class object:

Java- class-name.field-or-method-name

Question: What are the Final fields & Final Methods ?

Answer: Fields and methods can also be declared final. A final method cannot be overridden in
a subclass. A final field is like a constant: once it has been given a value, it cannot be assigned to
again.

Java Code

private static final int MAXATTEMPTS = 10;

Question: Describe the wrapper classes in Java ?

Answer: Wrapper class is wrapper around a primitive data type. An instance of a wrapper class
contains, or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes:

Primitive Wrapper
boolean java.lang.Boolean
byte java.lang.Byte
char java.lang.Character
double java.lang.Double
float java.lang.Float
int java.lang.Integer
long java.lang.Long
short java.lang.Short
void java.lang.Void
Question: What is clipping?

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

Question: What is a native method?

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

Question: Can a for statement loop indefinitely?

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

Question: What are order of precedence and associativity, and how are they used?

Answer: Order of precedence determines the order in which operators are evaluated in
expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-
left

Question: When a thread blocks on I/O, what state does it enter?

Answer: A thread enters the waiting state when it blocks on I/O.

Question: To what value is a variable of the String type automatically initialized?

Answer: The default value of an String type is null.

Question: What is the catch or declare rule for method declarations?

Answer: If a checked exception may be thrown within the body of a method, the method must
either catch the exception or declare it in its throws clause.

Question: What is the difference between a MenuItem and a CheckboxMenuItem?

Answer: The CheckboxMenuItem class extends the MenuItem class to support a menu item that
may be checked or unchecked.

Question: What is a task's priority and how is it used in scheduling?

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

Question: What class is the top of the AWT event hierarchy?

Answer: The java.awt.AWTEvent class is the highest-level class in the AWT event-class
hierarchy.
Question: When a thread is created and started, what is its initial state?

Answer: A thread is in the ready state after it has been created and started.

Question: Can an anonymous class be declared as implementing an interface and extending


a class?

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

Question: What is the range of the short type?

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

Question: What is the range of the char type?

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

Question: In which package are most of the AWT events that support the event-
delegation model defined?

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

Question: What is the immediate superclass of Menu?

Answer: MenuItem

Question: What is the purpose of finalization?

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

Question: Which class is the immediate superclass of the MenuComponent class.

Answer: Object

Question: What is a compilation unit?

Answer: A compilation unit is a Java source code file.

Question: What interface is extended by AWT event listeners?

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

Question: What restrictions are placed on method overriding?


Answer: Overridden methods must have the same name, argument list, and return type. The
overriding method may not limit the access of the method it overrides. The overriding method
may not throw any exceptions that may not be thrown by the overridden method.

Question: How can a dead thread be restarted?

Answer: A dead thread cannot be restarted.

Question: What happens if an exception is not caught?

Answer: An uncaught exception results in the uncaughtException() method of the thread's


ThreadGroup being invoked, which eventually results in the termination of the program in which
it is thrown.

Question: What is a layout manager?

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

Question: Which arithmetic operations can result in the throwing of an


ArithmeticException?

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

Question: What are three ways in which a thread can enter the waiting state?

Answer: A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O,
by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait()
method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

Question: Can an abstract class be final?

Answer: An abstract class may not be declared as final.

Question: What is the ResourceBundle class?

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

Question: What happens if a try-catch-finally statement does not have a catch clause to
handle an exception that is thrown within the body of the try statement?

Answer: The exception propagates up to the next higher level try-catch statement (if any) or
results in the program's termination.

Question: What is numeric promotion?


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

Question: What is the difference between a Scrollbar and a ScrollPane?

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 is the difference between a public and a non-public class?

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

Question: Name four Container classes.

Answer: Window, Frame, Dialog, File Dialog, Panel, Applet, or ScrollPane

Question: What is the difference between a Choice and a List?

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

Question: What class of exceptions are generated by the Java run-time system?

Answer: The Java runtime system generates Runtime Exception and Error exceptions.

Question: What class allows you to read objects directly from a stream?

Answer: The ObjectInputStream class supports the reading of objects from input streams.

Question: What is the difference between a field variable and a local variable?

Answer: A field variable is a variable that is declared as a member of a class. A local variable is
a variable that is declared local to a method.

Question: Under what conditions is an object's finalize() method invoked by the garbage
collector?

Answer: The garbage collector invokes an object's finalize() method when it detects that the
object has become unreachable.

Question: How are this() and super() used with constructors?


Answer: this() is used to invoke a constructor of the same class. super() is used to invoke a
superclass constructor.

Question: What is the relationship between a method's throws clause and the
exceptions that can be thrown during the method's execution?

Answer: A method's throws clause must declare any checked exceptions that are not caught
within the body of the method.

Question: What is the difference between the JDK 1.02 event model and the event-
delegation model introduced with JDK 1.1?

Answer: The JDK 1.02 event model uses an event inheritance or bubbling approach. In this
model, components are required to handle their own events. If they do not handle a particular
event, the event is inherited by (or bubbled up to) the component's container. The container then
either handles the event or it is bubbled up to its container and so on, until the highest-level
container has been tried.

In the event-delegation model, specific objects are designated as event handlers for GUI
components. These objects implement event-listener interfaces. The event-delegation model is
more efficient than the event-inheritance model because it eliminates the processing required to
support the bubbling of unhand led events.

Question: How is it possible for two String objects with identical values not to be
equal under the == operator?

Answer: The == operator compares two objects to determine if they are the same object in
memory. It is possible for two String objects to have the same value, but located indifferent areas
of memory.

Question: Why are the methods of the Math class static?

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

Question: What Checkbox method allows you to tell if a Checkbox is checked?

Answer: getState()

Question: What state is a thread in when it is executing?

Answer: An executing thread is in the running state.

Question: What are the legal operands of the instance of operator?

Answer: The left operand is an object reference or null value and the right operand is a class,
interface, or array type.
Conversion Casting and Promotion

Question: What are wrapped classes

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

Question: What are the four general cases for Conversion and Casting

Answer:

Conversion of primitives
Casting of primitives
Conversion of object references
Casting of object references

Question: When can conversion happen

Answer:

It can happen during

Assignment
Method call
Arithmetic promotion

Question: What are the rules for primitive assignment and method call conversion

Answer:

A boolean can not be converted to any other type


A non Boolean can be converted to another non boolean type, if the conversion is widening
conversion
A non Boolean cannot be converted to another non boolean type, if the conversion is narrowing
conversion
See figure below for simplicity

Question: What are the rules for primitive arithmetic promotion conversion

Answer:

For Unary operators :

If operant is byte, short or a char it is converted to an int


If it is any other type it is not converted
For binary operands :

If one of the operands is double, the other operand is converted to double


Else If one of the operands is float, the other operand is converted to float
Else If one of the operands is long, the other operand is converted to long
Else both the operands are converted to int

Question: What are the rules for casting primitive types

Answer:

You can cast any non Boolean type to any other non boolean type
You cannot cast a boolean to any other type; you cannot cast any other type to a boolean

Question: What are the rules for object reference assignment and method call conversion

Answer: An interface type can only be converted to an interface type or to object. If the new
type is an interface, it must be a superinterface of the old type. A class type can be converted to a
class type or to an interface type. If converting to a class type the new type should be superclass
of the old type. If converting to an interface type new type the old class must implement the
interface. An array maybe converted to class object, to the interface cloneable, or to an array.
Only an array of object references types may be converted to an array, and the old element type
must be convertible to the new element.

Question: What are the rules for Object reference casting

Answer: Casting from Old types to Newtypes


Compile time rules

When both Oldtypes and Newtypes are classes, one should be subclass of the other
When both Oldtype ad Newtype are arrays, both arrays must contain reference types (not
primitive), and it must be legal to cast an element of Oldtype to an element of Newtype
You can always cast between an interface and a non-final object

Runtime rules

If Newtype is a class. The class of the expression being converted must be Newtype or
must inherit from Newtype
If NewType is an interface, the class of the expression being converted must implement
Newtype

Question: What is transient variable?


Answer: Transient variable can't be serialize. For example if a variable is declared as transient in
a Serializable class and the class is written to an ObjectStream, the value of the variable can't be
written to the stream instead when the class is retrieved from the ObjectStream the value of the
variable becomes null.
Question: Name the containers which uses Border Layout as their default layout?
Answer: Containers which uses Border Layout as their default are: window, Frame and Dialog
classes.

Question: What do you understand by Synchronization?


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

Question: What is Collection API?


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

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


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

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


Answer: Differences are as follows:

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

Similarities:

Neither Abstract classes or Interface can be instantiated.

Question: How to define an Abstract class?


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

Question: How to define an Interface?


Answer: In Java Interface defines the methods but does not implement them. Interface can
include constants. A class that implements the interfaces is bound to implement all the methods
defined in Interface.
Emaple of Interface:

public interface sampleInterface {


public void functionOne();

public long CONSTANT_ONE = 1000;


}

Question: Explain the user defined Exceptions?


Answer: User defined Exceptions are the separate Exception classes defined by the user for
specific purposed. An user defined can created by simply sub-classing it to the Exception class.
This allows custom exceptions to be generated (using throw) and caught in the same way as
normal exceptions.
Example:
class myCustomException extends Exception {
// The class simply has to exist to be an exception
}
Question: Explain the new Features of JDBC 2.0 Core API?
Answer: The JDBC 2.0 API includes the complete JDBC API, which includes both core and
Optional Package API, and provides inductrial-strength database computing capabilities.
New Features in JDBC 2.0 Core API:

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

Question: Explain garbage collection?


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

Question: How you can force the garbage collection?


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

Question: What is OOPS?


Answer: OOP is the common abbreviation for Object-Oriented Programming.

Question: Describe the principles of OOPS.


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

Question: Explain the Encapsulation principle.


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

Question: Explain the Inheritance principle.


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

Question: Explain the Polymorphism principle.


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

Question: Explain the different forms of Polymorphism.


Answer: From a practical programming viewpoint, polymorphism exists in three distinct forms
in Java:

Method overloading
Method overriding through inheritance
Method overriding through the Java interface

Question: What are Access Specifiers available in Java?


Answer: Access specifiers are keywords that determines the type of access to the member of a
class. These are:

Public
Protected
Private
Defaults

Question: Describe the wrapper classes in Java.


Answer: Wrapper class is wrapper around a primitive data type. An instance of a wrapper class
contains, or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes:

Primitive Wrapper
boolean java.lang.Boolean
byte java.lang.Byte
char java.lang.Character
double java.lang.Double
float java.lang.Float
int java.lang.Integer
long java.lang.Long
short java.lang.Short
void java.lang.Void

Question: Read the following program:

public class test {


public static void main(String [] args) {
int x = 3;
int y = 1;
if (x = y)
System.out.println("Not equal");
else
System.out.println("Equal");
}
}

What is the result?


A. The output is “Equal”
B. The output in “Not Equal”
C. An error at " if (x = y)" causes compilation to fall.
D. The program executes but no output is show on console.
Answer: C

Question: what is the class variables ?


Answer: When we create a number of objects of the same class, then each object will share a
common copy of variables. That means that there is only one copy per class, no matter how
many objects are created from it. Class variables or static variables are declared with the static
keyword in a class, but mind it that it should be declared outside outside a class. These variables
are stored in static memory. Class variables are mostly used for constants, variable that never
change its initial value. Static variables are always called by the class name. This variable is
created when the program starts i.e. it is created before the instance is created of class by using
new operator and gets destroyed when the programs stops. The scope of the class variable is
same a instance variable. The class variable can be defined anywhere at class level with the
keyword static. It initial value is same as instance variable. When the class variable is defined as
int then it's initial value is by default zero, when declared boolean its default value is false and
null for object references. Class variables are associated with the class, rather than with any
object.

Question: What is the difference between the instanceof and getclass, these two are same or not
?
Answer: instanceof is a operator, not a function while getClass is a method of java.lang.Object
class. Consider a condition where we use
if(o.getClass().getName().equals("java.lang.Math")){ }
This method only checks if the classname we have passed is equal to java.lang.Math. The class
java.lang.Math is loaded by the bootstrap ClassLoader. This class is an abstract class.This class
loader is responsible for loading classes. Every Class object contains a reference to the
ClassLoader that defines. getClass() method returns the runtime class of an object. It fetches the
java instance of the given fully qualified type name. The code we have written is not necessary,
because we should not compare getClass.getName(). The reason behind it is that if the two
different class loaders load the same class but for the JVM, it will consider both classes as
different classes so, we can't compare their names. It can only gives the implementing class but
can't compare a interface, but instanceof operator can.
The instanceof operator compares an object to a specified type. We can use it to test if an object
is an instance of a class, an instance of a subclass, or an instance of a class that implements a
particular interface. We should try to use instanceof operator in place of getClass() method.
Remember instanceof opeator and getClass are not same. Try this example, it will help you to
better understand the difference between the two.
Interface one{
}

Class Two implements one {


}
Class Three implements one {
}

public class Test {


public static void main(String args[]) {
one test1 = new Two();
one test2 = new Three();
System.out.println(test1 instanceof one); //true
System.out.println(test2 instanceof one); //true
System.out.println(Test.getClass().equals(test2.getClass())); //false
}
}

Question: What is the difference between a Window and a Frame?

Answer: The Frame class extends Window to define a main application

window that can have a menu bar.


Question: Which class is extended by all other classes?

Answer: The Object class is extended by all other classes.

Question: Can an object be garbage collected while it is still reachable?

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

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

Answer: It is written x ? y : z.

Question: What is the difference between the Font and FontMetrics classes?

Answer: The FontMetrics class is used to define implementation-specific properties, such as


ascent and descent, of a Font object.

Question: How is rounding performed under integer division?

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

Question: What happens when a thread cannot acquire a lock on an object?

Answer: If a thread attempts to execute a synchronized method or synchronized statement and is


unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

Question: What is the difference between the Reader/Writer class hierarchy and
the InputStream/OutputStream class hierarchy?

Answer: The Reader/Writer class hierarchy is character-oriented, and the


InputStream/OutputStream class hierarchy is byte-oriented.

Question: What classes of exceptions may be caught by a catch clause?

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

Question: If a class is declared without any access modifiers, where may the class be
accessed?

Answer: A class that is declared without any access modifiers is said to have package access.
This means that the class can only be accessed by other classes and interfaces that are defined
within the same package.

Question: What is the SimpleTimeZone class?


Answer: The SimpleTimeZone class provides support for a Gregorian calendar.

Question: What is the Map interface?

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

Question: Does a class inherit the constructors of its superclass?

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

Question: For which statements does it make sense to use a label?

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

Question: What is the purpose of the System class?

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

Question: Which TextComponent method is used to set a TextComponent to the read-only


state?

Answer: setEditable()

Question: How are the elements of a CardLayout organized?

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

Flow Control and exception

Question: What is the difference between while and do while loop

Answer: Do while loop walways executes the body of the loop at least once, since the test is
performed at the end of the body

Question: When do you use continue and when do you use break statements

Answer: When continue statement is applied it prematurely completes the iteration of a loop.
When break statement is applied it causes the entire loop to be abandoned.

Question: What is the base class from which all exceptions are subclasses

Answer: All exceptions are subclasses of a class called java.lang.Throwable

Question: How do you intercept and thereby control exceptions


Answer: We can do this by using try/catch/finally blocks
You place the normal processing code in try block
You put the code to deal with exceptions that might arise in try block in catch block
Code that must be executed no matter what happens must be place in finally block

Question: When do we say an exception is handled

Answer: When an exception is thrown in a try block and is caught by a matching catch block,
the exception is considered to have been handled

Question: When do we say an exception is not handled

Answer: There is no catch block that names either the class of exception that has been thrown or
a class of exception that is a parent class of the one that has been thrown, then the exception is
considered to be unhandled, in such condition the execution leaves the method directly as if no
try has been executed

Question: In what sequence does the finally block gets executed

Answer: If you put finally after a try block without a matching catch block then it will be
executed after the try block
If it is placed after the catch block and there is no exception then also it will be executed after the
try block
If there is an exception and it is handled by the catch block then it will be executed after the
catch block

Question: What can prevent the execution of the code in finally block

Answer:

The death of thread


Use of system.exit()
Turning off the power to CPU
An exception arising in the finally block itself

What are the rules for catching multiple exceptions


A more specific catch block must precede a more general one in the source, else it gives
compilation error
Only one catch block, that is first applicable one, will be executed

Question: What does throws statement declaration in a method indicate

Answer: This indicates that the method throws some exception and the caller method should
take care of handling it

Question: What are checked exception


Answer: Checked exceptions are exceptions that arise in a correct program, typically due to user
mistakes like entering wrong data or I/O problems

Question: What are runtime exceptions

Answer: Runtime exceptions are due to programming bugs like out of bond arrays or null
pointer exceptions.

Question: What is difference between Exception and errors

Answer: Errors are usually compile time and exceptions can be runtime or checked

Question: How will you handle the checked exceptions

Answer: You can provide a try/catch block to handle it. OR Make sure method declaration
includes a throws clause that informs the calling method an exception might be thrown from this
particular method. When you extend a class and override a method, can this new method throw
exceptions other than those that were declared by the original method. No it cannot throw, except
for the subclasses of those exceptions.

Question: Is it legal for the extending class which overrides a method which throws an
exception, not o throw in the overridden class

Answer: Yes it is perfectly legal

Question: Explain the user defined Exceptions?

Answer: User defined Exceptions are the separate Exception classes defined by the user for
specific purposed. An user defined can created by simply sub-classing it to the Exception class.
This allows custom exceptions to be generated (using throw) and caught in the same way as
normal exceptions.

Example:

class myCustomException extends Exception {


// The class simply has to exist to be an exception
}

Question: How are the elements of a GridLayout organized?

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

Question: What an I/O filter?


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

Question: If an object is garbage collected, can it become reachable again?

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

Question: What is the Set interface?

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

Question: What classes of exceptions may be thrown by a throw statement?

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

Question: What are E and PI?

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

Question: Are true and false keywords?

Answer: The values true and false are not keywords.

Question: What is a void return type?

Answer: A void return type indicates that a method does not return a value.

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

Answer: The enableEvents() method is used to enable an event for a particular object. Normally,
an event is enabled when a listener is added to an object for a particular event. The
enableEvents() method is used by objects that handle events by overriding their event-dispatch
methods.

Question: What is the difference between the File and RandomAccessFile classes?

Answer: The File class encapsulates the files and directories of the local file system. The
RandomAccessFile class provides the methods needed to directly access data contained in any
part of a file.

Question: What happens when you add a double value to a String?

Answer: The result is a String object.


Question: What is your platform's default character encoding?

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

Question: Which package is always imported by default?

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

Question: What interface must an object implement before it can be written to a stream as
an object?

Answer: An object must implement the Serializable or Externalizable interface before it can be
written to a stream as an object.

Question: How are this and super used?

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

Question: What is the purpose of garbage collection?

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

Question: What are different types of inner classes ?

Answer: Inner classes nest within other classes. A normal class is a direct member of a package.
Inner classes, which became available with Java 1.1, are four types

Static member classes


Member classes
Local classes
Anonymous classes

Static member classes - 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.

Member Classes - a member class is also defined as a member of a class. Unlike the static
variety, the member class is instance specific and has access to any and all methods and
members, even the parent's this reference.

Local Classes - Local Classes declared within a block of code and these classes are visible only
within the block.

Anonymous Classes - These type of classes does not have any name and its like a local class
Java Anonymous Class Example public class SomeGUI extends JFrame { ... button member
declarations ... protected void buildGUI() { button1 = new JButton(); button2 = new JButton(); ...
button1.addActionListener( new java.awt.event.ActionListener() <------ Anonymous Class {
public void actionPerformed(java.awt.event.ActionEvent e) { // do something } } );

Question: What are the uses of Serialization?

Answer: In some types of applications you have to write the code to serialize objects, but in
many cases serialization is performed behind the scenes by various server-side containers.

These are some of the typical uses of serialization:

To persist data for future use.


To send data to a remote computer using such client/server Java technologies as RMI or
socket programming.
To "flatten" an object into array of bytes in memory.
To exchange data between applets and servlets.
To store user session in Web applications.
To activate/passivate enterprise java beans.
To send objects between the servers in a cluster.

Question: what is a collection ?

Answer: Collection is a group of objects. java.util package provides important types of


collections. There are two fundamental types of collections they are Collection and Map.
Collection types hold a group of objects, Eg. Lists and Sets where as Map types hold group of
objects as key, value pairs Eg. HashMap and Hashtable.

Question: For concatenation of strings, which method is good, StringBuffer or String ?

Answer: StringBuffer is faster than String for concatenation.

Question: What is Runnable interface ? Are there any other ways to make a java program as
multithred java program?

Answer: There are two ways to create new kinds of threads:

- Define a new class that extends the Thread class


- Define a new class that implements the Runnable interface, and pass an object of that class to a
Thread's constructor.
- An advantage of the second approach is that the new class can be a subclass of any class, not
just of the Thread class.

Here is a very simple example just to illustrate how to use the second approach to creating
threads: class myThread implements Runnable { public void run() { System.out.println("I'm
running!"); } } public class tstRunnable { public static void main(String[] args) { myThread my1
= new myThread(); myThread my2 = new myThread(); new Thread(my1).start(); new
Thread(my2).start(); }

Language Fundamentals

Question: How many number of non-public class definitions can a source file have A
source file can contain unlimited number of non-public class definitions List primitive data
types, there size and there range (min, max)

Answer:

Data Type Bytes bits min max


boolean - 1 - -
char 2 16 0 2^16-1
byte 1 8 -2^7 2^7-1
short 2 16 -2^15 2^15-1
int 4 32 -2^31 2^31-1
long 8 64 -2^63 2^63-1
float 4 32 - -
double 8 64 - -

Question: What types of values does boolean variables take It only takes values true and
false. Which primitive datatypes are signed.

Answer: All except char and Boolean

Question: Is char type signed or unsigned

Answer: char type is integral but unsigned. It range is 0 to 2^7-1

Question: What forms an integral literal can be

Answer: decimal, octal and hexadecimal, hence example it can be 28, 034 and 0x1c respectively

Question: What is the default value of Boolean

Answer: False

Question: Why is the main method static

Answer: So that it can be invoked without creating an instance of that class

Question: What is the difference between class variable, member variable and
automatic(local) variable
Answer: class variable is a static variable and does not belong to instance of class but rather
shared across all the instances
member variable belongs to a particular instance of class and can be called from any method of
the class
automatic or local variable is created on entry to a method and has only method scope

Question: When are static and non static variables of the class initialized

Answer: The static variables are initialized when the class is loadedNon static variables are
initialized just before the constructor is called

Question: When are automatic variable initialized

Answer: Automatic variable have to be initialized explicitly

Question: How is an argument passed in java, by copy or by reference

Answer: If the variable is primitive datatype then it is passed by copy.


If the variable is an object then it is passed by reference

Question: What is garbage collection

Answer: The runtime system keeps track of the memory that is allocated and is able to
determine whether that memory is still useable. This work is usually done in background by a
low-priority thread that is referred to as garbage collector. When the gc finds memory that is no
longer accessible from any live thread it takes steps to release it back to the heap for reuse

Question: Does System.gc and Runtime.gc() guarantee garbage collection

Answer: No

Operators and assignment

Question: What are different types of operators in java

Answer: Uniary ++, --, +, -, |, ~, ()


Arithmetic *, /, %,+, -
Shift <<, >>, >>>
Comparison =, instanceof, = =,!=Bitwise &, ^, |Short Circuit &&, ||Ternary ?:Assignment =

Question: How does bitwise (~) operator work

Answer: It converts all the 1 bits in a binary value to 0s and all the 0 bits to 1s, e.g 11110000
coverts to 00001111

Question: What is a modulo operator %


Answer: This operator gives the value which is related to the remainder of a divisione.g x=7%4
gives remainder 3 as an answer

Question: Can shift operators be applied to float types.

Answer: No, shift operators can be applied only to integer or long types

Question: What happens to the bits that fall off after shifting

Answer: They are discarded

Question: What values of the bits are shifted in after the shift

Answer: In case of signed left shift >> the new bits are set to zero But in case of signed right
shift it takes the value of most significant bit before the shift, that is if the most significant bit
before shift is 0 it will introduce 0, else if it is 1, it will introduce 1

Question: Does it matter in what order catch statements for FileNotFoundException and
IOExceptipon are written?

Answer: Yes, it does. The FileNoFoundException is inherited from the IOException.


Exception's subclasses have to be caught first.

Question: Can an inner class declared inside of a method access local variables of this
method?

Answer: It's possible if these variables are final.

Question: What can go wrong if you replace && with & in the following code: String
a=null; if (a!=null && a.length()>10) {...}

Answer: A single ampersand here would lead to a NullPointerException.

Question: What's the main difference between a Vector and an ArrayList

Answer: Java

Vector class is internally synchronized and ArrayList is not.

Question: When should the method invokeLater()be used?

Answer: This method is used to ensure that Swing components are updated through the event-
dispatching thread.

Question: How can a subclass call a method or a constructor defined in a superclass?


Answer: Use the following syntax: super.myMethod(); To call a constructor of the superclass,
just write super(); in the first line of the subclass's constructor.

For senior-level developers:

Question: What's the difference between a queue and a stack?

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

Question: You can create an abstract class that contains only abstract methods. On the
other hand, you can create an interface that declares the same methods. So can you use
abstract classes instead of interfaces?

Answer: Sometimes. But your class may be a descendent of another class and in this case the
interface is your only option.

Question: What comes to mind when you hear about a young generation in Java?

Answer: Garbage collection.

Question: What comes to mind when someone mentions a shallow copy in Java?

Answer: Object cloning.

Question: If you're overriding the method equals() of an object, which other method you
might also consider?

Answer: hashCode()

Question: You are planning to do an indexed search in a list of objects. Which of the two
Java collections should you use: ArrayList or LinkedList?

Answer: ArrayList

Question: How would you make a copy of an entire Java object with its state?

Answer: Have this class implement Cloneable interface and call its method clone().

Question: How can you minimize the need of garbage collection and make the memory use
more effective?

Answer: Use object pooling and weak object references.

Question: There are two classes: A and B. The class B need to inform a class A when some
important event has happened. What Java technique would you use to implement it?
Answer: If these classes are threads I'd consider notify() or notifyAll(). For regular classes you
can use the Observer interface.

Question: What access level do you need to specify in the class declaration to ensure that
only classes from the same directory can access it?

Answer: You do not need to specify any access level, and Java will use a default package access
level .

Question: What is an Iterator interface?

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

Question: What is the difference between the >> and >>> operators?

Answer: The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that
have been shifted out.

Question: Which method of the Component class is used to set the position and size of a
component?

Answer: setBounds()

Question: How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8
characters?

Answer: Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set
uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and
18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

Question: What is the difference between yielding and sleeping?

Answer: When a task invokes its yield() method, it returns to the ready state. When a task
invokes its sleep() method, it returns to the waiting state.

Question: Which java.util classes and interfaces support event handling?

Answer: The EventObject class and the EventListener interface support event processing.

Question: Is sizeof a keyword?

Answer: The sizeof operator is not a keyword.

Question: What are wrapped classes?

Answer: Wrapped classes are classes that allow primitive types to be accessed as objects.
Question: Does garbage collection guarantee that a program will not run out of memory?

Answer: Garbage collection does not guarantee that a program will not run out of memory. It is
possible for programs to use up memory resources faster than they are garbage collected. It is
also possible for programs to create objects that are not subject to garbage collection

Question: What restrictions are placed on the location of a package statement within a
source code file?

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

Question: Can an object's finalize() method be invoked while it is reachable?

Answer: An object's finalize() method cannot be invoked by the garbage collector while the
object is still reachable. However, an object's finalize() method may be invoked by other objects.

Question: What is the immediate superclass of the Applet class?

Answer: Panel

Question: What is the difference between preemptive scheduling and time slicing?

Answer: Under preemptive scheduling, the highest priority task executes until it enters the
waiting or dead states or a higher priority task comes into existence. Under time slicing, a task
executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler
then determines which task should execute next, based on priority and other factors.

Question: Name three Component subclasses that support painting.

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

Question: What value does readLine() return when it has reached the end of a file?

Answer: The readLine() method returns null when it has reached the end of a file.

Question: What is the immediate superclass of the Dialog class?

Answer: Window

Question: What is J2EE?


Answer: J2EE Stands for Java 2 Enterprise Edition. J2EE is an environment for developing and
deploying enterprise applications. J2EE specification is defined by Sun Microsystems Inc. The
J2EE platform is one of the best platform for the development and deployment of enterprise
applications. The J2EE platform is consists of a set of services, application programming
interfaces (APIs), and protocols, which provides the functionality necessary for developing
multi-tiered, web-based applications. You can download the J2EE SDK and development tools
from http://java.sun.com/.

Question: What do you understand by a J2EE module?


Answer: A J2EE module is a software unit that consists of one or more J2EE components of the
same container type along with one deployment descriptor of that type. J2EE specification
defines four types of modules:
a) EJB
b) Web
c) application client and
d) resource adapter

In the J2EE applications modules can be deployed as stand-alone units. Modules can also be
assembled into J2EE applications.

Question: Tell me something about J2EE component?


Answer: J2EE component is a self-contained functional software unit supported by a container
and configurable at deployment time. The J2EE specification defines the following J2EE
components:

Application clients and applets are components that run on the client.
Java servlet and JavaServer Pages (JSP) technology components are Web components
that run on the server.
Enterprise JavaBeans (EJB) components (enterprise beans) are business components that
run on the server. J2EE components are written in the Java programming language and
are compiled in the same way as any program in the language. The difference between
J2EE components and "standard" Java classes is that J2EE components are assembled
into a J2EE application, verified to be well formed and in compliance with the J2EE
specification, and deployed to production, where they are run and managed by the J2EE
server or client container.

Source: J2EE v1.4 Glossary

Question: What are the contents of web module?


Answer: A web module may contain:
a) JSP files
b) Java classes
c) gif and html files and
d) web component deployment descriptors
Question: Differentiate between .ear, .jar and .war files.
Answer: These files are simply zipped file using java jar tool. These files are created for
different purposes. Here is the description of these files:
.jar files: These files are with the .jar extenstion. The .jar files contains the libraries, resources
and accessories files like property files.
.war files: These files are with the .war extension. The war file contains the web application that
can be deployed on the any servlet/jsp container. The .war file contains jsp, html, javascript and
other files for necessary for the development of web applications.
.ear files: The .ear file contains the EJB modules of the application.

Question: What is the difference between Session Bean and Entity Bean?
Answer:
Session Bean: Session is one of the EJBs and it represents a single client inside the Application
Server. Stateless session is easy to develop and its efficient. As compare to entity beans session
beans require few server resources.

A session bean is similar to an interactive session and is not shared; it can have only one client,
in the same way that an interactive session can have only one user. A session bean is not
persistent and it is destroyed once the session terminates.

Entity Bean: An entity bean represents persistent global data from the database. Entity beans
data are stored into database.

Question: Why J2EE is suitable for the development distributed multi-tiered enterprise
applications?
Answer: The J2EE platform consists of multi-tiered distributed application model. J2EE
applications allows the developers to design and implement the business logic into components
according to business requirement. J2EE architecture allows the development of multi-tired
applications and the developed applications can be installed on different machines depending on
the tier in the multi-tiered J2EE environment . The J2EE application parts are:

a) Client-tier components run on the client machine.


b) Web-tier components run on the J2EE server.
c) Business-tier components run on the J2EE server and the
d) Enterprise information system (EIS)-tier software runs on the EIS servers

Question: Why do understand by a container?


Answer: Normally, thin-client multi-tiered applications are hard to write because they involve
many lines of intricate code to handle transaction and state management, multithreading,
resource pooling, and other complex low-level details. The component-based and platform-
independent J2EE architecture makes J2EE applications easy to write because business logic is
organized into reusable components. In addition, the J2EE server provides underlying services
in the form of a container for every component type. Because you do not have to develop these
services yourself, you are free to concentrate on solving the business problem at hand (Source:
http://java.sun.com/j2ee/1.3/docs/tutorial/doc/Overview4.html ).

In short containers are the interface between a component and the low-level platform specific
functionality that supports the component. The application like Web, enterprise bean, or
application client component must be assembled and deployed on the J2EE container before
executing.

Question: What are the services provided by a container?


Answer: The services provided by container are as follows:
a) Transaction management for the bean
b) Security for the bean
c) Persistence of the bean
d) Remote access to the bean
e) Lifecycle management of the bean
f) Database-connection pooling
g) Instance pooling for the bean

Question: What are types of J2EE clients?


Answer: J2EE clients are the software that access the services components installed on the J2EE
container. Following are the J2EE clients:
a) Applets
b) Java-Web Start clients
c) Wireless clients
d) Web applications

Question: What is Deployment Descriptor?


Answer: A deployment descriptor is simply an XML(Extensible Markup Language) file with the
extension of .xml. Deployment descriptor describes the component deployment settings.
Application servers reads the deployment descriptor to deploy the components contained in the
deployment unit. For example ejb-jar.xml file is used to describe the setting of the EJBs.

Question: What do you understand by JTA and JTS?


Answer: JTA stands for Java Transaction API and JTS stands for Java Transaction Service. JTA
provides a standard interface which allows the developers to demarcate transactions in a manner
that is independent of the transaction manager implementation. The J2EE SDK uses the JTA
transaction manager to implement the transaction. The code developed by developers does not
calls the JTS methods directly, but only invokes the JTA methods. Then JTA internally invokes
the JTS routines. JTA is a high level transaction interface used by the application code to control
the transaction.

Question: What is JAXP?


Answer: The Java API for XML Processing (JAXP) enables applications to parse and transform
XML documents independent of a particular XML processing implementation. JAXP or Java
API for XML Parsing is an optional API provided by Javasoft. It provides basic functionality for
reading, manipulating, and generating XML documents through pure Java APIs. It is a thin and
lightweight API that provides a standard way to seamlessly integrate any XML-compliant parser
with a Java application.
More at http://java.sun.com/xml/

Question: What is J2EE Connector architecture?


Answer: J2EE Connector Architecture (JCA) is a Java-based technology solution for connecting
application servers and enterprise information systems (EIS) as part of enterprise application
integration (EAI) solutions. While JDBC is specifically used to connect Java EE applications to
databases, JCA is a more generic architecture for connection to legacy systems (including
databases). JCA was developed under the Java Community Process as JSR 16 (JCA 1.0) and JSR
112 (JCA 1.5). As of 2006, the current version of JCA is version 1.5. The J2EE Connector API is
used by J2EE tools developers and system integrators to create resource adapters. Home page for
J2EE Connector architecture http://java.sun.com/j2ee/connector/.

Question: What is difference between Java Bean and Enterprise Java Bean?
Answer: Java Bean as is a plain java class with member variables and getter setter methods. Java
Beans are defined under JavaBeans specification as Java-Based software component model
which includes the features like introspection, customization, events, properties and
persistence.
Enterprise JavaBeans or EJBs for short are Java-based software components that comply with
Java's EJB specification. EJBs are delpoyed on the EJB container and executes in the EJB
container. EJB is not that simple, it is used for building distributed applications. Examples of
EJB are Session Bean, Entity Bean and Message Driven Bean. EJB is used for server side
programming whereas java bean is a client side. Bean is only development but the EJB is
developed and then deploy on EJB Container.

Question: What is the difference between JTS and JTA?


Answer: In any J2EE application transaction management is one of the most crucial
requirements of the application. Given the complexity of today's business requirements,
transaction processing occupies one of the most complex segments of enterprise level distributed
applications to build, deploy and maintain. JTS specifies the implementation of a Java
transaction manager. JTS specifies the implementation of a Transaction Manager which supports
the Java Transaction API (JTA) 1.0 This transaction manager supports the JTA, using which
application servers can be built to support transactional Java applications. Internally the JTS
implements the Java mapping of the OMG OTS 1.1 specifications. The Java mapping is
specified in two packages: org.omg.CosTransactions and org.omg.CosTSPortability. The JTS
thus provides a new architecture for transactional application servers and applications, while
complying to the OMG OTS 1.1 interfaces internally. This allows the JTA compliant
applications to interoperate with other OTS 1.1 complaint applications through the standard
IIOP. Java-based applications and Java-based application servers access transaction management
functionality via the JTA interfaces. The JTA interacts with a transaction management
implementation via JTS. Similarly, the JTS can access resources via the JTA XA interfaces or
can access OTS-enabled non-XA resources. JTS implementations can interoperate via CORBA
OTS interfaces.

The JTA specifies an architecture for building transactional application servers and defines a set
of interfaces for various components of this architecture. The components are: the application,
resource managers, and the application server. The JTA specifies standard interfaces for Java-
based applications and application servers to interact with transactions, transaction managers,
and resource managers JTA transaction management provides a set of interfaces utilized by an
application server to manage the beginning and completion of transactions. Transaction
synchronization and propagation services are also provided under the domain of transaction
management.

In the Java transaction model, the Java application components can conduct transactional
operations on JTA compliant resources via the JTS. The JTS acts as a layer over the OTS. The
applications can therefore initiate global transactions to include other OTS transaction managers,
or participate in global transactions initiated by other OTS compliant transaction managers.

Question: Can Entity Beans have no create() methods?


Answer: Entity Beans can have no create() methods. Entity Beans have no create() method,
when entity bean is not used to store the data in the database. In this case entity bean is used to
retrieve the data from database.

Question: What are the call back methods in Session bean?


Answer: Callback methods are called by the container to notify the important events to the beans
in its life cycle. The callback methods are defined in the javax.ejb.EntityBean interface.The
callback methods example are ejbCreate(), ejbPassivate(), and ejbActivate().

Question: What is bean managed transaction?


Answer: In EJB transactions can be maintained by the container or developer can write own
code to maintain the transaction. If a developer doesn’t want a Container to manage transactions,
developer can write own code to maintain the database transaction.

Question: What are transaction isolation levels in EJB?


Answer: Thre are four levels of transaction isolation are:
* Uncommitted Read
* Committed Read
* Repeatable Read
* Serializable
The four transaction isolation levels and the corresponding behaviors are described below:

Isolation Level Dirty Read Non-Repeatable Read Phantom Read


Read Uncommitted Possible Possible Possible
Read Committed Not possible Possible Possible
Repeatable Read Not possible Not possible Possible
Serializable Not possible Not possible Not possible

Jakarta Struts Interview Questions

Q: What is Jakarta Struts Framework?


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

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

Q: How you will make available any Message Resources Definitions file to the Struts
Framework Environment?
A: Message Resources Definitions file are simple .properties files and these files contains the
messages that can be used in the struts project. Message Resources Definitions files can be added
to the struts-config.xml file through <message-resources /> tag.
Example:
<message-resources parameter="MessageResources" />

Q: What is Action Class?


A: The Action is part of the controller. 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. The ActionServlet (commad) passes the parameterized class to Action
Form using the execute() method. There should be no database interactions in the action. The
action should receive the request, call business objects (which then handle database, or interface
with J2EE, etc) and then determine where to go next. Even better, the business objects could be
handed to the action at runtime (IoC style) thus removing any dependencies on the model. The
return type of the execute method is ActionForward which is used by the Struts Framework to
forward the request to the file as per the value of the returned ActionForward object.

Q: Write code of any Action Class?


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

package roseindia.net;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class TestAction extends Action


{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
return mapping.findForward("testAction");
}
}

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

Q: What is Struts Validator Framework?


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

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


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

Q. How you will display validation fail errors on jsp page?


A: Following tag displays all the errors:
<html:errors/>

Q. How you will enable front-end validation based on the xml in validation.xml?
A: The <html:javascript> tag to allow front-end validation based on the xml in validation.xml.
For example the code: <html:javascript formName="logonForm" dynamicJavascript="true"
staticJavascript="true" /> generates the client side java script for the form "logonForm" as
defined in the validation.xml file. The <html:javascript

> when added in the jsp file generates the client site validation script.

Question: How could Java classes direct program messages to the system console, but error
messages, say to a file?

Answer: The class System has a variable out that represents the standard output, and the variable
err that represents the standard error device. By default, they both point at the system console.
This how the standard output could be re-directed:

Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st);


System.setOut(st);

Question: What's the difference between an interface and an abstract class?

Answer: An abstract class may contain code in method bodies, which is not allowed in an
interface. With abstract classes, you have to inherit your class from it and Java does not allow
multiple inheritance. On the other hand, you can implement multiple interfaces in your class.

Question: Why would you use a synchronized block vs. synchronized method?

Answer: Synchronized blocks place locks for shorter periods than synchronized methods.

Question: Explain the usage of the keyword transient?


Answer: This keyword indicates that the value of this member variable does not have to be
serialized with the object. When the class will be de-serialized, this variable will be initialized
with a default value of its data type (i.e. zero for integers).

Question: How can you force garbage collection?

Answer: You can't force GC, but could request it by calling System.gc(). JVM does not
guarantee that GC will be started immediately.

Question: How do you know if an explicit object casting is needed?

Answer: 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;

When you assign a subclass to a variable having a supeclass type, the casting is performed
automatically.

Question: What's the difference between the methods sleep() and wait()

Answer: The code sleep(1000); puts thread aside for exactly one second. The code wait(1000),
causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or
notifyAll() call. The method wait() is defined in the class Object and the method sleep() is
defined in the class Thread.

Question: Can you write a Java class that could be used both as an applet as well as an
application?

Answer: Yes. Add a main() method to the applet.

Question: What's the difference between constructors and other methods?

Answer: Constructors must have the same name as the class and can not return a value. They are
only called once while regular methods could be called many times.

Question: Can you call one constructor from another if a class has multiple constructors

Answer: Yes. Use this() syntax.

Question: Explain the usage of Java packages.

Answer: This is a way to organize files when a project consists of multiple modules. It also helps
resolve naming conflicts when different packages have classes with the same names. Packages
access level also allows you to protect data from being used by the non-authorized classes.
Question: If a class is located in a package, what do you need to change in the OS
environment to be able to use it?

Answer: You need to add a directory or a jar file that contains the package directories to the
CLASSPATH environment variable. Let's say a class Employee belongs to a package
com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need
to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could
test it from a command prompt window as follows:

c:\>java com.xyz.hr.Employee

Question: What's the difference between J2SDK 1.5 and J2SDK 5.0?

Answer: There's no difference, Sun Microsystems just re-branded this version.

Question: What would you use to compare two String variables - the operator == or the method
equals()?

Answer: I'd use the method equals() to compare the values of the Strings and the == to check if
two variables point at the same instance of a String object.

Ajax Q& A

Q. Did Adaptive Path invent Ajax? Did Google? Did Adaptive Path help build Google’s Ajax
applications?

A. Neither Adaptive Path nor Google invented Ajax. Google’s recent products are simply the
highest-profile examples of Ajax applications. Adaptive Path was not involved in the
development of Google’s Ajax applications, but we have been doing Ajax work for some of our
other clients.

Q. Is Adaptive Path selling Ajax components or trademarking the name? Where can I download
it?

A. Ajax isn’t something you can download. It’s an approach — a way of thinking about the
architecture of web applications using certain technologies. Neither the Ajax name nor the
approach are proprietary to Adaptive Path.

Q. Is Ajax just another name for XMLHttpRequest?

A. No. XMLHttpRequest is only part of the Ajax equation. XMLHttpRequest is the technical
component that makes the asynchronous server communication possible; Ajax is our name for
the overall approach described in the article, which relies not only on XMLHttpRequest, but on
CSS, DOM, and other technologies.

Q. Why did you feel the need to give this a name?


A. I needed something shorter than “Asynchronous JavaScript+CSS+DOM+XMLHttpRequest”
to use when discussing this approach with clients.

Q. Techniques for asynchronous server communication have been around for years. What makes
Ajax a “new” approach?

A. What’s new is the prominent use of these techniques in real-world applications to change the
fundamental interaction model of the Web. Ajax is taking hold now because these technologies
and the industry’s understanding of how to deploy them most effectively have taken time to
develop.

Q. Is Ajax a technology platform or is it an architectural style?

A. It’s both. Ajax is a set of technologies being used together in a particular way.

Q. What kinds of applications is Ajax best suited for?

A. We don’t know yet. Because this is a relatively new approach, our understanding of where
Ajax can best be applied is still in its infancy. Sometimes the traditional web application model
is the most appropriate solution to a problem.

Q. Does this mean Adaptive Path is anti-Flash?

A. Not at all. Macromedia is an Adaptive Path client, and we’ve long been supporters of Flash
technology. As Ajax matures, we expect that sometimes Ajax will be the better solution to a
particular problem, and sometimes Flash will be the better solution. We’re also interested in
exploring ways the technologies can be mixed (as in the case of Flickr, which uses both).

Q. Does Ajax have significant accessibility or browser compatibility limitations? Do Ajax


applications break the back button? Is Ajax compatible with REST? Are there security
considerations with Ajax development? Can Ajax applications be made to work for users who
have JavaScript turned off?

A. The answer to all of these questions is “maybe”. Many developers are already working on
ways to address these concerns. We think there’s more work to be done to determine all the
limitations of Ajax, and we expect the Ajax development community to uncover more issues like
these along the way.

Q. Some of the Google examples you cite don’t use XML at all. Do I have to use XML and/or
XSLT in an Ajax application?

A. No. XML is the most fully-developed means of getting data in and out of an Ajax client, but
there’s no reason you couldn’t accomplish the same effects using a technology like JavaScript
Object Notation or any similar means of structuring data for interchange.

Q. Are Ajax applications easier to develop than traditional web applications?


A. Not necessarily. Ajax applications inevitably involve running complex JavaScript code on the
client. Making that complex code efficient and bug-free is not a task to be taken lightly, and
better development tools and frameworks will be needed to help us meet that challenge.

Q. Do Ajax applications always deliver a better experience than traditional web applications?

A. Not necessarily. Ajax gives interaction designers more flexibility. However, the more power
we have, the more caution we must use in exercising it. We must be careful to use Ajax to
enhance the user experience of our applications, not degrade it.

Defining Ajax

Ajax isn’t a technology. It’s really several technologies, each flourishing in its own right, coming
together in powerful new ways. Ajax incorporates:

standards-based presentation using XHTML and CSS;


dynamic display and interaction using the Document Object Model;
data interchange and manipulation using XML and XSLT;
asynchronous data retrieval using XMLHttpRequest;
and JavaScript binding everything together.

The classic web application model works like this: Most user actions in the interface trigger an
HTTP request back to a web server. The server does some processing — retrieving data,
crunching numbers, talking to various legacy systems — and then returns an HTML page to the
client. It’s a model adapted from the Web’s original use as a hypertext medium, but as fans
of The Elements of User Experience know, what makes the Web good for hypertext doesn’t
necessarily make it good for software applications.
Figure 1: The traditional model for web applications (left) compared to the Ajax model (right).

This approach makes a lot of technical sense, but it doesn’t make for a great user experience.
While the server is doing its thing, what’s the user doing? That’s right, waiting. And at every
step in a task, the user waits some more.

Obviously, if we were designing the Web from scratch for applications, we wouldn’t make users
wait around. Once an interface is loaded, why should the user interaction come to a halt every
time the application needs something from the server? In fact, why should the user see the
application go to the server at all?

How Ajax is Different

An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by


introducing an intermediary — an Ajax engine — between the user and the server. It seems like
adding a layer to the application would make it less responsive, but the opposite is true.

Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine —
written in JavaScript and usually tucked away in a hidden frame. This engine is responsible for
both rendering the interface the user sees and communicating with the server on the user’s
behalf. The Ajax engine allows the user’s interaction with the application to happen
asynchronously — independent of communication with the server. So the user is never staring at
a blank browser window and an hourglass icon, waiting around for the server to do something.

Figure 2: The synchronous interaction pattern of a traditional web application (top) compared
with the asynchronous pattern of an Ajax application (bottom).

Every user action that normally would generate an HTTP request takes the form of a JavaScript
call to the Ajax engine instead. Any response to a user action that doesn’t require a trip back to
the server — such as simple data validation, editing data in memory, and even some navigation
— the engine handles on its own. If the engine needs something from the server in order to
respond — if it’s submitting data for processing, loading additional interface code, or retrieving
new data — the engine makes those requests asynchronously, usually using XML, without
stalling a user’s interaction with the application.

Who’s Using Ajax

Google is making a huge investment in developing the Ajax approach. All of the major products
Google has introduced over the last year — Orkut, Gmail, the latest beta version of Google
Groups, Google Suggest, and Google Maps — are Ajax applications. (For more on the technical
nuts and bolts of these Ajax implementations, check out these excellent analyses
of Gmail, Google Suggest, and Google Maps.) Others are following suit: many of the features
that people love in Flickr depend on Ajax, and Amazon’s A9.com search engine applies similar
techniques.

These projects demonstrate that Ajax is not only technically sound, but also practical for real-
world applications. This isn’t another technology that only works in a laboratory. And Ajax
applications can be any size, from the very simple, single-function Google Suggest to the very
complex and sophisticated Google Maps.

At Adaptive Path, we’ve been doing our own work with Ajax over the last several months, and
we’re realizing we’ve only scratched the surface of the rich interaction and responsiveness that
Ajax applications can provide. Ajax is an important development for Web applications, and its
importance is only going to grow. And because there are so many developers out there who
already know how to use these technologies, we expect to see many more organizations
following Google’s lead in reaping the competitive advantage Ajax provides.

Moving Forward

The biggest challenges in creating Ajax applications are not technical. The core Ajax
technologies are mature, stable, and well understood. Instead, the challenges are for the designers
of these applications: to forget what we think we know about the limitations of the Web, and
begin to imagine a wider, richer range of possibilities.

It’s going to be fun.

Read this materials also:

Ajax Q&A

Mastering Ajax

What is Ajax

AJAX - Enhancing the user experience on the Web

JAVA Software Download - Ajax Frameworks

Application Server
Ajax Interview Questions

Getting started with Ajax

Cross-Domain Ajax

Web 2.0

Question: Is &&= a valid Java operator?

Answer: No, it is not.

Question: Name the eight primitive Java types.

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

Question: Which class should you use to obtain design information about an object?

Answer: The Class class is used to obtain information about an object's design.

Question: What is the relationship between clipping and repainting?

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

Question: Is "abc" a primitive value?

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

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


adapter class?

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: What restrictions are placed on the values of each case of a switch statement?

Answer: During compilation, the values of each case of a switch statement must evaluate to a
value that can be promoted to an int value.

Question: What modifiers may be used with an interface declaration?

Answer: An interface may be declared as public or abstract.

Question: Is a class a subclass of itself?


Answer: A class is a subclass of itself.

Question: What is the highest-level event class of the event-delegation model?

Answer: The java.util.EventObject class is the highest-level class in the event-delegation class
hierarchy.

Question: What event results from the clicking of a button?

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

Question: How can a GUI component handle its own events?

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

Question: What is the difference between a while statement and a dostatement?

Answer: A while statement checks at the beginning of a loop to see whether the next loop
iteration should occur. A do statement checks at the end of a loop to see whether the next
iteration of a loop should occur. The do statement will always execute the body of a loop at least
once.

Question: How are the elements of a GridBagLayout organized?

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

Question: What advantage do Java's layout managers provide over traditional windowing
systems?

Answer: Java uses layout managers to lay out components in a consistent manner across all
windowing platforms. Since Java's layout managers aren't tied to absolute sizing and positioning,
they are able to accomodate platform-specific differences among windowing systems.

Question: What is the Collection interface?

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

Question: What modifiers can be used with a local inner class?

Answer: A local inner class may be final or abstract.

java.lang & java.util Packages


Question: What is the ultimate ancestor of all java classes

Answer: Object class is the ancestor of all the java classes

Question: What are important methods of Object class

Answer: wait(), notify(), notifyAll(), equals(), toString().

Question: What is the difference between “= =” and “equals()”

Answer: “= =” does shallow comparison, It retuns true if the two object points to the same
address in the memory, i.e if the same the same reference
“equals()” does deep comparison, it checks if the values of the data in the object are same

Question: What would you use to compare two String variables - the operator == or the
method equals()?

Answer: I'd use the method equals() to compare the values of the Strings and the == to check if
two variables point at the same instance of a String object

Question: Give example of a final class

Answer: Math class is final class and hence cannot be extended

Question: What is the difference between String and StringBuffer

Answer: String is an immutable class, i.e you cannot change the values of that class

Example:

String str = “java”; // address in memory say 12345


And now if you assign a new value to the variable str then
str = “core java”; then the value of the variable at address 12345 will not change but a new
memory is allocated for this variable say 54321
So in the memory address 12345 will have value “java”
And the memory address 54321 will have value “core java” and the variable str will now be
pointing to address 54321 in memory

StringBuffer can be modified dynamically


Example:
StringBuffer strt =”java” // address in memory is say 12345
And now if you assign a new value to the variable str then
Str = “core java”; then value in the address of memory will get replaced, a new memory address
is not allocated in this case.
Question: What will be the result if you compare StringBuffer with String if both have
same values

Answer: It will return false as you cannot compare String with StringBuffer

Question: What is Collection API

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

Question: What are different types of collections

Answer: A collection has no special order and does not reject duplicates
A list is ordered and does not reject duplicates
A set has no special order but rejects duplicates
A map supports searching on a key field, values of which must be unique

Question: Tell me something about Arrays

Answer: Arrays are fast to access, but are inefficient if the number of elements grow and if you
have to insert or delete an element

Question: Difference between ArrayList and Vector

Answer: Vector methods are synchronized while ArrayList methods are not

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

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

Question: Difference between Hashtable and HashMap

Answer: Hashtable does not store null value, while HashMap does
Hashtable is synchronized, while HashMap is not

Question: What do you understand by JSP Actions?


Answer: JSP actions are XML tags that direct the server to use existing components or control
the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "jsp"
followed by a colon, followed by the action name followed by one or more attribute parameters.
There are six JSP Actions:

<jsp:include/>

<jsp:forward/>

<jsp:plugin/>

<jsp:usebean/>

<jsp:setProperty/>

<jsp:getProperty/>

Question: What is the difference between <jsp:include page = ... > and
<%@ include file = ... >?.
Answer: Both the tag includes the information from one page in another. The differences are as
follows:
<jsp:include page = ... >: This is like a function call from one jsp to
another jsp. It is executed ( the included page is executed and the
generated html content is included in the content of calling jsp) each time
the client page is accessed by the client. This approach is useful to for
modularizing the web application. If the included file changed then the new
content will be included in the output.

<%@ include file = ... >: In this case the content of the included file is
textually embedded in the page that have <%@ include file=".."> directive. In
this case in the included file changes, the changed content will not included
in the output. This approach is used when the code from one jsp file required
to include in multiple jsp files.

Question: What is the difference between <jsp:forward page = ... > and
response.sendRedirect(url),?.
Answer: The <jsp:forward> element forwards the request object containing the client request
information from one JSP file to another file. The target file can be an HTML file, another JSP
file, or a servlet, as long as it is in the same application context as the forwarding JSP file.
sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new
request to go the redirected page. The response.sendRedirect kills the session variables.

Question: Identify the advantages of JSP over Servlet.


a) Embedding of Java code in HTML pages
b) Platform independence
c) Creation of database-driven Web applications
d) Server-side programming capabilities

Answer :- Embedding of Java code in HTML pages

Write the following code for a JSP page:


<%@ page language = "java" %>

<HTML>
<HEAD><TITLE>RESULT PAGE</TITLE></HEAD>
<BODY>
<%

PrintWriter print = request.getWriter();


print.println("Welcome");

%>
</BODY>
</HTML>
Suppose you access this JSP file, Find out your answer.
a) A blank page will be displayed.
b) A page with the text Welcome is displayed
c) An exception will be thrown because the implicit out object is not used
d) An exception will be thrown because PrintWriter can be used in servlets only

Answer :- A page with the text Welcome is displayed

Question: What are implicit Objects available to the JSP Page?


Answer: Implicit objects are the objects available to the JSP page. These objects are created by
Web container and contain information related to a particular request, page, or application. The
JSP implicit objects are:

Variable Class Description


The context for the JSP page's servlet and any Web
application javax.servlet.ServletContext
components contained in the same application.
config javax.servlet.ServletConfig Initialization information for the JSP page's servlet.
exception java.lang.Throwable Accessible only from an error page.
out javax.servlet.jsp.JspWriter The output stream.
The instance of the JSP page's servlet processing the
page java.lang.Object
current request. Not typically used by JSP page authors.
The context for the JSP page. Provides a single API to
pageContext javax.servlet.jsp.PageContext
manage the various scoped attributes.
Subtype of
request The request triggering the execution of the JSP page.
javax.servlet.ServletRequest
Subtype of The response to be returned to the client. Not typically
response
javax.servlet.ServletResponse used by JSP page authors.
session javax.servlet.http.HttpSession The session object for the client.

Question: What are all the different scope values for the <jsp:useBean> tag?
Answer:<jsp:useBean> tag is used to use any java object in the jsp page. Here are the scope
values for <jsp:useBean> tag:
a) page
b) request
c) session and
d) application

Question: What is JSP Output Comments?


Answer: JSP Output Comments are the comments that can be viewed in the HTML source file.
Example:
<!-- This file displays the user login screen -->
and
<!-- This page was loaded on
<%= (new java.util.Date()).toLocaleString() %> -->

Question: What is expression in JSP?


Answer: Expression tag is used to insert Java values directly into the output. Syntax for the
Expression tag is:
<%= expression %>
An expression tag contains a scripting language expression that is evaluated, converted to a
String, and inserted where the expression appears in the JSP file. The following expression tag
displays time on the output:
<%=new java.util.Date()%>

Question: What types of comments are available in the JSP?


Answer: There are two types of comments are allowed in the JSP. These are hidden and output
comments. A hidden comments does not appear in the generated output in the html, while output
comments appear in the generated output.
Example of hidden comment:
<%-- This is hidden comment --%>
Example of output comment:
<!-- This is output comment -->
Question: What is JSP declaration?
Answer: JSP Decleratives are the JSP tag used to declare variables. Declaratives are enclosed in
the <%! %> tag and ends in semi-colon. You declare variables and functions in the declaration
tag and can use anywhere in the JSP. Here is the example of declaratives:

<%@page contentType="text/html" %>

<html>

<body>

<%!
int cnt=0;
private int getCount(){
//increment cnt and return the value
cnt++;
return cnt;
}
%>

<p>Values of Cnt are:</p>

<p><%=getCount()%></p>

</body>

</html>

Question: What is JSP Scriptlet?


Answer: JSP Scriptlet is jsp tag which is used to enclose java code in the JSP pages. Scriptlets
begins with <% tag and ends with %> tag. Java code written inside scriptlet executes every time
the JSP is invoked.
Example:
<%
//java codes
String userName=null;
userName=request.getParameter("userName");
%>

Question: What are the life-cycle methods of JSP?


Answer: Life-cycle methods of the JSP are:
a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before
any other method, and is called only once for a servlet instance.
b)_jspService(): The container calls the _jspservice() for each request and it passes the request
and the response objects. _jspService() method cann't be overridden.
c) jspDestroy(): The container calls this when its instance is about to destroyed.
The jspInit() and jspDestroy() methods can be overridden within a JSP page.
Page of the JSP Interview Questions.

Question: What is JSP Custom tags?


Answer: JSP Custom tags are user defined JSP language element. JSP custom tags are user
defined tags that can encapsulate common functionality. For example you can write your own
tag to access the database and performing database operations. You can also write custom tag for
encapsulate both simple and complex behaviors in an easy to use syntax and greatly simplify the
readability of JSP pages.

Question: What is JSP?


Answer: JavaServer Pages (JSP) technology is the Java platform technology for delivering
dynamic content to web clients in a portable, secure and well-defined way. The JavaServer Pages
specification extends the Java Servlet API to provide web application developers

Question: What is the role of JSP in MVC Model?


Answer: JSP is mostly used to develop the user interface, It plays are role of View in the MVC
Model.

Question: What do you understand by context initialization parameters?


Answer: The context-param element contains the declaration of a web application's servlet
context initialization parameters.
<context-param>
<param-name>name</param-name>
<param-value>value</param-value>
</context-param>

The Context Parameters page lets you manage parameters that are accessed through the
ServletContext.getInitParameterNames and ServletContext.getInitParameter methods.

Question: Can you extend JSP technology?


Answer: JSP technology lets the programmer to extend the jsp to make the programming more
easier. JSP can be extended and custom actions and tag libraries can be developed.

Question: What do you understand by JSP translation?


Answer: JSP translators generate standard Java code for a JSP page implementation class. This
class is essentially a servlet class wrapped with features for JSP functionality.

Question: What you can stop the browser to cash your page?
Answer: Instead of deleting a cache, you can force the browser not to catch the page.
<%
response.setHeader("pragma","no-cache");//HTTP 1.1
response.setHeader("Cache-Control","no-cache");
response.setHeader("Cache-Control","no-store");
response.addDateHeader("Expires", -1);
response.setDateHeader("max-age", 0);
//response.setIntHeader ("Expires", -1); //prevents caching at the proxy server
response.addHeader("cache-Control", "private");

%>
put the above code in your page.

Question: What you will handle the runtime exception in your jsp page?
Answer: The errorPage attribute of the page directive can be used to catch run-time exceptions
automatically and then forwarded to an error processing page.

For example:
<%@ page errorPage="customerror.jsp" %>
above code forwards the request to "customerror.jsp" page if an uncaught exception is
encountered during request processing. Within "customerror.jsp", you must indicate that it is an
error-processing page, via the directive: <%@ page isErrorPage="true" %>.

Question: Which containers may have a MenuBar?

Answer: Frame

Question: How are commas used in the intialization and iterationparts of a for statement?

Answer: Commas are used to separate multiple statements within the initialization and iteration
parts of a for statement.

Question: What is the purpose of the wait(), notify(), and notifyAll() methods?

Answer: The wait(),notify(), and notifyAll() methods are used to provide an efficient way for
threads to wait for a shared resource. When a thread executes an object's wait() method, it enters
the waiting state. It only enters the ready state after another thread invokes the object's notify() or
notifyAll() methods.

Question: What is an abstract method?

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

Question: How are Java source code files named?

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

Question: What is the relationship between the Canvas class and the Graphics class?

Answer: A Canvas object provides access to a Graphics object via its paint() method.

Question: What are the high-level thread states?

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

Question: What value does read() return when it has reached the end of a file?

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?

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

Question: What is the difference between a static and a non-static inner class?

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

Question: What is the difference between the String and StringBuffer classes?

Answer: String objects are constants. StringBuffer objects are not.

Question: If a variable is declared as private, where may the variable be accessed?

Answer: A private variable may only be accessed within the class in which it is declared.

Question: What is an object's lock and which object's have locks?

Answer: An object's lock is a mechanism that is used by multiple threads to obtain synchronized
access to the object. A thread may execute a synchronized method of an object only after it has
acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the
class's Class object.

Question: What is the Dictionary class?

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

Question: How are the elements of a BorderLayout organized?


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

Question: What is the % operator?

Answer: It is referred to as the modulo or remainder operator. It returns the remainder of


dividing the first operand by the second operand.

Question: When can an object reference be cast to an interface reference?

Answer: An object reference be cast to an interface reference when the object implements the
referenced interface.

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

Answer: We need

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


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

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?

Question: What is the difference between an Interface and an Abstract class

Answer: In abstract class you can define as well as declare methods, the methods which are
declared are to be marked as abstract.
In interface

all we just declare methods and the definition is provided by the class which is implementing it

Question: Explain serialization

Answer: Serialization means storing a state of a java object by coverting it to byte stream

Question: What are the rules of serialization

Answer: Rules:

1. Static fileds are not serialized because they are not part of any one particular object
2. Fileds from the base class are handled only if hose are serializable
3. Transient fileds are not serialized

Question: What is difference between error and exception

Answer: Error occurs at runtime and cannot be recovered, Outofmemory is one such example.
Exceptions on the other hand are due conditions which the application encounters such as
FileNotFound exception or IO exceptions

Question: What do you mean by object oreiented programming

Answer: In object oreinted programming the emphasis is more on data than on the procedure
and the program is divided into objects.
The data fields are hidden and they cant be accessed by external functions.
The design approach is bottom up.
The functions operate on data that is tied together in data structure

Question: What are 4 pillars of object oreinted programming

Answer:

1. Abstraction
It means hiding the details and only exposing the essentioal parts

2. Polymorphism
Polymorphism means having many forms. In java you can see polymorphism when you have
multiple methods with the same name

3. Inheritance
Inheritance means the child class inherits the non private properties of the parent class

4. Encapsulation
It means data hiding. In java with encapsulate the data by making it private and even we want
some other class to work on that data then the setter and getter methods are provided

Question: Difference between procedural and object oreinted language

Answer: In procedural programming the instructions are executed one after another and the data
is exposed to the whole program
In OOPs programming the unit of program is an object which is nothing but combination of data
and code and the data is not exposed outside the object

Question: What is the difference between constructor and method

Answer: Constructor will be automatically invoked when an object is created whereas method
has to be called explicitly.
Question: What is the difference between parameters and arguments

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

Question: What is reflection in java

Answer: Reflection allows Java code to discover information about the fields, methods and
constructors of loaded classes and to dynamically invoke them

Question: What is a cloneable interface and how many methods does it contain

Answer: It is not having any method because it is a TAGGED or MARKER interface

Question: What's the difference between a queue and a stack

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

Question: Can you make an instance of abstract class

Answer: No you cannot create an instance of abstract class

Question: What are parsers

Answer: Parsers are used for processing XML documents. There are 2 types of parsers DOM
parser and SAX Parser

Question: Difference between SAX and DOM parser

Answer: DOM parsers are Object based and SAX parsers are event based
DOM parsers creates Tree in the memory whereas SAX parser does not and hence it is faster
than DOM
DOM parser are useful when we have to modify the XML, with SAX parser you cannot modify
the xml, it is read only

Question: What is the difference between Java Bean and Java Class

Answer: Basically a Bean is a java class but it has getter and setter method and it does not have
any logic in it, it is used for holding data.
On the other hand the Java class can have what a java bean has and also has some logic inside it

Modifiers

Question: What are access modifiers


Answer: These public, protected and private, these can be applied to class, variables,
constructors and methods. But if you don't specify an access modifier then it is considered as
Friendly

Question: Can protected or friendly features be accessed from different packages

Answer: No when features are friendly or protected they can be accessed from all the classes in
that package but not from classes in another package

Question: How can you access protected features from another package

Answer: You can access protected features from other classes by subclassing the that class in
another package, but this cannot be done for friendly features

Question: What are the rules for overriding

Answer:

Private method can be overridden by private, friendly, protected or public methods


Friendly method can be overridden by friendly, protected or public methods
Protected method can be overridden by protected or public methods
Public method can be overridden by public method

Question: Explain modifier final

Answer: Final can be applied to classes, methods and variables and the features cannot be
changed. Final class cannot be subclassed, methods cannot be overridden

Question: Can you change the reference of the final object

Answer: No the reference cannot be change, but the data in that object can be changed

Question: Can abstract modifier be applied to a variable

Answer: No it is applied only to class and methods

Question: Can abstract class be instantiated

Answer: No abstract class cannot be instantiated i.e you cannot create a new object of this class

Question: When does the compiler insist that the class must be abstract

Answer:

If one or more methods of the class are abstract.


If class inherits one or more abstract methods from the parent abstract class and no
implementation is provided for that method
If class implements an interface and provides no implementation for those methods

Question: How is abstract class different from final class

Answer: Abstract class must be subclassed and final class cannot be subclassed

Question: Where can static modifiers be used

Answer: They can be applied to variables, methods and even a block of code, static methods and
variables are not associated with any instance of class

Question: When are the static variables loaded into the memory

Answer: During the class load time

Question: When are the non static variables loaded into the memory

Answer: They are loaded just before the constructor is called

Question: How can you reference static variables

Answer: Via reference to any instance of the class

Computer comp = new Computer ();


comp.harddisk where hardisk is a static variable
comp.compute() where compute is a method

Via the class name

Computer.harddisk
Computer.compute()

Question: Can static method use non static features of there class

Answer: No they are not allowed to use non static features of the class, they can only call static
methods and can use static data

Question: What is static initializer code

Answer: A class can have a block of initializer code that is simply surrounded by curly braces
and labeled as static e.g.
public class Demo{
static int =10;
static{
System.out.println(“Hello world');
}
}

And this code is executed exactly once at the time of class load

Where is native modifier used It can refer only to methods and it indicates that the body of the
method is to be found else where and it is usually written in non java language

Question: What are transient variables

Answer: A transient variable is not stored as part of objects persistent state and they cannot be
final or static

Question: What is synchronized modifier used for

Answer: It is used to control access of critical code in multithreaded programs

Question: What are volatile variables

Answer: It indicates that these variables can be modified asynchronously

Question: What is the difference between notify and notify All methods ?

Answer: A call to notify causes at most one thread waiting on the same object to be notified
(i.e., the object that calls notify must be the same as the object that called wait). A call to
notifyAll causes all threads waiting on the same object to be notified. If more than one thread is
waiting on that object, there is no way to control which of them is notified by a call to notify (so
it is often better to use notifyAll than notify).

Question: What is synchronized keyword? In what situations you will Use it?

Answer: synchronization is the act of serializing access to critical sections of code. We will use
this keyword when we expect multiple threads to access/modify the same data. To understand
synchronization we need to look into thread execution manner.

Threads may execute in a manner where their paths of execution are completely independent of
each other. Neither thread depends upon the other for assistance. For example, one thread might
execute a print job, while a second thread repaints a window. And then there are threads that
require synchronization, the act of serializing access to critical sections of code, at various
moments during their executions. For example, say that two threads need to send data packets
over a single network connection. Each thread must be able to send its entire data packet before
the other thread starts sending its data packet; otherwise, the data is scrambled. This scenario
requires each thread to synchronize its access to the code that does the actual data-packet
sending.

If you feel a method is very critical for business that needs to be executed by only one thread at a
time (to prevent data loss or corruption), then we need to use synchronized keyword.

EXAMPLE

Some real-world tasks are better modeled by a program that uses threads than by a normal,
sequential program. For example, consider a bank whose accounts can be accessed and updated
by any of a number of automatic teller machines (ATMs). Each ATM could be a separate thread,
responding to deposit and withdrawal requests from different users simultaneously. Of course, it
would be important to make sure that two users did not access the same account simultaneously.
This is done in Java using synchronization, which can be applied to individual methods, or to
sequences of statements.

One or more methods of a class can be declared to be synchronized. When a thread calls an
object's synchronized method, the whole object is locked. This means that if another thread tries
to call any synchronized method of the same object, the call will block until the lock is released
(which happens when the original call finishes). In general, if the value of a field of an object can
be changed, then all methods that read or write that field should be synchronized to prevent two
threads from trying to write the field at the same time, and to prevent one thread from reading the
field while another thread is in the process of writing it.

Here is an example of a BankAccount class that uses synchronized methods to ensure that
deposits and withdrawals cannot be performed simultaneously, and to ensure that the account
balance cannot be read while either a deposit or a withdrawal is in progress. (To keep the
example simple, no check is done to ensure that a withdrawal does not lead to a negative
balance.)

public class BankAccount { private double balance; // constructor: set balance to given amount
public BankAccount( double initialDeposit ) { balance = initialDeposit; } public synchronized
double Balance( ) { return balance; } public synchronized void Deposit( double deposit ) {
balance += deposit; } public synchronized void Withdraw( double withdrawal ) { balance -=
withdrawal; } }

Note: that the BankAccount's constructor is not declared to be synchronized. That is because it
can only be executed when the object is being created, and no other method can be called until
that creation is finished.

There are cases where we need to synchronize a group of statements, we can do that using
synchrozed statement.

Java Code Example synchronized ( B ) { if ( D > B.Balance() ) { ReportInsuffucientFunds(); }


else { B.Withdraw( D ); } }

Question: What are null or Marker interfaces in Java

Answer: The null interfaces are marker interfaces, they do not have function declarations in
them, they are empty interfaces, this is to convey the compiler that they have to be treated
differently

Question: Does java Support multiple inheritance

Answer: Java does not support multiple inheritance directly like C++, because then it is prone to
ambiguity, example if a class extends 2 other classes and these 2 parent classes have same
method names then there is ambiguity. Hence in Java Multiple inheritance is supported using
Interfaces

Question: What are virtual function

Answer: In OOP when a derived class inherits from a base class, an object of the derived class
may be referred to (or cast) as either being the base class type or the derived class type. If there
are base class functions overridden by the derived class, a problem then arises when a derived
object has been cast as the base class type. When a derived object is referred to as being of the
base's type, the desired function call behavior is ambiguous.

The distinction between virtual and not virtual is provided to solve this issue. If the function in
question is designated "virtual" then the derived class's function would be called (if it exists). If it
is not virtual, the base class's function would be called.

Question: Does java support virtual functions

Answer: No java does not support virtual functions direclty like in C++, but it supports using
Abstract class and interfaces

Question: Describe what happens when an object is created in Java

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

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.

Question: What is the purpose of System Class

Answer: The purpose of the system class is to provide the access to the System reources

Question: What is instanceOf operator used for

Answer: It is used to if an object can be cast into a specific type without throwing Class cast
exception

Question: Why we should not have instance variable in an interface

Answer: Since all data fields and methods in an Interface are public by default, then we
implement that interface in our class then we have public members in our class and this class will
expose these data members and this is violation of encapsulation as now the data is not secure

Question: What is JVM

Answer: When we install a java package. It contains 2 things


* The Java Runtime Environment (JRE)
* The Java Development Kit (JDK)

The JRE provides runtime support for Java applications. The JDK provides the Java compiler
and other development tools. The JDK includes the JRE.

Both the JRE and the JDK include a Java Virtual Machine (JVM). This is the application that
executes a Java program. A Java program requires a JVM to run on a particular platform

Question: Can abstract class be final

Answer: No, abstract class cannot be final

Question: When a new object of derived Class is created, whose constructor will be called
first, childs or parents

Answer: Even when the new object of child class is created, first the Base class constructor gets
executed and then the child classes constructor

Question: What is a singleton class

Answer: A singleton is an object that cannot be instantiated. The restriction on the singleton is
that there can be only one instance of a singleton created by the Java Virtual Machine (JVM) - by
prevent direct instantiation we can ensure that developers don't create a second copy.
Question: Can an abstract class have final method

Answer: Yes

Question: Can a final class have an abstract method

Answer: No, the compiler will give an error

Question: What is the difference between Authentication and Authorization

Answer: Authentication is a process for verifying that an individual is who they say they are.
Authorization is an additional level of security, and it means that a particular user (usually
authenticated), may have access to a particular resource say record, file, directory or script.

Objects and Classes

Question: What's the difference between constructors and other methods

Answer: Constructors must have the same name as the class and can not return a value. They are
only called once while regular methods could be called many times.

Question: What is the difference between Overloading and Overriding

Answer: Overloading : Reusing the same method name with different arguments and perhaps a
different return type is called as overloading
Overriding : Using the same method name with identical arguments and return type is know as
overriding

Question: What do you understand by late binding or virtual method Invocation. (Example
of runtime polymorphism)

Answer: When a compiler

for a non object oriented language comes across a method invocation, it determines exactly what
target code should be called and build machine language to represent that call. In an object
oriented language, this is not possible since the proper code to invoke is determined based upon
the class if the object being used to make the call, not the type of the variable. Instead code is
generated that will allow the decision to be made at run time. This delayed decision making is
called as late binding

Question: Can overriding methods have different return types

Answer: No they cannot have different return types


Question: If the method to be overridden has access type protected, can subclass have the
access type as private

Answer: No, it must have access type as protected or public, since an overriding method must
not be less accessible than the method it overrides

Question: Can constructors be overloaded

Answer: Yes constructors can be overloaded

Question: What happens when a constructor of the subclass is called

Answer: A constructor delays running its body until the parent parts of the class have been
initialized. This commonly happens because of an implicit call to super() added by the compiler.
You can provide your own call to super(arguments..) to control the way the parent parts are
initialized. If you do this, it must be the first statement of the constructor.

Question: If you use super() or this() in a constructor where should it appear in the
constructor

Answer: It should always be the first statement in the constructor

Question: What is an inner class

Answer: An inner class is same as any other class, but is declared inside some other class

Question: How will you reference the inner class

Answer: To reference it you will have to use OuterClass$InnerClass

Question: Can objects that are instances of inner class access the members of the outer
class

Answer: Yes they can access the members of the outer class

Question: What modifiers may be used with an inner class that is a member of an outer
class?

Answer: A (non-local) inner class may be declared as public, protected, private, static, final, or
abstract

Question: Can inner classes be static

Answer: Yes inner classes can be static, but they cannot access the non static data of the outer
classes, though they can access the static data
Question: Can an inner class be defined inside a method

Answer: Yes it can be defined inside a method and it can access data of the enclosing methods
or a formal parameter if it is final

Question: What is an anonymous class

Answer: Some classes defined inside a method do not need a name, such classes are called
anonymous classes

Question: What are the rules of anonymous class

Answer: The class is instantiated and declared in the same place The declaration and
instantiation takes the form new Xxxx () {// body}
Where Xxxx is an interface name. An anonymous class cannot have a constructor. Since you do
not specify a name for the class, you cannot use that name to specify a constructor

Question: What is serialization ?

Answer: Serialization is the process of writing complete state of java object into output stream,
that stream can be file or byte array or stream associated with TCP/IP socket.

Question: What does the Serializable interface do ?

Answer: Serializable is a tagging interface; it prescribes no methods. It serves to assign the


Serializable data type to the tagged class and to identify the class as one which the developer has
designed for persistence. ObjectOutputStream serializes only those objects which implement this
interface.

Question: How do I serialize an object to a file ?

Answer: To serialize an object into a stream perform the following actions:

- Open one of the output streams, for exaample FileOutputStream


- Chain it with the ObjectOutputStream - Call the method writeObject() providingg the instance
of a Serializable object as an argument.
- Close the streams

Java Code --------- try{ fOut= new FileOutputStream("c:\\emp.ser"); out = new


ObjectOutputStream(fOut); out.writeObject(employee); //serializing System.out.println("An
employee is serialized into c:\\emp.ser"); } catch(IOException e){ e.printStackTrace(); }

Question: How do I deserilaize an Object?


Answer: To deserialize an object, perform the following steps:

- Open an input stream


- Chain it with the ObjectInputStream - Call the method readObject() and cast tthe returned
object to the class that is being deserialized.
- Close the streams

Java Code try{ fIn= new FileInputStream("c:\\emp.ser"); in = new ObjectInputStream(fIn); //de-


serializing employee Employee emp = (Employee) in.readObject();
System.out.println("Deserialized " + emp.fName + " " + emp.lName + " from emp.ser ");
}catch(IOException e){ e.printStackTrace(); }catch(ClassNotFoundException e){
e.printStackTrace(); }

Question: What is Externalizable Interface ?

Answer : Externalizable interface is a subclass of Serializable. Java provides Externalizable


interface that gives you more control over what is being serialized and it can produce smaller
object footprint. ( You can serialize whatever field values you want to serialize)

This interface defines 2 methods: readExternal() and writeExternal() and you have to implement
these methods in the class that will be serialized. In these methods you'll have to write code that
reads/writes only the values of the attributes you are interested in. Programs that perform
serialization and deserialization have to write and read these attributes in the same sequence.

Question: Explain garbage collection ?

Answer: Garbage collection is an important part of Java's security strategy. Garbage collection
is also called automatic memory management as JVM automatically removes the unused
variables/objects from the memory. The name "garbage collection" implies that objects that are
no longer needed by the program are "garbage" and can be thrown away. A more accurate and
up-to-date metaphor might be "memory recycling." When an object is no longer referenced by
the program, the heap space it occupies must be recycled so that the space is available for
subsequent new objects. The garbage collector must somehow determine which objects are no
longer referenced by the program and make available the heap space occupied by such
unreferenced objects. In the process of freeing unreferenced objects, the garbage collector must
run any finalizers of objects being freed

Question : How you can force the garbage collection ?

Answer : Garbage collection automatic process and can't be forced. We can call garbage
collector in Java by calling System.gc() and Runtime.gc(), JVM tries to recycle the unused
objects, but there is no guarantee when all the objects will garbage collected.

Question : What are the field/method access levels (specifiers) and class access levels ?

Answer: Each field and method has an access level:


private: accessible only in this class
(package): accessible only in this package
protected: accessible only in this package and in all subclasses of this class
public: accessible everywhere this class is available

Similarly, each class has one of two possible access levels:

(package): class objects can only be declared and manipulated by code in this package

public: class objects can be declared and manipulated by code in any package

Question: What are the static fields & static Methods ?

Answer: If a field or method defined as a static, there is only one copy for entire class, rather
than one copy for each instance of class. static method cannot accecss non-static field or call
non-static method

Example Java Code

static int counter = 0;

A public static field or method can be accessed from outside the class using either the usual
notation:

Java-class-object.field-or-method-name

or using the class name instead of the name of the class object:

Java- class-name.field-or-method-name

Question: What are the Final fields & Final Methods ?

Answer: Fields and methods can also be declared final. A final method cannot be overridden in
a subclass. A final field is like a constant: once it has been given a value, it cannot be assigned to
again.

Java Code

private static final int MAXATTEMPTS = 10;

Question: Describe the wrapper classes in Java ?

Answer: Wrapper class is wrapper around a primitive data type. An instance of a wrapper class
contains, or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes:
Primitive Wrapper
boolean java.lang.Boolean
byte java.lang.Byte
char java.lang.Character
double java.lang.Double
float java.lang.Float
int java.lang.Integer
long java.lang.Long
short java.lang.Short
void java.lang.Void

Question: What are different types of inner classes ?

Answer: Inner classes nest within other classes. A normal class is a direct member of a package.
Inner classes, which became available with Java 1.1, are four types

Static member classes


Member classes
Local classes
Anonymous classes

Static member classes - 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.

Member Classes - a member class is also defined as a member of a class. Unlike the static
variety, the member class is instance specific and has access to any and all methods and
members, even the parent's this reference.

Local Classes - Local Classes declared within a block of code and these classes are visible only
within the block.

Anonymous Classes - These type of classes does not have any name and its like a local class

Java Anonymous Class Example public class SomeGUI extends JFrame { ... button member
declarations ... protected void buildGUI() { button1 = new JButton(); button2 = new JButton(); ...
button1.addActionListener( new java.awt.event.ActionListener() <------ Anonymous Class {
public void actionPerformed(java.awt.event.ActionEvent e) { // do something } } );

Question: What is the difference between static and non-static variables?

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

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

Question: What is the purpose of the File class?

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

Question: Can an exception be rethrown?

Answer: Yes, an exception can be rethrown.

Question: Which Math method is used to calculate the absolute value of a number?

Answer: The abs() method is used to calculate absolute values.

Question: How does multithreading take place on a computer with a single CPU?

Answer: The operating system's task scheduler allocates execution time to multiple tasks. By
quickly switching between executing tasks, it creates the impression that tasks execute
sequentially.

Question: When does the compiler supply a default constructor for a class?

Answer: The compiler supplies a default constructor for a class if no other constructors are
provided.

Question: When is the finally clause of a try-catch-finally statement executed?

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

Question: Which class is the immediate superclass of the Container class?

Answer: Component

Question: If a method is declared as protected, where may the method be accessed?

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

Question: How can the Checkbox class be used to create a radio button?

Answer: By associating Checkbox objects with a CheckboxGroup.


Question: Which non-Unicode letter characters may be used as the first character of an
identifier?

Answer: The non-Unicode letter characters $ and _ may appear as the first character of an
identifier

Question: What restrictions are placed on method overloading?

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

Question: What happens when you invoke a thread's interrupt method while it is sleeping
or waiting?

Answer: When a task's interrupt() method is executed, the task enters the ready state. The next
time the task enters the running state, an InterruptedException is thrown.

Question: What is casting?

Answer: There are two types of casting, casting between primitive numeric types and casting
between object references. Casting between numeric types is used to convert larger values, such
as double values, to smaller values, such as byte values. Casting between object references is
used to refer to an object by a compatible class, interface, or array type reference.

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

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

Question: Can I setup Apache Struts to use multiple configuration files

?
Answer: Yes Struts can use multiple configuration files. Here is the configuration example:
<servlet>
<servlet-name>banking</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,
/WEB-INF/struts-authentication.xml,
/WEB-INF/struts-help.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

Question: What are the disadvantages of Struts?


Answer: Struts is very robust framework and is being used extensively in the industry. But there
are some disadvantages of the Struts:
a) High Learning Curve
Struts requires lot of efforts to learn and master it. For any small project less experience
developers could spend more time on learning the Struts.

b) Harder to learn
Struts are harder to learn, benchmark and optimize.

Question: What is Struts Flow?


Answer: Struts Flow is a port of Cocoon's Control Flow to Struts to allow complex workflow,
like multi-form wizards, to be easily implemented using continuations-capable JavaScript. It
provides the ability to describe the order of Web pages that have to be sent to the client, at any
given point in time in an application. The code is based on a proof-of-concept Dave Johnson put
together to show how the Control Flow could be extracted from Cocoon. (Ref:
http://struts.sourceforge.net/struts-flow/index.html )

Question: What are the difference between <bean:message> and <bean:write>?


Answer: <bean:message>: This tag is used to output locale-specific text (from the properties
files) from a MessageResources bundle.

<bean:write>: This tag is used to output property values from a bean. <bean:write> is a
commonly used tag which enables the programmers to easily present the data.

Question: What is LookupDispatchAction?


Answer: An abstract Action that dispatches to the subclass mapped execute method. This is
useful in cases where an HTML form has multiple submit buttons with the same name. The
button name is specified by the parameter property of the corresponding ActionMapping. (Ref.
http://struts.apache.org/1.2.7/api/org/apache/struts/actions/LookupDispatchAction.html).

Question: What are the components of Struts?


Answer: Struts is based on the MVC design pattern. Struts components can be categories into
Model, View and Controller.
Model: Components like business logic / business processes and data are the part of Model.
View: JSP, HTML etc. are part of View
Controller: Action Servlet of Struts is part of Controller components which works as front
controller to handle all the requests.
Question: What are Tag Libraries provided with Struts?
Answer: Struts provides a number of tag libraries that helps to create view components easily.
These tag libraries are:
a) Bean Tags: Bean Tags are used to access the beans and their properties.
b) HTML Tags: HTML Tags provides tags for creating the view components like forms,
buttons, etc..
c) Logic Tags: Logic Tags provides presentation logics that eliminate the need for scriptlets.
d) Nested Tags: Nested Tags helps to work with the nested context.

Question: What are the core classes of the Struts Framework?


Answer: Core classes of Struts Framework are ActionForm, Action, ActionMapping,
ActionForward, ActionServlet etc.

Question: What are difference between ActionErrors and ActionMessage?


Answer: ActionMessage: A class that encapsulates messages. Messages can be either global or
they are specific to a particular bean property.
Each individual message is described by an ActionMessage object, which contains a message
key (to be looked up in an appropriate message resources database), and up to four placeholder
arguments used for parametric substitution in the resulting message.

ActionErrors: A class that encapsulates the error messages being reported by the validate()
method of an ActionForm. Validation errors are either global to the entire ActionForm bean they
are associated with, or they are specific to a particular bean property (and, therefore, a particular
input field on the corresponding form).

Question: How you will handle exceptions in Struts?


Answer: In Struts you can handle the exceptions in two ways:
a) Declarative Exception Handling: You can either define global exception handling tags in
your struts-config.xml or define the exception handling tags within <action>..</action> tag.
Example:
<exception

key="database.error.duplicate"

path="/UserExists.jsp"

type="mybank.account.DuplicateUserException"/>

b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the
exception.

Question: What is RequestProcessor and RequestDispatcher?


Answer: The controller is responsible for intercepting and translating user input into actions to
be performed by the model. The controller is responsible for selecting the next view based on
user input and the outcome of model operations. The Controller receives the request from the
browser, invoke a business operation and coordinating the view to return to the client.
The controller is implemented by a java servlet, this servlet is centralized point of control for the
web application
. In struts framework the controller responsibilities are implemented by several different
components like
The ActionServlet Class
The RequestProcessor Class
The Action Class

The ActionServlet extends the javax.servlet.http.httpServlet class. The ActionServlet class is


not abstract and therefore can be used as a concrete controller by your application.
The controller is implemented by the ActionServlet class. All incoming requests are mapped to
the central controller in the deployment descriptor as follows.
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
</servlet>

All request URIs with the pattern *.do are mapped to this servlet in the deployment descriptor as
follows.

<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
<url-pattern>*.do</url-pattern>
A request URI that matches this pattern will have the following form.
http://www.my_site_name.com/mycontext/actionName.do

The preceding mapping is called extension mapping, however, you can also specify path
mapping where a pattern ends with /* as shown below.
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>/do/*</url-pattern>
<url-pattern>*.do</url-pattern>
A request URI that matches this pattern will have the following form.
http://www.my_site_name.com/mycontext/do/action_Name
The class org.apache.struts.action.requestProcessor process the request from the controller.
You can sublass the RequestProcessor with your own version and modify how the request is
processed.

Once the controller receives a client request, it delegates the handling of the request to a helper
class. This helper knows how to execute the business operation associated with the requested
action. In the Struts framework this helper class is descended of org.apache.struts.action.Action
class. It acts as a bridge between a client-side user action and business operation. The Action
class decouples the client request from the business model. This decoupling allows for more than
one-to-one mapping between the user request and an action. The Action class also can perform
other functions such as authorization, logging before invoking business operation. the Struts
Action class contains several methods, but most important method is the execute() method.
public ActionForward execute(ActionMapping mapping,
ActionForm form, HttpServletRequest request, HttpServletResponse response) throws
Exception;
The execute() method is called by the controller when a request is received from a client. The
controller creates an instance of the Action class if one doesn’t already exist. The strut
framework will create only a single instance of each Action class in your application.

Action are mapped in the struts configuration file and this configuration is loaded into memory at
startup and made available to the framework at runtime. Each Action element is represented in
memory by an instance of the org.apache.struts.action.ActionMapping class . The
ActionMapping object contains a path attribute that is matched against a portion of the URI of
the incoming request.
<action>
path= "/somerequest"
type="com.somepackage.someAction"
scope="request"
name="someForm"
validate="true"
input="somejsp.jsp"
<forward name="Success" path="/action/xys" redirect="true"/>
<forward name="Failure" path="/somejsp.jsp" redirect="true"/>
</action>
Once this is done the controller should determine which view to return to the client. The execute
method signature in Action class has a return type org.apache.struts.action.ActionForward class.
The ActionForward class represents a destination to which the controller may send control once
an action has completed. Instead of specifying an actual JSP page in the code, you can
declaratively associate as action forward through out the application. The action forward are
specified in the configuration file.
<action>
path= "/somerequest"
type="com.somepackage.someAction"
scope="request"
name="someForm"
validate="true"
input="somejsp.jsp"
<forward name="Success" path="/action/xys" redirect="true"/>
<forward name="Failure" path="/somejsp.jsp" redirect="true"/>
</action>
The action forward mappings also can be specified in a global section, independent of any
specific action mapping.
<global-forwards>
<forward name="Success" path="/action/somejsp.jsp" />
<forward name="Failure" path="/someotherjsp.jsp" />
</global-forwards>

public interface RequestDispatcher

Defines an object that receives requests from the client and sends them to any resource (such as a
servlet, HTML file, or JSP file) on the server. The servlet container creates the
RequestDispatcher object, which is used as a wrapper around a server resource located at a
particular path or given by a particular name.
This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher
objects to wrap any type of resource.

getRequestDispatcher

public RequestDispatcher getRequestDispatcher(java.lang.String path)

Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given
path. A RequestDispatcher object can be used to forward a request to the resource or to include
the resource in a response. The resource can be dynamic or static.
The pathname must begin with a "/" and is interpreted as relative to the current context root. Use
getContext to obtain a RequestDispatcher for resources in foreign contexts. This method returns
null if the ServletContext cannot return a RequestDispatcher.

Parameters:
path - a String specifying the pathname to the resource
Returns:
a RequestDispatcher object that acts as a wrapper for the resource at the specified path
See Also:
RequestDispatcher, getContext(java.lang.String)

getNamedDispatcher

public RequestDispatcher getNamedDispatcher(java.lang.String name)

Returns a RequestDispatcher object that acts as a wrapper for the named servlet.
Servlets (and JSP pages also) may be given names via server administration or via a web
application deployment descriptor. A servlet instance can determine its name using
ServletConfig.getServletName().
This method returns null if the ServletContext cannot return a RequestDispatcher for any reason.

Parameters:
name - a String specifying the name of a servlet to wrap
Returns:
a RequestDispatcher object that acts as a wrapper for the named servlet
See Also:
RequestDispatcher, getContext(java.lang.String), ServletConfig.getServletName()
Question: Why cant we overide create method in StatelessSessionBean?
Answer: From the EJB Spec : - A Session bean's home interface defines one or morecreate(...)
methods. Each create method must be named create and must match one of the ejbCreate
methods defined in the enterprise Bean class. The return type of a create method must be the
enterprise Bean's remote interface type. The home interface of a stateless session bean must have
one create method that takes no arguments.

Question: Is struts threadsafe?Give an example?


Answer: Struts is not only thread-safe but thread-dependant. The response to a request is
handled by a light-weight Action object, rather than an individual servlet. Struts instantiates each
Action class once, and allows other requests to be threaded through the original object. This core
strategy conserves resources and provides the best possible throughput. A properly-designed
application will exploit this further by routing related operations through a single Action.

Question: Can we Serialize static variable?


Answer: Serialization is the process of converting a set of object instances that contain
references to each other into a linear stream of bytes, which can then be sent through a socket,
stored to a file, or simply manipulated as a stream of data. Serialization is the mechanism used
by RMI to pass objects between JVMs, either as arguments in a method invocation from a client
to a server or as return values from a method invocation. In the first section of this book, There
are three exceptions in which serialization doesnot necessarily read and write to the stream.
These are
1. Serialization ignores static fields, because they are not part of any particular object's state.
2. Base class fields are only handled if the base class itself is serializable.
3. Transient fields. There are four basic things you must do when you are making a class
serializable. They are:

1. Implement the Serializable interface.


2. Make sure that instance-level, locally defined state is serialized properly.
3. Make sure that superclass state is serialized properly.
4. Override equals( )and hashCode( ).
it is possible to have control over serialization process. The class should implement
Externalizable interface. This interface contains two methods namely readExternal and
writeExternal. You should implement these methods and write the logic for customizing
the serialization process .... (Source:
http://www.oreilly.com/catalog/javarmi/chapter/ch10.html)
Question: What are the uses of tiles-def.xml file, resourcebundle.properties file,
validation.xml file?
Answer: tiles-def.xml is is an xml file used to configure tiles with the struts application. You
can define the layout / header / footer / body content for your View. See more at
http://www.roseindia.net/struts/using-tiles-defs-xml.shtml.

The resourcebundle.properties file is used to configure the message (error/ other messages) for
the struts applications.

The file validation.xml is used to declare sets of validations that should be applied to Form
Beans. Fpr more information please visit
http://www.roseindia.net/struts/address_struts_validator.shtml.

Question: What is the difference between perform() and execute() methods?


Answer: Perform method is the method which was deprecated in the Struts Version 1.1. In
Struts 1.x, Action.perform() is the method called by the ActionServlet. This is typically where
your business logic resides, or at least the flow control to your JavaBeans and EJBs that handle
your business logic. As we already mentioned, to support declarative exception handling, the
method signature changed in perform. Now execute just throws Exception. Action.perform() is
now deprecated; however, the Struts v1.1 ActionServlet is smart enough to know whether or not
it should call perform or execute in the Action, depending on which one is available.

Question: What are the various Struts tag libraries?


Answer: Struts is very rich framework and it provides very good and user friendly way to
develop web application forms. Struts provide many tag libraries to ease the development of web
applications. These tag libraries are:
* Bean tag library - Tags for accessing JavaBeans and their properties.
* HTML tag library - Tags to output standard HTML, including forms, text boxes, checkboxes,
radio buttons etc..
* Logic tag library - Tags for generating conditional output, iteration capabilities and flow
management
* Tiles or Template tag library - For the application using tiles
* Nested tag library - For using the nested beans in the application

Question: What do you understand by DispatchAction?


Answer: DispatchAction is an action that comes with Struts 1.1 or later, that lets you combine
Struts actions into one class, each with their own method. The
org.apache.struts.action.DispatchAction class allows multiple operation to mapped to the
different functions in the same Action class.
For example:
A package might include separate RegCreate, RegSave, and RegDelete Actions, which just
perform different operations on the same RegBean object. Since all of these operations are
usually handled by the same JSP page, it would be handy to also have them handled by the same
Struts Action.

A very simple way to do this is to have the submit button modify a field in the form which
indicates which operation to perform.

<html:hidden property="dispatch" value="error"/>


<SCRIPT>function set(target)
{document.forms[0].dispatch.value=target;}</SCRIPT>
<html:submit onclick="set('save');">SAVE</html:submit>
<html:submit onclick="set('create');">SAVE AS NEW</html:submitl>
<html:submit onclick="set('delete);">DELETE</html:submit>

Then, in the Action you can setup different methods to handle the different operations, and
branch to one or the other depending on which value is passed in the dispatch field.

String dispatch = myForm.getDispatch();


if ("create".equals(dispatch)) { ...
if ("save".equals(dispatch)) { ...

The Struts Dispatch Action [org.apache.struts.actions] is designed to do exactly the same thing,
but without messy branching logic. The base perform method will check a dispatch field for you,
and invoke the indicated method. The only catch is that the dispatch methods must use the same
signature as perform. This is a very modest requirement, since in practice you usually end up
doing that anyway.

To convert an Action that was switching on a dispatch field to a DispatchAction, you simply
need to create methods like this

public ActionForward create(


ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException { ...

public ActionForward save(


ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException { ...

Cool. But do you have to use a property named dispatch? No, you don't. The only other step is to
specify the name of of the dispatch property as the "parameter" property of the action-mapping.
So a mapping for our example might look like this:

<action
path="/reg/dispatch"
type="app.reg.RegDispatch"
name="regForm"
scope="request"
validate="true"
parameter="dispatch"/>

If you wanted to use the property "o" instead, as in o=create, you would change the mapping to

<action
path="/reg/dispatch"
type="app.reg.RegDispatch"
name="regForm"
scope="request"
validate="true"
parameter="o"/>

Again, very cool. But why use a JavaScript button in the first place? Why not use several buttons
named "dispatch" and use a different value for each?

You can, but the value of the button is also its label. This means if the page designers want to
label the button something different, they have to coordinate the Action programmer.
Localization becomes virtually impossible. (Source: http://husted.com/struts/tips/002.html).

Question: How Struts relates to J2EE?


Answer: Struts framework is built on J2EE technologies (JSP, Servlet, Taglibs), but it is itself
not part of the J2EE standard.

Question: What is Struts actions and action mappings?


Answer: A Struts action is an instance of a subclass of an Action class, which implements a
portion of a Web application and whose perform or execute method returns a forward.

An action can perform tasks such as validating a user name and password.

An action mapping is a configuration file entry that, in general, associates an action name with
an action. An action mapping can contain a reference to a form bean that the action can use, and
can additionally define a list of local forwards that is visible only to this action.

An action servlet is a servlet that is started by the servlet container of a Web server to process a
request that invokes an action. The servlet receives a forward from the action and asks the servlet
container to pass the request to the forward's URL. An action servlet must be an instance of an
org.apache.struts.action.ActionServlet class or of a subclass of that class. An action servlet is the
primary component of the controller.

Structs Interview Questions and Answers

What is Struts?
Struts is a web page development framework and an open source software that helps developers
build web applications quickly and easily. Struts combines Java Servlets, Java Server Pages,
custom tags, and message resources into a unified framework. It is a cooperative, synergistic
platform, suitable for development teams, independent developers, and everyone between.

How is the MVC design pattern used in Struts framework?


In the MVC design pattern, application flow is mediated by a central Controller. The Controller
delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler
acts as an adapter between the request and the Model. The Model represents, or encapsulates, an
application's business logic or state. Control is usually then forwarded back through the
Controller to the appropriate View. The forwarding can be determined by consulting a set of
mappings, usually loaded from a database or configuration file. This provides a loose coupling
between the View and Model, which can make an application significantly easier to create and
maintain.
Controller--Servlet controller which supplied by Struts itself; View --- what you can see on the
screen, a JSP page and presentation components; Model --- System state and a business logic
JavaBeans.

Who makes the Struts?


Struts is hosted by the Apache Software Foundation(ASF) as part of its Jakarta project, like
Tomcat, Ant and Velocity.

Why it called Struts?


Because the designers want to remind us of the invisible underpinnings that hold up our houses,
buildings, bridges, and ourselves when we are on stilts. This excellent description of Struts
reflect the role the Struts plays in developing web applications.

Do we need to pay the Struts if being used in commercial purpose?


No. Struts is available for commercial use at no charge under the Apache Software License. You
can also integrate the Struts components into your own framework just as if they were written in
house without any red tape, fees, or other hassles.

What are the core classes of Struts?


Action, ActionForm, ActionServlet, ActionMapping, ActionForward are basic classes of Structs.

What is the design role played by Struts?


The role played by Structs is controller in Model/View/Controller(MVC) style. The View is
played by JSP and Model is played by JDBC or generic data source classes. The Struts controller
is a set of programmable components that allow developers to define exactly how the application
interacts with the user.

How Struts control data flow?


Struts implements the MVC/Layers pattern through the use of ActionForwards and
ActionMappings to keep control-flow decisions out of presentation layer.

What configuration files are used in Struts?


ApplicationResources.properties
struts-config.xml
These two files are used to bridge the gap between the Controller and the Model.

What helpers in the form of JSP pages are provided in Struts framework?
--struts-html.tld
--struts-bean.tld
--struts-logic.tld

Is Struts efficient?
The Struts is not only thread-safe but thread-dependent(instantiates each Action once and allows
other requests to be threaded through the original object.
ActionForm beans minimize subclass code and shorten subclass hierarchies
The Struts tag libraries provide general-purpose functionality
The Struts components are reusable by the application
The Struts localization strategies reduce the need for redundant JSPs
The Struts is designed with an open architecture--subclass available
The Struts is lightweight (5 core packages, 5 tag libraries)
The Struts is open source and well documented (code to be examined easily)
The Struts is model neutral

How you will enable front-end validation based on the xml in validation.xml?
The < html:javascript > tag to allow front-end validation based on the xml in validation.xml. For
example the code: < html:javascript formName=logonForm dynamicJavascript=true
staticJavascript=true / > generates the client side java script for the form logonForm as defined in
the validation.xml file. The < html:javascript > when added in the jsp file generates the client site
validation script.

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

How you will make available any Message Resources Definitions file to the Struts
Framework Environment?
Message Resources Definitions file are simple .properties files and these files contains the
messages that can be used in the struts project. Message Resources Definitions files can be added
to the struts-config.xml file through < message-resources / > tag. Example: < message-resources
parameter= MessageResources / >
Structs Interview Questions and Answers

What is Action Class?


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

Write code of any Action Class?


Here is the code of Action Class that returns the ActionForward object.
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class TestAction extends Action


{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
return mapping.findForward(\"testAction\");
}
}

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

What is Struts Validator Framework?


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

Give the Details of XML files used in Validator Framework?


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

Why do we need Struts?


Java technologies give developers a serious boost when creating and maintaining applications to
meet the demands of today's public Web sites and enterprise intranets. Struts combines Java
Servlets, Java ServerPages, custom tags, and message resources into a unified framework. The
end result is a cooperative, synergistic platform, suitable for development teams, independent
developers, and everyone in between.

How does Struts work?


Java Servlets are designed to handle requests made by Web browsers. Java ServerPages are
designed to create dynamic Web pages that can turn billboard sites into live applications. Struts
uses a special Servlet as a switchboard to route requests from Web browsers to the appropriate
ServerPage. This makes Web applications much easier to design, create, and maintain.

Is Struts compatible with other Java technologies?


Yes. Struts is committed to supporting industry standards. Struts acts as an integrator of Java
technologies so that they can be used in the "real world".

Who wrote Struts?


There are several active committers to the Struts project, working cooperatively from around the
globe. Dozens of individual developers and committers contributed to the Struts 1.x codebase.
All interested Java developers are invited to contribute to the project. Struts is a Apache Software
Foundation project, with the mission to "provide secure, enterprise-grade server solutions based
on the Java Platform that are developed in an open and cooperative fashion".
Struts was created by Craig R. McClanahan and donated to The Apache Software Foundation in
May 2000. Craig was the primary developer of both Struts 1.x and Tomcat 4. Tomcat 4 was the
basis for the official reference implementation for a servlet 2.3 and JSP 1.2 container.
Craig's current focus is as architect of the Sun Java Studio Creator (formerly Project Rave).
Craig also serves as the Specification Lead for JavaServer Faces (JSR-127), and is the Web
Layer Architect for the Java2 Enterprise Edition (J2EE) platform as a whole.
Structs Interview Questions and Answers

Why is it called Struts?


It's a reference to struts in the architectural sense, a reminder of the nearly invisible pieces that
hold up buildings, houses, and bridges.

Do I have to credit Struts on my own website?


You need to credit Struts if you redistribute your own framework based on Struts for other
people to use. (See the Apache License for details.) But you do not need to credit Struts just
because your web application utilizes the framework. It's the same situation as using the Apache
HTTPD server or Tomcat. Not required if its just running your web site.

Where can I get a copy of Struts?


The best place to download Struts is at struts.apache.org. The nightly builds are very stable, and
recommended as the best place to start today.

How do I install Struts?


To develop applications with Struts, you can usually just add the Struts JAR file to your Java
development environment. You can then start using the Struts classes as part of your own
application. A blank Struts application (in the webapps directory, open struts-blank.war) is
provided, which you can just copy to get a quick-start on your own brainchild.
Since the full source code for Struts is available, we also provide complete instructions for
compiling your own Struts JAR from scratch. (This is actually easier than it looks!)
Your Struts application can usually be deployed using a standard WAR file. In most cases, you
simply deposit the WAR file on your application server, and it is installed automatically. If not,
step-by-step installation instructions for various servlet containers are available.

When do I need "struts.jar" on my classpath?


When you are compiling an application that uses the Struts classes, you must have the "struts.jar"
on the classpath your compiler sees -- it does not have to be on your CLASSPATH environment
variable.
Why is that an important distinction? Because if you are using a servlet container on your
development machine to test your application, the "struts.jar" must not be on your CLASSPATH
environment variable when running the container. (This is because each Web application must
also have their own copy of the Struts classes, and the container will become confused if it is on
the environment path as well.)
There are several general approaches to this issue:
* Use ANT for building your projects -- it can easily assemble classpaths for the compiler. (This
is how Struts itself is built, along with Tomcat and most other Java-based projects).
* Use an IDE where you can configure the "class path" used for compilation independent of the
CLASSPATH environment variable.
* Use a shell script that temporarily adds struts.jar to the classpath just for compilation, for
example javac -classpath /path/to/struts.jar:$CLASSPATH $@

Does Struts include its own unit tests?


Struts currently has two testing environments, to reflect the fact that some things can be tested
statically, and some really need to be done in the environment of a running servlet container.
For static unit tests, we use the JUnit framework. The sources for these tests are in the "src/test"
hierarchy in the source repository, and are executed via the "test.junit" target in the top-level
build.xml file. Such tests are focused on the low-level functionality of individual methods, are
particularly suitable for the static methods in the org.apache.struts.util utility classes. In the test
hierarchy, there are also some "mock object" classes (in the org.apache.struts.mock package) so
that you can package up things that look like servlet API and Struts API objects to pass in as
arguments to such tests.
Another valuable tool is Struts TestCase which provides a useful harness for Action classes that
can be used with JUnit or Cactus.

If the framework doesn't do what I want, can I request that a feature be added?
First, it's important to remember that Struts is an all-volunteer project. We don't charge anyone
anything to use Struts. Committers and other developers work on Struts because they need to use
it with their own applications. If others can use it too, that's "icing on the cake". If you submit a
patch for a feature that a Committer finds useful, then that Committer may choose to volunteer
his or her time to apply the patch. If you just submit an idea without a patch, it is much less
likely to be added (since first someone else has to volunteer their time to write the patch).
We are grateful for any patches, and we welcome new ideas, but the best way to see that
something gets added to the framework is to do as much of the work as you can, rather than rely
on the "kindness of strangers". Worst case, you can apply the patch to your copy of Struts and
still use the feature in your own application. (Which is what open source is ~really~ all about.)

Where can I get help with Struts?


The Struts package comes complete with a Users Guide to introduce people to the framework
and its underlying technologies. Various components also have their own in-depth Developers
Guide, to cover more advanced topics. Comprehensive Javadocs are included along with the full
source code. For your convenience, these are bundled together as a self-installing application.
The struts-documentation.war is the same bundle that is deployed as the Struts Web site.
The Strut's mailing list is also very active, and welcomes posts from new users. Before posting a
new question, be sure to consult the MAILING LIST ARCHIVE and the very excellent How To
Ask Questions The Smart Way by Eric Raymond. Please do be sure to turn off HTML in your
email client before posting.

What's the difference between Struts and Turbine? What's the difference between Struts
and Espresso?
If you are starting from scratch, packages like Turbine and Espresso can be very helpful since
they try to provide all of the basic services that your team is likely to need. Such services include
things like data persistence and logging.
If you are not starting from scratch, and need to hook up your web application to an existing
infrastructure, then "plain vanilla" Struts can be a better choice. The core Struts framework does
not presuppose that you are using a given set of data persistence, presentation, or logging tools.
Anything goes =:0)
Compared to other offerings, Struts endeavors to be a minimalist framework. We try leverage
existing technologies whenever we can and provide only the missing pieces you need to combine
disparate technologies into a coherent application. This is great when you want to select your
own tools to use with Struts. But, if you prefer a more integrated infrastructure, then packages
like Turbine or Espresso (which uses Struts) are perfectly good ways to go.
See also
* < http://www.mail-archive.com/struts-user@jakarta.apache.org/msg03206.html >
* < http://www.mail-archive.com/general@jakarta.apache.org/msg00495.html >
* < http://jakarta.apache.org/velocity/ymtd/ymtd.html >

Structs Interview Questions and Answers

Why aren't the Struts tags maintained as part of the Jakarta Taglibs project ?
Development of both products began about the same time. Leading up to the release of 1.0, it
was thought better to continue to develop the taglibs alongside the controller. Now that 1.0 is
out, the JavaServer Pages Standard Taglib is in active development. Once work on JSTL
stabilizes, the Struts taglibs will be revisited. Tags which are not linked directly to the framework
may be hosted at Jakarta Taglibs instead.

Are the Struts tags XHTML compliant ?


If you use an <html:html xhtml="true> or <html:xhtml/> element on your page, the tags will
render as XHTML (since Struts 1.1).

Will the Struts tags support other markup languages such as WML ?
Struts itself is markup neutral. The original Struts taglibs are only one example of how
presentation layer components can access the framework. The framework objects are exposed
through the standard application, session, and request contexts, where any Java component in the
application can make use of them.
Markup extensions that use Struts are available for Velocity and XLST, among others. A new
Struts tag library for Java Server Faces is also in development.
For more about using WAP/WML with Struts see the article WAP up your EAserver.

What about JSTL and JavaServer Faces ?


JSTL, the JavaServer Standard Tag Library, is a set of JSP tags that are designed to make it
easier to develop Web applications. JavaServer Faces (JSF) is a specification for a new
technology that promises to make it easier to write MVC applications, both for the Web and for
the desktop.
The inventor of Struts, Craig McClanahan, is the specification co-lead for JavaServer Faces (JSR
127), and architect of the reference implemenation as well as Java Studio Creator. Both JSTL
and JSF are complementary to Struts.
The mainstay of the Struts framework is the controller components, which can be used with any
Java presentation technology. As new technologies become available, it is certain that new
"glue" components will also appear to help these technologies work as well with Struts.
Struts originally came bundled with a set of custom JSP tags. Today, several extensions are
available to help you use Struts with other popular presentation technologies, like XSLT and
Velocity. Likewise, extensions for JSTL and JSF are now available as well.
The JSTL reference implementation is available through the Jakarta Taglibs site. A JSTL taglibs
for Struts, Struts-El , is available and distributed with Struts beginning with the 1.1 release.
The JSF specification and reference implementation is available through Sun's The JSF
specification and reference implementation is available through Sun's Java ServerFaces page. An
early-release JavaServer Faces taglib for Struts, Struts-Faces, is also in early release and
available through the nightly build. The Struts Faces taglib is expected to work with any
compliant JSF implementation, including MyFaces.

Is there a particularly good IDE to use with Struts


Struts should work well with any development environment that you would like to use, as well as
with any programmers editor. The members of the Struts development team each use their own
tools such as Emacs, IDEA, Eclipse, and NetBeans.

Why was reload removed from Struts (since 1.1)?


The problem with ReloadAction was that Struts was trying to act like a container, but it couldn't
do a proper job of it. For example, you can't reload classes that have been modified, or (portably)
add new classes to a running web application (even if the container supported it).
Meanwhile, as Struts 1.1 was being developed, work progressed on things like Tomcat's reload
command via the Manager webapp. This feature allows you to quickly reload-on-demand,
complete with saving and restoring your session). It started to make even less sense for Struts to
half-implement a feature that containers are implementing fully.
A more minor point is that freezing the configuration information at application startup time
allows Struts to safely access the mapping information without bothering with synchronization.
The "startup-only" strategy creates a modest but real improvement in performance for all users.
So, ReloadAction is not supported since Struts 1.1 for two reasons:
* It never did let you reload everything that you would really want to -- particularly changed
classes -- so many people ended up having to reload the webapp anyway.
* Containers are starting to offer reload-on-demand features which does the same thing as the
Struts ReloadAction, only better.
* Not supporting ReloadAction lets Struts avoid doing synchronization locks around all the
lookups (like figuring out which action to use, or the destination of an ActionForward) so
applications can run a little faster.
Of course, if someone came up with an implementation that solved these problems without
creating any others, we would not be opposed to including a new ReloadAction.

What is a modular application? What does module-relative mean?


Since Struts 1.1, the framework supports multiple application modules. All applications have at
least one root, or default, module. Like the root directory in a file system, the default application
has no name. (Or is named with an empty string, depending your viewpoint.) Developing an
application with only a default module is no different from how applications were developed
under Struts 1.0. Since Struts 1.1, you can add additional modules to your application, each of
which can have their own configuration files, messages resources, and so forth. Each module is
developed in the same way as the default module. Applications that were developed as a single
module can added to a multiple module application, and modules can promoted to a standalone
application without change. For more about configuring your application to support multiple
modules, see Configuring Applications in the User Guide.
But to answer the question =:0), a modular application is a Struts application that uses more than
one module. Module-relative means that the URI starts at the module level, rather than at the
context level, or the absolute-URL level.
* Absolute URL: http://localhost/myApplication/myModule/myAction.do
* context-relative: /myModule/myAction.do
* module-relative: /myAction.do
The Struts Examples application is a modular application that was assembled from several
applications that were created independently.

Structs Interview Questions and Answers

Why are some of the class and element names counter-intuitive?


The framework grew in the telling and, as it evolved, some of the names drifted.
The good thing about a nightly build, is that everything becomes available to the community as
soon as it is written. The bad thing about a nightly build is that things like class names get locked
down early and then become difficult to change.

Why is ActionForm a base class rather than an interface?


The MVC design pattern is very simple to understand but much more difficult to live with. You
just need this little bit of Business Logic in the View logic or you need just that little bit of View
logic in the Business tier and pretty soon you have a real mess.
Making ActionForm a class takes advantage of the single inheritance restriction of Java to it
makes it more difficult for people to do things that they should not do.
ActionForms implemented as interfaces encourage making the property types match the
underlying business tier instead of Strings, which violates one of the primary purposes for
ActionForms in the first place (the ability to reproduce invalid input, which is a fundamental user
expectation). ActionForms as an interface would also encourage using existing DAO objects as
ActionForms by adding ‘implements ActionForm’ to the class. This violates the MVC
design pattern goal of separation of the view and business logic.
Since the goal of struts is to enforce this separation, it just makes more sense for Struts to own
the ActionForm.
DynaActionForms relieve developers of maintaining simple ActionForms. For near zero
maintenance, try Niall Pemberton's LazyActionForm

Do ActionForms have to be true JavaBeans?


The utilities that Struts uses (Commons-BeanUtils since 1.1) require that ActionForm properties
follow the JavaBean patterns for mutators and accessors (get*,set*,is*). Since Struts uses the
Introspection API with the ActionForms, some containers may require that all the JavaBean
patterns be followed, including declaring "implements Serializable" for each subclass. The safest
thing is to review the JavaBean specification and follow all the prescribed patterns.
Since Struts 1.1, you can also use DynaActionForms and mapped-backed forms, which are not
true JavaBeans. For more see ActionForm classes in the User Guide and Using Hashmaps with
ActionForms in this FAQ.

Can I use multiple HTML form elements with the same name?
Yes. Define the element as an array and Struts will autopopulate it like any other.
private String[] id= {};
public String[] getId() { return this.id; }
public void setItem(String id[]) {this.id = id;}
And so forth

Can I use multiple HTML form elements with the same name?
Yes. The issue is that only one action class can be associated with a single form. So the real issue
is how do I decode multiple submit types to a single Action class. There is more than one way to
achieve this functionality.
The way that is suggested by struts is right out of the javadoc for LookupDispatchAction .
Basically, LookupDispatchAction is using the keys from ApplicationProperties.resources as keys
to a map of actions available to your Action class. It uses reflection to decode the request and
invoke the proper action. It also takes advantage of the struts <html:submit> tags and is straight
forward to implement.
You can roll your own with JavaScript events and javascript:void
(document.forms["myform"].submit) on any html element. This gives you control of how you
want your page to look. Again you will have to decode the expected action in the execute method
of your action form if you choose this route.

Why doesn't the focus feature on the <html:form> tag work in every circumstance?
Unfortunately, there is some disagreement between the various browsers, and different versions
of the same browser, as to how the focus can be set. The <html:form> tag provides a quick and
easy JavaScript that will set the focus on a form for most versions of most browsers. If this
feature doesn't work for you, then you should set the focus using your own JavaScript. The focus
feature is a convenient "value-add" -- not a core requirement of the tag. If you do come up with a
JavaScript that provides the final solution to this project, please post your patch to this Bugzilla
ticket.

Why are my checkboxes not being set from ON to OFF?


A problem with a checkbox is that the browser will only include it in the request when it is
checked. If it is not checked, the HTML specification suggests that it not be sent (i.e. omitted
from the request). If the value of the checkbox is being persisted, either in a session bean or in
the model, a checked box can never unchecked by a HTML form -- because the form can never
send a signal to uncheck the box. The application must somehow ascertain that since the element
was not sent that the corresponding value is unchecked.
The recommended approach for Struts applications is to use the reset method in the ActionForm
to set all properties represented by checkboxes to null or false. The checked boxes submitted by
the form will then set those properties to true. The omitted properties will remain false. Another
solution is to use radio buttons instead, which always submit a value.
It is important to note that the HTML specification recommends this same behavior whenever a
control is not "successful". Any blank element in a HTML form is not guaranteed to submitted. It
is therefor very important to set the default values for an ActionForm correctly, and to implement
the reset method when the ActionForm might kept in session scope.

Can't I just create some of my JavaBeans in the JSP using a scriptlet?


Struts is designed to encourage a Model 2/MVC architecture. But there is nothing that prevents
you from using Model 1 techniques in your JavaServer Pages, so the answer to the question is
"Yes, you can".
Though, using Model 1 techniques in a Struts application does go against the grain. The
approach recommended by most Struts developers is to create and populate whatever objects the
view may need in the Action, and then forward these through the request. Some objects may also
be created and stored in the session or context, depending on how they are used.
Likewise, there is nothing to prevent you from using scriptlets along with JSP tags in your pages.
Though, many Struts developers report writing very complex scriplet-free applications and
recommend the JSP tag approach to others.
For help with Model 1 techniques and scriptlets, you might consider joining the Javasoft JSP-
interest mailing list, where there are more people still using these approaches.

Structs Interview Questions and Answers

Can I use JavaScript to submit a form?


You can submit a form with a link as below. BTW, the examples below assume you are in an
block and 'myForm' is picked up from the struts-config.xml name field of the action.
<a href='javascript:void(document.forms["myForm"].submit()>My Link</a>
Now the trick in the action is to decode what action you intend to perform. Since you are using
JavaScript, you could set a field value and look for it in the request or in the form.
... html/javascript part ...
<input type='hidden' value='myAction' />
<input type='button' value='Save Meeeee'
onclick='document.forms["myForm"].myAction.value="save";
document.forms["myForm"].submit();' />
<input type='button' value='Delete Meeeee'
onclick='document.forms["myForm"].myAction.value="delete";
document.forms["myForm"].submit();' />
... the java part ...
class MyAction extends ActionForm implements Serializable {

public ActionForward execute (ActionMapping map, ActionForm form,


HttpServletRequest req, HttpServletResponse) {

String myAction = req.getParameter("myAction");

if (myAction.equals("save") {
// ... save action ...
} else if (myAction.equals("delete") {
// ... delete action ...
}
}
}
}
This is just one of many ways to achieve submitting a form and decoding the intended action.
Once you get used to the framework you will find other ways that make more sense for your
coding style and requirements. Just remember this example is completely non-functional without
JavaScript.

How do I use JavaScript to ...


Struts is mainly a server-side technology. We bundled in some JSP tags to expose the framework
components to your presentation page, but past that, the usual development process applies.
Interactive pages require the use of JavaScript. (That's why it was invented.) If you want things
popping up or doing this when they click that, you are outside the scope of Struts and back into
the web development mainstream.
You use JavaScript with Struts the same way you use with any presentation page. Since
JavaScript is a client-side technology, you can use simple relative references to your scripts. If
you need to fire a JavaScript from a HTML control, the Struts HTML tags have properties for the
JavaScript events.
A very good JavaScript resource is Matt Kruse's site at http://www.mattkruse.com/javascript/ Do
I need to implement reset and set all my form properties to their initial values?
No. You need to set checkbox properties to false if the ActionForm is being retained in session
scope. This is because an unchecked box does not submit an attribute. Only checked boxes
submit attributes. If the form is in session scope, and the checkbox was checked, there is no way
to turn it back off without the reset method. Resetting the properties for other controls, or for a
request scope form, is pointless. If the form is in request scope, everything already just started at
the initial value.

Can I use other beans or hashmaps with ActionForms?


Yes. There are several ways that you can use other beans or hashmaps with ActionForms.
* ActionForms can have other beansor hashmaps as properties
* "Value Beans" or "Data Transfer Objects" (DTOs) can be used independently of ActionForms
to transfer data to the view
* ActionForms can use Maps to support "dynamic" properties (since Struts 1.1)
ActionForms (a.k.a. "form beans") are really just Java beans (with a few special methods) that
Struts creates and puts into session or request scope for you. There is nothing preventing you
from using other beans, or including them in your form beans. Here are some examples:
Collections as properties Suppose that you need to display a pulldown list of available colors on
an input form in your application. You can include a string-valued colorSelected property in your
ActionForm to represent the user's selection and a colorOptions property implemented as a
Collection (of strings) to store the available color choices. Assuming that you have defined the
getters and setters for the colorSelected and colorOptions properties in your orderEntryForm
form bean, you can render the pulldown list using:
<html:select property="colorSelected">
<html:options property="colorOptions" name="orderEntryForm"/>
</html:select>
The list will be populated using the strings in the colorOptions collection of the orderEntryForm
and the value that the user selects will go into the colorSelected property that gets posted to the
subsequent Action. Note that we are assuming here that the colorOptions property of the
orderEntryForm has already been set.
See How can I prepopulate a form? for instructions on how to set form bean properties before
rendering edit forms that expect properties to be pre-set.
Independent DTO An Action that retrieves a list of open orders (as an ArrayList of Order
objects) can use a DTO independently of any form bean to transfer search results to the view.
First, the Action's execute method performs the search and puts the DTO into the request:
ArrayList results = businessObject.executeSearch(searchParameters);
request.setAttribute("searchResults",results);
Then the view can iterate through the results using the "searchResults" request key to reference
the DTO:
` <logic:iterate id="order" name="searchResults" type="com.foo.bar.Order">
<tr><td><bean:write name="order" property="orderNumber"/><td>
<td>..other properties...</td></tr>
</logic:iterate>

How can I scroll through list of pages like the search results in google?
Many Struts developers use the Pager from the JSPTags site.
http://jsptags.com/tags/navigation/pager/

Structs Interview Questions and Answers

Why do the Struts tags provide for so little formatting?


The Struts tags seem to provide only the most rudimentary functionality. Why is there not better
support for date formatting and advanced string handling?
Three reasons:
First, work started on the JSTL and we didn't want to duplicate the effort.
Second, work started on Java Server Faces, and we didn't want to duplicate that effort either.
Third, in a Model 2 application, most of the formatting can be handled in the ActionForms (or in
the business tier), so all the tag has to do is spit out a string. This leads to better reuse since the
same "how to format" code does not need to be repeated in every instance. You can "say it once"
in a JavaBean and be done with it. Why don't the Struts taglibs offer more layout options?
Since the Struts tags are open source, you can extend them to provide whatever additional
formatting you may need. If you are interested in a pre-written taglib that offers more layout
options, see the struts-layout taglib.
In the same arena, there is a well regarded contributor taglib that can help you create Menus for
your Struts applications.

Why does the <html:link> tag URL-encode javascript and mailto links?
The <html:link> tag is not intended for use with client-side references like those used to launch
Javascripts or email clients. The purpose of link tag is to interject the context (or module) path
into the URI so that your server-side links are not dependent on your context (or module) name.
It also encodes the link, as needed, to maintain the client's session on the server. Neither feature
applies to client-side links, so there is no reason to use the <html:link> tag. Simply markup the
client-side links using the standard tag.

Why does the option tag render selected=selected instead of just selected?
Attribute minimization (that is, specifying an attribute with no value) is a place where HTML
violates standard XML syntax rules. This matters a lot for people writing to browsers that
support XHTML, where doing so makes the page invalid. It's much better for Struts to use the
expanded syntax, which works the same on existing browsers interpreting HTML, and newer
browsers that expect XHTML-compliant syntax. Struts is following the behavior recommended
by the XHTML specification

Do I have to use JSPs with my application?


The short answer to this question is: No, you are not limited to JavaServer Pages.
The longer answer is that you can use any type of presentation technology which can be returned
by a web server or Java container. The list includes but is not limited to:
* JavaServer Pages,
* HTML pages,
* WML files,
* Java servlets,
* Velocity templates, and
* XML/XLST
Some people even mix and match apparently unrelated technologies, like PHP, into the same
web application.

Do ActionForms have to be true JavaBeans?


ActionForms are added to a servlet scope (session or request) as beans. What this means is that,
for certain functionality to be available, your ActionForms will have to follow a few simple
rules.
First, your ActionForm bean must have a zero-arguments constructor. This is required because
Struts must be able to dynamically create new instances of your form bean class, while knowing
only the class name. This is not an onerous restriction, however, because Struts will also
populate your form bean's properties (from the request parameters) for you.
Second, the fields of your form bean are made available to the framework by supplying public
getter and setter methods that follow the naming design patterns described in the JavaBeans
Specification. For most users, that means using the following idiom for each of your form bean's
properties:
private {type} fieldName;
public {type} getFieldName() {
return (this.fieldName);
}

public void setFieldName({type} fieldName) {


this.fieldName = fieldName;
}
NOTE - you MUST obey the capitalization conventions shown above for your ActionForm
properties to be recognized. The property name in this example is "fieldName", and that must
also be the name of the input field that corresponds to this property. A bean property may have a
"getter" method and a "setter" method (in a form bean, it is typical to have both) whose name
starts with "get" or "set", followed by the property name with the first character capitalized. (For
boolean properties, it is also legal to use "is" instead of "get" as the prefix for the getter method.)
Advanced JavaBeans users will know that you can tell the system you want to use different
names for the getter and setter methods, by using a java.beans.BeanInfo class associated with
your form bean. Normally, however, it is much more convenient to follow the standard
conventions.
WARNING - developers might be tempted to use one of the following techniques, but any of
them will cause your property not to be recognized by the JavaBeans introspection facilities, and
therefore cause your applications to misbehave:
* Using getter and setter method names that do not match - if you have a getFoo() method for
your getter, but a setBar() method for your setter, Java will not recognize these methods as
referring to the same property. Instead, the language will think you have a read-only property
named "foo" and a write-only property named "bar".
* Using more than one setter method with the same name - The Java language lets you
"overload" methods, as long as the argument types are different. For example, you could have a
setStartDate(java.util.Date date) method and a setStartDate(String date) method in the same
class, and the compiled code would know which method to call based on the parameter type
being passed. However, doing this for form bean properties will prevent Java from recognizing
that you have a "startDate" property at all.
There are other rules to follow if you want other features of your form beans to be exposed.
These include indexed attributes and mapped attributes. They are covered in detail in other areas
of the Struts documentation, in particular: indexedprops.html

Structs Interview Questions and Answers

Do I have to have a separate ActionForm bean for every HTML form?


This is an interesting question. As a newbie, it is a good practice to create a new ActionForm for
each action sequence. You can use DynaActionForms to help reduce the effort required, or use
the code generation facilities of your IDE.
Some issues to keep in mind regarding reuse of form beans are as follows:
* Validation - You might need to use different validation rules depending upon the action that is
currently being executed.
* Persistence - Be careful that a form populated in one action is not unexpectedly reused in a
different action. Multiple entries in struts-config.xml for the same ActionForm subclass can help
(especially if you store your form beans in session scope). Alternatively, storing form beans in
request scope can avoid unexpected interactions (as well as reduce the memory footprint of your
application, because no server-side objects will need to be saved in between requests.
* Checkboxes - If you do as recommended and reset your boolean properties (for fields
presented as checkboxes), and the page you are currently displaying does not have a checkbox
for every boolean property on the form bean, the undisplayed boolean properties will always
appear to have a false value.
* Workflow - The most common need for form bean reuse is workflow. Out of the box, Struts
has limited support for workflow, but a common pattern is to use a single form bean with all of
the properties for all of the pages of a workflow. You will need a good understanding of the
environment (ActionForms, Actions, etc.) prior to being able to put together a smooth workflow
environment using a single form bean.
As you get more comfortable, there are a few shortcuts you can take in order to reuse your
ActionForm beans. Most of these shortcuts depend on how you have chosen to implement your
Action / ActionForm combinations.
How can I prepopulate a form?
The simplest way to prepopulate a form is to have an Action whose sole purpose is to populate
an ActionForm and forward to the servlet or JSP to render that form back to the client. A
separate Action would then be use to process the submitted form fields, by declaring an instance
of the same form bean name.
The struts-example example application that is shipped with Struts illustrates this design pattern
nicely. Note the following definitions from the struts-config.xml file:
...
<form-beans>
...
<-- Registration form bean -->
<form-bean name="registrationForm"
type="org.apache.struts.webapp.example.RegistrationForm"/>
...
</form-beans>
...
<action-mappings>
...
<-- Edit user registration -->
<action path="/editRegistration"
type="org.apache.struts.webapp.example.EditRegistrationAction"
name="registrationForm"
scope="request"
validate="false"/>
...
<-- Save user registration -->
<action path="/saveRegistration"
type="org.apache.struts.webapp.example.SaveRegistrationAction"
name="registrationForm"
input="registration"
scope="request"/>
...
</action-mappings>

Note the following features of this approach:


* Both the /editRegistration and /saveRegistration actions use the same form bean.
* When the /editRegistration action is entered, Struts will have pre-created an empty form bean
instance, and passed it to the execute() method. The setup action is free to preconfigure the
values that will be displayed when the form is rendered, simply by setting the corresponding
form bean properties.
* When the setup action completes configuring the properties of the form bean, it should return
an ActionForm that points at the page which will display this form. If you are using the Struts
JSP tag library, the action attribute on your <html:form> tag will be set to /saveRegistration in
order for the form to be submitted to the processing action.
* Note that the setup action (/editRegistration) turns off validation on the form that is being set
up. You will normally want to include this attribute in the configuration of your setup actions,
because you are not planning to actually process the results -- you simply want to take advantage
of the fact that Struts will precreate a form bean instance of the correct class for you.
* The processing action (/saveRegistration), on the other hand, leaves out the validate attribute,
which defaults to true. This tells Struts to perform the validations associated with this form bean
before invoking the processing action at all. If any validation errors have occurred, Struts will
forward back to your input page (technically, it forwards back to an ActionForward named
"registration" in this case, because the example webapp uses the inputForward attribute in the
element -- see the documentation describing struts-config.xml for more information) instead of
calling your processing action.

Can I have an Action without a form?


Yes. If your Action does not need any data and it does
not need to make any data available to the view or
controller component that it forwards to, it doesn't need
a form. A good example of an Action with no ActionForm is
the LogoffAction in the struts example application:

<action path="/logoff"
type="org.apache.struts.webapp.example.LogoffAction">
<forward name="success" path="/index.jsp"/>
</action>

This action needs no data other than the user's session, which
it can get from the Request, and it doesn't need to prepare any
view elements for display, so it does not need a form.

However, you cannot use the <html:form> tag without


an ActionForm. Even if you want to use the <html:form>
tag with a simple Action that does not require input,
the tag will expect you to use some type of ActionForm,
even if it is an empty subclass without any properties.

Structs Interview Questions and Answers

Can you give me a simple example of using the requiredif Validator rule?
First off, there's an even newer Validator rule called
validwhen, which is almost certainly what you want to use,
since it is much easier and more powerful.
It will be available in the first release after 1.1 ships.
The example shown below could be coded with validwhen as:
<form name="medicalStatusForm">

<field
property="pregnancyTest" depends="validwhen">
<arg0 key="medicalStatusForm.pregnancyTest.label"/>
<var>
<var-name>test</var-name>
<var-value>((((sex == 'm') OR (sex == 'M'))
AND (*this* == null)) OR (*this* != null))</test>
</var>
</field>

Let's assume you have a medical information form


with three fields,
sex, pregnancyTest, and testResult. If sex is 'f' or 'F',
pregnancyTest is required. If pregnancyTest is not blank,
testResult is required. The entry in your validation.xml
file would look like this:

<form name="medicalStatusForm">

<field
property="pregnancyTest" depends="requiredif">
<arg0 key="medicalStatusForm.pregnancyTest.label"/>
<var>
<var-name>field[0]</var-name>
<var-value>sex</var-value>
</var>
<var>
<var-name>fieldTest[0]</var-name>
<var-value>EQUAL</var-value>
</var>
<var>
<var-name>fieldValue[0]</var-name>
<var-value>F</var-value>
</var>
<var>
<var-name>field[1]</var-name>
<var-value>sex</var-value>
</var>
<var>
<var-name>fieldTest[1]</var-name>
<var-value>EQUAL</var-value>
</var>
<var>
<var-name>fieldValue[1]</var-name>
<var-value>f</var-value>
</var>
<var>
<var-name>fieldJoin</var-name>
<var-value>OR</var-value>
</var>
</field>

<field
property="testResult" depends="requiredif">
<arg0 key="medicalStatusForm.testResult.label"/>
<var>
<var-name>field[0]</var-name>
<var-value>pregnancyTest</var-value>
</var>
<var>
<var-name>fieldTest[0]</var-name>
<var-value>NOTNULL</var-value>
</var>
</field>
</form>

When is the best time to validate input?


This is an excellent question. Let's step back a second and think about a typical mid to large size
application. If we start from the back end and work toward the view we have:
1) Database: Most modern databases are going to validate for required fields, duplicate records,
security constraints, etc.
2) Business Logic: Here you are going to check for valid data relationships and things that make
sense for the particular problem you are triing to solve.
... This is where struts comes into the picture, by now the system should be pretty well
bulletproof. What we are going to do is make validation friendlier and informative. Rember it is
OK to have duplicate validations...
3) ActionErrors validate(ActionMapping map, HttpServletRequest req) is where you can do your
validation and feed back to the view, information required to correct any errors. validate is run
after the form has been reset and after the ActionForm properties have been set from
corresponding view based input. Also remember you can turn validation off with
validate="false" in the action mapping in the struts-config.xml. This is done by returning an
ActionErrors collection with messages from your ApplicationResources.properties file.
Here you have access to the request so you can see what kinds of action is being requested to
fine tune your validations. The <html:error> tag allows you to dump all errors on your page or a
particular error associated with a particular property. The input attribute of the struts-config.xml
action allows you to send validation errors to a particular jsp / html / tile page.
4) You can have the system perform low level validations and client side feedback using a
ValidatorForm or its derivatives. This will generate javascript and give instant feedback to the
user for simple data entry errors. You code your validations in the validator-rules.xml file. A
working knowledge of regular expressions is necessary to use this feature effectively.
Structs Interview Questions and Answers

How can I avoid validating a form before data is entered?


The simplest way is to have two actions. The first one has the job of setting the form data, i.e. a
blank registration screen. The second action in our writes the registration data to the database.
Struts would take care of invoking the validation and returning the user to the correct screen if
validation was not complete.
The EditRegistration action in the struts example application illustrates this:
< action path="/editRegistration">
type="org.apache.struts.webapp.example.EditRegistrationAction"
attribute="registrationForm"
scope="request"
validate="false">
<forward name="success path="/registration.jsp"/>
</action>
When the /editRegistration action is invoked, a registrationForm is created and added to the
request, but its validate method is not called. The default value of the validate attribute is true, so
if you do not want an action to trigger form validation, you need to remember to add this
attribute and set it to false.

How can I create a wizard workflow?


The basic idea is a series of actions with next, back, cancel and finish actions with a common
bean. Using a LookupDispatchAction is reccomended as it fits the design pattern well and can be
internationalized easily. Since the bean is shared, each choice made will add data to the wizards
base of information. A sample of struts-config.xml follows:

< form-beans>
<form-bean name="MyWizard"
type="forms.MyWizard" />
</form-beans>

<!-- the first screen of the wizard (next action only available) -->
<!-- no validation, since the finish action is not available -->
<actions>
<action path="/mywizard1"
type="actions.MyWizard"
name="MyWizard"
validate="false"
input="/WEB-INF/jsp/mywizard1.jsp">
<forward name="next"
path="/WEB-INF/jsp/mywizard2.jsp" />
<forward name="cancel"
path="/WEB-INF/jsp/mywizardcancel.jsp" />
</action>

<!-- the second screen of the wizard (back, next and finish) -->
<!-- since finish action is available, bean should validated, note
validation should not necessarily validate if back action requested, you
might delay validation or do conditional validation -->
<action path="/mywizard2"
type="actions.MyWizard"
name="MyWizard"
validate="true"
input="/WEB-INF/jsp/mywizard2.jsp">
<forward name="back"
path="/WEB-INF/jsp/mywizard1.jsp" />
<forward name="next"
path="/WEB-INF/jsp/mywizard3.jsp" />
<forward name="finish"
path="/WEB-INF/jsp/mywizarddone.jsp" />
<forward name="cancel"
path="/WEB-INF/jsp/mywizardcancel.jsp" />
</action>

<!-- the last screen of the wizard (back, finish and cancel only) -->
<action path="/mywizard3"
type="actions.MyWizard"
name="MyWizard"
validate="true"
input="/WEB-INF/jsp/mywizard3.jsp">
<forward name="back"
path="/WEB-INF/jsp/mywizard2.jsp" />
<forward name="finish"
path="/WEB-INF/jsp/mywizarddone.jsp" />
<forward name="cancel"
path="/WEB-INF/jsp/mywizardcancel.jsp" />
</action>

The pieces of the wizard are as follows:


forms.MyWizard.java - the form bean holding the information required
actions.MyWizard.java - the actions of the wizard, note the use of LookupDispatchAction allows
for one action class with several methods. All the real work will be done in the 'finish' method.
mywizard[x].jsp - the data collection jsp's
mywizarddone.jsp - the 'success' page
mywizardcancel.jsp - the 'cancel' page

What's the best way to deal with migrating a large application from Struts to JSF? Is there
any tool support that can help?
Answer: This is a complicated task depending on your Struts application. Because the two
frameworks have different goals, there are some challenges. Migrate your response pages first.
Keep the Struts controller and place and forward to JSF pages. Then you can configure Struts
forwards to go through the Faces servlet. Consider looking at the Struts-Faces framework from
Apache. See the framework chapter in JSF in Action.

Structs Interview Questions and Answers

How can I 'chain' Actions?


Chaining actions can be done by simply using the
proper mapping in your forward entries in the struts-config.xml file.
Assume you had the following two classes:

/* com/AAction.java */
...

public class AAction extends Action


{
public ActionForward
execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws
Exception
{
// Do something

return mapping.findForward("success");
}
}

/* com/BAction.java */
...

public class BAction extends Action


{
public ActionForward
execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws
Exception
{
// Do something else
return mapping.findForward("success");
}
}

Then you can chain together these two actions with


the Struts configuration as shown in the following excerpt:

...
<action-mappings type="org.apache.struts.action.ActionMapping">
<action path="/A"
type="com.AAction"
validate="false">
<forward name="success" path="/B.do" />
</action>
<action path="/B"
type="com.BAction"
scope="session"
validate="false">
<forward name="success" path="/result.jsp" />
</action>
</action-mappings>
...

Here we are assuming you are using a suffix-based (.do) servlet mapping, which is recommended
since module support requires it. When you send your browser to the web application and name
the action A.do (i.e. http://localhost:8080/app/A.do) it will execute AAction.execute(), which
will then forward to the "success" mapping.
This causes the execution of BAction.execute() since the entry for "success" in the configuration
file uses the .do suffix.
Of course it is also possible to chain actions programmatically, but the power and ease of being
able to "reroute" your web application's structure using the XML configuration file is much
easier to maintain.
As a rule, chaining Actions is not recommended. If your business classes are properly factored,
you should be able to call whatever methods you need from any Action, without splicing them
together into a cybernetic Rube Goldberg device.
If you must chain Actions, be aware of the following: calling the second Action from the first
Action has the same effect as calling the second Action from scratch. If both of your Actions
change the properties of a formbean, the changes made by the first Action will be lost because
Struts calls the reset() method on the formbean when the second Action is called.

Declarative Exception Handling


If you have developed web applications long enough, you will realize a recurring pattern
emerges: when the backend (e.g. the EJB tier) throws you an exception, you nearly always need
to display an error page corresponding to the type of that exception. Sooner or later, you will
come up with a mechanism to use a lookup table (e.g. an HashMap) to lookup an error page from
the exception class.
Struts 1.1 now provides a similar but more powerful mechanism to declare exception handling.
In Struts 1.1, you can declare in the struts-config.xml the associations between an exception class
and an exception handler. Using the default exception handler included in Struts, you can also
specify the path of the error pages. With this information, Struts will automatically forward to
the specified pages when an uncaught exception is thrown from an Action.
Like other facilities in Struts, the exception handlers are pluggable. You can write and define
your own handler classes if needed.

Structs Interview Questions and Answers

Struts GenericDataSource Just a general question - I'm building an application that will
run stand-alone, not in an application server. I need to manage some database connections.
Is the struts GenericDataSource a good candidate to do this for me? I basicly just need a
connection pool from where I can get connections and then return them to optimize
performance.
If this struts class is not a good candidate, can someone recommend a similar pool-manager
that is lean and mean and easy to use?
Answer 1
The Struts 1.0 GenericDataSource is not a good candidate for a production server. In Struts 1.1,
the Commons DBCP is used istead, which is a good candidate for a production server. (You can
also use the DBCP in Struts 1.0 by specifying the type and including the Commons JARs.)
Another popular choice is Poolman. It's not under active development, but I believe you can still
download it from SourceForge. Poolman is also very easy to use outside of Struts.
Many containers also offer support for connection pools. The one that ships with Resin is quite
good. The later versions of Tomcat bundle the Commons DBCP.
Regardless of what pool you use, a good practice is to hide it behind some type of adaptor class
of your own (often a singleton), to make it easy to change later. So your classes call your
adaptor, and your adaptor calls whichever pool you are using.
A neat and often-overlooked aspect of the Struts DataSource manager is that it supports loading
multiple connection pools and giving each a name. So you might have one pool for internal use
and another for public use. This way, the public connections can't swap your administrative
access to the application. Each pool could also have its own login, and therefore different rights
to the underlying database.
Answer 2

int i=1;

with Struts 1.0 and jdbc i'am use GenericDataSource


not in struts-xml, but in Client.properties

my Client.properties
instanceBd=oraID
userPasswd=xxx/yyyy
maxCount=20
minCount=19
port=1521
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@serverName:port:instanceBd

then, on my code i have init (struts 1.0 or struts 1.1):

GenericDataSource ng = new GenericDataSource ();

ng.setUser (mprop.getUserBd());
ng.setPassword (mprop.getPasswdBd());
ng.setUrl (mprop.getUrl());
ng.setDriverClass(mprop.getDriverClass());
ng.setMaxCount(mprop.getMaxCount());
ng.setMinCount (mprop.getMinCount());
ng.setDescription("jdbc OracleDriver");
ng.setAutoCommit(true);
try { ng.open(); } catch (java.sql.SQLException e) {
}

in business logic (or pool) :


Connect cn = ng.getConnection();

it's work.

with struts 1.1 , struts-legacy.jar is necessy for this codes.

it's work.

Dynamic pages using struts


Is it possible to create the elements of a page(jsp) dynamically based on the results of a data
base query, when using struts framework?
If you are talking about rendering a report, then sure. The Action iteracts with the business
layer/data access objects to acquire the data, and then passes it to the presentation page bundled
up as a JavaBean or a collection of JavaBeans. The JSP tags (and other systems) all use
reflection, so you can use whatever JavaBean you like.
If you are talking about creating a dynamic data-entry form, then "not so much".
Struts 1.1 supports map-backed ActionForms, but the page still needs to know what input fields
are going to be needed. For a truly dynamic input form, I guess the key would be some type of
tag that took a map and then generated a column of input fields. (Wouldn't work for everyone,
since a lot of forms must be designed just so.) For extra credit, the entry names could
(optionally) be resource keys that were used to find the label text.
Text fields would be easy. Others would need some type of JavaBean with properties to tell the
tag what to output. A bit of work, but obviously doable.
Of course, you'd probably want to validate the form before passing it back to the database. I
imagine it's possible to use the validator in a non-declarative way, but I don't know anyone
whose doing that. If you can do a db query to get the information about the form, I imagine you
could also do a query to get the information about validations for the form. It would probably be
easier to write your own engine than adopt the validator. (It's not really that complicated to do.)
People often ask about "dynamic input forms", but most of us just can't get our head around the
use case. It's hard to understand what you do with the dynamic data when it comes back. Most
application don't allow you to input or update an arbitrary (e.g. dynamic) set of fields.

Both JSF and Struts will continue to exist for a while. The Struts community is aware of
JSF and is positioning itself to have strong support for JSF. See What about JSTL and
JavaServer faces?
From a tools perspective, if you look at the support for JSF versus Struts in WebSphere Studio,
the Struts tools are focused around the controller aspects. The Web Diagram editor helps build
your Struts configuration and the wizards/editors build Struts artifacts. The JSF tools are geared
towards building pages, and in essence, hide the JSF framework from you. Expect WebSphere
Studio to support both frameworks for a while. As JSF matures, expect to see some of the
controller aspects in JSF to become toolable.

Structs Interview Questions and Answers

Can you compare the advantages and disadvantages of JSF vs. Struts. Both now, and from
what you may know of futures, how and if JSF will evolve into a superior technology vs.
Struts? Include how WSAD plays into the comparison if it will help differentiate the two.
This is a very popular question these days. In general, JSF is still fairly new and will take time to
fully mature. However, I see JSF being able to accomplish everything Struts can, plus more.
Struts evolved out of necessity. It was created by developers who were tired of coding the same
logic again and again. JSF emerged both from necessity and competition.
Struts has several benefits:
* Struts is a mature and proven framework. It has been around for a few years and deployed
successfully on many projects. The WebSphere Application Server admin console is a Struts
application.
* Struts uses the Front Controller and Command patterns and can handle sophisticated controller
logic.
* In addition to the core controller function, it has many add-on benefits such as layouts with
Tiles, declarative exception handling, and internationalization.

There are disadvantages:

* Struts is very JSP-centric and takes other frameworks to adapt to other view technologies.
* Although Struts has a rich tag library, it is still geared towards helping the controller aspect of
development and does not give a sense that you are dealing with components on a page.
Therefore, it is not as toolable from a view perspective.
* Struts requires knowledge of Java™. Its goal was to aid Java developers, but not to hide Java.
It does not hide details of the Java language to Web developers that well.
* ActionForms are linked programmatically to the Struts framework. Therefore, to decouple the
model, you need to write transfer code or use utilities to move data from Action Forms to the
Model on input.

JSF is an evolution of a few frameworks, including Struts. The creator of Struts, Craig
McClanahan, is one of the JSF specification leads. Therefore, it is not by accident to see some
overlap between Struts and JSF. However, one of JSF's major goals is to help J2EE Web
applications to be easily developed using RAD tools. As such, it introduces a rich component
model. JSF has several advantages:
* JSF is a specification from Sun® and will be included in future versions of the J2EE
specification. All major vendors are pledging strong support for JSF.
* JSF uses the Page Controller Pattern and therefore aids in Page rich applications. Components
can respond to event from components on a page.
* JSF has a well-defined request lifecycle allowing for plugability at different levels.
* One powerful example of plugability is building your own render toolkit. The ability to
separate the rendering portion from the controller portion of the framework allows for wonderful
opportunities of extensibility. Component providers can write their own toolkits to render
different markup languages, such as XML or WML. In addition, the render toolkit is not tied to
JSP.
* Because JSF has a rich component model, it favors a RAD style of development. I can now
build my Web pages using drag and drop technology. In addition, JSF gives me a way to link
visual components to back model components without breaking the layering.
JSF has disadvantages:
* JSF is still quite new and evolving. It will take some time to see successful deployments and
wide usage. In addition, as vendors write components, they may not do everything you want
them to.
* JSF by hand is not easier than Struts. Its goal was more oriented to RAD. Those who prefer to
do things by hand (for example, the vi type guy who does not like IDEs) may find Struts easier to
develop.
* Struts navigation may be a bit more flexible and adhere to more complex controller logic.

Multiple Sub-applications
One of the shortcomings in Struts 1.0 is manageability of the configuration file (commonly
known as struts-config.xml) when the development of the application involves a sizable team.
This problem arises because a Struts-based application must run under one controller servlet, the
ActionServlet, and the ActionServlet can use only one struts-config.xml. It is not an issue when
the project is relatively small and the team consists of a couple of developers; however, when the
project size becomes significant and the project involves a large number of developers,
maintaining all the mapping information in a single file becomes increasingly problematic.
Struts 1.1 solves this problem nicely by introducing multiple sub-applications. In Struts 1.1, each
sub-application has its own struts-config.xml file. A large Struts-based application can thus be
easily partitioned into largely independent modules, i.e. sub-applications, and each sub-team can
maintain their struts-config.xml independently.
The sub-application scheme is a natural extension of the servlet context mapping scheme of the
URI paths used by servlet containers. According to the Servlet standard, when the servlet
container receives a request with a URL, the servlet container will try to match the prefix of the
URI path to a deployed web-application in the container. What Struts 1.1 does is it maps the
second prefix of the path to a sub-application. In effect, this prefix mapping scheme creates
another level of namespace for each sub-application. For example, for the URI,
http://some-host.com/myApp/module2/editSubscription.do
/myApp is the context path for a web-application called "myApp" and /module2 is the sub-app
prefix for a Struts sub-application called "module2".

DynaBean and BeanUtils


Another major complaint usually heard amongst Struts 1.0 users is the extensive effort involved
in writing the FormBean (a.k.a. ActionForm) classes.
Struts provides two-way automatic population between HTML forms and Java objects, the
FormBeans. To take advantage of this however, you have to write one FormBean per HTML
form. (In some use cases, a FormBean can actually be shared between multiple HTML forms.
But those are specific cases.) Struts' FormBean standard follows faithfully the verbose JavaBean
standard to define and access properties. Besides, to encourage a maintainable architecture,
Struts enforces a pattern such that it is very difficult to 'reuse' a model-layer object (e.g. a
ValueObject from the EJB tier) as a FormBean. Combining all these factors, a developer has to
spend a significant amount of time to write tedious getters/setters for all the FormBean classes.
Struts 1.1 offers an alternative, Dynamic ActionForms, which are based on DynaBeans. Simply
put, DynaBeans are type-safe name-value pairs (think HashMaps) but behave like normal
JavaBeans with the help of the BeanUtils library. (Both the DynaBeans and the BeanUtils library
were found to be useful and generic enough that they have been 'promoted' into Jakarta's
Commons project.) With Dynamic ActionForms, instead of coding the tedious setters/getters,
developers can declare the required properties in the struts-config.xml files. Struts will instantiate
and initialize Dynamic ActionForm objects with the appropriate metadata. From then onwards,
The Dynamic ActionForm instance is treated as if it is an ordinary JavaBean by Struts and the
BeanUtils library.

Structs Interview Questions and Answers

Validator
The Validator is not exactly a new feature. The Validator has been in the contrib package in the
distribution since Struts 1.0.1. Since then, part of it has now been refactored and moved into the
Jakarta-Commons subproject and renamed the Commons-Validator and the Struts specific
portion is now called the Struts-Validator. However, since it is in the contrib package, people
may overlook it and it is worthwhile to mention it here.
The Validator provides an extensible framework to define validation rules to validate user inputs
in forms. What is appealing in the Validator is that it generates both the server-side validation
code and the client-side validation code (i.e. Javascript) from the same set of validation rules
defined in an XML configuration file. The Validator performs the validation based on regular-
expression pattern matching. While a handful of commonly used validators are shipped with the
framework (e.g. date validator, range validator), you can always define your own ones to suit
your need.
Default Sub-application
To maintain backward compatibility, Struts 1.1 allows one default sub-application per
application. The URI of the resources (i.e. JSPs, HTMLs, etc) in the default sub-application will
have an empty sub-app prefix. This means when an existing 1.0 application is "dropped" into
Struts 1.1, theoretically, it will automatically become the default sub-application.

Direct Requests to JSPs


To take the full advantage of sub-application support, Struts 1.1 stipulates the requirement that
all requests must flow through the controller servlet, i.e. the ActionServlet. Effectively, this
means all JSPs must be fronted by Actions. Instead of allowing direct requests to any of the
JSPs, all requests must go through an Action and let the Action forward to the appropriate JSP.
This is perhaps the biggest impact of migration to Struts 1.1 if you have not followed this idiom
in your applications. This restriction is required because without going through the
ActionServlet, Struts navigation taglibs (e.g. <html:form> and <html:link>) used in the JSPs will
not have the correct sub-app context to work with.

ActionServlet Configurations
With the introduction of sub-applications, a more flexible way is introduced to configure each
sub-application independently. Many of the configuration entries (e.g. resource bundle location,
maximum upload file size, etc) that used to be defined in web.xml have now been moved to
struts-config.xml. The original entries in web.xml are deprecated but will still be effective.

Action.execute() and Action.getResources()


In Struts 1.0, request handling logic is coded in Action.perform(); however, Action.perform()
throws only IOException and SevletException. To facilitate the new declarative exception
handling , the request handling method needs to throw Exception, the superclass of all the
checked exceptions. Therefore, to both maintain backward compatibility and facilitate
declarative exception handling, Action.perform() is now deprecated in favour of
Action.execute().
You also have to be careful if you use DispatchAction in your existing applications. At the time
of writing, the DispatchAction in Struts 1.1 beta has not yet been updated to use execute(). (A
bug report has been filed in Struts' bug database.) Therefore, without modifying the
DispatchAction class yourself, declarative exception handling will not work with DispatchAction
subclasses.
In addition, Action.getResources() is now deprecated. Instead, you should call
Action.getResources(HttpServletRequest) instead. This allows Struts to return to you the sub-
application specific message resources. Otherwise, the message resources for the default sub-app
will be used.

Library Dependency
Struts 1.1 now depends on a handful of libraries from other Jakarta subprojects (e.g. Commons-
Logging, Commons-Collections, etc.). Some of these libraries may cause classloading conflicts
in some servlet containers. So far, people have reported in the mailing list the classloading
problem of commons-digester/jaxp1.1, and commons-logging causing deployment difficulties in
Struts 1.1 applications running on Weblogic 6.0. (The problems have been corrected in Weblogic
6.1 and 7.0.)

Resources under WEB-INF


According to the Servlet specification, resources (e.g. JSP files) stored under WEB-INF are
protected and cannot be accessed directly by the browsers. One design idiom for Struts 1.0 is to
put all the JSP files under WEB-INF and front them by Actions so that clients cannot illegally
access the JSPs. With the introduction of sub-application prefixes in Struts 1.1, mapping
resources under WEB-INF gets complicated. Extra configuration steps utilizing the pagePattern
and forwardPattern attributes of the element in struts-config.xml is required to inform Struts to
construct the paths correctly. More specifically, you need to set these attributes to the pattern
"/WEB-INF/$A$P".

What is the Jakarta Struts Framework?


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

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

How can one make any “Message Resources” definitions file available to the “Struts
Framework” environment?
Answer: “Message Resources” definitions file are simple .properties files and
these files contain the messages that can be used in the struts project.
“Message Resources” definition files can be added to the struts-config.xml file
through <message-resources /> tag. Example:
<message-resources parameter="MessageResources" />

Structs Interview Questions and Answers

What is an “Action Class”?


The “Action Class” is part of the “Model” and is a wrapper around the business logic.

The purpose of the “Action Class” is to translate the HttpServletRequest to the business logic.
To use the “Action”, we need to subclass and overwrite the execute() method.

All the database and business processing is done in the “Action” class.

It is advisable to perform all the database related work in the “Action” class.

The ActionServlet (command) passes the parameterized class to ActionForm 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 according to the value of the returned ActionForward object.

Write code of any Action Class?


Here is the code of Action Class that returns the ActionForward object.

package j2eeonline.jdj.com;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class TestAction extends Action{

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest


request,
HttpServletResponse response) throws Exception{
return mapping.findForward("testAction");
}
}

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

What is Struts Validator Framework?


The “Struts Framework” provides the functionality to validate the form data.
It can be used to validate the data in the user’s browser as well as on the server side.
Struts Framework checks the JavaScript code and it can be used to validate the form data on the
client browser.

Server side validation of form data can be accomplished by subclassing your “form” Bean with
DynaValidatorForm class.

The “Validator” framework was developed by David Winterfeldt as a third-party “add-on” to


Struts.
Now the Validator framework is part of the “Jakarta Commons” project and it can be used with
or without Struts.

The Validator framework comes integrated with the Struts Framework and
can be used without any making any additional settings.

Describe the details of XML files used in the “Validator Framework”?


The Validator Framework uses two XML configuration files

1) validator-rules.xml and

2) validation.xml.

The validator-rules.xml defines the standard validation routines.

These are reusable and used in validation.xml to define the form specific validations.

The validation.xml defines the validations applied to a form bean.

How would you display “validation fail” errors on a JSP page?


Following tag displays all the errors:
<html:errors/>

How can one enable front-end validation based on the xml in validation.xml?
The
<html:javascript>
tag allows front-end validation based on the xml in validation.xml.

For example the code:

generates the client side JavaScript for the form "logonForm" as defined in the validation.xml
file.
The <html:javascript> when added in the JSP file generates the client side validation script.

Question: How can i tell what state a thread is in ?

Answer: Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive()
returned false the thread was either new or terminated but there was simply no way to
differentiate between the two.

Starting with the release of Tiger (Java 5) you can now get what state a thread is in by using the
getState() method which returns an Enum of Thread.States. A thread can only be in one of the
following states at a given point in time.

NEW A Fresh thread that has not yet started to execute.


RUNNABLE A thread that is executing in the Java virtual machine.
BLOCKED A thread that is blocked waiting for a monitor lock.
WAITING A thread that is wating to be notified by another thread.
A thread that is wating to be notified by another thread for a specific amount
TIMED_WAITING
of time
TERMINATED A thread whos run method has ended.
The folowing code prints out all thread states. public class ThreadStates{ public static void
main(String[] args){ Thread t = new Thread(); Thread.State e = t.getState(); Thread.State[] ts =
e.values(); for(int i = 0; i < ts.length; i++){ System.out.println(ts[i]); } } }

Question: What methods java providing for Thread communications ?

Answer: Java provides three methods that threads can use to communicate with each other: wait,
notify, and notifyAll. These methods are defined for all Objects (not just Threads). The idea is
that a method called by a thread may need to wait for some condition to be satisfied by another
thread; in that case, it can call the wait method, which causes its thread to wait until another
thread calls notify or notifyAll.

Question: What is the difference between notify and notify All methods ?

Answer: A call to notify causes at most one thread waiting on the same object to be notified
(i.e., the object that calls notify must be the same as the object that called wait). A call to
notifyAll causes all threads waiting on the same object to be notified. If more than one thread is
waiting on that object, there is no way to control which of them is notified by a call to notify (so
it is often better to use notifyAll than notify).

Question: What is synchronized keyword? In what situations you will Use it?

Answer: Synchronization is the act of serializing access to critical sections of code. We will use
this keyword when we expect multiple threads to access/modify the same data. To understand
synchronization

we need to look into thread execution manner.

Threads may execute in a manner where their paths of execution are completely independent of
each other. Neither thread depends upon the other for assistance. For example, one thread might
execute a print job, while a second thread repaints a window. And then there are threads that
require synchronization, the act of serializing access to critical sections of code, at various
moments during their executions. For example, say that two threads need to send data packets
over a single network connection. Each thread must be able to send its entire data packet
before the other thread starts sending its data packet; otherwise, the data is scrambled. This
scenario requires each thread to synchronize its access to the code that does the actual data-
packet sending.

If you feel a method is very critical for business that needs to be executed by only one thread at a
time (to prevent data loss or corruption), then we need to use synchronized keyword.

EXAMPLE

Some real-world tasks are better modeled by a program that uses threads than by a normal,
sequential program. For example, consider a bank whose accounts can be accessed and updated
by any of a number of automatic teller machines (ATMs). Each ATM could be a separate thread,
responding to deposit and withdrawal requests from different users simultaneously. Of course, it
would be important to make sure that two users did not access the same account simultaneously.
This is done in Java using synchronization, which can be applied to individual methods, or to
sequences of statements.

One or more methods of a class can be declared to be synchronized. When a thread calls an
object's synchronized method, the whole object is locked. This means that if another thread tries
to call any synchronized method of the same object, the call will block until the lock is released
(which happens when the original call finishes). In general, if the value of a field of an object can
be changed, then all methods that read or write that field should be synchronized to prevent two
threads from trying to write the field at the same time, and to prevent one thread from reading the
field while another thread is in the process of writing it.

Here is an example of a BankAccount class that uses synchronized methods to ensure that
deposits and withdrawals cannot be performed simultaneously, and to ensure that the account
balance cannot be read while either a deposit or a withdrawal is in progress. (To keep the
example simple, no check is done to ensure that a withdrawal does not lead to a negative
balance.)
public class BankAccount { private double balance; // constructor: set balance to given amount
public BankAccount( double initialDeposit ) { balance = initialDeposit; } public synchronized
double Balance( ) { return balance; } public synchronized void Deposit( double deposit ) {
balance += deposit; } public synchronized void Withdraw( double withdrawal ) { balance -=
withdrawal; } }

Note: that the BankAccount's constructor is not declared to be synchronized. That is because it
can only be executed when the object is being created, and no other method can be called until
that creation is finished.

There are cases where we need to synchronize a group of statements, we can do that using
synchrozed statement.

Java Code Example synchronized ( B ) { if ( D > B.Balance() ) { ReportInsuffucientFunds(); }


else { B.Withdraw( D ); } }

Threads

Question: Where does java thread support reside

Answer: It resides in three places


The java.lang.Thread class (Most of the support resides here)
The java.lang.Object class
The java language and virtual machine

Question: What is the difference between Thread and a Process

Answer: Threads run inside process and they share data.


One process can have multiple threads, if the process is killed all the threads inside it are killed,
they dont share data

Question: What happens when you call the start() method of the thread

Answer: This registers the thread with a piece of system code called thread scheduler
The schedulers determines which thread is actually running

Question: Does calling start () method of the thread causes it to run

Answer: No it merely makes it eligible to run. The thread still has to wait for the CPU time
along with the other threads, then at some time in future, the scheduler will permit the thread to
run

Question: When the thread gets to execute, what does it execute

Answer: The thread executes a method call run(). It can execute run() method of either of the
two choices given below :
The thread can execute it own run() method.
The thread can execute the run() method of some other objects
For the first case you need to subclass the Thread class and give your subclass a run() method
For the second method you need to have a class implement the interface runnable. Define your
run method. Pass this object as an argument to the Thread constructor

Question: How many methods are declared in the interface runnable

Answer: The runnable method declares only one method :


public void run();

Question: Which way would you prefer to implement threading , by extending Thread
class or implementing Runnable interface

Answer: The preferred way will be to use Interface Runnable, because by subclassing the
Thread class you have single inheritance i.e you wont be able to extend any other class

Question: What happens when the run() method returns


Answer: When the run() method returns, the thread has finished its task and is considered dead.
You can't restart a dead thread. You can call the methods of dead thread

Question: What are the different states of the thread

Answer: They are as follows:

Running: The state that all thread aspire to be


Various waiting states : Waiting, Sleeping, Suspended and Bloacked
Ready : Waiting only for the CPU
Dead : All done

Question: What is Thread priority

Answer: Every thread has a priority, the higher priorit thread gets preference over the lower
priority thread by the thread scheduler

Question: What is the range of priority integer

Answer: It is from 1 to 10. 10 beings the highest priority and 1 being the lowest

Question: What is the default priority of the thread

Answer: The default priority is 5

Question: What happens when you call Thread.yield()

Answer: It caused the currently executing thread to move to the ready state if the scheduler is
willing to run any other thread in place of the yielding thread. Yield is a static method of class
Thread

Question: What is the advantage of yielding

Answer: It allows a time consuming thread to permit other threads to execute

Question: What happens when you call Thread.sleep()

Answer: It passes time without doing anything and without using the CPU. A call to sleep
method requests the currently executing thread to cease executing for a specified amount of time.

Question: Does the thread method start executing as soon as the sleep time is over

Answer: No, after the specified time is over the thread enters into ready state and will only
execute when the scheduler allows it to do so.
Question: What do you mean by thread blocking

Answer: If a method needs to wait an indeterminable amount of time until some I/O occurrence
takes place, then a thread executing that method should graciously step out of the Running state.
All java I/O methods behave this way. A thread that has graciously stepped out in this way is
said to be blocked.

Question: What threading related methods are there in object class

Answer: wait(), notify() and notifyAll() are all part of Object class and they have to be called
from synchronized code only

Question: What is preemptive scheduling

Answer: In preemptive scheduling there are only two ways for the thread to leave the running
state without ecplicitly calling wait() or suspended() It can cease t be ready to execute ()by
calling a blocking I/O method). It can get moved out by CPU by a higher priorit thread that
becomes ready to execute

Question: What is non-preemptive or Time sliced or round robin scheduling

Answer: With time slicing the thread is allowd to execute for a limited amount of time. It is then
moved to ready state, where it must contend with all the other ready threads.

Question: What are the two ways of synchronizing the code

Answer: Synchronizing an entire method by putting the synchronized modifier in the methods
declaration. To execute the method, a thread must acquire the lock of the object that owns the
method.

Synchronize a subset of a method by surrounding the desired lines of code with curly brackets
and inserting the synchronized expression before the opening curly. This allows you to
synchronize the block on the lock of any object at all, not necessarily the object that owns the
code

Question: What happens when the wait() method is called

Answer: The calling thread gives up CPU


The calling thread gives up the lock
The calling thread goes into the monitor's waiting pool

Question: What happens when the notify() method is called

Answer: One thread gets moved out of monitors waiting pool and into the ready state
The thread that was notified ust reacquire the monitors locl before it can proceed
Question: Using notify () method how you can specify which thread should be notified

Answer: You cannot specify which thread is to be notified, hence it is always better to call
notifyAll() method

Question: What invokes a thread's run() method?

Answer: After a thread is started, via its start() method or that of the Thread class, the JVM
invokes the thread's run() method when the thread is initially executed.

Question: What is the difference between the Boolean & operator and the && operator?

Answer: If an expression involving the Boolean & operator is evaluated, both operands are
evaluated. Then the & operator is applied to the operand. When an expression involving the &&
operator is evaluated, the first operand is evaluated. If the first operand returns a value of true
then the second operand is evaluated. The && operator is then applied to the first and second
operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.

Question: Name three subclasses of the Component class.

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

Question: What is the GregorianCalendar class?

Answer: The GregorianCalendar provides support for traditional Western calendars.

Question: Which Container method is used to cause a container to be laid out and
redisplayed?

Answer: validate()

Question: What is the purpose of the Runtime class?

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

Question: How many times may an object's finalize() method be invoked by the garbage
collector?

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

Question: What is the purpose of the finally clause of a try-catch-finally statement?

Answer: The finally clause is used to provide the capability to execute code no matter whether
or not an exception is thrown or caught.
Question: What is the argument type of a program's main() method?

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

Question: Which Java operator is right associative?

Answer: The = operator is right associative.

Question: What is the Locale class?

Answer: The Locale class is used to tailor program output to the conventions of a particular
geographic, political, or cultural region.

Question: Can a double value be cast to a byte?

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

Question: What is the difference between a break statement and a continue statement?

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

Question: What must a class do to implement an interface?

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

Question: What method is invoked to cause an object to begin executing as a separate


thread?

Answer: The start() method of the Thread class is invoked to cause an object to begin executing
as a separate thread.

Question: Name two subclasses of the TextComponent class.

Answer: TextField and TextArea

Question: What is the advantage of the event-delegation model over the earlier event-
inheritance model?

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.

Question: What is a transient variable?

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

Question: Which containers use a border Layout as their default layout?

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

Question: Why do threads block on I/O?

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

Question: How are Observer and Observable used?

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

Question: What is synchronization and why is it important?

Answer: With respect to multithreading, synchronization is the capability to control the access
of multiple threads to shared resources. Without synchronization, it is possible for one thread to
modify a shared object while another thread is in the process of using or updating that object's
value. This often leads to significant errors.

Question: Can a lock be acquired on a class?

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

Question: What's new with the stop(), suspend() and resume() methods in JDK 1.2?

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

Question: Is null a keyword?

Answer: The null value is not a keyword.

Question: What is the preferred size of a component?


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

Question: What method is used to specify a container's layout?

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

Question: Which containers use a FlowLayout as their default layout?

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

Question: What state does a thread enter when it terminates its processing?

Answer: When a thread terminates its processing, it enters the dead state.

Question: What is the Collections API?

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

Question: Which characters may be used as the second character of an identifier, but not
as the first character of an identifier?

Answer: The digits 0 through 9 may not be used as the first character of an identifier but they
may be used after the first character of an identifier.

Question: What is the List interface?

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

Question: How does Java handle integer overflows and underflows?

Answer: It uses those low order bytes of the result that can fit into the size of the type allowed
by the operation.

Question: What is the Vector class?

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

Question: What modifiers may be used with an inner class that is a member of an outer
class?

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

Question: What are the uses of Serialization?


Answer: In some types of applications you have to write the code to serialize objects, but in
many cases serialization is performed behind the scenes by various server-side containers.

These are some of the typical uses of serialization:

To persist data for future use.


To send data to a remote computer using such client/server Java technologies as RMI
or socket programming.
To "flatten" an object into array of bytes in memory.
To exchange data between applets and servlets.
To store user session in Web applications .
To activate/passivate enterprise java beans.
To send objects between the servers in a cluster.

Question: what is a collection ?

Answer: Collection is a group of objects. java.util package provides important types of


collections. There are two fundamental types of collections they are Collection and Map.
Collection types hold a group of objects, Eg. Lists and Sets where as Map types hold group of
objects as key, value pairs Eg. HashMap and Hashtable.

Question: For concatenation of strings, which method is good, StringBuffer or String ?

Answer: StringBuffer is faster than String for concatenation.

Question: What is Runnable interface ? Are there any other ways to make a java program as
multithred java program?

Answer: There are two ways to create new kinds of threads:

- Define a new class that extends the Thread class


- Define a new class that implements the Runnable interface, and pass an object of that class to a
Thread's constructor.
- An advantage of the second approach is that the new class can be a subclass of any class, not
just of the Thread class.

Here is a very simple example just to illustrate how to use the second approach to creating
threads: class myThread implements Runnable { public void run() { System.out.println("I'm
running!"); } } public class tstRunnable { public static void main(String[] args) { myThread my1
= new myThread(); myThread my2 = new myThread(); new Thread(my1).start(); new
Thread(my2).start(); }

Question: How can i tell what state a thread is in ?

Answer: Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive()
returned false the thread was either new or terminated but there was simply no way to
differentiate between the two.

Starting with the release of Tiger (Java 5) you can now get what state a thread is in by using the
getState() method which returns an Enum of Thread.States. A thread can only be in one of the
following states at a given point in time.

NEW A Fresh thread that has not yet started to execute.


RUNNABLE A thread that is executing in the Java virtual machine.
BLOCKED A thread that is blocked waiting for a monitor lock.
WAITING A thread that is wating to be notified by another thread.
A thread that is wating to be notified by another thread for a specific amount
TIMED_WAITING
of time
TERMINATED A thread whos run method has ended.

The folowing code prints out all thread states. public class ThreadStates{ public static void
main(String[] args){ Thread t = new Thread(); Thread.State e = t.getState(); Thread.State[] ts =
e.values(); for(int i = 0; i < ts.length; i++){ System.out.println(ts[i]); } } }

Question: What methods java providing for Thread communications ?

Answer: Java provides three methods that threads can use to communicate with each other: wait,
notify, and notifyAll. These methods are defined for all Objects (not just Threads). The idea is
that a method called by a thread may need to wait for some condition to be satisfied by another
thread; in that case, it can call the wait method, which causes its thread to wait until another
thread calls notify or notifyAll.

Question: What is serialization ?

Answer: Serialization is the process of writing complete state of java object into output stream,
that stream can be file or byte array or stream associated with TCP/IP socket.

Question: What does the Serializable interface do ?

Answer: Serializable is a tagging interface; it prescribes no methods. It serves to assign the


Serializable data type to the tagged class and to identify the class as one which the developer
has designed for persistence. ObjectOutputStream serializes only those objects which implement
this interface.

Question: How do I serialize an object to a file ?

Answer: To serialize an object into a stream perform the following actions:

- Open one of the output streams, for exxample FileOutputStream


- Chain it with the ObjectOutputStream <
- Call the method writeObject() providinng the instance of a Serializable object as an argument.
- Close the streams

Java Code --------- try{ fOut= new FileOutputStream("c:\\emp.ser"); out = new


ObjectOutputStream(fOut); out.writeObject(employee); //serializing System.out.println("An
employee is serialized into c:\\emp.ser"); } catch(IOException e){ e.printStackTrace(); }

Question: How do I deserilaize an Object?

Answer: To deserialize an object, perform the following steps:

- Open an input stream


- Chain it with the ObjectInputStream - Call the method readObject() and cast the returned object
to the class that is being deserialized.
- Close the streams

Java Code try{ fIn= new FileInputStream("c:\\emp.ser"); in = new ObjectInputStream(fIn); //de-


serializing employee Employee emp = (Employee) in.readObject();
System.out.println("Deserialized " + emp.fName + " " + emp.lName + " from emp.ser ");
}catch(IOException e){ e.printStackTrace(); }catch(ClassNotFoundException e){
e.printStackTrace(); }

Question: What is Externalizable Interface ?

Answer: Externalizable interface is a subclass of Serializable. Java provides Externalizable


interface that gives you more control over what is being serialized and it can produce smaller
object footprint. ( You can serialize whatever field values you want to serialize)

This interface defines 2 methods: readExternal() and writeExternal() and you have to implement
these methods in the class that will be serialized. In these methods you'll have to write code that
reads/writes only the values of the attributes you are interested in. Programs that perform
serialization and deserialization have to write and read these attributes in the same sequence.