Академический Документы
Профессиональный Документы
Культура Документы
1.The volatile keyword is used on variables that may be modified simultaneously by other threads. This
warns the compiler to fetch them fresh each time, rather than caching them in registers. This also inhibits
certain optimisations that assume no other thread will change the values unexpectedly. Since other threads
cannot see local variables, there is never any need to mark local variables volatile.
2.During execution, compiled code might cache the values of fields for efficiency reasons. Since multiple
threads can access the same field, it is vital that caching is not allowed to cause inconsistencies when
reading and writing the value in the field. The volatile modifier can be used to inform the compiler that it
should not attempt to perform optimizations on the field, which could cause unpredictable results when the
field is accessed by multiple threads.In the simple example that follows, the value of the field clockReading
might be changed unexpectedly by another thread while one thread is performing a task that involves
always using the current value of the field clockReading. Declaring the field as volatile ensures that a write
operation will always be performed on the master field variable, and a read operation will always return the
correct current value.class VitalControl { // ... volatile long clockReading; // Two successive reads might give
different results.
1.Run time polimorphism means function call is resolved at run time.It means which function code will
execute in response to a perticular function call is not known till execution of program.ex- Funtion overriding.
Compile time polimorphism means function call is resolved at compile time.It means which function code will
execute in response to a perticular function call is known to compiler at compile time.example- Function
overloading
2.Compile time polymorphism: In this the linking between method call & method definition takes place at
compile time.It means at compile time only, compiler decides where to jump to execute the method body.
Run time polymorphism: In this the linking between method call & method definition takes place
at execution time.It means at run time , Java virtual machine(In case of Java) decides where to jump to
execute the method body.
Runtime polymorphism means overriding using inheritance - (same method name, same parameter list,
same return type, same or higher visibility, same or less or child exceptions (may add runtime exceptions))
Compile-time polymorphism means Overloading (- same method name, different parameter list)
java support above three consepts but in "inheritance" java does not support multiple inheritance.
== compare : the object address. where as equals : compare the value of object.but exceptional case is
string.but in case of String object suppose.
String s1 = "nirav";
String s2 = "nirav";
if(s1.equals(s2))
it returns "true"; and s1 == s2 also retrun "true";
where as
String s1 = new String("nirav");
String s2 = new String("nirav");
second condition :
if (s1.equals(s2)) it return "true" but s1 == s2 return "false".
the difrence between one and two is :according to first codition java automatically refer the same address,
address that before used to assing some value. (java use pretend word for first codition)while in second
condition : java enforce to create a new object (using new).thats diffrence that you have to notice.
A framework is essentialy a set of classes and/or interfaces of reusable code that has been
designed and developed for some specific bussiness requirement. The collection is said to
be a framework just because it contains the core logic for implementing what we say
Data Structure.
A synchronized block is a thread safe block which means it cant be accessed by more than one object at a
time. It is accessed by objects in a queue on a priority basis.So it can be used to make data integrity.
While a normal block can be accessed by any no of objects at a time. Data Integrity cant be made with this.
Singleton Design pattern helps us to have only one instance of a class in the entire JVM(for a class-loader)
and provides global one-point access to it.
1.
Iterator :--- Iterator takes the place of Enumeration in the Java collections framework. One can traverse
throughr the the collection with the help of iterator in forward direction only and Iterators allow the caller to
remove elements from the underlying collection during the iteration with well-defined semantics
ListIterator:--An iterator for lists that allows one to traverse the list in either direction.modify the list during
iteration, and obtain the iterator's current position in the list. A ListIterator has no current element. its
cursor position always lies between the element that would be returned by a call to previous() and the
element that would be returned by a call to next(). In a list of length n, there are n+1 valid index values,
from 0 to n, inclusive.
13. in Execption handling What is exactly difference between throws and throw?
'Throws' is used while defining a method to indicate the exceptions that can be thrown by that method.
'Throw' is used to throw an exception.
14. Why default constructor of base class will be called first in java?
whenever v create an object of child class ,automatically an obj of parent class is also created,with this what
i mean is that data members of base class also accessible ,provided access specifier permits.
When obj of child class is created its constructor is called ,form which base class constructor is called and
then cursor returns to child class constructor
ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for
example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is
contained within the ServletConfig object, which the Web server provides the servlet when the servlet is
initialized
ServletConfig: The object created after a servlet is instantiated and its default
constructor is read. It is created to pass initialization information to the servlet.
Prepare statement is precompiled by the database for faster execution while callable statement is used to
execute stored procedure in database
prepared statement is compiled only once and executed many times with different parameters avoiding
delay of compilation for every retrival (execution).In prepared statements the date formats and number
formats are taken care of. Also it takes care if we have a string with apostrophe,which otherwise needs to be
escaped everytime.
Callable statement is used for SQL statements already built inside database (PL/SQL procedures etc.)
which are permanently precompiled in database.
collction framework reduces the programming effort while increasing the performance.
Collection framework provides set of classes and interfaces to work with group of objects. The collection
framework mainly provieds three interface classes Set, List, and Map. Set's Implementation are HashSet,
TreeSet and LinkedHashSet. ArrayList and LinkedList implement List interface. HashMap, TreeMap and
LinkedHashMap implement Map.
When we need to instantiate the class at the time of declaration, we can use anonymous class. There will
not any constructor of anonymous class be provided since the class has NO name.
20. Tell me the differences between enumeration and iteration?Which can use where in
realtime?
Enumeration and Iterator both are interfaces present in util package. Enumeration is a legacy interface
which does not come under the collection framework, wheras Iterator is an interface present in the collection
framework. All the legacy classes like Stack, Vector , Hashtable, Properties can use Enumeration for
enumerating the elements from the collection. The classes under the collection framework like ArrayList,
LinkedList, HashSet ,Tree Set etc can use the Iterator interface
Enumerator and Iterator are almost same.But in Iterator there is one extra method called "remove".and
iterator is part of the new collection class.Java API says to use more of iterator than Enumerator which is
kind of old class.
21. what are the other ways to prevent a class from being subclassed.one way is to
declare the class final.
does declaring a class private prevent it from being subclassed?
As per ur question, yes we prevent a class to be subclass by making class as final, bt also if we make the
constructor of that class private then also we cant inherite that class or cant subclass that class
22. Why there is no guarentee for System.gc() method will perform garbage collection
for a particular time?
Becuase it depends on the heapsize settings/memory aallocation for the objects to reside once the memory
is full the gc is called.
The garbage collection thread is looking at what percentage of available memory is already allocated..and if
the memory allocation goes above a perticular level..say 80 %, the gc thread is invoced to claim back any
unused memory, so that efficiency is not hompered when a memory request is made by an application
thread.
Further if there is enough memory laying free...there is no need for the gc thread to look for memory...the
same cycles can be used by some other thread.....efficiency considerations of the java design
23. What is the difference between interrupt() and join() in threads?Give an example
program?
interrupt() throw an interrupt if the thread is blocked.join() waits for a thread to terminate.
Interupt is the method on the thread to distrub or interupt on the other thread which are under execution.
Where as the join method is used to say t.join() is to suspend the current thread operation for a time being
and go to the other thread and return back after completing the other task.
t.join();
t.join(200);//here the current thread is suspended for a 200msec,with in this time u have to return back after
completing the task.
String is immutable means that : Say s = "hello" would point to certain location , say location 1234h in
memory.Now if we modify s = "world" , then s will point to a new location in memory, i.e 2314h(say).Thats
the reason String is considered to be immutable, one cannot change contents in same meory location.Acc to
this question, String s1 is just appended with s.So it doesnt necessarily show that s1 is mutated
immutable means un-changeable
So String s = "Hello";
means s is refering to some memory location where you have value ("Hello")
so now s will refer to new memory location where new value of s stored ("Hello World") and old memory
location is not free yet (wasted) until garbage collected.
Classpath: The CLASSPATH is an environment variable that tells the Java compiler javac.exe where to look
for class files to import or java.exe where to find class files to interpret.
Path: The PATH is an environment variable that tells the command processor where to look for executable
files, e.g. *.exe, *.com and *.bat files.
26. If we have two public classes in a single java file ,how i have to give the name of
the particular java file and how i can compile it?
As per the Java convention and guide lines every class declared as public must be defined individually in a
single file. If we have two public classes then we need to have to separate files for them. We can not put
them in a single Java file. If you try to put also, you will see syntax error.
27. How single threaded model works after implementation in class, basically
architecture point of view.
The Single Thread Model is an interface which is used to indicate that only a single thread will execute the
service( ) method of a servlet at a given time. It defines no constants and declares no methods. If a servlet
implements this interface, the server has only two options. 1st, it can creat several instances of the servlet.
2nd, it can synchronized access to the servlet.
28. WHEN UR USING ARRAYLIST AND LIKEDLIST AND VECTOR AND HASHMAP AND
HASHTABLE?
ArrayList contains objects in any order while with LinkList objects are stored in the order which you entered,
but both are not thread safe.
You normally use ArrayList to keep a list when you only insert at the end. ArrayList is not synchronized but it
is the fastest. A Vector do the same thing as the ArrayList but it is synchronized and a little slower.
You use a LinkedList when you need to insert an element at the middle of the list. A LinkedList is
not synchronized.
A HashMap is the same as Hashtable as you hash the list for ease of extraction. Hashtable is synchronized
while HashMap is not.
29. Can wehave run() method directly without start() method in threads?
Tthe start() method performs some other actions before calling the run() method. Due to these startup
processes a separate thread is created, i.e. a different path of execution is created and on this path run() is
executed.If we call run() directly, no separate thread will be created and it is just like calling any other
method of the class which will be executed in the same thread.ThanksGautam
30. when programmer using the vector and arrylist? and when ur using linkedlist and
hashmap and hashtable?
ArrayList is not Synchronized. Hence in multithreaded programming use ArrayList While Vector is
Synchronized. So if we have a Banking ATM transaction where u dont want 2 people to access the same
account at the same time in 2 different m/c use Vector.
Both Vector and ArrayList are implemented using Arrays and both are collections whose data can be
accessed by using an index. Both are essentially the same except that a Vector is synchronized and an
ArrayList is not.
31. What is JVM Heap Size? How does it affect the performance of the Application
The heap is the runtime data area from which memory for all class instances and arrays is allocated. The
heap may be of a fixed size or may be expanded. The heap is created on virtual machine start-up. If you
have complicated algorithms or big caching which might create lot of objects in memory you may need
bigger heap size.
32. we know that Object class is super class of every class & a class extends only one
class. so
how is it possible to a class to extend other than Object class?
case 1
suppose you have a class Test, which doesn't extend any other class. So by default, Object becomes it's
super class.
Object->Test
case 2
If your Test class wants to extend some other class, for example Hashtable, your class will become a sub
class of Object through Hashtable because Hashtable is a subclass of Object. Any class you are trying to
extend will be a subclass of Object directly or due to hierarchy.
Object->Map->Hashtable->Test
Object is the superclass of Test even when you have Test extend HahTable
so no matter you extend a class or not, your class will always be a subclass of Object.
34. if interface & abstract class have same methods & abstract class also not contain
any implementation for those methods which one you prefer ?
Obviously one should ideally go for an interface.Coz as we all know one can only extend just 1 class , where
as one can implement as many interfaces as one can.And in case the class under contention has got some
threads to invoke or if it is some JFrame kind of class then obviously it would make sense to use the
interface.
This class implements the set interface, backed by a hash table (actually a HashMap instance). It makes no
guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain
constant over time. This class permits the Null element.
This class offers constant time performance for the basic operations (add, remove, contains and
size), assuming the hash function disperses the elements properly among the buckets. Iterating over this
set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the
"capacity" of the backing HashMap instance (the number of buckets). Thus, it's very important not to set the
initial capacity too high (or the load factor too low) if iteration performance is important
supporting multiple inheritance in java is tedious b'case if u defined a method with the same signature in the
two super classes when u invoke that method by using the sub class object it leads confusion to which super
class method to invoke
If there will be multiple base classes,then the class which is extending from those base classes will be in
ambiguity problem,this problem is named as Diamond problem.That's why Java doesn't support multiple
inheritance.
We can create a new class including the properties of the previous class without destroying it.This is
possible through inheritance only.
B'coz Servlets and JSP's are based on Client-Server architecture,and in this Server has to receive the
request of the client through its Service() method and this is only the main method in Servlet \JSP(J2EE
applications
object :means when memory location is associated with the object( is a runtime entity of the class) by using
the new operator
interface is a set of abstract methods, all of which have to be overriden by the class whichever implements
the interface
abstract class is a collection of data and methods which are abstact (not all of them)
38. What is the difference between String and StringBuffer? Which is better to use in
project?
String buffer is a mutable string object. String is a non - mutable object. When we say mutable
means which can be changed anytime. Its better to string buffer if we want to modify a string from
multiple threads(Some places synchronization is required).
When a String is created, it is not destroyed. It remains in the pool of memory and whenever that string is
referred, the JVM searches for the String from the string pool of memory and gets the relevant data. So as
such String is expensive operation.
String buffer can be changed/modified based on our requirement. There are chances that you may need to
form a query based on some conditions. Such queries can be formed using String buffer. Finally you can
user the toString method to get the final String version of the stringBuffer
Native threads can switch between threads pre-emptively, switching control from a running thread to a non-
running thread at any time. Green threads only switch when control is explicitly given up by a thread
(Thread.yield(), Object.wait(), etc.) or a thread performs a blocking operation (read(), etc.). On multi-CPU
machines, native threads can run more than one thread simultaneously by assigning different threads to
different CPUs. Green threads run on only one CPU. Native threads create the appearance that many Java
processes are running: each thread takes up its own entry in the process table. One clue that these are all
threads of the same process is that the memory size is identical for all the threads - they are all using the
same memory. Unfortunately, this behavior limits the scalability of Java on Linux. The process table is not
infinitely large, and processes can only create a limited number of threads before running out of system
resources or hitting configured limits.
Daemon thread is a kind of threads: normally it will run forever, but when all other non-daemon threads are
dead, daemon thread will be killed by JVM
When the class is loaded into the memory first of all the static block is executed.
static blocks are loaded when the jvm loads the class for the first time........
Static variable are loaded when classloader brings the class to the JVM. It is not neccessary that an object
has to be created. When u access any of the static variable or static methods then the class will be loaded.
Static variables are loaded at the beginning of the class loading. Static
variables will be allocated memory space when they have been loaded.
constructors are designed for initialising objects of a perticular "class".Here class means the class which
contains the constructor.
If a class extends other class,then the base class contains constructor for initialising objects of the
base class.if any constructor is not provided by base class a default constructor will be provided.Then what
is the need to inherit the constructor from the base class.
43. How many threads will be created for a java program, when it is compail & run?
and what are they?
There are atleast three thread created when we compile& run one program. first one is Main
thread,second one which handels Garbage collector & third one is , In programs that use the AWT, there's
also a screen updater thread. Anshuman chhotray(orissa,India
while using ejb, ejb container provides some services like persistence,transaction,security etc implicitly it
doesn't require coding.
1) class .forName
2) new keyword
3) class method
4) newInstance method
ArrayList is faster than Vector, because ArrayList is not synchronized. Synchronization will reduce the
performance of Vector.
static keyword ,means only one copy per class if u have a static block or static method it will run first then
only other statements like constructor will run . it dosen't need an object to access its method .Though u can
access it using object u can access it using class nameso using object is eliminated.
A method if needed to handled independent of any objects then it should be declred as static. static block is
executed before main method. we can aceess static method by classname.ex.Integer.ParseInt is a static
method
48. What is the difference between an object and an instance? And give me a real time
example to differentiate these two?
the key diff between an object and an instance is that in real time synanyo is that--------i
think u know about "blueprint" (plans) which is used for house construction.think this as
an a "instance" and implementation of this plan is nothing but "object" ok bye
50. how do i upload a file from client side to server side using servlet and jsp this will
happen when I click upload button on web-page?
51. )what are the other ways to create an object otherthan creating as new object?
int, float etc are primitives not objects so that part is ruled out.
Date d= Date.getInstance();
Serialization works by converting the object to be saved into a stream of bytes and writing it to a disk or a
fille.
ObjectOutputStream makes an object so that it can be converted as bytes and then it coonects to another
stream FileOutputStream which makes bytes toi be wriiten to file.
Encapsulation:wrappering up the data and associated methods into a single unit in such a way that data
can be accessed with the help of associated methods.
a method be static and synchronized . here the lock is acquired on the class it self instead of synchronized
block(entire class will be under monitor)
56. How would you pass a java integer by reference to another function
U can pass int, as a refrence through integer wrapper class. But still ur purpose not solved through this to
change the value of actual integer variable. If u want to get changes through function then u have to use Int
handler.
58. can we declare multiple main() methods in multiple classes.ie can we have each
main method in its class in our program?
Yaa u can declare multiple main methods in different classes, this wont through any error while complition ,
but it through u runtime exception stating that no main method found.So there should be only one main
method in a program
In java the Objects are passed by reference But internally it is pass by value.
primitive data is directly pass by value
60. Will there be a performance penalty if you make a method synchronized? If so, can
you make any design changes to improve the performance
Performance does take a hit when using synchronization. I think the way to reduce this hit is to synchronize
only a block of code that will be accessed by threads and not synchronize the entire method.
61. What are the different kinds of exceptions? How do you catch a Runtime exception
Checked exception is catched at the compile time while unchecked exception is checked at run time.
If a programmer really wants to explicitly request a garbage collection at some point, System.gc() or
Runtime.gc() can be invoked, which will fire off a garbage collection at that time
we can use system.gc() or runtime.gc() method to garbage collect but note one point that its not sure that it
will garbage collect the object Better assign Null to unused objects
This class is an generic implementation of a thread pool, which takes the following input
a) Size of the pool to be constructed
b) Name of the class which implements Runnable (which has a visible default constructor)
and constructs a thread pool with active threads that are waiting for activation. once the threads have
finished processing they come back and wait once again in the pool.
This thread pool engine can be locked i.e. if some internal operation is performed on the pool then it is
preferable that the thread engine be locked. Locking ensures that no new threads are issued by the engine.
However, the currently executing threads are allowed to continue till they come back to the passivePool
64. Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is
this the OS heap or the heap maintained by the JVM? Why
yes the JVM maitain a cache by itself.No it allocates the objects in stack ,in heap on references .Heap
maintained by the JVM because
every time the JVM should not use objects directly it uses only references that's why the heap maintained by
the JVM
yes the JVM maitain a cache by itself.No it allocates the objects in stack ,in heap on references
Suppose, you have a class named UserInformation . And with that class you are having a object instance
named UserContactInfo
Class UserInformation {
UserContactInfo userContactInfo ;
This leads to aggregation. The UserContactInfo object is aggreated within UserInformation class. Both the
classes have individual identity.
Now , suppose we have a class named Rectangle . And within that class you have Class Point as a object.
Class Rectangle {
Point point ;
}
Now , rectangle is a composition of points. Point class doesn't have any individual important . It is point that
makes a rectangle . This is known as composition.
""static methods are called when u don't want to instantiate"".but that is not the "main" use of static in this
case.static is used when u want to define a variable or a method that is shared by all objects of a class. but
the purpose of the constructor is to initialise a "PERTICULAR" object.and the purpose of static is to share
the information across all the objects.here we are getting conflict.so we can not use static to a constructor.
67. The real time environment , when do we go for abstract class and when do we go
for interfaces , can any one please revert back in this regard?
Interface is the one which can be implemented by many number of methods in different classes as it
requires, so there may be a chance that u may have some functionality which wil be need for many methods
, in that case u u use interface to declare
Abstract class is the one which can implement more than one of this kind of interfaces but only the conditon
is that all of its methods sud be implemented in the subclasses
Yes, We can serialize the Static data also.For this we use the Externalizable tagged interface anduse
writeObject() is used.Otherwise if we implement the Serializable interface if we serialize the data then static
variable value is stored as zero.So instead of this we use Externalizable interface.
Abstraction is mapping real world entity with s/w entity. By writing a class we can implement abstraction.
While Encapsulation is encapsulating all properties with in the class.Using getter, setter methods we can
implement encapsulation.
encapsulationIt is process of enclosing or wrapping of data and functions with the help of classes is known
as encapsulation. Encapsulation provide security to your code. It protect your data from unauthorised
access etcAbstraction:is the process by which you will hide unwanted details from the user. It means the
details which are needed for the user are only provided to him.
the initial size of the hash table is 11. and the load factor is 0.75.if it reach the bound(i.e. 11*0.75=8) then its
doubled the size ie 16. like that it keep on increase its size up to RAM size.
we say this as an mark up interface we use this interface because it shouid be recognized by Java Virtual
Machine in order to make the objects selected for network enable and serialized and select particular
objects to be participated in Client/server Communication
72. I can get the size(length) of any array (let a[]) by a.length. please tell me what is this
"length" word actually signifies, where it is defined in java and what is its actual
definition ?
length is not a method ,It is a varaible which identifies the length of the array by subtracting one with the
index position of (null)'/0'.
postion of the index at present - 1 ---------> gives the len of the variable
if you use an array ,we use length key word to know the size of an array. because array used primitive data
types.
if you use String then you use length() method. which returns the size of the string.which stores an objects
Serialization means to convert into byte stream ,we need to serialize object so that if many thread calls that
function then consistentency should be maintained.
If you are working with distributed apps, if we want to pass object over the network, only reference will be
passed from client to the server. Then how can it refer object from server to the client memory...so object to
be serialized means that all the fields to be converted into bytes and sent. The same to be deserialized as
objects in the destination. So we can get the exact object what we have in the client. In case if we want
certain fields not to be serialized, just use TRANSIENT when you declare variables
JDBC can't do its job without a driver, and the JDBC management layer must know the location of each and
every database driver available to it. There are two ways that JDBC does this. First, upon initialization, the
java.sql.DriverManager class searches for the sql.drivers property in the system's properties. If it exists, the
DriverManager class will load it. Second, you can call the specific driver explicitly, thus avoiding the search.
Drivers may be downloaded over the network (Internet or Intranet) as an option.
import java.net.URL;
import java.sql.*;
class Select {
stmt.close();
con.close();
Multithreading is the ability to perform different tasks of a process simultaneously.This is achieved by using
a seperate thread for each task.Though there are several threads in a process, at a time the processor will
handle only a single thread.Though it appears to be concurrent processing to the end user, internally only
single thread will be running.Processor is able to multitask by switching between the threads.
When it comes to Multiprocessing there will be more than one processor and each thread will be handled
by a different processor.Thus leading to concurrent processing of tasks
You just need to implement the Interface Serializable and don't have to implements any methods.This is
because Serialiazble Interface has no methods.Its just a Marker/Tag Interface which tells that this object is
serilizable.
A class with no restriction on accesors , mutators or constructor can be considered as a plain Java
class.Java Bean is a spl java class with accessors(getters) and mutators(setters) for the instance variables
present.Moreover, it can only have a defalut constructor
Java client is a user those who r developing applications or working with the java. and Java server is a
JVM/JRE which r running our applications or set of instructions with the bussiness logic
79. Mention 5 basic difference between Array List and Vector in Java Colletion
FrameWork.
2. vectors grows double in size while array list grows just 50%.
ArrayList give better performance as Vector has to suffer this due to synchronisation
80. How you can add the 10 days in the current date in jsp?
date=cal.setTime(Calendar.DAYS+10)
date=cal.getTime(date
81. Plz give me detail difference between Tomcat & Weblogic server
Basically, Tomcat can be called a WEB CONTAINER which has to the ability to run War files(JSPs, struts,
servlets,etc) and not Ear files(EJBs) where as WebLogic is an Application Server also called EJB
CONTAINER in which you can also deploy Ear files with JTA/JTS, JMS, etc support.
82. why main method should be declared as public and why in some versions it is
mandatory and in some versions it is not mandatory?
Here we helping the jvm to call main method without any object
HashMap will not store the elements in order.Whereas TreeMap stores in order.so while retrieving we will
get in a particular order.But for HashMap we won't.
by using notify() or notifyAll() method we can release the lock.But notify() method sometimes notify
unwanted thread.So in some situation notify() method is avoidable
in java.lang package Object class is there which is the super super class of all class in java language so in
order to import that jdk soft implicitly provides Default package
in servlets, we canot seperate the presentation logic from business logic.where as in jsp we can seperate
the presentation logic from business logic.in jsp compilisation is two stages
Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the
object. The general intent is that, for any object x, the expression: x.clone() != x will be true, and that the
expression: x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements. While
it is typically the case that: x.clone().equals(x) will be true, this is not an absolute requirement. Copying an
object will typically entail creating a new instance of its class, but it also may require copying of internal data
structures as well. No constructors are called. The method clone for class Object performs a specific cloning
operation. First, if the class of this object does not implement the interface Cloneable, then a
CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface
Cloneable. Otherwise, this method creates a new instance of the class of this object and initializes all its
fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of
the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep
copy" operation. The class Object does not itself implement the interface Cloneable, so calling the clone
method on an object whose class is Object will result in throwing an exception at run time. The clone method
is implemented by the class Object as a convenient, general utility for subclasses that implement the
interface Cloneable, possibly also overriding the clone method, in which case the overriding definition can
refer to this utility definition by the call: super.clone() Returns: a clone of this instance. Throws:
CloneNotSupportedException - if the object's class does not support the Cloneable interface. Subclasses
that override the clone method can also throw this exception to indicate that an instance cannot be cloned.
OutOfMemoryError - if there is not enough memory.
we can get lock on the class's Class object by using "static synchronize". This is the most exclusive lock.
In class level the most exclusive lock can be achieved by synchronising the class's class object and
declaring it static.
Memory leak is when memory used by an object or variable cannot be freed even after the code that created
the object/ variable has finished execution.
According to wikipedia:
Memory leaks are often thought of as failures to release unused memory by a computer program. Strictly
speaking, it is just unnecessary memory consumption. A memory leak occurs when the program loses the
ability to free the memory. A memory leak diminishes the performance of the computer, as it becomes
unable to use all its available memory.
90. Is it necessary that there should be only one controller in MVC architechture? and
why?
This is basically an architecture that is used to stress the reusing object oriented concept that will be
conducive for programmer as well others.
You can use more than one controller.As when you undergo different kind of design pattern then you will
come to know that there are different controllers like Front controller that handles the first request and later
on forward to particular controller.'
But when you are simply using MVC then it depends on the programmer or developer whther he is going to
use only one controller or more than one.This is a broad concept .
So Answer for your question is that yes we can use moe than one controller in MVC architecture.
Class.forName() first loads the respective driver into the memory, registers the driver with the Driver
Manager class and then creates an instance of the driver to carry out the necessary JDBC actions.
93. What value does readLine() return when it has reached the end of a file
It does not return null value. it return -1when it reaches the end of file
94. Suppose server object is not loaded into the memory, and the client requests for it,
what will happen
If a server object is not loaded in the memory and the request for it comes, then the server object is loaded
in to the memory and is initialized.
jvm is platform dependent.why because,which is residing the one operating system of jvm is totally
different then the jvm of other operating system. that converts Java bytecode into machine language and
executes it.
Differences
1. The difference between interface and abstract class is that in an interface no method body is permitted
only method declarations.In an abstract class you can have method bodies as well as declarations.You can
assume interface as absolute abstract class.
2.As interface contains only method declarations they are assumed abstract by default, you dont have to
explicitly declare them as abstract.But as the abstract class can contain method bodies as well as method
declarations , you have to explicitly state them as abstract methods.
3.The modifiers for methods in interface can be only public, the modifiers for methods in abstract class can
be public or protected.
4.One or more interfaces can be implemented, only one abstract class can be extended
------------------------------------------------
Similarities
1.Both the interface and the abstract class can contain zero or nil abstract methods.
2.In both cases all the abstract methods declared should be implemented/extended respectively.
-----------------------------------------------------------
Note: Since an abstract class cannot be instantiated and it can contain method body..you can use it to your
advantage if and when required
In the Java world, serialization is the storing of an object's current state on any permanent storage media for
later reuse. This is done using when you use the seriazlizable interface or when using the
ObjectOutputStream and ObjectInputStream classes.
The J2EE platform is designed to provide server-side and client-side support for developing enterprise,
multi-tier applications. Such applications are typically configured as a client tier to provide the user interface,
one or more middle-tier modules that provide client services and business logic for an application, and
backend enterprise information systems providing data management.
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.
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.
Serialization is the process of taking an object and converting it to a format in which it can be transported
across a network or persisted to a storage location. The storage location could be as simple as using a file
or a database. The serialized format contains the object's state information.
Deserialization is the process of using the serialized state information to reconstruct the object from the
serialized state to its original state
prepared statement is a precomplie SQL statement.It is the compiled version of the query.Prepared
statement has got a faster excecution time than any other statement.
final is used for declaring a variable as a constant, final class can't be inherited, final methods cannot be
overloaded but overridden
finally statement should execute not depending upon an exception is catch or thrown
finalize method is used for finalize the unreachable objects before garbage collection
An abstract class cannot be declared as final. This is because the abstract class has to be inherited by a
subclass in order to implement the abstract methods. If is is declared as final, the abstract class cannot be
inhereited
An Error is unrecoverable: OutOfMemoryError means that the JVM has no more memory to contin
There are two methods in the Externalizable interface. You have to implement these two methods in order to
make your class externalizable. These two methods are readExternal() and writeExternal().
Java bean is a simple java class with setter and getter methods which can hold data.
instanceof is used to check to see if an object can be cast into a specified type without throwing a cast class
exception. isInstance() determines if the specified object is assignment-compatible with the object
represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator.
The method returns true if the specified Object argument is nonnull and can be cast to the reference type
represented by this Class object without raising a ClassCastException. It returns false otherwise.
Struts
1. type="com.test.LoginForm"/>
path="/login"
type="com.test.user.login.LoginAction"
name="loginForm"
validate="false">
Choice 1
String password = request.getParameter("password");
Choice 2
String password = request.getAttribute("password");
Choice 3
request.getParameterNames().getParameter("password");
Choice 4
String password = ((LoginForm) form).getPassword();
Choice 5
String password = form.getPassword();
if you set the passord value in Formbean Already Then we can Directly call that value by using " String
password = form.getPassword(); "
if u Wann use that by in Action only Means just Set the Value in action as
<formName.set("Password",value)> in the Form of dynaactionform, after setting the value u hav to declare
that in strutsconfig.xml..
if this is not Clear Just let me know i Will Send u one Example..
If you implement non - http specific execute() method of Action class and to that Action class
if you make http protocol specific request then this execute() method with convert the
received ServletRequest, ServletResponse object into Http Secific and then internally calls
perform() method.
Actually perform() and execute() can do same tasks.In struts1.0, have performExecute() and sturts 1.1 have
execute() for performing or executing business logic.
Jakarta is a sub project of Apache. Struts used to be a Jakarta sub project. Struts is now a Apache top
level project. To answer the question Jakarta Struts and Apache Struts are the same.
3. can we go one page to other page using java script or action Mapping ?
No , when we go one page to other page then we using both , but no together
otherwise browser incompatible problem arise.
No, because we donot use both , because the struts does not support both togther otherwise browser
incomptable problem come arise.
4. Is there any way to define a default method for every in the action mapping of
Struts-Config.XML file? If yes then how? Give a piece of code demonstrating
the same.
As far as my knowledge and experience is concern there is no way to have default method for
all the Action Mappings. But what i can suggest you is try to define one interface with the
default method declaration and implement in all the Action Forms in that way you can get a
default method for all the ActionForm its just an idea.
5. What is ActionMapping ?
Through Action mapping we first specify the action class with the action call and we also set the various
forewards for the pages to various JSPs. This entries are done in struts-config.xml .
6. Explain Struts Framework flow? and How JSP file can be processed?
Struts follows MVC architecture and has many design patterns which it uses inside(ex Frontcontroller,Value
Objects).First it maps incoming path with path attribute of ActionMapping in struts-config.xml file and finds
appropriate Action class for the request and maps the name attribute of ActionMapping with that of
FormBeans tag. Then finds appropriate ActionForm for the request. Then it calls Validate() method of
ActionForm if required.If there are no validation errors then Action class is called.Here business Logic starts
and results are returned to the controller which presents in the appropriate View.
Acatually a lot of things happen behind the scene which will complicate the matter.
1. Whenever a request comes to controller ActionServlet is Invoked which looks for ActioMapping in struts-
config.xml
2. Action Servlet looks for existence of form bean corresponds to input request.
6. Action Servlet then do ActionMapping the forward to the Corresponding View according to the lookup
value of ActionForward Class.
This is achieved by suitable 'url-mapping' in web.xml file.We have been doing 'URL-
pattern' in Tomcat4,when using servlets.
And in j2ee webserver like Tomcat, this facilitates 'centralized-declarative change
management', by editing the concerned XML files, without touching the source or class
files of the servlets.or Struts Actions...
ii) All data submitted by user are sent to corresponding ActionForm.There are many
actionforms but only one ActionServlet(because, it is the controller).
iii) The ActionServlet, examines the source of request and extracts the data from
specified actionform and sends it to a specified instance of Action class.(as specified in
struts-config.xml).
iv) The action object carries out the business logic either directly or through helper
classes , creates an instance of valuebean, populates this bean with data and sends the
bean to the View JSP.( an instance of ActionForward).
v) The important and distinctive feature of this arrangement is that the entire thing is
done by 'Declarative-Management'.(and hence ActionMapping)
vi) Sometimes, the data submitted has to be validated and error messages , generated.
(ActionErrors).
vii) We use tags in input side and also for output view.(The input form also belongs to
'view' category in MVC.)( Struts-tags)
viii) The details about the ActionServlet and other servlets if any ,in our application are
given in web.xml
ix) Details about various action classes,forms, action-forwards etc are given in struts-
config.xml
Its a good design practice to implement the business logic in static methods.1. static method access is
faster, you don't have to create, initialize the instance. 2. you perform some action/manipulaton on the
input data and return the result, so why to make it a bulky object, keep it simpler.3. For holding data you
have Beans/Data Objects and for holding client information you have session objectThe nature of the
business logic implementation should be generic, i.e. it should not depend upon any pre-condition like
initializing some variables, etc. For that use Facade or Validators, or context objects.
Instance methods need the class to be instantiated and are hence dependent on that particular instance
of the class. Instances of an object can vary widely.In static methods, all references to it point to one
copy only, and are hence independent of the instance. So any method which needs to be independent
of the class instance should be declared static. Static methods are specially useful in Factory Methods.
A Framework is a skeleton of code used for developing an application with ease.It could have used several
design patterns to implement the skeleton upon which we generally build applications.Eg. Struts Framework
uses MVC2 architecture, various design patterns like Front- Controller,Composite,Command patterns.
Such design patterns used in the framework also helps to build applications with simplicity eg.. struts-
config.xml makes ur app configurable ,resuable,fewer impacts on changes to functionality (Command
pattern)Can go thru Struts architecture for further details.
FrameWork in general specifies collection Of classes and Interfaces that are designed to work together to
handle a particular type of Problem. eg:-Struts
Design Pattern refers to a repetable solution for a commonly occuring software problem eg:- DAO
The findByPrimaryKey() method works like the read() method, except that the
findByPrimaryKey() method retrieves a single TxObject directly from the database using a primary
key without going through a TxCursor. The primary key can be any primary key. For example, RealmId is
the official primary key for the PIRealm table. Because the realm name is unique, it can also be used as an
alternate primary key to retrieve a realm.
You decide what the primary key will be. However, the object must exist, and it must be unique. For
example, to use the findByPrimaryKey() method to find subscribers using their daytime telephone
numbers, you must ensure that each daytime telephone number is unique.
You can combine the findByPrimaryKey() method with the read(TxObject) method.
11. In which pattern does all the action classes in the struts are organized
12. What is the actual difference between MVC and MVC Model2
MVC1 - There will one dedicated controller which will interact with model and produces the view
MVC2- There will be a centralized controller which delegates the request to specific (Action) controller. The
action controller interacts with model and produces the view. There are 2 controller in MVC2, this is the
major difference
1)MVC1 IS JSP PAGE CENTRIC THAT ,EANS JSP ACT AS A CONTROLLER.Suppose 50 jsp files are
hyperlinked through Mian JSP Page this situation accessing the jsp pages is depnd on the Main jsp
page and Jsp page responsibilty is presentation and controller .Peformence point of view this is
lagging.presentation layer and model both are combined.
2)Another major difference is if u change any modifications in the presentation layer that is also effect
on bussiness layer.overcome these drawbacks we go for MVC2
1)In MVC2 we invent controller is servlet.2)we can divisde whole application in to 3 parts MODEL---
Java Beans,Session BEANS,Java Classes VIEW-JSP Controller---Servllets
12. how can i pass info from dyna form bean to Entity Bean(CMP)
we can access dynaform bean information in action class after that calls ejb entity beans in execute
method .use that entity beans and pass the information of form beans in create or findByprimarykey
methods after use if u require
13. When we are saving form bean ,What is the difference between session scope
and request scope.
if you are using request scope the ActionForm is available only until the end of the request/response
cycle.once the response has been returned to the client the actionform and the data within it are no
longer accessible.if u want to keep the form data around for longer than a single request you can have
actonform in session scopeby default the actionform is in session scope until unless u define scope as
request the one practical scenario where i have come across is when we have checkbox or multibox in
the view page then the actionform need to be set to request scope in order to get the correct values of
the checkbox/multibox during multiple inserts.else i havn't come across any considerable difference, we
can use session scope.
sesion scope exists throutout the the session. i.e until the session expires(default 30 mins) or the users
logs out. request scope dies once the page is loaded.
The core of the Struts framework is a flexible control layer based on standard technologies like Java
Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons packages.
Struts encourages application architectures based on the Model 2 approach, a variation of the classic
Model-View-Controller (MVC) design paradigm.
Struts provides its own Controller component and integrates with other technologies to provide the
Model and the View. For the Model, Struts can interact with standard data access technologies, like
JDBC and EJB, as well as most any third-party packages, like Hibernate, iBATIS, or Object Relational
Bridge. For the View, Struts works well with JavaServer Pages, including JSTL and JSF, as well as
Velocity Templates, XSLT, and other presentation systems.
The Struts framework provides the invisible underpinnings every professional web application needs to
survive. Struts helps you create an extensible development environment for your application, based on
published standards and proven design patterns.
An ActionForm represents an HTML form that the user interacts with over one or more pages. You will
provide properties to hold the state of the form with getters and setters to access them.
Maintaining a separate concrete ActionForm class for each form in your Struts application is time-
consuming. It is particularly frustrating when all the ActionForm does is gather and validate simple
properties that are passed along to a business JavaBean.
This bottleneck can be alleviated through the use of DynaActionForm classes. Instead of creating a new
ActionForm subclass and new get/set methods for each of your bean's properties, you can list its
properties, type, and defaults in the Struts configuration file.
The DispatchAction class is used to group related actions into one class. DispatchAction is an abstract
class, so
you must override it to use it. It extends the Action class.
It should be noted that you dont have to use the DispatchAction to group multiple actions into one
Action class.
You could just use a hidden field that you inspect to delegate to member() methods inside of your
action.
17. What is the difference between Struts 1.0 and Struts 1.1
The new features added to Struts 1.1 are 1. RequestProcessor class 2. Method perform() replaced by
execute() in Struts base Action Class 3. Changes to web.xml and struts-config.xml4.Declarative
exception handling5.Dynamic ActionForms6.Plug-ins7.Multiple Application Modules8.Nested Tags9.The
Struts Validator10.Change to the ORO package11.Change to Commons logging12.Removal of Admin
actions13. Deprecation of the GenericDataSource
4. We can write our own Controller by Inheriting RequestProcessor class. i.e., nothing but we can override
the process() method of the RequestProcessor class.
In the perform method of the Action class u can can drop the code that is responisble for connecting to
the EJB.
19. How you will handle errors and exceptions using Struts
The core classes of struts are ActionForm, Action, ActionMapping, ActionForward etc.
The difference between the classes is zero -- all behavior in ActionErrors was pushed up into
ActionMessages and all behavior in ActionError was pushed up into ActionMessage. This was done in the
attempt to clearly signal that these classes can be used to pass any kind of messages from the controller to
the view -- errors being only one kind of message
EnterpriseJavaBeans(EJB)
1. what is the use of using session facade design pattern in EJB'S?
2. how we deploy in weblogic?
eg: if all your app'n code , etc is in say folder d:/mybankappn then which is a web app'n then..
and in right side browse and select the bankappb.war (we created above) select the server and go
next and finally from the list of war files displayed (bankaaan wil also be init), check our war file and
say target....give "name" of app'n (the one which u want to give while calling the pg)
Like if i give app name here as "mybank" . then say target . we wil be shown with success of failure msg.
Ho Gaya.
similarly you have deployent option is in Load your file link in the weblogic console.
ejb activate() is the method that donotes the objects which are at active state and at the same time
passivate() tells us that objects which are at passive state(at sleeping condition).That means if we take an
example like bottle.
If there are 10 bottels are in the box which currently using and means they are active and if u want to fill ane
more bottle into that box then we should kept that bottle at another place and if u wants to be activate that
11th bottle then u must lift one bottle from first box and u fill the 11th bottle int that empty space.so,in this
conclusion there is one thing iam telling u that if u want to use an object in activate state if there is no space
in that part then u must passivate on item in that part must and only fill the one more object.
4. what kind of bean(entity/session) will you use if there are no database
transactions and all you use is a read-only database
It depends on the available infrastructure and programming efforts to be put in.Read only Entity
bean(CMP) will minimize progarmmer time and effors, if one is comfortable with CMP
developmet.Stateless or BMP requires more effort and coding than CMP
If u are only reading the database then u dont need to use Entity been at all.
For specifically, For Session Beans, the default Transaction Attribute is Required, For Entity Beans is
Supports.
Section 11.5 of EJB v1.1 spec says that the deployer must specify a value for the transaction attribute for
those methods having container managed transaction.
It is used for transaction support in stateful session beans. EJB container calls call back functions on sfsb (if it
implements SessionSynchronization interface) after transaction started, before completion and after
completion.Bean developer can do house keeping stuff in these methods.
7. How do J2EE application servers in general and the Weblogic servers in particular
help software development?
J2EE application server in general or Weblogic appliction server in particular provide services such as
security, data integration and resource management. So the developers can concentrate only on the
functionality they need to implement.
Also since these servers are written according to the j2EE specifications, any application written in J2EE can
be put on those servers with out doing code modifications.
For CMP Bean, it return NULL and BMP Entity bean, it returns Primary Key Class Object.
9. when should we use session bean/entity bean?I was unable to judge?For Example
:For Airline Project where we can use EJB\'s?
How can we differentiate the stateful and stateless session beans
Session beans are used to execute business logici.e in airline reservation entity beans are connected to
database to get the data and give it to the session beans to update like suppose to reserve one
seat::::::::entitybeans load the current reserved seats and give it to the session beans session beans update
the current reserved seat and give it to the entity beans then entity beans save the updated data into the entity
beanssuppose:entity bans load data like::::::::load(){seat 1,2,3,4,5,6.......... , 10 are reserved(entity beans load
this data and send it to the}session beanssession beans do like:::::::::reserve(){reserve=seat10+1}in entity
beans:::::::store(){ updateseat(reserve);}this reserve varible has give to the entity beans to save it into the
database.
Since client never talk to bean directly ,client get reference to component interface (EJBObject) by calling
create() method on home interface
Client use JNDI to get reference to home interface, for that it first gets the InitialContext
Client use initial context to lookup bean home, but home stub returned from JNDI lookup might not
implement the home interface, To get the stub that is castable to home interface you have to narrow() the
object you get from JNDI lookup , so to cast the object we get from JNDI lookup we use narrow()
method.
11. Just by seeing the signature of the bean how can you specify whether it is a Stateful
or Stateless Session Bean?
u can just check the home interface of the session bean in order to detemine the whether it is stateless or
stateful.
The create method in a stateless session bean cannot have arguments, and can only have a single method
called create(). While create in Stateful bean can have arguments and could be any method starting with
create string eg. create<method>(arg1, arg2,...). Although it is not compiler checked but in stateless bean
the ejbPassivate() and ejbActivate() methods has to be empty as these functions are never called by EJB
container. As conceptually in stateful session bean we might need to store the clients information hence
arguments in create<method> are necessary. While in stateless bean we don't, hence no arguments are
necessary. It's intutive isn't. I my life I haven't seen such a futuristic server programming tool as EJB.
Transactions ensure that database actions are consistent. Consider a case where a record is required to be
added to say two databases simultaneaously. If the record is added to both the databases, action is consistent
& transaction is complete but if the record is not added to one of the databases, then the action of "Add" record
is rolled back across both the databases for this record, making records in both the databases consistent.
Transactions ensure atomic nature of database action.
EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container
contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass
called SessionContext. These EJBContext objects provide the bean class with information about its container,
the client using the bean and the bean itself. They also provide other functions. See the API docs and the spec
for more details.
EJBContext interface provides methods for interacting with the container.Such as u can obtain the enterprise
bean's remote home interface(getEJBHome() method),local home interface(getEJBLocalHome()
method),enterprise bean's environment properties(getEnvironment() method),to identify the
caller(getCallerPrincipal() method),to know abt transactions.
14. how to transfer a bulk amount of tabular data from a jsp page to an ejb thru a servlet
and viceversa
Anyway, if you want to send huge amount of data from the jsp to an ejb via servlet what you can do is write a
data-object class where you declare a certain number of instance fields and define getter and setter
methods for those fields. Now in the JSP, set the values of those fields in hidden variables. In the servlet,
extract the values of those fields using request.getParameter("param-name"). Create an object of the data-
object class that you had written earlier and use the setter methods in that class to set the values of the
parameters that you have extracted in the servlet.Now pass this object to the ejb (session bean) method. In
the ejb, you can get the values of the fields using getter methods of the data-access object.
By tabular data if you mean, that the same form field can contain multiple values, then in the servlet use
request.getParameterValues("param-name").
16. what is business delicate ? Use ? and what is session faced ? use ?
Business delicate is a small java bean object which is used for make loose coupling b/w controller to
model.Session facade design pattern in which palce session bean b/w model to contriller.why beacuse
sesssion bean process the business logic . if you place business logic in model(entity beans) you loss the
reusabiity of entity beans. if you place business logic within the controller ,this makes tightly coupling b/w
model to controller.
we can think session faced as little extended form of DTO Data transfer object .both is used to transfer
Data(Rows) from Entity -> Session ->jsp/servlet and vice versa.this class implements Serializable interface
and has gettrs/setters for all the fields of undelying table.
17. Give a scenario where you have used stateless session beans and why was it
necessary?
The stateless bean is used whereever the logic does the same for all client irrespective of remembering the
client state.
For Example, Consider a simple EJB Client which just converts dollar to ruppee value. So as per logic, it
does not matter who is requesting but the importance is that, if a client reqests it has to provide ruppee
equvalent value against dollar.
1. setSessionContext()
2.ejbCreate()
3.ejbPassivate()
4.ejbActivate()
5.ejbRemove()
19. What is the difference between normal Java object and EJB
Java Object:it's a reusable componetEJB:is reusable and deployable component which can be deployed in
any container
• the bean class must implement the session bean interface. ejbcreate is declared in the interface.
• ejbCreate() is a container call back method which is invoked when the cleint calls create on the
home stub class, hence if it is not called the life cycle of the bean is not complete, in which case
there will be no session bean to use.
• Wehn we call create on stateful session bean each time a new bean is created, and when we call
this on the stateless bean the bean is pulled otu of the pool and assigned the ejbobject which the
client gets.
21. What is the difference between Stateful session bean and Stateless session bean
a) Stateful beans are also Persistent session beans. They are designed to service business processes that
span multiple method requests or transactions.
Stateless beans are designed to service business process that last only for a single method call or request.
e) Stateful S.Beans can be passivated and reuses them for many clients.
Stateless S.Beans, client specific data has to be pushed to the bean for each method invocation which result
in increase of network traffic.
EJB is designed to work in distributed environment using rmi/iiop protocol where as JavaBean is standalone
and works only in the same JVM.
Implicit services are provided to EJb by the Container, in which it si deployed according to EJB contract but
in JavaBean we need to code all these services
24. Can we use instance variables in Stateless session beans? If yes, Why and How? If
the answer is no , explain why and how?
Yes we can have instance variables in Stateless Session Bean ,but these are not used to maintain the client
specific state.
25. what is the difference between distributed transactions and Flat transactions in
EJB?
If your EJB container talks with Multiple databases(EIS) in single trasaction that is been called as distributed
transacation.
26. What is the difference between HTTPSession and Stateful Session Bean
From a logical point of view, a Servlet/JSP session is similar to an EJB session. Using a session, in fact, a
client can connect to a server and maintain his state.
But, is important to understand, that the session is maintained in different ways and, in theory, for different
scopes.
A session in a Servlet, is maintained by the Servlet Container through the HttpSession object, that is
acquired through the request object. You cannot really instantiate a new HttpSession object, and it does not
contains any business logic, but is more of a place where to store objects.
A session in EJB is maintained using the SessionBeans. You design beans that can contain business logic,
and that can be used by the clients. You have two different session beans: Stateful and Stateless. The first
one is somehow connected with a single client. It maintains the state for that client, can be used only by that
client and when the client "dies" then the session bean is "lost".
27. What are the various isolation levels in a transaction and differences between them
There are three isolation levels in Transaction. They are 1. Dirty reads 2.Non repeatable reads 3. Phantom
reads.
Dirrty Reads If transaction A updates a record in database followed by the transaction B reading the record
then the transaction A performs a rollback on its update operation, the result that transaction B had read is
invalid as it has been rolled back by transaction A.
NonRepeatable ReadsIf transaction A reads a record, followed by transaction B updating the same record,
then transaction A reads the same record a second time, transaction A has read two different values for the
same record.
Phantom ReadsIf transaction A performs a query on the database with a particular search criteria (WHERE
clause), followed by transaction B creating new records that satisfy the search criteria, followed by transaction
A repeating its query, transaction A sees new, phantom records in the results of the second query.
Isolation levels are Dirty_Read, Non Repeatable read and phantoms. These are the inconsistancies which
are occured in transactions. To avoid these inconsistencies , we have 4 types of
attributes.TRANSACTION_READ_UNCOMMITED TRANSACTION_READ_COMMITED=== Avoids dirty
read TRANSACTION_REPEATABLE_READ ===Avoids dirty read and Non repeatable read
TRANSACTION_SERIALIZABLE=== Avoids dirty read , Non repeatable read and Avoids Phontom reads
CMP -- Container-managed persistence beans are the simplest for the bean developer to create and the
most difficult for the EJB server to support. This is because all the logic for synchronizing the bean's state
with the database is handled automatically by the container. This means that the bean developer doesn't
need to write any data access logic, while the EJB server is supposed to take care of all the persistence
needs automatically. With CMP, the container manages the persistence of the entity bean. Vendor tools are
used to map the entity fields to the database and absolutely no database access code is written in the bean
class
BMP--bean-managed persistence (BMP) enterprise bean manages synchronizing its state with the database
as directed by the container. The bean uses a database API to read and write its fields to the database, but
the container tells it when to do each synchronization operation and manages the transactions for the bean
automatically. Bean-managed persistence gives the bean developer the flexibility to perform persistence
operations that are too complicated for the container or to use a data source that is not supported by the
container.
30. What is Entity Bean. What are the various types of Entity Bean
31. What is the life cycle of Stateless session bean, Stateful session bean
EJB does indeed support the effect of pooling stateful session beans.Only a few instances can be in
memory when there are actually many clients. But this pooling effect does not come for free---the
passivation/activation steps could entail an input/output bottleneck. Contrast this to stateless session beans,
which are easily pooled because there is no state to save.
33. Why are ejbActivate() and ejb Passivate() included for stateless session bean even
though they are never required as it is nonconversational bean
The simple reason is to manage your resources. For eg. if you use/open any third party resource on
ejbActivate, you need to make sure ejbPassivate close the connection/ release the use of resource
regardless of stateful session or stateless session.
34. How is Stateful Session bean maintain their states with client
stateful beans maintains their state through instance variables. the values of the instance variables is
specific to client. when the bean instance needs to be removed from the pool (usually LRU replacement) ,
the state is passivated to secondary storage. or we can say object is serialized to secondary storage.
35. How will you propagate exception thrown inside session bean to JSP or Servlet
client
1.System Exception - We can define some error codes the in the property file and show it to the JSP
2.Application Exception.. - We can customise the exception and show the appropriate error
Transaction support An EJB container must support transactions. EJB specifications provide an approach to
transaction management called declarative transaction management. In declarative transaction
management, you specify the type of transaction support required by your EJB component. When the bean
is deployed, the container provides the necessary transaction support.
Persistence support An EJB container can provide support for persistence of EJB components. An EJB
component is persistent if it is capable of saving and retrieving its state. A persistent EJB component saves
its state to some type of persistent storage (usually a file or a database). With persistence, an EJB
component does not have to be re-created with each use.
An EJB component can manage its own persistence (by means of the logic you provide in the bean) or
delegate persistence services to the EJB container. Container-managed persistence means that the data
appears as member data and the container performs all data retrieval and storage operations for the EJB
component. See Chapter 27, "Creating Entity Components" for more information.
Naming support An EJB container must provide an implementation of Java Naming and Directory Interface
(JNDI) API to provide naming services for EJB clients and components. Naming services provide:
Location transparency Clients can instantiate components by name, and do not need to know the details
about the server hosting the component.
Deployment flexibility Beginning in EJB version 1.1, EJB components can be configured with naming aliases
for components and resources such as databases, JavaMail sessions, and JMS message queues. Using
aliases simplifies the procedure to deploy the component on a server where the accessed components and
resources use different JNDI names.
EJB 2.0 came with new features which not available in EJB1.1 they are auto primarykey generation,EJB-
query language,local interfaces,relationships.
EJB 2.0 adds the local beans, which are accessible only from within the JVM where beans are running in.
In EJB 1.1, we had to implement remote client views for all these beans, even if we had no remote clients
3.New CMP Model. It is based on a new contract called the abstract persistence schema, that will allow to
the container to handle the persistence automatically at runtime.
4.ejbHome methods. Entity beans can declare ejbHome methods that perform operations related to the EJB
component but that are not specific to a bean instance.
38. What are simple rules that a Primary key class has to follow
sendredirect will happen on clint side & request , rsponse will be newly created, for forward action it
is server side action & request, response is passed & not modified or destroyed.
pooling of instances.
in stateless session beans and Entity Beans server maintains a pool of instances.whenever server
got a request from client, it takes one instance from the pool and serves the client request.
41. What is the difference between ejbCreate() and ejbPostCreate()
Session and Message Driven Bean will have only ejbCreate() method and no ejbPostCreate()
method. Entity bean will have both ejbCreate() and ejbPostCreate() methods.
The ejbPostCreate method returns void, and it has the same input parameters as the ejbCreate
method. If we want to set a relationship field to initialize the bean instance, we should do so in the
ejbPostCreate method. we cannot set a
relationship field in the ejbCreate method.
The ejbPostCreate() allows the bean to do any post-create processing before it begins serving
client requests. For every ejbCreate() there must be a matching (matching arguments)
ejbPostCreate() method.
Session Context Contains information that a Session Bean would require from the container
Entity Context contains the information that an Entity Bean would require from a container
Activation and Passivation is appilicable for only Stateful session bean and Entity bean.
When Bean instance is not used for a while by client then EJB Container removes it from memory
and puts it in secondary storage (often disk) so that the memory can be reused. This is called
Passivation.
When Client calls the bean instance again then Container takes the passivated bean from
secondary storage and puts it in memory to serve the client request. This is called Activation.
44. What is the difference between EAR, JAR and WAR file
In J2EE application modules are packaged as EAR, JAR and WAR based on their functionality
JAR:
EJB modules which contains enterprise java beans class files and EJB deployment descriptor are
packed as JAR files with .jar extenstion
WAR
Web modules which contains Servlet class files,JSP FIles,supporting files, GIF and HTML files are
packaged as JAR file with .war( web achive) extension
EAR
All above files(.jar and .war) are packaged as JAR file with .ear ( enterprise archive) extension and
deployed into Application Server
There are no structural differences between the files; they are all archived using zip-jar
compression. However, they are intended for different purposes.--Jar files (files with a .jar
extension) are intended to hold generic libraries of Java classes, resources, auxiliary files, etc. --
War files (files with a .war extension) are intended to contain complete Web applications. In this
context, a Web application is defined as a single group of files, classes, resources, .jar files that
can be packaged and accessed as one servlet context. --Ear files (files with a .ear extension) are
intended to contain complete enterprise applications. In this context, an enterprise application is
defined as a collection of .jar files, resources, classes, and multiple Web applications. Each type of
file (.jar, .war, .ear) is processed uniquely by application servers, servlet containers, EJB
containers, etc. RegardsSecretcoder
45. What is the difference between local interface and remote interface
We can describe the following common rules for choosing whether to use remote client view or
local client view:
When you will potentially use a distributed environment (if your enterprise bean should be
independent of its deployment place), you should obviously choose remote client view.
Use remote client view when you need to be sure that parameters passed between your EJB and
the client (and/or other enterprise beans) should be passed "by value" instead of "by reference."
With pass-by-value, the bean will have its own copy of the data, completely separated from the
copy of the data at the client. With local client view, you can do pass-by-reference, which means
your bean, as well as the client, will work directly with one copy of the data. Any changes made by
the bean will be seen by the client and vice versa. Pass-by-reference eliminates time/system
expenses for copying data variables, which provides a performance advantage.
If you create an entity bean, you need to remember that it is usually used with a local client view. If
your entity bean needs to provide access to a client outside of the existing JVM (i.e., a remote
client), you typically use a session bean with a remote client view. This is the so-called Session
Facade pattern, the goal of which is that the session bean provides the remote client access to the
entity bean.
If you want to use container-managed relationship (CMR) in your enterprise bean, you must expose
local interfaces, and thus use local client view. This is mentioned in the EJB specification.
Enterprise beans that are tightly coupled logically are good candidates for using local client view. In
other words, if one enterprise bean is always associated with another, it is perfectly appropriate to
co-locate them (i.e., deploy them both in one JVM) and organize them through a local interface.
a) EJB Server
b) EJB containers that run on these servers,
c) Home Objects, Remote EJB Objects and Enterprise Beans that run within these containers,
d) EJB Clients and
e) Auxillary systems like JNDI (Java Naming and Directory Interface), JTS(Java Transaction
Service) and security services.
JDBC
1. 1.why constructor does not have return type in java?
constructor is a special method in java. the purpose of the constructor is to assign values to the
instance variable when the object is created for the first time. the name of the constructor is same
as the class name. to call the constructor in two ways.with new operator eg: Test t1=new Test();
here Test() is nothing but to call the construtor of class.with newInstanceOf() method in Class class
eg: object obj=class.newInstance();
2. why static does not support " this" and "super" keyword in java ?
this and super keyword points to the object reference. in java static variable and method are not the
part of the object it is the realted class. objects are stored in heap where as static variableand static
methods are stored in static context.
2. by extending the thread class it overload all the method in the superclass to subclass where our
subclass have no use of other mehtod in thread class
Oracle has a thin client driver, which mean you can connect to a oracle database without the Oracle client
installed on your machine.
Thick client would need the Oracle Client, database drivers,etc.. Drivers include JDBC-ODBC bridge
drivers,JDBC drivers depending on tns resolution.
Batch execution in java can reduce the no of database hits,threby reducing load on
the database process,reduce network traffic,can provide flexibility to use the
network at when at low traffic.
ResultSetMetaData interface is used to find out the types and properties of the column in the ResultSet
whereas DatabaseMetaData interface provides comprehensive information about the database as a whole.
Class.forName method searches for the class specified in the method and returns the Class object. It is
defined in java.lang package. And can be used to load driver or native code. For instance the following line
is used to load and register the oracle thin dirver in the DriverManager class:
Class.forName("oracle.jdbc.driver.OracleDriver");
Class is the class in class.forName(). The forName method will return the object of the class that we are
passing as string.
every database has its own driver classes which are usually distributed through jar files.
There is not specific installation for these drivers. If you want to use these drivers, you need to have these
driver jar files in your classpath.
9. State true or falseCan we retrieve a whole row of data at once, instead of calling an
individual ResultSet.getXXX method for each column ?
The ResultSet.getXXX methods are the only way to retrieve data from a ResultSet object, which means that
you have to make a method call for each column of a row. It is unlikely that this is the cause of a
performance problem, however, because it is difficult to see how a column could be fetched without at least
the cost of a function call in any scenario.
10. how can we connect database in java without using the Class.forname() method
with our application?
A) Drivers can also be specified from the command line via the jdbc.drivers system property, but this
method requires the driver(s) to be in the classpath at compile time:
jdbc.drivers=foo.bah.Driver:wombat.sql.Driver:bad.taste.ourDriver
11. how many statements can be created with one connection
12. which is the best driver among the 4 jdbc drivers?how can we load that driver?
Type 4 driver is the best driver among 4 drivers because it need not be load other API's, because the code
is developed only in java language, so other language API's are not need.
Actually when u submit a simple statement to the databse, at first the DBMS parses it and sends it back with
the result, so again when u send the same statement again the DBMS server parses it and sends back the
result so here a lot of time is wasted and because the statement is again parsed though it has been sent
twice or thrice it consumes a lot of time and response will be slow.Prepared Statement is used when u want
to execute a statement object many times. when u submit a PreparedStatement the DBMS server parses it
and creates a execution plan. This e-plan can be used when u again send the same statement to the
database.That is the DBMS server zest executes the compiled statement rather that executing it from first,
hence we get an precompiled statement.And also the advanatge of using this PreparedStatement is it is
used to send dynamic sql statements, which u can give values later than giving the values at the time of
creation.
proc.registerOutParameter(1, Types.OTHER);
proc.execute();
Auto-commit mode indicates to the database whether to issue an automatic COMMIT operation after every
SQL operation. Being in auto-commit mode can be expensive in terms of time and processing effort if, for
example, you are repeating the same statement with different bind variables.
By default, new connection objects are in auto-commit mode. However, you can disable auto-commit mode
with the setAutoCommit() method of the connection object (either java.sql.Conection or
oracle.jdbc.OracleConnection).
In auto-commit mode, the COMMIT operation occurs either when the statement completes or the next
execute occurs, whichever comes first. In the case of statements returning a ResultSet, the statement
completes when the last row of the ResultSet has been retrieved or when the ResultSet has been closed. In
more complex cases, a single statement can return multiple results as well as output parameter values.
Here, the COMMIT occurs when all results and output parameter values have been retrieved.
If you disable auto-commit mode with a setAutoCommit(false) call, then you must manually commit or roll
back groups of operations using the commit() or rollback() method of the connection object.
JSP
1. what is the difference between , pagedirective include, action tag include ?
Include directive , the process can be done at compilation time. and here we can see only one servlet. Any
modifications in the header,we need to recompile the servlet.
Action include: The process can be done at client request time.and here we can see more than one
servlet.Any modification in the page ,no need to recompile the servlet.
2. There is an object that provides one point access to page, request, response,
session, out, exception, config and application. What is that object or mechanism?
Is it pageContext, if so give an example.
javax.servlet.jsp.PageContext
HttpSession getSession()
PageContext is used for the following objects: Exception, JspWriter, ServletContext, ServletResponse,
ServletRequest, ServletConfig, HttpSession.
3. When many Users are browsing the same application at the same time and they
click the "Submit" button will many objects be created for each and every User?
Whenever more than one user hits Submit button, server created thread of the servlet, which made after
compilation, and runs its _jspService() method to response him.
As Pavan said we can create our servlet thread safe by making synchronized the service method.
Use request.forward()
5. What is the difference betweeen JSP forward and servlet forward methods?
There is no difference between jsp and servlet forward. both use request dispatcher. Jsp turns in to servlet
and jsp:forward internally converted into the rd.forward(request, respone)
Implementing an interface means providing a specific behavior to your class. Since jsp are to be interpreted
by servlet-container and will then be executed as a servlet, it cant be used for that extended behavior. Thus
no use of implementing it.
and in servlet use just used servletInput stream to get that file
U can,t Implement Interfaces but u can Extend Class Using <% @ page extend="className">
A session can be created via the getSession () method of HttpServletRequest. An HttpSession object is
returned. This object can store set bindings that associated names with objects. This setAttribute (),
getAttribute (), getAttributeNames (), and removeAttribute () method of HttpSession manage these bindings.
It is important to note that session state is shared among all the servlets that are associated with a particular
client.
11. what is the differences between JSP LifeCycle and Servlet LifeCycle?
in servlet we can implement init,service and destroy method but in jsp we dont have any implementation for
that i.e jsp container taking care of that implimentation . Finally only translation phase is different i.e jsp
converted into servlet
12. What is the Difference between sendRedirect() and Forward? Forward Request-
When we invoke a forward request it is sent to another resource on the server itself, without
the client being informed that a different resource is going to process the request.The process
occurs completly within the web container.
Send-Redirect- When this method is invoked , it causes the web container to return to the
browser indicating that a new URL is requested.Process does not occur just within web container.
Because the browser issues completly new request any object value that are stored as
request attributes are lost in case of Send Redirect but forward retains that.
N because of the extra round trip redirect is slower than the forward.
So many difference for forward and send redirect i will explain as follows
1. in forward the resource will be with in the container,in case of send redirect the resource would be outside
the web container.i.e send redirect used for resource contain in the other web application.
2. incase of send redirect there request will back to the browser then redirect to other url i.e extra round trip
taken place but it is not possible in forward only one request send to the container.
3. form attributes are not available in the send redirect and it is available in forward i.e request parameter
values.
4.According to performance forward will better performance compare to send redirect because it's taking
extra round trip
the two types of include are page include and jsp include. If u use page include, only one servlet will be
generated(code of the included jsp will be merged with the first jsp) by the JSP Compiler. If we use jsp
include two servlets will be generated and requestdispatcher will be used in the first servlet to include the
second servlet.
If we make any changes in any of the JSPs, and if we use jsp include only that jsp which has been changed
will be compiled by the JSP Compiler.The other JSP will not be re-compiled. And if we use page include JSP
Compiler generates the servlet irrespective of the jsp to which the change has been made.(This is the
scenario on Tomcat 5 .)