P. 1
Faqs

Faqs

|Views: 457|Likes:
Published by api-3744705

More info:

Published by: api-3744705 on Oct 15, 2008
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as DOC, PDF, TXT or read online from Scribd
See more
See less

03/18/2014

pdf

text

original

Q) What exactly is volatile & please tell the at what situation we use this key-word and please give

an example as well
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.

2.what is the difference between runtime polimorphism, and compiletime polimorphism ?

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. Advantage : Faster execution of code. Disadvantage: The size of compiled code is high. 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. Advantage : Slower execution of code. Disadvantage: The size of compiled code is less. 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)

3. why java is not 100% oops

For 100 % oops we need 100% support in following things 1) inheritance 2) polymorphism 3) encapsulation java support above three consepts but in "inheritance" java does not support multiple inheritance. so that why java is not a 100% oops language. now ? java not support multiple inheritance support. it is due to "Deadly Diamond of Death" problem. To avoid this problem java use interface.

4. What is the difference between .equals and ==?
== 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.

5. advantages of Implementing Runnable over extending Thread
whenever u can extend the Thread class to u r class, u can not extends the other class (because java not support the multiple inhiretence),So most of the devilopers prefer to implements the Runnable interface in place of Thread class 6. why is collection framework called as framework?

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. 7. what is the difference between synchronized block and normal block ?
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.

8. Can we serialize the static variable?
We cannot serialize the static and transient variables.

By default static variables are not serializable.This is due to the reason that they are not bound to a particular object.If u want to exclude an ordinary variable from serialization then qualify that variable as transient 9. What is a Singleton class, what is it\'s significance? Thanks in advance!

the class which contains single method is called singleton class

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. There are several ways to achieve this: 1. public class Singleton { 10. What method should the key class of hashmap override the methods to over ride are equals() and hashCode(). 11. What is the difference b/w Iterator & ListIterator 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. 12. what significance of protected Constructors? Consider Class A extends Class B. If Class B has protected constructors then 1.Cannot create object from Class A directly. 2.Indirectly you can create object of Class A by instantialting Class B. 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

15. Can i limit the initial capacity of vector in java? Ya u can limit the initial capacity we can construct an empty vector with specified initial capacity public vector(int initialcapacity) 16. Differences between servlet context and servlet config? 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. 17. What is the difference between a CallableStatement and PreparedStatement?
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. 18. what is collction framework?How it is working?Explain. 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. 19. In which case i can go for Anonymous class? 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. 24. Strings are immutable.But

String s="Hello"; String s1=s+"World"; S.O.P(s1); means printing "HelloWorld".How ?
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") now you do s = s + " World"; 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. 25. What is the difference between classpath and path variable? 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?
All are use when we want to handle Objects, alougth difference is ArrayList contains objects in any order while with LinkList objects are stored in the order which you entered, but both are not thread safe. Vector is similar to ArrayLias but is Thread Safe. HashMap is not synchronized, but HashTable is Synchronized 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 according to case 1 Test is a subclass of Object directly. According to case 2 Test is a subclass of Object due to the hierarchy. so no matter you extend a class or not, your class will always be a subclass of Object. 33. what is difference between string and stringtokenizer?

Obviously StringTokenizer as it is suggested by its name tokenizes a String supplied to it as an argument to its constructor and the character based on which tokens of that string are to be made.The default tokenizing character is space " ". 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. 35. how can we use hashset in collection 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 36. why java does not support inheritance of multiple superclasses?

what is achieved by inheritance? why there is no main method in servlets/jsps?
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 37. what is difference between instance and object.?

what are the all difference between interface and abstract class?
instance means just creating a reference(copy) . 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

39. what is a green thread?

Native threads can switch between threads pre-emptively, switching control from a running thread to a nonrunning 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 40. When exactly a static block is loaded in Java ? Before creation of object ,static block is loaded 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........ 41. When will a static variable is loaded?is it at compile time or runtime? 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. 42. Constructor can not be inherited.Why? Tell me the reason. 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 44. Why should i use ejb as i can do it in servlet? while using ejb, ejb container provides some services like persistence,transaction,security etc implicitly it doesn't require coding. 45. How many ways do we have to load a class There are 4 ways to load a object 1) class .forName 2) new keyword 3) class method 4) newInstance method 46. Why ArrayList is faster than Vector? ArrayList is faster than Vector, because ArrayList is not synchronized. Synchronization will reduce the performance of Vector. 47. explain the importance of "static"keyword 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
49. Is java a fully object oriented programming or not? if not why?

No,Because it has data types like int,float,double,char etc. whose objects can't be created unless used in a wrapper class like Integer or Float 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?
<input type=file name=f> 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. String s= "hello" is a valid way other valid ways include reflection also by using methods that return new objects Date d= Date.getInstance(); Toolkit tk= Toolkit.getDefaultToolkit(); String s= "hello".concat("world"); etc 52. How would you keep track of a session In servlets, session can be tracked using a) URL rewriting b) Hiddin FormField c) cookies and d) HttpSession API In EJB to maintain session go for stateful session beans. 53. How does serialization work 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.

54. What is data encapsulation? What does it buy you 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. Encapsulation provides data security. It is nothing but data hiding 55. Can a method be static and synchronized

Each object has a lock associated with it. When any thread attempts to access a synchronized member, it must first acquire the associated objects lock. Once one thread owns the lock, no other thread may acquire the lock until the owning thread releases it which happens automatically when the synchronous operation completes. You can even make static members synchronized. Then the lock affects all objects of a given class, not just one particular instance. 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. 57. How is serialization implemented in Java A particular class has to implement an Interface java.io.Serializable for implementing serialization. 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 59. In Java, how are objects / values passed around 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 There are 2 types of exceptions. 1. Checked exception 2. Unchecked exception. Checked exception is catched at the compile time while unchecked exception is checked at run time. CHECKED EXCEPTION: WHICH R KNOWN AT THE COMPILE TIME.EG PASSING OF WRONG NO OF ARGUMENTS. UNCHECKED EXCEPTION:WHICH RC KNOWN AT THE RUN TIME EXCEPTION.EG NUMBER DIVIDE BY 0.

62. How all can you free memory

With the help of finalize() method. 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 63. How would you implement a thread pool.

public class ThreadPool extends java.lang.Object implements ThreadPoolInt 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 65. What is aggregation and composition of objects?

What is the diff between monolithic and composite object?
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. Hope it makes clear. 66. Can we make construtor STATIC? ""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

68.Can we serialize the static members?
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. 69. what is the difference between encapsulation & abstraction? Encapsulation is internal behavior, while Abstraction is External behavior 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. 70. what is the capacity of Hashtable()? 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. The capacity of HashTable is initalCapacity * LoadFactor. Genarally LoadFactor is 0.75.

71. What is the significance of null interface in Java? 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 Ex SingleThreadModel it provide information about our servlet as Thread safe.

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 ( so subtractin the one represent the postion of the index ) So the index postion is stored in the vairable called length 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 73. Why we need to serialize the object 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. Objects are always passed by reference. Let us consider the following 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 74. how to make jdbc connection a protable without specific drivers 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 { public static void main(String argv[]) { try { // Create a URL specifying an ODBC data source name. String url = "jdbc:odbc:wombat"; // Connect to the database at that URL. Connection con = DriverManager.getConnection(url, "kgh", ""); // Execute a SELECT statement Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT a, b, c, d, key FROM Table1"); // Step through the result rows. System.out.println("Got results:"); while (rs.next()) { // get the values from the current row: int a = rs.getInt(1); Numeric b = rs.getNumeric(2); char c[] = rs.getString(3).tocharArray(); boolean d = rs.getBoolean(4); String key = rs.getString(5); // Now print out the results: System.out.print(" key=" + key); System.out.print(" a-" + a); System.out.print(" b=" + b); System.out.print(" c="); for (int I = 0; I < c.lngth; I++) { System.out.print(c[i]); } System.out.print(" d=" + d); System.out.print("\n"); } stmt.close(); con.close(); } catch (java.lang.Exception ex) { ex.printStackTrace(); } } } 75. WHAT IS THE DIFFERENCE BETWEEN MULTI-THREADING AND MULTI-

PROCESSING?
multithreding means we can excute different parts of a program simaltaniously
multiprocessing means excute different parts of a program at a time 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 76. If i create a object which is to be serialized then do I need to implement any

methods?
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. 77. What is difference in between Java Class and Bean 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 Bean class have the follwing standards comapre to normalcalss. 1. palce a default constructor 2. declared varibales have private 3. access the varibales through getXXX() and setXXX() methods. 4. It is used store the values. 78. What is a "Java Client" ? 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.
1. vectors are synchronized while array list are not. 2. vectors grows double in size while array list grows just 50%. 3. Array list are faster than vector as they are unsyncronized. Vector is a legacy class but ArrayList is not Vector is thread safe but ArrayList is not 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 date = new Date(); Calendar cal = new GregorianCalendar(); date=cal.setTime(Calendar.DAYS+10)

date=cal.getTime(date 81. Plz give me detail difference between Tomcat & Weblogic server 1)Tomcat is a web-server and Weblogic is an Application Server;2)Tomcat is 3-tier Architecture whereas Weblogic is n-tier Architecture;3)In Webserver,generally only http protocol are used whereas In Application Server http protocol along with other protocols are used. 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?
public static void main(String args[]) Here we helping the jvm to call main method without any object that is why main is declared as public static. 83. Difference between HashMap and TreeMap 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. 84. How do you release an object which is locked in a synchronized block 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 85. Why java.lang Package is the Default package? 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 86. what is the difference between servlets and jsp 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 87. where exactly we make use of Clone objects in a real time? 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. 88. Can a lock be acquired on a class 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. 89. What is meant by memory leak? 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. 91. How will you perform transaction using JDBC Using the autocommit method provided by the connection object. 92. what is the difference between Class.forName and registerDriver() registerDriver() registers the JDBC driver with the DriverManager class. 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. 95. What is JVM 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. 96. What is the diffrence between an Abstract class and Interface 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 Variables declared in Interface are static and final by default. 97. What is the use of Interface 1. To incorporate multiple inheritence in Java Application. 2. To Develop Distributed applications. 98. What is serialization 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. 99. What are the tiers in J2EE architecture

The J2EE Platform provides a component-based approach to the design, development, assembly, and deployment of enterprise applications. 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. 100. What is the difference between static and non-static variables A static variable is associated with the class as a whole rather than with specific instances of a class. Nonstatic variables take on unique values with each object instance. 101. What is the difference between yielding and sleeping When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state. 102. What is Serialization and Deserialization 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 103. What are 4 drivers available in JDBC there 4 drivers available in java they are JDBC-ODBC bridge driver Native API partly java driver JDBC Net pure java driver Native protocol pure java driver 104. What is the main functionality of the Prepared Statement 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. 105. What is the difference between final, finally and finalized 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 106. Can the abstract class be final 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 107. What is the difference between exception and error

An Exception can be caught and recovered: ArrayIndexOutOfBoundsException means you tried to access a position of an Array that does not exist - no big deal. An Error is unrecoverable: OutOfMemoryError means that the JVM has no more memory to contin 108. How many methods in the Externalizable interface? 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(). 109. What is Java Beans ? Java bean is a simple java class with setter and getter methods which can hold data. 110. What is the difference between instanceof and isInstance? 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. 111. What is the Dictionary class The Dictionary class provides the capability to store key-value pairs.

Struts

1.

type="com.test.LoginForm"/>

path="/login" type="com.test.user.login.LoginAction" name="loginForm" validate="false">

Question: Assuming the class LoginForm contains a String property named "password", how does the LoginAction class access the attribute called "password" in the above request? Explain why. 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();
the "Password" attribute can be Called in Action as "String password = form.getPassword(); " as per the FormClass.. If you are Used as an dynaActionForm For Hidden purpose the syntax Will be <formName.set("Password",<value>)> the Passowrd Parmeter should be mention in the strutsConfig.Xml 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.. 2.what is the diff between perform() and execute() method? 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. 2.

What is the diffrence between Apache struts and jakarta struts ?

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.

yes , give only the welcome jsp page. 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. MVC Model 2 Architecture is Struts. 1. Whenever a request comes to controller ActionServlet is Invoked which looks for ActioMapping in strutsconfig.xml 2. Action Servlet looks for existence of form bean corresponds to input request. 3. If not exist then instatinate the correpsonding ActionForm 4. ActionServlet Call the execute method of the corresponding Action Class 5. Which return ActionForward object with lookup value. 6. Action Servlet then do ActionMapping the forward to the Corresponding View according to the lookup value of ActionForward Class. 7. View Responds it to Client. This is MVC 2 Architecture. This is Servlet Centric

i) All requests are passed through a controller servlet, known as Action-servlet. This is achieved by suitable 'url-mapping' in web.xml file.We have been doing 'URLpattern' 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 strutsconfig.xml
7.

Why we use static method in Business Logic?

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

What is difference between Design Pattern and FrameWork.

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.. strutsconfig.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 9.

What is super class of Action and ActionForm?

Object is the super class for Action and ActionForm. Action is a class and ActionForm is an abstract class. 10. what is the use of findbyprimarykey()? 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 Struts design pattern is MVC(Model-View-Controller) View - Jsps,Custom Tags, etc., Model - Simaple Java Bean (In Struts its Form Bean) Controller - Servlets(Action Calsses) 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 Actual difference between MVC1 and MVC2 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. 14. What is Struts The core of the Struts framework is a flexible control layer based on standard technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons packages. Struts encourages application architectures based on the Model 2 approach, a variation of the classic Model-View-Controller (MVC) design paradigm. Struts provides its own Controller component and integrates with other technologies to provide the Model and the View. For the Model, Struts can interact with standard data access technologies, like JDBC and EJB, as well as most any third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts works well with JavaServer Pages, including JSTL and JSF, as well as Velocity Templates, XSLT, and other presentation systems. The Struts framework provides the invisible underpinnings every professional web application needs to survive. Struts helps you create an extensible development environment for your application, based on published standards and proven design patterns. 15. What is the difference between ActionForm and DynaActionForm 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 timeconsuming. 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. 16. What are the Important Components of Struts?

Struts Configuration File ActionServlet RequestProcessor ActionForm Action ActionFroward ActionMapping ActionErrors 16. What is DispatchAction 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 The main differences are 1. In Action class Perform() method was replaced by execute() method. 2. DynaActionForms are added. 3. Tiles Concept is introduced. 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. Apart from these some updates in web.xml and Struts-Config.xml. 18. How to call ejb from Struts In the perform method of the Action class u can can drop the code that is responisble for connecting to the EJB. 1. Get Initial Context 2. Get home object using JNDI 3 Create the bean and call teh business methods 19. How you will handle errors and exceptions using Struts there are various ways to handle exception: 1) To handle errors server side validation can be used using ActionErrors classes can be used. 2) The exceptions can be wrapped across different layers to show a user showable exception. 3)using validators

20. What are the core classes of struts? The core classes of struts are ActionForm, Action, ActionMapping, ActionForward etc. 20. What is the difference between ActionErrors and ActionMessages 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. 2.

what is the use of using session facade design pattern in EJB'S? how we deploy in weblogic?

Make a war /ear/jar file of the application eg: if all your app'n code , etc is in say folder d:/mybankappn then which is a web app'n then.. go to D:\mybankappn> jar -cvf bankappn.war *.* start weblogic server. Go to weblogic console (in browser : http:\\localhost:7001\console) and login.. click web-app'n from lefside pane -> deployment 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. if its sucess----> then go to browser and call ( http:\\localhost:7001\mybank\index.html Ho Gaya. similarly you have deployent option is in Load your file link in the weblogic console. 3.

what is the use of activate, passivate methods in EJB?

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. Entity been slows down data fetch operation. U just need to use stateless session bean.

5. what is the default transaction attribute in transactions
There is no default transaction attribute for an EJB. In weblogic, the default transaction attribute for EJB is SUPPORTS. 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.

6. what is session synchronization in EJB
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.

8. What is return type of create method of an entity bean
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. 10. What is the importance of the Narrow class in RMI? 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 Context ic=new InitialContext(); Object 0=ic.lookup("String"); 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.

12. why we need the transactions?
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. 13. What is an EJB Context? EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions. See the API docs and the spec for more details. 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 dataobject 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"). 15. what is requestdespatcher? RequestDiapatcher is a interface comes from javax.servlet package.It has two methods include(request,response)forwared(request,response)it is used to transfer the request and the response object to the other layes life (jsps & servlets )server side .Advantage :- when ever u used request despatcher it mean transfering from one layer to another is done by your server not by the client i.e browser. 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. 18. What are the call back methods in Session bean Stateless Session Bean 1. setSessionContext() 2. ejbCreate() 3. ejbRemove() Stateful Session Bean 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 20. Can a Session Bean be defined without ejbCreate() method We cannot have a session bean without ejbCreate().

• • •

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. b) Stateful session beans remembers the previous requests and reponses. Stateless session beans do not remember the previous request and responses. c)Stateful session beans does not have pooling concept. Stattless session bean instances are pooled. d) Stateful S.Beans can retain their state on behave of an individual client. Stateless S.Beans donot maintain states. 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. 22. How statefull session bean remembers it's client state Through its convesational state, may be a member variable of the bean 23. What is the difference between JavaBean and EJB 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 28. What is ACID

29. What is the difference between CMP and BMP
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 32. Does Stateful Session bean support instance pooling
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
2types of exceptions can occur 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 36. What are the services provided by container The services include transaction, naming, and persistence support. 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. 37. What is difference between EJB 1.1 and EJB 2.0 EJB 2.0 came with new features which not available in EJB1.1 they are auto primarykey generation,EJBquery 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 some more features along with Local beans 1.message driven beans 2.Support for EJB Query language 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

Primary key class has to meet the following requirements • The access control modifier of the class is public.
• •

All fields are declared as public. The class has a public default constructor. The class implements the hashCode() and equals(Object other) methods. The class is serializable

39. What is the difference b/w sendRedirect() and <jsp: forward>?
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. 40. What is Instance pooling 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. 42. What is the difference between sessioncontext and entitycontext 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 43. What is the difference between activation and passivation 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. 46. What is EJB architecture(components) EJB Architecture consists of : 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.

3.which one is better to create a thread by implementing Runnable or By Extending Thread in java?
creating a thread by implementing Runnable interface is best.

1. by extends the thread class in the subclass, forther the subclass doesnot extend any other classes. 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 4. what is thin driver and thick driver.why it is called so? Basic difference between thin and thick client 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. 5. what is the need of BatchUpdates?

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. 6. In which case i can use ResultSetMetaData and DatabaseMetaData?
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. 7. What is class in class.forname()? 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"); for Oracle8i thin jdbc driver. Class is the class in class.forName(). The forName method will return the object of the class that we are passing as string. 8. How can you configure Type-4 driver in cleandesktop? Type 4 driver is pure java JDBC driver. 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. Example is classes12.jar which is Oracle driver. 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:

java -Djdbc.drivers=DriverClassName AJavaApp (B)As part of its initialization, the DriverManager class will attempt to load the driver classes referenced in the "jdbc.drivers" system property.This allows a user to customize the JDBC Drivers used by their applications.
For example in your ~/.hotjava/properties file you might specify:

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. 13. why do we use prepared statement when already statement is present 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. 14. How to get the resultset of stroedProcedure By invoking the getObject on the CallableStatement. CallableStatement proc = conn.prepareCall("{ ? = call " + functionSql + " }"); proc.registerOutParameter(1, Types.OTHER); proc.execute(); ResultSet results = (ResultSet) proc.getObject(1); 15. Difference between Type-2 and Type-3 driver

Type-2 driver is Part Java Part Native Driver. This driver is a mixture of Jdbc driver and Vendor speciifc driver . You not only use ODBC to communicate with DataBase. You can also use Vendor specif Apis like Oracle Call Level Interface (OCI) that is supplied by Oracle.When an application is sent to the Jdbc driver this driver sends this request to Vendor specific api and that inturn communicates with the Database.Type-3 driver is Intermediate Acess Protocol Driver where as in this case when an application is sent to the JDBC Driver and that is sent to another intermediate acess servers and that inturn is sent to another native driver (can be an Type-2 driver)and then the request is sent to Database. 16. What is the purpose of setAutoCommit( ) 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 Page Directive 1. includes static content at compile time 2. if the file includes static text if the file is rarely changed (the JSP engine may not recompile the JSP if this type of included file is modified) if you have a common code snippet that you can reuse across multiple pages (e.g. headers and footers) 3. Sy. <%@ include file=”filename” %> 4. after inclusion any change in source file will not reflect the jsp. 5 we are using page directive in the application it means it is going to include that into the page at translation time 6. in translation time it will create 2 servlets 7. it is evaluated only once at

Include Action Tag 1. action include includes static or dynamic content at run time 2. content that changes at runtime to select which content to render at runtime (because the page and src attributes can take runtime expressions) for files that change often 3. Sy. <jsp:include page:”URL” > 4. after inclusion if there any changes in source file will reflect in jsp 5. where as when ever we are using standard action it is includes the page at runtime 6. in translation it will create only one servlet. 7. it is evaluated with every request.

translation time. 8. parsed by container.

8. not parsed, but included in place the specified url is specified at runtime as a separate resource. The included url may map to a servlet rather than a jsp. 9. use it if our resource is not going to 9. use it when the resource changes change frequently frequently or is dynamic. 10. the attribute of page directive is ‘file’ 10. attribute of action include is ‘page’ and values is ‘filename’ and values is ‘URL’
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 pageContext is the object. Eg: ServletRequest getRequest() 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?
SingleThreadModel is now deprecated. 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. 4. how do we perform redirect action without using

response.sendRedirect(" ");
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) 6. How to delete cookies in JSP?

Use the setMaxAge() of the Cookie class...by setting it to zero (0), u can delete the cookie... 7. Why we can't implement interface in JSP?

Why we can only extend classes in JSP?
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. 8. How to Upload a textfile from JSP to Servlet if u used MVC architecture u just used in jsp<input type="file" > tag and in servlet use just used servletInput stream to get that file and do whatever u want by using IO.api package 9. How Do you implement interface in JSP? U can,t Implement Interfaces but u can Extend Class Using <% @ page extend="className"> 10. How do u maintain a Session? How do u maintain a Session? 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 RequestWhen 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 5.Send Redirect is in client and Forward was in server side i think everybody has clear these facts 13. What is the difference betweeen a statis and dynamic include? 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 .)

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->