Академический Документы
Профессиональный Документы
Культура Документы
Answer: When i want child class to implement the behavior of the 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.
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.
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.
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 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.
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.
Answer: An object is subject to garbage collection when it becomes unreachable to the program
in which it is used.
Question: What methods are used to get and set the text label displayed by a Button
object?
Answer: Canvas
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.
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.
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.
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.
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 ?
(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
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
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
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.
Answer: A native method is a method that is implemented in a language other than Java.
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
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.
Answer: The CheckboxMenuItem class extends the MenuItem class to support a menu item that
may be checked or unchecked.
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.
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.
Answer: An anonymous class may implement an interface or extend a superclass, but may not
be declared to do both.
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.
Answer: MenuItem
Answer: The purpose of finalization is to give an unreachable object the opportunity to perform
any cleanup processing before the object is garbage collected.
Answer: Object
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.
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.
Answer: A public class may be accessed outside of its package. A non-public class may not be
accessed outside of its package.
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: 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.
Answer: getState()
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
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
Answer:
Assignment
Method call
Arithmetic promotion
Question: What are the rules for primitive assignment and method call conversion
Answer:
Question: What are the rules for primitive arithmetic promotion conversion
Answer:
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.
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
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:
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.
Method overloading
Method overriding through inheritance
Method overriding through the Java interface
Public
Protected
Private
Defaults
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 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{
}
Answer: A reachable object cannot be garbage collected. Only unreachable objects may be
garbage collected..
Answer: It is written x ? y : z.
Question: What is the difference between the Font and FontMetrics classes?
Answer: The fractional part of the result is truncated. This is known as rounding toward zero.
Question: What is the difference between the Reader/Writer class hierarchy and
the InputStream/OutputStream class hierarchy?
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.
Answer: The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys
with values.
Answer: A class does not inherit constructors from any of its superclasses.
Answer: The only statements for which it makes sense to use a label are those statements that
can enclose a break or continue statement.
Answer: The purpose of the System class is to provide access to system resources.
Answer: setEditable()
Answer: The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.
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: 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
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
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:
Answer: This indicates that the method throws some exception and the caller method should
take care of handling it
Answer: Runtime exceptions are due to programming bugs like out of bond arrays or null
pointer exceptions.
Answer: Errors are usually compile time and exceptions can be runtime or checked
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: 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:
Answer: The elements of a GridBad layout are of equal size and are laid out using the squares of
a grid.
Answer: Once an object is garbage collected, it ceases to exist.It can no longer become
reachable again.
Answer: The Set interface provides methods for accessing the elements of a finite mathematical
set. Sets do not allow duplicate elements.
Answer: A throw statement may throw any expression that may be assigned to the Throwable
type.
Answer: E is the base of the natural logarithm and PI is mathematical value pi.
Answer: A void return type indicates that a method does not return a value.
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.
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: 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.
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.
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.
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 - 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 } } );
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.
Question: What is Runnable interface ? Are there any other ways to make a java program as
multithred java program?
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:
Question: What types of values does boolean variables take It only takes values true and
false. Which primitive datatypes are signed.
Answer: decimal, octal and hexadecimal, hence example it can be 28, 034 and 0x1c respectively
Answer: False
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
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
Answer: No
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
Answer: No, shift operators can be applied only to integer or long types
Question: What happens to the bits that fall off after shifting
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?
Question: Can an inner class declared inside of a method access local variables of this
method?
Question: What can go wrong if you replace && with & in the following code: String
a=null; if (a!=null && a.length()>10) {...}
Answer: Java
Answer: This method is used to ensure that Swing components are updated through the event-
dispatching thread.
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?
Question: What comes to mind when someone mentions a shallow copy in Java?
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?
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 .
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.
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.
Answer: The EventObject class and the EventListener interface support event processing.
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).
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.
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.
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.
Answer: Window
In the J2EE applications modules can be deployed as stand-alone units. Modules can also be
assembled into J2EE applications.
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.
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:
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 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.
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.
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" />
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;
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. 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:
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.
Answer: You can't force GC, but could request it by calling System.gc(). JVM does not
guarantee that GC will be started immediately.
Answer: If you assign a superclass object to a variable of a subclass's data type, you need to do
explicit casting. For example:
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: 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: 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?
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.
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. 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.
A. It’s both. Ajax is a set of technologies being used together in a particular way.
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.
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).
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. 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:
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?
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.
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.
Ajax Q&A
Mastering Ajax
What is Ajax
Application Server
Ajax Interview Questions
Cross-Domain Ajax
Web 2.0
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.
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.
Answer: The String literal "abc" is not a primitive value. It is a String object.
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.
Answer: The java.util.EventObject class is the highest-level class in the event-delegation class
hierarchy.
Answer: The ActionEvent event is generated as the result of the clicking of a button.
Answer: A component can handle its own events by implementing the required event-listener
interface and adding itself as its own event listener.
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.
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.
Answer: The Collection interface provides support for the implementation of a mathematical
bag - an unordered collection of objects that may contain duplicates.
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
Answer: String is an immutable class, i.e you cannot change the values of that class
Example:
Answer: It will return false as you cannot compare String with StringBuffer
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.
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
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
Answer: Vector methods are synchronized while ArrayList methods are not
Answer: Iterator is an interface which is used to step through the elements of a Collection
Answer: Hashtable does not store null value, while HashMap does
Hashtable is synchronized, while HashMap is not
<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.
<HTML>
<HEAD><TITLE>RESULT PAGE</TITLE></HEAD>
<BODY>
<%
%>
</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
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
<html>
<body>
<%!
int cnt=0;
private int getCount(){
//increment cnt and return the value
cnt++;
return cnt;
}
%>
<p><%=getCount()%></p>
</body>
</html>
The Context Parameters page lets you manage parameters that are accessed through the
ServletContext.getInitParameterNames and ServletContext.getInitParameter methods.
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" %>.
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.
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.
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: 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: A private variable may only be accessed within the class in which it is declared.
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.
Answer: The Dictionary class provides the capability to store key-value pairs.
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
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?
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
Answer: Serialization means storing a state of a java object by coverting it to byte stream
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
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
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
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
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
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.
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: Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule
Answer: Parsers are used for processing XML documents. There are 2 types of parsers DOM
parser and SAX 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
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
Answer:
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
Answer: No the reference cannot be change, but the data in that object can be changed
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:
Answer: Abstract class must be subclassed and final class cannot be subclassed
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
Question: When are the non static variables loaded into the memory
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
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
Answer: A transient variable is not stored as part of objects persistent state and they cannot be
final or static
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.
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
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
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.
Answer: No java does not support virtual functions direclty like in C++, but it supports using
Abstract class and interfaces
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.
Answer: The purpose of the system class is to provide the access to the System reources
Answer: It is used to if an object can be cast into a specific type without throwing Class cast
exception
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
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: 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
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
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.
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.
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)
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
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
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: An inner class is same as any other class, but is declared inside some other class
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
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
Answer: Some classes defined inside a method do not need a name, such classes are called
anonymous classes
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
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.
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.
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
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 ?
(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
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
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
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
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
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 - 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 } } );
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.
Answer: The File class is used to create objects that provide access to the files and directories of
a local file system.
Question: Which Math method is used to calculate the absolute value of a number?
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.
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.
Answer: Component
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: The non-Unicode letter characters $ and _ may appear as the first character of an
identifier
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.
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.
?
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>
b) Harder to learn
Struts are harder to learn, benchmark and optimize.
<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.
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).
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.
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>
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
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
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.
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.
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.
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.
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
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).
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.
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.
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 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.
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.)
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 >
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.
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.
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.
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 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/
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
<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.
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>
<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>
< 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>
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.
/* com/AAction.java */
...
return mapping.findForward("success");
}
}
/* com/BAction.java */
...
...
<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.
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;
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
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) {
}
it's work.
it's work.
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.
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.
* 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".
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.
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.
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.)
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" />
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.
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{
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.
Server side validation of form data can be accomplished by subclassing your “form” Bean with
DynaValidatorForm class.
The Validator framework comes integrated with the Struts Framework and
can be used without any making any additional settings.
1) validator-rules.xml and
2) validation.xml.
These are reusable and used in validation.xml to define the form specific validations.
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.
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.
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.
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
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.
Threads
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
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
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: 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
Answer: Every thread has a priority, the higher priorit thread gets preference over the lower
priority thread by the thread scheduler
Answer: It is from 1 to 10. 10 beings the highest priority and 1 being the lowest
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
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.
Answer: wait(), notify() and notifyAll() are all part of Object class and they have to be called
from synchronized code only
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
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.
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
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
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.
Answer: Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or
TextComponent
Question: Which Container method is used to cause a container to be laid out and
redisplayed?
Answer: validate()
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.
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: The Locale class is used to tailor program output to the conventions of a particular
geographic, political, or cultural region.
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.
Answer: It must provide all of the methods in the interface and identify the interface in its
implements clause.
Answer: The start() method of the Thread class is invoked to cause an object to begin executing
as a separate thread.
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.
Answer: The window, Frame and Dialog classes use a border layout as their default layout.
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.
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.
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.
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.
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.
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.
Answer: The List interface provides support for ordered collections of objects.
Answer: It uses those low order bytes of the result that can fit into the size of the type allowed
by the operation.
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 is Runnable interface ? Are there any other ways to make a java program as
multithred java program?
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(); }
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.
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]); } } }
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.
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.
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.