Saturday, September 03, 2005

J2EE questions

1. Can we use the constructor, instead of init(), to initialize servlet? - Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.
2. How can a servlet refresh automatically if some new data has entered the database? - You can use a client-side Refresh or Server Push.
3. The code in a finally clause will never fail to execute, right? - Using System.exit(1); in try block will not allow finally code to execute.
4. How many messaging models do JMS provide for and what are they? - JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing.
5. What information is needed to create a TCP Socket? - The Local System?s IP Address and Port Number. And the Remote System’s IPAddress and Port Number.
6. What Class.forName will do while loading drivers? - It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.
7. How to Retrieve Warnings? - SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object
8. SQLWarning warning = stmt.getWarnings();
9. if (warning != null)
10. {
11. while (warning != null)
12. {
13. System.out.println("Message: " + warning.getMessage());
14. System.out.println("SQLState: " + warning.getSQLState());
15. System.out.print("Vendor error code: ");
16. System.out.println(warning.getErrorCode());
17. warning = warning.getNextWarning();
18. }
19. }
20. How many JSP scripting elements are there and what are they? - There are three scripting language elements: declarations, scriptlets, expressions.
21. In the Servlet 2.4 specification SingleThreadModel has been deprecates, why? - Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.
22. What are stored procedures? How is it useful? - A stored procedure is a set of statements/commands which reside in the database. The stored procedure is precompiled and saves the database the effort of parsing and compiling sql statements everytime a query is run. Each Database has it’s own stored procedure language, usually a variant of C with a SQL preproceesor. Newer versions of db’s support writing stored procedures in Java and Perl too. Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to implement the business logic( A lot of systems still do it). The biggest advantage is of course speed. Also certain kind of data manipulations are not achieved in SQL. Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when you want to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection may be significant in these cases.
23. How do I include static files within a JSP page? - Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. The following example shows the syntax: Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.
24. Why does JComponent have add() and remove() methods but Component does not? - because JComponent is a subclass of Container, and can contain other components and jcomponents.
25. How can I implement a thread-safe JSP page? - You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" % > within your JSP page.
26. Is is possible for an EJB client to marshal an object of class java.lang.Class to an EJB? - Technically yes, spec. compliant NO! - The enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language.
27. Is it legal to have static initializer blocks in EJB? - Although technically it is legal, static initializer blocks are used to execute some piece of code before executing any constructor or method while instantiating a class. Static initializer blocks are also typically used to initialize static fields - which may be illegal in EJB if they are read/write - In EJB this can be achieved by including the code in either the ejbCreate(), setSessionContext() or setEntityContext() methods.
28. Is it possible to stop the execution of a method before completion in a SessionBean? - Stopping the execution of a method inside a Session Bean is not possible without writing code inside the Session Bean. This is because you are not allowed to access Threads inside an EJB.
29. What is the default transaction attribute for an EJB? - There is no default transaction attribute for an EJB. Section 11.5 of EJB v1.1 spec says that the deployer must specify a value for the transaction attribute for those methods having container managed transaction. In WebLogic, the default transaction attribute for EJB is SUPPORTS.
30. What is the difference between session and entity beans? When should I use one or the other? - An entity bean represents persistent global data from the database; a session bean represents transient user-specific data that will die when the user disconnects (ends his session). Generally, the session beans implement business methods (e.g. Bank.transferFunds) that call entity beans (e.g. Account.deposit, Account.withdraw)
31. Is there any default cache management system with Entity beans ? In other words whether a cache of the data in database will be maintained in EJB ? - Caching data from a database inside the Application Server are what Entity EJB’s are used for.The ejbLoad() and ejbStore() methods are used to synchronize the Entity Bean state with the persistent storage(database). Transactions also play an important role in this scenario. If data is removed from the database, via an external application - your Entity Bean can still be “alive” the EJB container. When the transaction commits, ejbStore() is called and the row will not be found, and the transaction rolled back.
32. Why is ejbFindByPrimaryKey mandatory? - An Entity Bean represents persistent data that is stored outside of the EJB Container/Server. The ejbFindByPrimaryKey is a method used to locate and load an Entity Bean into the container, similar to a SELECT statement in SQL. By making this method mandatory, the client programmer can be assured that if they have the primary key of the Entity Bean, then they can retrieve the bean without having to create a new bean each time - which would mean creating duplications of persistent data and break the integrity of EJB.
33. Why do we have a remove method in both EJBHome and EJBObject? - With the EJBHome version of the remove, you are able to delete an entity bean without first instantiating it (you can provide a PrimaryKey object as a parameter to the remove method). The home version only works for entity beans. On the other hand, the Remote interface version works on an entity bean that you have already instantiated. In addition, the remote version also works on session beans (stateless and stateful) to inform the container of your loss of interest in this bean.
34. How can I call one EJB from inside of another EJB? - EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference, and so forth.
35. What is the difference between a Server, a Container, and a Connector? - An EJB server is an application, usually a product such as BEA WebLogic, that provides (or should provide) for concurrent client connections and manages system resources such as threads, processes, memory, database connections, network connections, etc. An EJB container runs inside (or within) an EJB server, and provides deployed EJB beans with transaction and security management, etc. The EJB container insulates an EJB bean from the specifics of an underlying EJB server by providing a simple, standard API between the EJB bean and its container. A Connector provides the ability for any Enterprise Information System (EIS) to plug into any EJB server which supports the Connector architecture. See Sun’s J2EE Connectors for more in-depth information on Connectors.
36. How is persistence implemented in enterprise beans? - Persistence in EJB is taken care of in two ways, depending on how you implement your beans: container managed persistence (CMP) or bean managed persistence (BMP) For CMP, the EJB container which your beans run under takes care of the persistence of the fields you have declared to be persisted with the database - this declaration is in the deployment descriptor. So, anytime you modify a field in a CMP bean, as soon as the method you have executed is finished, the new data is persisted to the database by the container. For BMP, the EJB bean developer is responsible for defining the persistence routines in the proper places in the bean, for instance, the ejbCreate(), ejbStore(), ejbRemove() methods would be developed by the bean developer to make calls to the database. The container is responsible, in BMP, to call the appropriate method on the bean. So, if the bean is being looked up, when the create() method is called on the Home interface, then the container is responsible for calling the ejbCreate() method in the bean, which should have functionality inside for going to the database and looking up the data.
37. 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.
38. Is method overloading allowed in EJB? - Yes you can overload methods
39. Should synchronization primitives be used on bean methods? - No. The EJB specification specifically states that the enterprise bean is not allowed to use thread primitives. The container is responsible for managing concurrent access to beans at runtime.
40. Are we allowed to change the transaction isolation property in middle of a transaction? - No. You cannot change the transaction isolation level in the middle of transaction.
41. For Entity Beans, What happens to an instance field not mapped to any persistent storage, when the bean is passivated? - The specification infers that the container never serializes an instance of an Entity bean (unlike stateful session beans). Thus passivation simply involves moving the bean from the “ready” to the “pooled” bin. So what happens to the contents of an instance variable is controlled by the programmer. Remember that when an entity bean is passivated the instance gets logically disassociated from it’s remote object. Be careful here, as the functionality of passivation/activation for Stateless Session, Stateful Session and Entity beans is completely different. For entity beans the ejbPassivate method notifies the entity bean that it is being disassociated with a particular entity prior to reuse or for dereference.
42. What is a Message Driven Bean, what functions does a message driven bean have and how do they work in collaboration with JMS? - Message driven beans are the latest addition to the family of component bean types defined by the EJB specification. The original bean types include session beans, which contain business logic and maintain a state associated with client sessions, and entity beans, which map objects to persistent data. Message driven beans will provide asynchrony to EJB based applications by acting as JMS message consumers. A message bean is associated with a JMS topic or queue and receives JMS messages sent by EJB clients or other beans. Unlike entity beans and session beans, message beans do not have home or remote interfaces. Instead, message driven beans are instantiated by the container as required. Like stateless session beans, message beans maintain no client-specific state, allowing the container to optimally manage a pool of message-bean instances. Clients send JMS messages to message beans in exactly the same manner as they would send messages to any other JMS destination. This similarity is a fundamental design goal of the JMS capabilities of the new specification. To receive JMS messages, message driven beans implement the javax.jms.MessageListener interface, which defines a single “onMessage()” method. When a message arrives, the container ensures that a message bean corresponding to the message topic/queue exists (instantiating it if necessary), and calls its onMessage method passing the client’s message as the single argument. The message bean’s implementation of this method contains the business logic required to process the message. Note that session beans and entity beans are not allowed to function as message beans.
43. Does RMI-IIOP support code downloading for Java objects sent by value across an IIOP connection in the same way as RMI does across a JRMP connection? - Yes. The JDK 1.2 support the dynamic class loading.
44. The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes? - The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. while refering the EJB Object classes the container creates a separate instance for each client request. The instance pool maintainence is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is again up to the implementer.
45. What is the advantage of putting an Entity Bean instance from the “Ready State” to “Pooled state"? - The idea of the “Pooled State” is to allow a container to maintain a pool of entity beans that has been created, but has not been yet “synchronized” or assigned to an EJBObject. This mean that the instances do represent entity beans, but they can be used only for serving Home methods (create or findBy), since those methods do not relay on the specific values of the bean. All these instances are, in fact, exactly the same, so, they do not have meaningful state. Jon Thorarinsson has also added: It can be looked at it this way: If no client is using an entity bean of a particular type there is no need for cachig it (the data is persisted in the database). Therefore, in such cases, the container will, after some time, move the entity bean from the “Ready State” to the “Pooled state” to save memory. Then, to save additional memory, the container may begin moving entity beans from the “Pooled State” to the “Does Not Exist State", because even though the bean’s cache has been cleared, the bean still takes up some memory just being in the “Pooled State".
46. Can a Session Bean be defined without ejbCreate() method? - The ejbCreate() methods is part of the bean’s lifecycle, so, the compiler will not return an error because there is no ejbCreate() method. However, the J2EE spec is explicit: the home interface of a Stateless Session Bean must have a single create() method with no arguments, while the session bean class must contain exactly one ejbCreate() method, also without arguments. Stateful Session Beans can have arguments (more than one create method) stateful beans can contain multiple ejbCreate() as long as they match with the home interface definition. You need a reference to your EJBObject to startwith. For that Sun insists on putting a method for creating that reference (create method in the home interface). The EJBObject does matter here. Not the actual bean.
47. Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB? - You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be consider as “passed-by-value", that means that it’s read-only in the EJB. If anything is altered from inside the EJB, it won’t be reflected back to the HttpSession of the Servlet Container.The “pass-by-reference” can be used between EJBs Remote Interfaces, as they are remote references. While it IS possible to pass an HttpSession as a parameter to an EJB object, it is considered to be “bad practice (1)” in terms of object oriented design. This is because you are creating an unnecessary coupling between back-end objects (ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for your ejb’s api. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your ejb needs to support a non-http-based client. This higher level of abstraction will be flexible enough to support it. (1) Core J2EE design patterns (2001)
48. Is there any way to read values from an entity bean without locking it for the rest of the transaction (e.g. read-only transactions)? We have a key-value map bean which deadlocks during some concurrent reads. Isolation levels seem to affect the database only, and we need to work within a transaction. - The only thing that comes to (my) mind is that you could write a ‘group accessor’ - a method that returns a single object containing all of your entity bean’s attributes (or all interesting attributes). This method could then be placed in a ‘Requires New’ transaction. This way, the current transaction would be suspended for the duration of the call to the entity bean and the entity bean’s fetch/operate/commit cycle will be in a separate transaction and any locks should be released immediately. Depending on the granularity of what you need to pull out of the map, the group accessor might be overkill.
49. What is the difference between a “Coarse Grained” Entity Bean and a “Fine Grained” Entity Bean? - A ‘fine grained’ entity bean is pretty much directly mapped to one relational table, in third normal form. A ‘coarse grained’ entity bean is larger and more complex, either because its attributes include values or lists from other tables, or because it ‘owns’ one or more sets of dependent objects. Note that the coarse grained bean might be mapped to a single table or flat file, but that single table is going to be pretty ugly, with data copied from other tables, repeated field groups, columns that are dependent on non-key fields, etc. Fine grained entities are generally considered a liability in large systems because they will tend to increase the load on several of the EJB server’s subsystems (there will be more objects exported through the distribution layer, more objects participating in transactions, more skeletons in memory, more EJB Objects in memory, etc.)
50. What is EJBDoclet? - EJBDoclet is an open source JavaDoc doclet that generates a lot of the EJB related source files from custom JavaDoc comments tags embedded in the EJB source file.
51. Is “abc” a primitive value? - The String literal “abc” is not a primitive value. It is a String object.
52. What restrictions are placed on the values of each case of a switch statement? - During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.
53. What modifiers may be used with an interface declaration? - An interface may be declared as public or abstract.
54. Is a class a subclass of itself? - A class is a subclass of itself.
55. What is the difference between a while statement and a do statement? - A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.
56. What modifiers can be used with a local inner class? - A local inner class may be final or abstract.
57. What is the purpose of the File class? - The File class is used to create objects that provide access to the files and directories of a local file system.
58. Can an exception be rethrown? - Yes, an exception can be rethrown.
59. When does the compiler supply a default constructor for a class? - The compiler supplies a default constructor for a class if no other constructors are provided.
60. If a method is declared as protected, where may the method be accessed? - A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.
61. Which non-Unicode letter characters may be used as the first character of an identifier? - The non-Unicode letter characters $ and _ may appear as the first character of an identifier
62. What restrictions are placed on method overloading? - Two methods may not have the same name and argument list but different return types.
63. What is casting? - There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.
64. What is the return type of a program’s main() method? - A program’s main() method has a void return type.
65. What class of exceptions are generated by the Java run-time system? - The Java runtime system generates RuntimeException and Error exceptions.
66. What class allows you to read objects directly from a stream? - The ObjectInputStream class supports the reading of objects from input streams.
67. What is the difference between a field variable and a local variable? - A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.
68. How are this() and super() used with constructors? - this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
69. What is the relationship between a method’s throws clause and the exceptions that can be thrown during the method’s execution? - A method’s throws clause must declare any checked exceptions that are not caught within the body of the method.
70. Why are the methods of the Math class static? - So they can be invoked as if they are a mathematical code library.
71. What are the legal operands of the instanceof operator? - The left operand is an object reference or null value and the right operand is a class, interface, or array type.
72. What an I/O filter? - An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.
73. If an object is garbage collected, can it become reachable again? - Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.
74. What are E and PI? - E is the base of the natural logarithm and PI is mathematical value pi.
75. Are true and false keywords? - The values true and false are not keywords.
76. What is the difference between the File and RandomAccessFile classes? - The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.
77. What happens when you add a double value to a String? - The result is a String object.
78. What is your platform’s default character encoding? - If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1.
79. Which package is always imported by default? - The java.lang package is always imported by default.
80. What interface must an object implement before it can be written to a stream as an object? - An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.
81. How can my application get to know when a HttpSession is removed? - Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method. Create an instance of that class and put that instance in HttpSession.
82. Whats the difference between notify() and notifyAll()? - notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change (for example, when freeing a buffer back into a pool). notifyAll() is necessary (for correctness) if multiple threads should resume (for example, when releasing a “writer” lock on a file might permit all “readers” to resume).
83. Why can’t I say just abs() or sin() instead of Math.abs() and Math.sin()? - The import statement does not bring methods into your local name space. It lets you abbreviate class names, but not get rid of them altogether. That’s just the way it works, you’ll get used to it. It’s really a lot safer this way.
However, there is actually a little trick you can use in some cases that gets you what you want. If your top-level class doesn’t need to inherit from anything else, make it inherit from java.lang.Math. That *does* bring all the methods into your local name space. But you can’t use this trick in an applet, because you have to inherit from java.awt.Applet. And actually, you can’t use it on java.lang.Math at all, because Math is a “final” class which means it can’t be extended.
84. Why are there no global variables in Java? - Global variables are considered bad form for a variety of reasons: Adding state variables breaks referential transparency (you no longer can understand a statement or expression on its own: you need to understand it in the context of the settings of the global variables), State variables lessen the cohesion of a program: you need to know more to understand how something works. A major point of Object-Oriented programming is to break up global state into more easily understood collections of local state, When you add one variable, you limit the use of your program to one instance. What you thought was global, someone else might think of as local: they may want to run two copies of your program at once. For these reasons, Java decided to ban global variables.
85. What does it mean that a class or member is final? - A final class can no longer be subclassed. Mostly this is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. Methods may be declared final as well. This means they may not be overridden in a subclass. Fields can be declared final, too. However, this has a completely different meaning. A final field cannot be changed after it’s initialized, and it must include an initializer statement where it’s declared. For example, public final double c = 2.998; It’s also possible to make a static field final to get the effect of C++’s const statement or some uses of C’s #define, e.g. public static final double c = 2.998;
86. What does it mean that a method or class is abstract? - An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class is abstract with the abstract keyword like this:
87. public abstract class Container extends Component {
Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the current class. It exists only to be overridden in subclasses. It has no body. For example,
public abstract float price();
Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract.
88. What is a transient variable? - transient variable is a variable that may not be serialized.
89. How are Observer and Observable used? - Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.
90. Can a lock be acquired on a class? - Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object.
91. What state does a thread enter when it terminates its processing? - When a thread terminates its processing, it enters the dead state.
92. How does Java handle integer overflows and underflows? - It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
93. What is the difference between the >> and >>> operators? - The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.
94. Is sizeof a keyword? - The sizeof operator is not a keyword.
95. Does garbage collection guarantee that a program will not run out of memory? - Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection
96. Can an object’s finalize() method be invoked while it is reachable? - An object’s finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object’s finalize() method may be invoked by other objects.
97. What value does readLine() return when it has reached the end of a file? - The readLine() method returns null when it has reached the end of a file.
98. Can a for statement loop indefinitely? - Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;
99. To what value is a variable of the String type automatically initialized? - The default value of an String type is null.
100. What is a task’s priority and how is it used in scheduling? - A task’s priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.
101. What is the range of the short type? - The range of the short type is -(2^15) to 2^15 - 1.
102. What is the purpose of garbage collection? - The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused.
103. What do you understand by private, protected and public? - These are accessibility modifiers. Private is the most restrictive, while public is the least restrictive. There is no real difference between protected and the default type (also known as package protected) within the context of the same package, however the protected keyword allows visibility to a derived class in a different package.
104. What is Downcasting ? - Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy
105. Can a method be overloaded based on different return type but same argument type ? - No, because the methods can be called without using their return type in which case there is ambiquity for the compiler
106. What happens to a static var that is defined within a method of a class ? - Can’t do it. You’ll get a compilation error
107. How many static init can you have ? - As many as you want, but the static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope.
108. What is the difference amongst JVM Spec, JVM Implementation, JVM Runtime ? - The JVM spec is the blueprint for the JVM generated and owned by Sun. The JVM implementation is the actual implementation of the spec by a vendor and the JVM runtime is the actual running instance of a JVM implementation
109. Describe what happens when an object is created in Java? - Several things happen in a particular order to ensure the object is constructed properly: Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data. The instance variables of the objects are initialized to their default values. The constructor for the most derived class is invoked. The first thing a constructor does is call the consctructor for its superclasses. This process continues until the constrcutor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.
110. What does the “final” keyword mean in front of a variable? A method? A class? - FINAL for a variable: value is constant. FINAL for a method: cannot be overridden. FINAL for a class: cannot be derived
111. 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 non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.
112. Why does it take so much time to access an Applet having Swing Components the first time? - Because behind every swing component are many Java objects and resources. This takes time to create them in memory. JDK 1.3 from Sun has some improvements which may lead to faster execution of Swing applications.
113. What is the query used to display all tables names in SQL Server (Query analyzer)?
114. select * from information_schema.tables
115. How many types of JDBC Drivers are present and what are they?- There are 4 types of JDBC Drivers
1. JDBC-ODBC Bridge Driver
2. Native API Partly Java Driver
3. Network protocol Driver
4. JDBC Net pure Java Driver
116. Can we implement an interface in a JSP?- No
117. What is the difference between ServletContext and PageContext?- ServletContext: Gives the information about the container. PageContext: Gives the information about the Request
118. What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?- request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource, context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.
119. How to pass information from JSP to included JSP?- Using <%jsp:param> tag.
120. What is the difference between directive include and jsp include?- <%@ include>: Used to include static resources during translation time. JSP include: Used to include dynamic content or static content during runtime.
121. What is the difference between RequestDispatcher and sendRedirect?- RequestDispatcher: server-side redirect with request and response objects. sendRedirect : Client-side redirect with new request and response objects.
122. How does JSP handle runtime exceptions?- Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP.
123. How do you delete a Cookie within a JSP?
124. Cookie mycook = new Cookie("name","value");
125. response.addCookie(mycook);
126. Cookie killmycook = new Cookie("mycook","value");
127. killmycook.setMaxAge(0);
128. killmycook.setPath("/");
129. killmycook.addCookie(killmycook);
130. How do I mix JSP and SSI #include?- If you’re just including raw HTML, use the #include directive as usual inside your .jsp file.
131.
But it’s a little trickier if you want the server to evaluate any JSP code that’s inside the included file. If your data.inc file contains jsp code you will have to use
<%@ vinclude="data.inc" %>
The is used for including non-JSP files.
132. I made my class Cloneable but I still get Can’t access protected method clone. Why?- Some of the Java books imply that all you have to do in order to have your class support clone() is implement the Cloneable interface. Not so. Perhaps that was the intent at some point, but that’s not the way it works currently. As it stands, you have to implement your own public clone() method, even if it doesn’t do anything special and just calls super.clone().
133. Why is XML such an important development?- It removes two constraints which were holding back Web developments: dependence on a single, inflexible document type (HTML) which was being much abused for tasks it was never designed for; the complexity of full SGML, whose syntax allows many powerful but hard-to-program options. XML allows the flexible development of user-defined document types. It provides a robust, non-proprietary, persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web; and it removes the more complex options of SGML, making it easier to program for.
134. What is the fastest type of JDBC driver?- JDBC driver performance will depend on a number of issues:
1. the quality of the driver code,
2. the size of the driver code,
3. the database server and its load,
4. network topology,
5. the number of times your request is translated to a different API.
In general, all things being equal, you can assume that the more your request and response change hands, the slower it will be. This means that Type 1 and Type 3 drivers will be slower than Type 2 drivers (the database calls are make at least three translations versus two), and Type 4 drivers are the fastest (only one translation).
135. How do I find whether a parameter exists in the request object?
136. boolean hasFoo = !(request.getParameter("foo") == null
137. || request.getParameter("foo").equals(""));
or
boolean hasParameter =
request.getParameterMap().contains(theParameter); //(which works in Servlet 2.3+)
138. How can I send user authentication information while makingURLConnection?- You’ll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.
139. Are enterprise beans allowed to use Thread.sleep()? - Enterprise beans make use of the services provided by the EJB container, such as life-cycle management. To avoid conflicts with these services, enterprise beans are restricted from performing certain operations: Managing or synchronizing threads
140. Is it possible to write two EJB’s that share the same Remote and Home interfaces, and have different bean classes? if so, what are the advantages/disadvantages? - It’s certainly possible. In fact, there’s an example that ships with the Inprise Application Server of an Account interface with separate implementations for CheckingAccount and SavingsAccount, one of which was CMP and one of which was BMP.
141. Is it possible to specify multiple JNDI names when deploying an EJB? - No. To achieve this you have to deploy your EJB multiple times each specifying a different JNDI name.
142. Is there any way to force an Entity Bean to store itself to the db? I don’t wanna wait for the container to update the db, I want to do it NOW! Is it possible? - Specify the transaction attribute of the bean as RequiresNew. Then as per section 11.6.2.4 of the EJB v 1.1 spec EJB container automatically starts a new transaction before the method call. The container also performs the commit protocol before the method result is sent to the client.
143. I am developing a BMP Entity bean. I have noticed that whenever the create method is invoked, the ejbLoad() and the ejbStore() methods are also invoked. I feel that once my database insert is done, having to do a select and update SQL queries is major overhead. is this behavior typical of all EJB containers? Is there any way to suppress these invocations? - This is the default behaviour for EJB. The specification states that ejbLoad() will be called before every transaction and ejbStore() after every transaction. Each Vendor has optimizations, which are proprietary for this scenario.
144. Can an EJB send asynchronous notifications to its clients? - Asynchronous notification is a known hole in the first versions of the EJB spec. The recommended solution to this is to use JMS, which is becoming available in J2EE-compliant servers. The other option, of course, is to use client-side threads and polling. This is not an ideal solution, but it’s workable for many scenarios.
145. How can I access EJB from ASP? - You can use the Java 2 Platform, Enterprise Edition Client Access Services (J2EETM CAS) COM Bridge 1.0, currently downloadable from Sun
146. Is there a guarantee of uniqueness for entity beans? - There is no such guarantee. The server (or servers) can instantiate as many instances of the same underlying Entity Bean (with the same PK) as it wants. However, each instance is guaranteed to have up-to-date data values, and be transactionally consistent, so uniqueness is not required. This allows the server to scale the system to support multiple threads, multiple concurrent requests, and multiple hosts.
147. How do the six transaction attributes map to isolation levels like “dirty read"? Will an attribute like “Required” lock out other readers until I’m finished updating? - The Transaction Attributes in EJB do not map to the Transaction Isolation levels used in JDBC. This is a common misconception. Transaction Attributes specify to the container when a Transaction should be started, suspended(paused) and committed between method invocations on Enterprise JavaBeans. For more details and a summary of Transaction Attributes refer to section 11.6 of the EJB 1.1 specification.
148. I have created a remote reference to an EJB in FirstServlet. Can I put the reference in a servlet session and use that in SecondServlet? - Yes. The EJB client (in this case your servlet) acquires a remote reference to an EJB from the Home Interface; that reference is serializable and can be passed from servlet to servlet. If it is a session bean, then the EJB server will consider your web client’s servlet session to correspond to a single EJB session, which is usually (but not always) what you want.
149. Can the primary key in the entity bean be a Java primitive type such as int? - The primary key can’t be a primitive type–use the primitive wrapper classes, instead. For example, you can use java.lang.Integer as the primary key class, but not int (it has to be a class, not a primitive)
150. What’s new in the EJB 2.0 specification? - Following are the main features supported in EJB 2.0: Integration of EJB with JMS, Message Driven Beans, Implement additional Business methods in Home interface which are not specific for bean instance, EJB QL.
151. How many types of protocol implementations does RMI have? - RMI has at least three protocol implementations: Java Remote Method Protocol(JRMP), Internet Inter ORB Protocol(IIOP), and Jini Extensible Remote Invocation(JERI). These are alternatives, not part of the same thing, All three are indeed layer 6 protocols for those who are still speaking OSI reference model.
152. What is the need of Remote and Home interfaces. Why can’t there be one? - In a few words, I would say that the main reason is because there is a clear division of roles and responsabilities between the two interfaces. The home interface is your way to communicate with the container, that is who is responsable of creating, locating even removing one or more beans. The remote interface is your link to the bean, that will allow you to remotely access to all its methods and members. As you can see there are two distinct elements (the container and the beans) and you need two different interfaces for accessing to both of them.
153. What is the difference between Java Beans and EJB? - Java Beans are client-side objects and EJBs are server side object, and they have completely different development, lifecycle, purpose.
154. Question With regard to Entity Beans, what happens if both my EJB Server and Database crash, what will happen to unsaved changes? Is there any transactional log file used? - Actually, if your EJB server crashes, you will not even be able to make a connection to the server to perform a bean lookup, as the server will no longer be listening on the port for incoming JNDI lookup requests. You will lose any data that wasn’t committed prior to the crash. This is where you should start looking into clustering your EJB server. Any unsaved and uncommited changes are lost the moment your EJB Server crashes. If your database also crashes, then all the saved changes are also lost unless you have some backup or some recovery mechanism to retrieve the data. So consider database replication and EJB Clustering for such scenarios, though the occurence of such a thing is very very rare. Thx, Uma All databse have the concept of log files(for exampe oracle have redo log files concept). So if data bases crashes then on starting up they fill look up the log files to perform all pending jobs. But is EJB crashes, It depend upon the container how frequenlty it passivates or how frequesntly it refreshes the data with Database.
155. Question Can you control when passivation occurs? - The developer, according to the specification, cannot directly control when passivation occurs. Although for Stateful Session Beans, the container cannot passivate an instance that is inside a transaction. So using transactions can be a a strategy to control passivation. The ejbPassivate() method is called during passivation, so the developer has control over what to do during this exercise and can implement the require optimized logic. Some EJB containers, such as BEA WebLogic, provide the ability to tune the container to minimize passivation calls. Taken from the WebLogic 6.0 DTD - “The passivation-strategy can be either “default” or “transaction". With the default setting the container will attempt to keep a working set of beans in the cache. With the “transaction” setting, the container will passivate the bean after every transaction (or method call for a non-transactional invocation).”
156. Does RMI-IIOP support dynamic downloading of classes? - No, RMI-IIOP doesn’t support dynamic downloading of the classes as it is done with CORBA in DII (Dynamic Interface Invocation).Actually RMI-IIOP combines the usability of Java Remote Method Invocation (RMI) with the interoperability of the Internet Inter-ORB Protocol (IIOP).So in order to attain this interoperability between RMI and CORBA,some of the features that are supported by RMI but not CORBA and vice versa are eliminated from the RMI-IIOP specification.
157. Does EJB 1.1 support mandate the support for RMI-IIOP ? What is the meaning of “the client API must support the Java RMI-IIOP programming model for portability, but the underlying protocol can be anything” ? - EJB1.1 does mandate the support of RMI-IIOP. There are 2 types of implementations that an EJB Server might provide: CORBA-based EJB Servers and Proprietry EJB Servers. Both support the RMI-IIOP API but how that API is implemented is a different story. (NB: By API we mean the interface provided to the client by the stub or proxy). A CORBA-based EJB Server actually implements its EJB Objects as CORBA Objects (it therefore encorporates an ORB and this means that EJB’s can be contacted by CORBA clients (as well as RMI-IIOP clients) A proprietry EJB still implements the RMI-IIOP API (in the client’s stub) but the underlying protocol can be anything. Therefore your EJB’s CANNOT be contacted by CORBA clients. The difference is that in both cases, your clients see the same API (hence, your client portability) BUT how the stubs communicate with the server is different.
158. The EJB specification says that we cannot use Bean Managed Transaction in Entity Beans. Why? - The short, practical answer is… because it makes your entity beans useless as a reusable component. Also, transaction management is best left to the application server - that’s what they’re there for. It’s all about atomic operations on your data. If an operation updates more than one entity then you want the whole thing to succeed or the whole thing to fail, nothing in between. If you put commits in the entity beans then it’s very difficult to rollback if an error occurs at some point late in the operation.
159. Can I invoke Runtime.gc() in an EJB? - You shouldn’t. What will happen depends on the implementation, but the call will most likely be ignored. You should leave system level management like garbage collection for the container to deal with. After all, that’s part of the benefit of using EJBs, you don’t have to manage resources yourself.
160. What is clustering? What are the different algorithms used for clustering? - Clustering is grouping machines together to transparantly provide enterprise services.The client does not now the difference between approaching one server or approaching a cluster of servers.Clusters provide two benefits: scalability and high availability. Further information can be found in the JavaWorld article J2EE Clustering.
161. What is the advantage of using Entity bean for database operations, over directly using JDBC API to do database operations? When would I use one over the other? - Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC API. There are two types of Entity Beans Container Managed and Bean Mananged. In Container Managed Entity Bean - Whenever the instance of the bean is created the container automatically retrieves the data from the DB/Persistance storage and assigns to the object variables in bean for user to manipulate or use them. For this the developer needs to map the fields in the database to the variables in deployment descriptor files (which varies for each vendor). In the Bean Managed Entity Bean - The developer has to specifically make connection, retrive values, assign them to the objects in the ejbLoad() which will be called by the container when it instatiates a bean object. Similarly in the ejbStore() the container saves the object values back the the persistance storage. ejbLoad and ejbStore are callback methods and can be only invoked by the container. Apart from this, when you use Entity beans you dont need to worry about database transaction handling, database connection pooling etc. which are taken care by the ejb container. But in case of JDBC you have to explicitly do the above features. what suresh told is exactly perfect. ofcourse, this comes under the database transations, but i want to add this. the great thing about the entity beans of container managed, whenever the connection is failed during the transaction processing, the database consistancy is mantained automatically. the container writes the data stored at persistant storage of the entity beans to the database again to provide the database consistancy. where as in jdbc api, we, developers has to do manually.
162. What is the role of serialization in EJB? - A big part of EJB is that it is a framework for underlying RMI: remote method invocation. You’re invoking methods remotely from JVM space ‘A’ on objects which are in JVM space ‘B’ – possibly running on another machine on the network. To make this happen, all arguments of each method call must have their current state plucked out of JVM ‘A’ memory, flattened into a byte stream which can be sent over a TCP/IP network connection, and then deserialized for reincarnation on the other end in JVM ‘B’ where the actual method call takes place. If the method has a return value, it is serialized up for streaming back to JVM A. Thus the requirement that all EJB methods arguments and return values must be serializable. The easiest way to do this is to make sure all your classes implement java.io.Serializable.
163. What is EJB QL? - EJB QL is a Query Language provided for navigation across a network of enterprise beans and dependent objects defined by means of container managed persistence. EJB QL is introduced in the EJB 2.0 specification. The EJB QL query language defines finder methods for entity beans with container managed persistenceand is portable across containers and persistence managers. EJB QL is used for queries of two types of finder methods: Finder methods that are defined in the home interface of an entity bean and which return entity objects. Select methods, which are not exposed to the client, but which are used by the Bean Provider to select persistent values that are maintained by the Persistence Manager or to select entity objects that are related to the entity bean on which the query is defined.
164. Can there be an abstract class with no abstract methods in it? - Yes
165. Can an Interface be final? - No
166. Can an Interface have an inner class? - Yes.
167. public interface abc
168. {
169. static int i=0; void dd();
170. class a1
171. {
172. a1()
173. {
174. int j;
175. System.out.println("inside");
176. };
177. public static void main(String a1[])
178. {
179. System.out.println("in interfia");
180. }
181. }
182. }
183. Can we define private and protected modifiers for variables in interfaces? - No
184. What is Externalizable? - Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)
185. What modifiers are allowed for methods in an Interface? - Only public and abstract modifiers are allowed for methods in interfaces.
186. What is a local, member and a class variable? - Variables declared within a method are “local” variables. Variables declared within the class i.e not within any methods are “member” variables (global variables). Variables declared within the class i.e not within any methods and are defined as “static” are class variables
187. What are the different identifier states of a Thread? - The different identifiers of a Thread are: R - Running or runnable thread, S - Suspended thread, CW - Thread waiting on a condition variable, MW - Thread waiting on a monitor lock, MS - Thread suspended waiting on a monitor lock
188. What are some alternatives to inheritance? - Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).
189. Why isn’t there operator overloading? - Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn’t even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().
190. What does it mean that a method or field is “static"? - Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That’s how library methods like System.out.println() work. out is a static field in the java.lang.System class.
191. How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?
192. String hostname = InetAddress.getByName("192.18.97.39").getHostName();
193. Difference between JRE/JVM/JDK?
194. Why do threads block on I/O? - Threads block on i/o (that is enters the waiting state) so that other threads may execute while the I/O operation is performed.
195. What is synchronization and why is it important? - With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.
196. Is null a keyword? - The null value is not a keyword.
197. Which characters may be used as the second character of an identifier,but not as the first character of an identifier? - The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.
198. What modifiers may be used with an inner class that is a member of an outer class? - A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
199. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? - Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
200. What are wrapped classes? - Wrapped classes are classes that allow primitive types to be accessed as objects.
201. What restrictions are placed on the location of a package statement within a source code file? - A package statement must appear as the first line in a source code file (excluding blank lines and comments).
202. What is the difference between preemptive scheduling and time slicing? - Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
203. What is a native method? - A native method is a method that is implemented in a language other than Java.
204. What are order of precedence and associativity, and how are they used? - Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left
205. What is the catch or declare rule for method declarations? - If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.
206. Can an anonymous class be declared as implementing an interface and extending a class? - An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
207. What is the range of the char type? - The range of the char type is 0 to 2^16 - 1.
208. What is garbage collection? What is the process that is responsible for doing that in java? - Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process
209. What kind of thread is the Garbage collector thread? - It is a daemon thread.
210. What is a daemon thread? - These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly.
211. How will you invoke any external process in Java? - Runtime.getRuntime().exec(….)
212. What is the finalize method do? - Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected.
213. What is mutable object and immutable object? - If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, …)
214. What is the basic difference between string and stringbuffer object? - String is an immutable object. StringBuffer is a mutable object.
215. What is the purpose of Void class? - The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.
216. What is reflection? - Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions.
217. What is the base class for Error and Exception? - Throwable
218. What is the byte range? -128 to 127
219. What is the implementation of destroy method in java.. is it native or java code? - This method is not implemented.
220. What is a package? - To group set of classes into a single unit is known as packaging. Packages provides wide namespace ability.
221. What are the approaches that you will follow for making a program very efficient? - By avoiding too much of static methods avoiding the excessive and unnecessary use of synchronized methods Selection of related classes based on the application (meaning synchronized classes for multiuser and non-synchronized classes for single user) Usage of appropriate design patterns Using cache methodologies for remote invocations Avoiding creation of variables within a loop and lot more.
222. What is a DatabaseMetaData? - Comprehensive information about the database as a whole.
223. What is Locale? - A Locale object represents a specific geographical, political, or cultural region
224. How will you load a specific locale? - Using ResourceBundle.getBundle(…);
225. What is JIT and its use? - Really, just a very fast compiler… In this incarnation, pretty much a one-pass compiler – no offline computations. So you can’t look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, it’s an on-line problem.
226. Is JVM a compiler or an interpreter? - Interpreter
227. When you think about optimization, what is the best way to findout the time/memory consuming process? - Using profiler
228. What is the purpose of assert keyword used in JDK1.4.x? - In order to validate certain expressions. It effectively replaces the if block and automatically throws the AssertionError on failure. This keyword should be used for the critical arguments. Meaning, without that the method does nothing.
229. How will you get the platform dependent values like line separator, path separator, etc., ? - Using Sytem.getProperty(…) (line.separator, path.separator, …)
230. What is skeleton and stub? what is the purpose of those? - Stub is a client side representation of the server, which takes care of communicating with the remote server. Skeleton is the server side representation. But that is no more in use… it is deprecated long before in JDK.
231. What is the final keyword denotes? - final keyword denotes that it is the final implementation for that method or variable or class. You can’t override that method/variable/class any more.
232. What is the significance of ListIterator? - You can iterate back and forth.
233. What is the major difference between LinkedList and ArrayList? - LinkedList are meant for sequential accessing. ArrayList are meant for random accessing.
234. What is nested class? - If all the methods of a inner class is static then it is a nested class.
235. What is inner class? - If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class.
236. What is composition? - Holding the reference of the other class within some other class is known as composition.
237. What is aggregation? - It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its reference, then it is called aggregation.
238. What are the methods in Object? - clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString
239. Can you instantiate the Math class? - You can’t instantiate the math class. All the methods in this class are static. And the constructor is not public.
240. What is singleton? - It is one of the design pattern. This falls in the creational pattern of the design pattern. There will be only one instance for that entire JVM. You can achieve this by having the private constructor in the class. For eg., public class Singleton { private static final Singleton s = new Singleton(); private Singleton() { } public static Singleton getInstance() { return s; } // all non static methods … }
241. What is DriverManager? - The basic service to manage set of JDBC drivers.
242. What is Class.forName() does and how it is useful? - It loads the class into the ClassLoader. It returns the Class. Using that you can get the instance ( “class-instance".newInstance() ).
243. Inq adds a question: Expain the reason for each keyword of
public static void main(String args[])
1. What is a Marker Interface? - An interface with no methods. Example: Serializable, Remote, Cloneable
2. What interface do you implement to do the sorting? - Comparable
3. What is the eligibility for a object to get cloned? - It must implement the Cloneable interface
4. What is the purpose of abstract class? - It is not an instantiable class. It provides the concrete implementation for some/all the methods. So that they can reuse the concrete functionality by inheriting the abstract class.
5. What is the difference between interface and abstract class? - Abstract class defined with methods. Interface will declare only the methods. Abstract classes are very much useful when there is a some functionality across various classes. Interfaces are well suited for the classes which varies in functionality but with the same method signatures.
6. What do you mean by RMI and how it is useful? - RMI is a remote method invocation. Using RMI, you can work with remote object. The function calls are as though you are invoking a local variable. So it gives you a impression that you are working really with a object that resides within your own JVM though it is somewhere.
7. What is the protocol used by RMI? - RMI-IIOP
8. What is a hashCode? - hash code value for this object which is unique for every object.
9. What is a thread? - Thread is a block of code which can execute concurrently with other threads in the JVM.
10. What is the algorithm used in Thread scheduling? - Fixed priority scheduling.
11. What is hash-collision in Hashtable and how it is handled in Java? - Two different keys with the same hash value. Two different entries will be kept in a single hash bucket to avoid the collision.
12. What are the different driver types available in JDBC? - 1. A JDBC-ODBC bridge 2. A native-API partly Java technology-enabled driver 3. A net-protocol fully Java technology-enabled driver 4. A native-protocol fully Java technology-enabled driver For more information: Driver Description
13. Is JDBC-ODBC bridge multi-threaded? - No
14. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? - No
15. What is the use of serializable? - To persist the state of an object into any perminant storage device.
16. What is the use of transient? - It is an indicator to the JVM that those variables should not be persisted. It is the users responsibility to initialize the value when read back from the storage.
17. What are the different level lockings using the synchronization keyword? - Class level lock Object level lock Method level lock Block level lock
18. What is the use of preparedstatement? - Preparedstatements are precompiled statements. It is mainly used to speed up the process of inserting/updating/deleting especially when there is a bulk processing.
19. What is callable statement? Tell me the way to get the callable statement? - Callablestatements are used to invoke the stored procedures. You can obtain the callablestatement from Connection using the following methods prepareCall(String sql) prepareCall(String sql, int resultSetType, int resultSetConcurrency)
20. In a statement, I am executing a batch. What is the result of the execution? - It returns the int array. The array contains the affected row count in the corresponding index of the SQL.
21. Can a abstract method have the static qualifier? - No
22. What are the different types of qualifier and what is the default qualifier? - public, protected, private, package (default)
23. What is the super class of Hashtable? - Dictionary
24. What is a lightweight component? - Lightweight components are the one which doesn’t go with the native call to obtain the graphical units. They share their parent component graphical units to render them. Example, Swing components
25. What is a heavyweight component? - For every paint call, there will be a native call to get the graphical units. Example, AWT.
26. What is an applet? - Applet is a program which can get downloaded into a client environment and start executing there.
27. What do you mean by a Classloader? - Classloader is the one which loads the classes into the JVM.
28. What are the implicit packages that need not get imported into a class file? - java.lang
29. What is the difference between lightweight and heavyweight component? - Lightweight components reuses its parents graphical units. Heavyweight components goes with the native graphical unit for every component. Lightweight components are faster than the heavyweight components.
30. What are the ways in which you can instantiate a thread? - Using Thread class By implementing the Runnable interface and giving that handle to the Thread class.
31. What are the states of a thread? - 1. New 2. Runnable 3. Not Runnable 4. Dead
32. What is a socket? - A socket is an endpoint for communication between two machines.
33. How will you establish the connection between the servlet and an applet? - Using the URL, I will create the connection URL. Then by openConnection method of the URL, I will establish the connection, through which I can be able to exchange data.
34. What are the threads will start, when you start the java program? - Finalizer, Main, Reference Handler, Signal Dispatcher
35. What is the relationship between local interfaces and container-managed relationships? - Entity beans that have container-managed relationships with other entity beans, must be accessed in the same local scope as those related beans, and therefore typically provide a local client view. In order to be the target of a container-managed relationship, an entity bean with container-managed persistence must provide a local interface.
36. What does a remove method do for different cases of beans? - Stateless Session : Does not do anything to the bean as moving the bean from free pool to cache are managed by the container depending on load. Stateful Session: Removes the bean from the cache. Entity Bean: Deletes the bean (data) from persistent storage
37. How does a container-managed relationship work? - An entity bean accesses related entity beans by means of the accessor methods for its container-managed relationship fields, which are specified by the cmr-field elements of its abstract persistence schema defined in the deployment descriptor. Entity bean relationships are defined in terms of the local interfaces of the related beans, and the view an entity bean presents to its related beans is defined by its local home and local interfaces. Thus, an entity bean can be the target of a relationship from another entity bean only if it has a local interface.
38. What is the new basic requirement for a CMP entity bean class in 2.0 from that of ejb 1.1? - It must be abstract class. The container extends it and implements methods which are required for managing the relationships
39. What are the basic classes required in the client for invoking an EJB? - The home and the remote interfaces, the implementation of the Naming Context Factory, the stubs and skeletons. In some App servers the stubs and the skeletons can be dynamically downloaded from the server
40. What is the difference between Message Driven Beans and Stateless Session beans? - In several ways, the dynamic creation and allocation of message-driven bean instances mimics the behavior of stateless session EJB instances, which exist only for the duration of a particular method call. However, message-driven beans are different from stateless session EJBs (and other types of EJBs) in several significant ways:
1. Message-driven beans process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls.
2. Message-driven beans have no home or remote interface, and therefore cannot be directly accessed by internal or external clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS Queue or Topic.
3. Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary.
4. The Container maintains the entire lifecycle of a message-driven bean; instances cannot be created or removed as a result of client requests or other API calls.
41. What is the need for Clustering? - To scale the application so that it is highly available and has high throughput.
42. What are the benefits of Clustering and workload management? - They are
1. It balances client processing requests, allowing incoming work requests to be distributed according to a configured Workload Management selection policy.
2. It provides fail over capability by redirecting client requests to a running server when one or more servers are unavailable. This improves the availability of applications and administrative services.
3. It enables systems to be scaled up to serve a higher client load than provided by the basic configuration. With server groups and clones additional instances of servers can easily be added to the configuration.
4. It enables servers to be transparently maintained and upgraded while applications remain available for users.
5. It centralizes administration of application servers and other objects.
43. What are the types of Scaling? - There are two types of scaling: Vertical Scaling and Horizontal Scaling.
44. What is Vertical Scaling? - When multiple server clones of an application server are defined on the same physical m/c, it is called Vertical Scaling. The objective is to use the processing power of that m/c more efficiently.
45. What is Horizontal Scaling? - When Clones of an application server are defined on multiple physical m/c, it is called Horizontal Scaling. The objective is to use more than one less powerful m/c more efficiently.
46. What is a Server Group? - A server group is a template of an Application Server(and its contents) i.e, it is a logical representation of the application server. It has the same structure and attributes as the real Application Server, but it is not associated with any node, and does not correspond to any real server process running on any node.
47. What is a Clone? - The copies of a server group are called Clones. But unlike a Server Group Clones are associated with a node and are real server process running in that node.
48. What is Ripple Effect? - The process of propagating the changes in the properties of a server group during runtime to all the associated clones is called Ripple Effect.
49. What level of Load Balancing is possible with EJBs? - The workload management service provides load balancing for the following types of enterprise beans: Homes of entity or session beans, Instances of entity beans, Instances of stateless session beans.
50. What is the basic requirement for in-memory replication in Weblogic? - The data in session should consist only of Serialized objects. Only setAttribute function should be used to set objects in session.
51. How JDBC services can be used in clustered environment? - Identical DataSource has to be created in each clustered server instances and configure to use different connection pools.
52. What are the services that should not be used in a Clustered Environment? - Non-clustered services:
1. File Services
2. Time services
3. Weblogic events
4. Weblogic Workspaces (In WebLogic 5.1)
53. Mention some tools to cluster Web Servers? - Web Servers can be clustered using Edge Server or DNS.
54. What is in-memory replication? - The process by which the contents in the memory of one physical m/c are replicated in all the m/c in the cluster is called in-memory replication.
55. Difference Between Abstraction and Encapsulation - Abstraction is removing some distinctions between objects, so as to show their commonalities. Encapsulation is hiding the details of the implementation of an object so that there are no external dependencies on the particular implementation.
56. What is the difference between URL instance and URLConnection instance? - A URL instance represents the location of a resource, and a URLConnection instance represents a link for accessing or communicating with the resource at the location.
57. What are the two important TCP Socket classes? - Socket and ServerSocket. ServerSocket is used for normal two-way socket communication. Socket class allows us to read and write through the sockets. getInputStream() and getOutputStream() are the two methods available in Socket class.
58. What technologies are included in J2EE? - The primary technologies in J2EE are: Enterprise JavaBeansTM (EJBsTM), JavaServer PagesTM (JSPsTM), Java Servlets, the Java Naming and Directory InterfaceTM (JNDITM), the Java Transaction API (JTA), CORBA, and the JDBCTM data access API.
59. What is the Java Authentication and Authorization Service (JAAS) 1.0? - The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. JAAS is a Java programing language version of the standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization.
60. What’s the difference between JNDI lookup(), list(), listBindings(), and search()? - lookup() attempts to find the specified object in the given context. I.e., it looks for a single, specific object and either finds it in the current context or it fails. list() attempts to return an enumeration of all of the NameClassPair’s of all of the objects in the current context. I.e., it’s a listing of all of the objects in the current context but only returns the object’s name and the name of the class to which the object belongs. listBindings() attempts to return an enumeration of the Binding’s of all of the objects in the current context. I.e., it’s a listing of all of the objects in the current context with the object’s name, its class name, and a reference to the object itself. search() attempts to return an enumeration of all of the objects matching a given set of search criteria. It can search across multiple contexts (or not). It can return whatever attributes of the objects that you desire. It’s by far the most complex and powerful of these options but is also the most expensive.
61. Components of JNDI - Naming Interface- The naming interface organizes information hierarchically and maps human-friendly names to addresses or objects that are machine-friendly. It allows access to named objects through multiple namespaces. Directory Interface - JNDI includes a directory service interface that provides access to directory objects, which can contain attributes, thereby providing attribute-based searching and schema support. Service Provider Interface - JNDI comes with the SPI, which supports the protocols provided by third parties.
62. What is the Max amount of information that can be saved in a Session Object? - As such there is no limit on the amount of information that can be saved in a Session Object. Only the RAM available on the server machine is the limitation. The only limit is the Session ID length(Identifier), which should not exceed more than 4K. If the data to be store is very huge, then it’s preferred to save it to a temporary file onto hard disk, rather than saving it in session. Internally if the amount of data being saved in Session exceeds the predefined limit, most of the servers write it to a temporary cache on Hard disk.
63. Must my bean-managed persistence mechanism use the WebLogic JTS driver? - BEA recommend that you use the TxDataSource for bean-managed persistence.
64. Do EJBs have to be homogeneously deployed across a cluster? Why? - Yes. Beginning with WebLogic Server version 6.0, EJBs must be homogeneously deployed across a cluster for the following reasons:
1. To keep clustering EJBs simple
2. To avoid cross server calls which results in more efficiency. If EJBs are not deployed on all servers, cross server calls are much more likely.
3. To ensure that every EJB is available locally
4. To ensure that all classes are loaded in an undeployable way
5. Every server must have access to each EJB’s classes so that it can be bound into the local JNDI tree. If only a subset of the servers deploys the bean, the other servers will have to load the bean’s classes in their respective system classpaths which makes it impossible to undeploy the beans.
65. Is an XSLT processor bundled in WebLogic Server? - Yes, an XSLT processor, based on Apache’s Xalan 2.0.1 processor, in WebLogic Server 6.1.
66. I plugged in a version of Apache Xalan that I downloaded from the Apache Web site, and now I get errors when I try to transform documents. What is the problem? - You must ensure that the version of Apache Xalan you download from the Apache Web site is compatible with Apache Xerces version 1.3.1. Because you cannot plug in a different version of Apache Xerces , the only version of Apache Xerces that is compatible with WebLogic Server 6.1 is 1.3.1. The built-in parser (based on version 1.3.1 of Apache Xerces) and transformer (based on version 2.0.1 of Apache Xalan) have been modified by BEA to be compatible with each other.
67. How do I increase WebLogic Server memory? - Increase the allocation of Java heap memory for WebLogic Server. (Set the minimum and the maximum to the same size.) Start WebLogic Server with the -ms32m option to increase the allocation, as in this example:
68. $ java ... -ms32m -mx32m ...
This allocates 32 megabytes of Java heap memory to WebLogic Server, which improves performance and allows WebLogic Server to handle more simultaneous connections. You can increase this value if necessary.
69. What causes Java.io exceptions in the log file of WebLogic Server? - You may see messages like these in the log file:
70. (Windows NT)
71. java.io.IOException Connection Reset by Peer
72. java.io.EOFException Connection Reset by Peer
73. (Solaris)
74. java.io.Exception: Broken pipe
These messages occur when you are using servlets. A client initiates an HTTP request, and then performs a series of actions on the browser:
1. Click Stop or enter equivalent command or keystrokes
2. Click Refresh or enter equivalent command or keystrokes
3. Send a new HTTP request.
The messages indicate that WebLogic Server has detected and recovered from an interrupted HTTP request.
75. What is the function of T3 in WebLogic Server? - T3 provides a framework for WebLogic Server messages that support for enhancements. These enhancements include abbreviations and features, such as object replacement, that work in the context of WebLogic Server clusters and HTTP and other product tunneling. T3 predates Java Object Serialization and RMI, while closely tracking and leveraging these specifications. T3 is a superset of Java Object. Serialization or RMI; anything you can do in Java Object Serialization and RMI can be done over T3. T3 is mandated between WebLogic Servers and between programmatic clients and a WebLogic Server cluster. HTTP and IIOP are optional protocols that can be used to communicate between other processes and WebLogic Server. It depends on what you want to do. For example, when you want to communicate between a browser and WebLogic Server-use HTTP, or an ORB and WebLogic Server-IIOP.
76. What are the enhancements in EJB 2.0 specification with respect to Asynchronous communication? - EJB 2.0 mandates integration between JMS and EJB. We have specified the integration of Enterprise JavaBeans with the Java Message Service, and have introduced message-driven beans. A message-driven bean is a stateless component that is invoked by the container as a result of the arrival of a JMS message. The goal of the message-driven bean model is to make developing an enterprise bean that is asynchronously invoked to handle the processing of incoming JMS messages as simple as developing the same functionality in any other JMS MessageListener.
77. What are the enhancements in EJB 2.0 with respect to CMP? - EJB 2.0 extends CMP to include far more robust modeling capability, with support for declarative management of relationships between entity EJBs. Developers no longer need to re-establish relationships between the various beans that make up their application – the container will restore the connections automatically as beans are loaded, allowing bean developers to navigate between beans much as they would between any standard Java objects.
EJB 2.0 also introduces for the first time a portable query language, based on the abstract schema, not on the more complex database schema. This provides a database and vendor-independent way to find entity beans at run time, based on a wide variety of search criteria.
78. Can you briefly describe local interfaces? - EJB was originally designed around remote invocation using the Java Remote Method Invocation (RMI) mechanism, and later extended to support to standard CORBA transport for these calls using RMI/IIOP. This design allowed for maximum flexibility in developing applications without consideration for the deployment scenario, and was a strong feature in support of a goal of component reuse in J2EE. Many developers are using EJBs locally - that is, some or all of their EJB calls are between beans in a single container. With this feedback in mind, the EJB 2.0 expert group has created a local interface mechanism. The local interface may be defined for a bean during development, to allow streamlined calls to the bean if a caller is in the same container. This does not involve the overhead involved with RMI like marshalling etc. This facility will thus improve the performance of applications in which co-location is planned. Local interfaces also provide the foundation for container-managed relationships among entity beans with container-managed persistence.
79. What are the special design care that must be taken when you work with local interfaces? - It is important to understand that the calling semantics of local interfaces are different from those of remote interfaces. For example, remote interfaces pass parameters using call-by-value semantics, while local interfaces use call-by-reference. This means that in order to use local interfaces safely, application developers need to carefully consider potential deployment scenarios up front, then decide which interfaces can be local and which remote, and finally, develop the application code with these choices in mind. While EJB 2.0 local interfaces are extremely useful in some situations, the long-term costs of these choices, especially when changing requirements and component reuse are taken into account, need to be factored into the design decision.
80. What happens if remove( ) is never invoked on a session bean? - In case of a stateless session bean it may not matter if we call or not as in both cases nothing is done. The number of beans in cache is managed by the container. In case of stateful session bean, the bean may be kept in cache till either the session times out, in which case the bean is removed or when there is a requirement for memory in which case the data is cached and the bean is sent to free pool.
81. What is the difference between creating a distributed application using RMI and using a EJB architecture? - It is possible to create the same application using RMI and EJB. But in case of EJB the container provides the requisite services to the component if we use the proper syntax. It thus helps in easier development and lesser error and use of proven code and methodology. But the investment on application server is mandatory in that case. But this investment is warranted because it results in less complex and maintainable code to the client, which is what the end client wants. Almost all the leading application servers provide load balancing and performance tuning techniques. In case of RMI we have to code the services and include in the program the way to invoke these services.
82. Why would a client application use JTA transactions? - One possible example would be a scenario in which a client needs to employ two (or more) session beans, where each session bean is deployed on a different EJB server and each bean performs operations against external resources (for example, a database) and/or is managing one or more entity beans. In this scenario, the client’s logic could required an all-or-nothing guarantee for the operations performed by the session beans; hence, the session bean usage could be bundled together with a JTA UserTransaction object. In the previous scenario, however, the client application developer should address the question of whether or not it would be better to encapsulate these operations in yet another session bean, and allow the session bean to handle the transactions via the EJB container. In general, lightweight clients are easier to maintain than heavyweight clients. Also, EJB environments are ideally suited for transaction management.
83. Context c = new InitialContext(); UserTransaction ut = (UserTransaction)
84. c.lookup("java:comp/UserTransaction");
85. ut.begin();
86. // perform multiple operations...
87. ut.commit() ...
88. Can the bean class implement the EJBObject class directly? If not why? - It is better not to do it will make the Bean class a remote object and its methods can be accessed without the containers? security, and transaction implementations if our code by mistake passed it in one of its parameters. Its just a good design practice.
89. What does isIdentical() method return in case of different type of beans? - Stateless - true always. Stateful - depends whether the references point to the same session object. Entity - Depends whether the primary key is the same and the home is same.
90. How should you type cast a remote object? Why? - A client program that is intended to be interoperable with all compliant EJB Container implementations must use the javax.rmi.PortableRemoteObject.narrow(…) method to perform type-narrowing of the client-side representations of the remote home and remote interfaces. Programs using the cast operator for narrowing the remote and remote home interfaces are likely to fail if the Container implementation uses RMI-IIOP as the underlying communication transport.
91. What should you do in a passive method? - You try to make all nontransient variables, which are not one of the following to null. For the given list the container takes care of serializing and restoring the object when activated. Serializable objects, null, UserTransaction, SessionContext, JNDI contexts in the beans context, reference to other beans, references to connection pools.
Things that must be handled explicitly are like a open database connection etc. These must be closed and set to null and retrieved back in the activate method.
1. How do you call a Stored Procedure from JDBC? - The first step is to create a CallableStatement object. As with Statement and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure.
2. CallableStatement cs =
3. con.prepareCall("{call SHOW_SUPPLIERS}");
4. ResultSet rs = cs.executeQuery();
5. Is the JDBC-ODBC Bridge multi-threaded? - No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won’t get the advantages of multi-threading.
6. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? - No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.
7. What is cold backup, hot backup, warm backup recovery? - Cold backup (All these files must be backed up at the same time, before the databaseis restarted). Hot backup (official name is ‘online backup’) is a backup taken of each tablespace while the database is running and is being accessed by the users.
8. When we will Denormalize data? - Data denormalization is reverse procedure, carried out purely for reasons of improving performance. It maybe efficient for a high-throughput system to replicate data for certain data.
9. What is the advantage of using PreparedStatement? - If we are using PreparedStatement the execution time will be less. The PreparedStatement object contains not just an SQL statement, but the SQL statement that has been precompiled. This means that when the PreparedStatement is executed,the RDBMS can just run the PreparedStatement’s Sql statement without having to compile it first.
10. What is a “dirty read"? - Quite often in database processing, we come across the situation wherein one transaction can change a value, and a second transaction can read this value before the original change has been committed or rolled back. This is known as a dirty read scenario because there is always the possibility that the first transaction may rollback the change, resulting in the second transaction having read an invalid value. While you can easily command a database to disallow dirty reads, this usually degrades the performance of your application due to the increased locking overhead. Disallowing dirty reads also leads to decreased system concurrency.
11. What is Metadata and why should I use it? - Metadata (’data about data’) is information about one of two things: Database information (java.sql.DatabaseMetaData), or Information about a specific ResultSet (java.sql.ResultSetMetaData). Use DatabaseMetaData to find information about your database, such as its capabilities and structure. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns
12. Different types of Transaction Isolation Levels? - The isolation level describes the degree to which the data being updated is visible to other transactions. This is important when two transactions are trying to read the same row of a table. Imagine two transactions: A and B. Here three types of inconsistencies can occur:
o Dirty-read: A has changed a row, but has not committed the changes. B reads the uncommitted data but his view of the data may be wrong if A rolls back his changes and updates his own changes to the database.
o Non-repeatable read: B performs a read, but A modifies or deletes that data later. If B reads the same row again, he will get different data.
o Phantoms: A does a query on a set of rows to perform an operation. B modifies the table such that a query of A would have given a different result. The table may be inconsistent.
TRANSACTION_READ_UNCOMMITTED : DIRTY READS, NON-REPEATABLE READ AND PHANTOMS CAN OCCUR.
TRANSACTION_READ_COMMITTED : DIRTY READS ARE PREVENTED, NON-REPEATABLE READ AND PHANTOMS CAN OCCUR.
TRANSACTION_REPEATABLE_READ : DIRTY READS , NON-REPEATABLE READ ARE PREVENTED AND PHANTOMS CAN OCCUR.
TRANSACTION_SERIALIZABLE : DIRTY READS, NON-REPEATABLE READ AND PHANTOMS ARE PREVENTED.
13. What is 2 phase commit? - A 2-phase commit is an algorithm used to ensure the integrity of a committing transaction. In Phase 1, the transaction coordinator contacts potential participants in the transaction. The participants all agree to make the results of the transaction permanent but do not do so immediately. The participants log information to disk to ensure they can complete In phase 2 f all the participants agree to commit, the coordinator logs that agreement and the outcome is decided. The recording of this agreement in the log ends in Phase 2, the coordinator informs each participant of the decision, and they permanently update their resources.
14. How do you handle your own transaction ? - Connection Object has a method called setAutocommit(Boolean istrue)
- Default is true. Set the Parameter to false , and begin your transaction
15. What is the normal procedure followed by a java client to access the db.? - The database connection is created in 3 steps:
1. Find a proper database URL
2. Load the database driver
3. Ask the Java DriverManager class to open a connection to your database
In java code, the steps are realized in code as follows:
4. Create a properly formatted JDBR URL for your database. (See FAQ on JDBC URL for more information). A JDBC URL has the form
jdbc:someSubProtocol://myDatabaseServer/theDatabaseName
5. Class.forName("my.database.driver");
6. Connection conn = DriverManager.getConnection("a.JDBC.URL", “databaseLogin","databasePassword");
16. What is a data source? - A DataSource class brings another level of abstraction than directly using a connection object. Data source can be referenced by JNDI. Data Source may point to RDBMS, file System , any DBMS etc.
17. What are collection pools? What are the advantages? - A connection pool is a cache of database connections that is maintained in memory, so that the connections may be reused
18. How do you get Column names only for a table (SQL Server)? Write the Query. -
19. select name from syscolumns
20. where id=(select id from sysobjects where name='user_hdr')
21. order by colid --user_hdr is the table name
1. What are the types of messaging? - There are two kinds of Messaging. Synchronous messaging involves a client that waits for the server to respond to a message. Asynchronous messaging involves a client that does not wait for a message from the server. An event is used to trigger a message from a server.
2. What is publish/subscribe messaging? - With publish/subscribe message passing the sending application/client establishes a named topic in the JMS broker/server and publishes messages to this queue. The receiving clients register (specifically, subscribe) via the broker to messages by topic; every subscriber to a topic receives each message published to that topic. There is a one-to-many relationship between the publishing client and the subscribing clients.
3. Why doesn’t the JMS API provide end-to-end synchronous message delivery and notification of delivery? -Some messaging systems provide synchronous delivery to destinations as a mechanism for implementing reliable applications. Some systems provide clients with various forms of delivery notification so that the clients can detect dropped or ignored messages. This is not the model defined by the JMS API. JMS API messaging provides guaranteed delivery via the once-and-only-once delivery semantics of PERSISTENT messages. In addition, message consumers can insure reliable processing of messages by using either CLIENT_ACKNOWLEDGE mode or transacted sessions. This achieves reliable delivery with minimum synchronization and is the enterprise messaging model most vendors and developers prefer. The JMS API does not define a schema of systems messages (such as delivery notifications). If an application requires acknowledgment of message receipt, it can define an application-level acknowledgment message.
4. What are the core JMS-related objects required for each JMS-enabled application? - Each JMS-enabled client must establish the following:
o A connection object provided by the JMS server (the message broker)
o Within a connection, one or more sessions, which provide a context for message sending and receiving
o Within a session, either a queue or topic object representing the destination (the message staging area) within the message broker
o Within a session, the appropriate sender or publisher or receiver or subscriber object (depending on whether the client is a message producer or consumer and uses a point-to-point or publish/subscribe strategy, respectively). Within a session, a message object (to send or to receive)
5. What is the Role of the JMS Provider? - The JMS provider handles security of the messages, data conversion and the client triggering. The JMS provider specifies the level of encryption and the security level of the message, the best data type for the non-JMS client.
6. How does a typical client perform the communication? -
1. Use JNDI to locate administrative objects.
2. Locate a single ConnectionFactory object.
3. Locate one or more Destination objects.
4. Use the ConnectionFactory to create a JMS Connection.
5. Use the Connection to create one or more Session(s).
6. Use a Session and the Destinations to create the MessageProducers and MessageConsumers needed.
7. Perform your communication.
7. Give an example of using the point-to-point model. - The point-to-point model is used when the information is specific to a single client. For example, a client can send a message for a print out, and the server can send information back to this client after completion of the print job.
8. How does the Application server handle the JMS Connection? -
0. App server creates the server session and stores them in a pool.
1. Connection consumer uses the server session to put messages in the session of the JMS.
2. Server session is the one that spawns the JMS session.
3. Applications written by Application programmers creates the message listener.
9. What are the implicit objects? - Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are: request, response, pageContext, session, application, out, config, page, exception.
10. Is JSP technology extensible? - Yes. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
11. How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it? - You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" %> within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe
12. How does JSP handle run-time exceptions? - You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example: <%@ page errorPage="error.jsp" %>
redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage="true" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.
13. How do I prevent the output of my JSP or Servlet pages from being cached by the browser? - You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.
<%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>
14. How do I use comments within a JSP page? - You can use “JSP-style” comments to selectively block out code while debugging or simply to comment your scriptlets. JSP comments are not visible at the client. For example:
15. <%-- the scriptlet is now commented out
16. <%
17. out.println("Hello World");
18. %>
19. --%>
You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example:

Of course, you can also use comments supported by your JSP scripting language within your scriptlets. For example, assuming Java is the scripting language, you can have:
<%
//some comment
/**
yet another comment
**/
%>
20. Response has already been commited error. What does it mean? - This error show only when you try to redirect a page after you already have written something in your page. This happens because HTTP specification force the header to be set up before the lay out of the page can be shown (to make sure of how it should be displayed, content-type="text/html” or “text/xml” or “plain-text” or “image/jpg", etc.) When you try to send a redirect status (Number is line_status_402), your HTTP server cannot send it right now if it hasn’t finished to set up the header. If not starter to set up the header, there are no problems, but if it ’s already begin to set up the header, then your HTTP server expects these headers to be finished setting up and it cannot be the case if the stream of the page is not over… In this last case it’s like you have a file started with some output (like testing your variables.) Before you indicate that the file is over (and before the size of the page can be setted up in the header), you try to send a redirect status. It s simply impossible due to the specification of HTTP 1.0 and 1.1
21. How do I use a scriptlet to initialize a newly instantiated bean? - A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.
The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.
22.
23. 24. value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>"/ >
25. <%-- scriptlets calling bean setter methods go here --%>
26.

27. How can I enable session tracking for JSP pages if the browser has disabled cookies? - We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.
28. hello1.jsp
29. <%@ page session="true" %>
30. <%
31. Integer num = new Integer(100);
32. session.putValue("num",num);
33. String url =response.encodeURL("hello2.jsp");
34. %>
35. hello2.jsp
36. hello2.jsp
37. <%@ page session="true" %>
38. <%
39. Integer i= (Integer )session.getValue("num");
40. out.println("Num value in session is "+i.intValue());
41. How can I declare methods within my JSP page? - You can declare methods for use within your JSP page as declarations. The methods can then be invoked within any other methods you declare, or within JSP scriptlets and expressions. Do note that you do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the methods you declare. For example:
42. <%!
43. public String whereFrom(HttpServletRequest req) {
44. HttpSession ses = req.getSession();
45. ...
46. return req.getRemoteHost();
47. }
48. %>
49. <%
50. out.print("Hi there, I see that you are coming in from ");
51. %>
52. <%= whereFrom(request) %>
53. Another Example
54. file1.jsp:
55. <%@page contentType="text/html"%>
56. <%!
57. public void test(JspWriter writer) throws IOException{
58. writer.println("Hello!");
59. }
60. %>
61. file2.jsp
62. <%@include file="file1.jsp"%>
63.
64.
65. <%test(out);% >
66.
67.
68. Is there a way I can set the inactivity lease period on a per-session basis? - Typically, a default inactivity lease period for all sessions is set within your JSP engine admin screen or associated properties file. However, if your JSP engine supports the Servlet 2.1 API, you can manage the inactivity lease period on a per-session basis. This is done by invoking the HttpSession.setMaxInactiveInterval() method, right after the session has been created. For example:
69. <%
70. session.setMaxInactiveInterval(300);
71. %>
would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds.
72. How can I set a cookie and delete a cookie from within a JSP page? - A cookie, mycookie, can be deleted using the following scriptlet:
73. <%
74. //creating a cookie
75. Cookie mycookie = new Cookie("aName","aValue");
76. response.addCookie(mycookie);
77. //delete a cookie
78. Cookie killMyCookie = new Cookie("mycookie", null);
79. killMyCookie.setMaxAge(0);
80. killMyCookie.setPath("/");
81. response.addCookie(killMyCookie);
82. %>
83. How does a servlet communicate with a JSP page? - The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.
84. public void doPost (HttpServletRequest request, HttpServletResponse response) {
85. try {
86. govi.FormBean f = new govi.FormBean();
87. String id = request.getParameter("id");
88. f.setName(request.getParameter("name"));
89. f.setAddr(request.getParameter("addr"));
90. f.setAge(request.getParameter("age"));
91. //use the id to compute
92. //additional bean properties like info
93. //maybe perform a db query, etc.
94. // . . .
95. f.setPersonalizationInfo(info);
96. request.setAttribute("fBean",f);
97. getServletConfig().getServletContext().getRequestDispatcher
98. ("/jsp/Bean1.jsp").forward(request, response);
99. } catch (Exception ex) {
100. . . .
101. }
102. }
The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action.
jsp:useBean id="fBean" class="govi.FormBean" scope="request"
/ jsp:getProperty name="fBean" property="name"
/ jsp:getProperty name="fBean" property="addr"
/ jsp:getProperty name="fBean" property="age"
/ jsp:getProperty name="fBean" property="personalizationInfo" /
103. How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default? - One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP engine. In doing so, you may lose out on any advanced optimization that may be provided by the JSP engine. In any case, your new superclass has to fulfill the contract with the JSP engine by:
Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the methods in the Servlet interface are declared final Additionally, your servlet superclass also needs to do the following:
0. The service() method has to invoke the _jspService() method
1. The init() method has to invoke the jspInit() method
2. The destroy() method has to invoke jspDestroy()
If any of the above conditions are not satisfied, the JSP engine may throw a translation error.
Once the superclass has been developed, you can have your JSP extend it as follows:
<%@ page extends="packageName.ServletName" %>
104. How can I prevent the word "null" from appearing in my HTML input text fields when I populate them with a resultset that has null values? - You could make a simple wrapper function, like
105. <%!
106. String blanknull(String s) {
107. return (s == null) ? "" : s;
108. }
109. %>
110. then use it inside your JSP form, like
111.
112. How can I get to print the stacktrace for an exception occuring within my JSP page? - By printing out the exception’s stack trace, you can usually diagonse a problem better when debugging JSP pages. By looking at a stack trace, a programmer should be able to discern which method threw the exception and which method called that method. However, you cannot print the stacktrace using the JSP out implicit variable, which is of type JspWriter. You will have to use a PrintWriter object instead. The following snippet demonstrates how you can print a stacktrace from within a JSP error page:
113. <%@ page isErrorPage="true" %>
114. <%
115. out.println(" ");
116. PrintWriter pw = response.getWriter();
117. exception.printStackTrace(pw);
118. out.println(" ");
119. %>
120. How do you pass an InitParameter to a JSP? - The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can use in their pages and are invoked in much the same manner as the init() and destory() methods of a servlet. The example page below enumerates through all the parameters and prints them to the console.
121. <%@ page import="java.util.*" %>
122. <%!
123. ServletConfig cfg =null;
124. public void jspInit(){
125. ServletConfig cfg=getServletConfig();
126. for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) {
127. String name=(String)e.nextElement();
128. String value = cfg.getInitParameter(name);
129. System.out.println(name+"="+value);
130. }
131. }
132. %>
133. How can my JSP page communicate with an EJB Session Bean? - The following is a code snippet that demonstrates how a JSP page can interact with an EJB session bean:
134. <%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %>
135. <%!
136. //declare a "global" reference to an instance of the home interface of the session bean
137. AccountHome accHome=null;
138. public void jspInit() {
139. //obtain an instance of the home interface
140. InitialContext cntxt = new InitialContext( );
141. Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
142. accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
143. }
144. %>
145. <%
146. //instantiate the session bean
147. Account acct = accHome.create();
148. //invoke the remote methods
149. acct.doWhatever(...);
150. // etc etc...
151. %>
1. What makes J2EE suitable for distributed multitiered Applications?
- The J2EE platform uses a multitiered distributed application model. Application logic is divided into components according to function, and the various application components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs. The J2EE application parts are:
o Client-tier components run on the client machine.
o Web-tier components run on the J2EE server.
o Business-tier components run on the J2EE server.
o Enterprise information system (EIS)-tier software runs on the EIS server.
2. What is J2EE? - J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications.
3. What are the components of J2EE application?
- A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:
1. Application clients and applets are client components.
2. Java Servlet and JavaServer Pages technology components are web components.
3. Enterprise JavaBeans components (enterprise beans) are business components.
4. Resource adapter components provided by EIS and tool vendors.
4. What do Enterprise JavaBeans components contain? - Enterprise JavaBeans components contains Business code, which is logic
that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. All the business code is contained inside an Enterprise Bean which receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program.
5. Is J2EE application only a web-based? - No, It depends on type of application that client wants. A J2EE application can be web-based or non-web-based. if an application client executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle tasks such as J2EE system or application administration. It typically has a graphical user interface created from Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP connection to establish communication with a servlet running in the web tier.
6. Are JavaBeans J2EE components? - No. JavaBeans components are not considered J2EE components by the J2EE specification. They are written to manage the data flow between an application client or applet and components running on the J2EE server or between server components and a database. JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans components used in this way are typically simple in design and implementation, but should conform to the naming and design conventions outlined in the JavaBeans component architecture.
7. Is HTML page a web component? - No. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification. Even the server-side utility classes are not considered web components, either.
8. What can be considered as a web component? - J2EE Web components can be either servlets or JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content.
9. What is the container? - Containers are the interface between a component and the low-level platform specific functionality that supports the component. Before a Web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container.
10. What are container services? - A container is a runtime support of a system-level entity. Containers provide components with services such as lifecycle management, security, deployment, and threading.
11. What is the web container? - Servlet and JSP containers are collectively referred to as Web containers. It manages the execution of JSP page and servlet components for J2EE applications. Web components and their container run on the J2EE server.
12. What is Enterprise JavaBeans (EJB) container? - It manages the execution of enterprise beans for J2EE applications.
Enterprise beans and their container run on the J2EE server.
13. What is Applet container? - IManages the execution of applets. Consists of a Web browser and Java Plugin running on the client together.
14. How do we package J2EE components? - J2EE components are packaged separately and bundled into a J2EE application for deployment. Each component, its related files such as GIF and HTML files or server-side utility classes, and a deployment descriptor are assembled into a module and added to the J2EE application. A J2EE application is composed of one or more enterprise bean,Web, or application client component modules. The final enterprise solution can use one J2EE application or be made up of two or more J2EE applications, depending on design requirements. A J2EE application and each of its modules has its own deployment descriptor. A deployment descriptor is an XML document with an .xml extension that describes a component’s deployment settings.
15. What is a thin client? - A thin client is a lightweight interface to the application that does not have such operations like query databases, execute complex business rules, or connect to legacy applications.
16. What are types of J2EE clients? - Following are the types of J2EE clients:
o Applets
o Application clients
o Java Web Start-enabled rich clients, powered by Java Web Start technology.
o Wireless clients, based on Mobile Information Device Profile (MIDP) technology.
17. What is deployment descriptor? - A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a component’s deployment settings. A J2EE application and each of its modules has its own deployment descriptor. For example, an enterprise bean module deployment descriptor declares transaction attributes and security authorizations
for an enterprise bean. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts upon the component accordingly.
18. What is the EAR file? - An EAR file is a standard JAR file with an .ear extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file.
19. What is JTA and JTS? - JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Jave Transaction Service. JTA provides a standard interface and allows you to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK implements the transaction manager with JTS. But your code doesn’t call the JTS methods directly. Instead, it invokes the JTA methods, which then call the lower-level JTS routines. Therefore, JTA is a high level transaction interface that your application uses to control transaction. and JTS is a low level transaction interface and ejb uses behind the scenes (client code doesn’t directly interact with JTS. It is based on object transaction service(OTS) which is part of CORBA.
20. What is JAXP? - JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. It provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations.
21. What is J2EE Connector? - The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged into any J2EE product. Each type of database or EIS has a different resource adapter. Note: A resource adapter is a software component that allows J2EE application components to access and interact with the underlying resource manager. Because a resource adapter is specific to its resource manager, there is typically a different resource adapter for each type of database or enterprise information system.
22. What is JAAP? - The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. It is a standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization.
23. What is Java Naming and Directory Service? - The JNDI provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object. Because JNDI is independent of any specific implementations, applications can use JNDI to access multiple naming and directory services, including existing naming and
directory services such as LDAP, NDS, DNS, and NIS.
24. What is Struts? - A Web page development framework. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between.
25. How is the MVC design pattern used in Struts framework? - In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model represents, or encapsulates, an application’s business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to create and maintain. Controller: Servlet controller which supplied by Struts itself; View: what you can see on the screen, a JSP page and presentation components; Model: System state and a business logic JavaBeans.
26. What is the difference between CGI and Servlet?
27. What is meant by a servlet?
28. What are the types of servlets? What is the difference between 2 types of Servlets?
29. What is the type of method for sending request from HTTP server ?
30. What are the exceptions thrown by Servlets? Why?
31. What is the life cycle of a servlet?
32. What is meant by cookies? Why is Cookie used?
33. What is HTTP Session?
34. What is the difference between GET and POST methods?
35. How can you run a Servlet Program?
36. What is the middleware? What is the functionality of Webserver?
37. What webserver is used for running the Servlets?
38. How do you invoke a Servelt? What is the difference in between doPost and doGet methods?
39. What is the difference in between the HTTPServlet and Generic Servlet? Explain their methods? Tell me their parameter names also?
40. What are session variable in Servlets?
41. What is meant by Session? Tell me something about HTTPSession Class?
42. What is Session Tracking?
43. Difference between doGet and doPost?
44. What are the methods in HttpServlet?
45. What are the types of SessionTracking? Why do you use Session Tracking in HttpServlet?
46. What is the protocol used by server and client ?
47. Can I modify an object in CORBA ?
48. What is the functionality stubs and skeletons ?

49. What is the mapping mechanism used by Java to identify IDL language ?
50. Diff between Application and Applet ?
51. What is serializable Interface ?
52. What is the difference between CGI and Servlet ?
53. What is the use of Interface ?
54. Why Java is not fully objective oriented ?
55. Why does not support multiple Inheritance ?
56. What it the root class for all Java classes ?
57. What is polymorphism ?
58. Suppose If we have variable ‘ I ‘ in run method, If I can create one or more thread each thread will occupy a separate copy or same variable will be shared ?
59. In servlets, we are having a web page that is invoking servlets username and password ? which is checked in the database ? Suppose the second page also If we want to verify the same information whether it will connect to the database or it will be used previous information?
60. What are virtual functions ?
61. Write down how will you create a binary Tree ?
62. What are the traverses in Binary Tree ?
63. Write a program for recursive Traverse ?
64. What are session variable in Servlets ?
65. What is client server computing ?
66. What is Constructor and Virtual function? Can we call Virtual function in a constructor ?
67. Why we use OOPS concepts? What is its advantage ?
68. What is the middleware ? What is the functionality of Webserver ?
69. Why Java is not 100 % pure OOPS ? ( EcomServer )
70. When we will use an Interface and Abstract class ?
71. What is an RMI?
72. How will you pass parameters in RMI ? Why u serialize?
73. What is the exact difference in between Unicast and Multicast object ? Where we will use ?
74. What is the main functionality of the Remote Reference Layer ?
75. How do you download stubs from a Remote place ?
76. What is the difference in between C++ and Java ? can u explain in detail ?
77. I want to store more than 10 objects in a remote server ? Which methodology will follow ?
78. What is the main functionality of the Prepared Statement ?
79. What is meant by static query and dynamic query ?
80. What are the Normalization Rules ? Define the Normalization ?
81. What is meant by Servlet? What are the parameters of the service method ?
82. What is meant by Session ? Tell me something about HTTPSession Class ?
83. How do you invoke a Servlet? What is the difference in between doPost and doGet methods ?
84. What is the difference in between the HTTPServlet and Generic Servlet ? Explain their methods ? Tell me their parameter names also ?
85. Have you used threads in Servlet ?
86. Write a program on RMI and JDBC using StoredProcedure ?
87. How do you sing an Applet ?
88. In a Container there are 5 components. I want to display the all the components names, how will you do that one ?
89. Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA ?
90. Tell me the latest versions in JAVA related areas ?
91. What is meant by class loader ? How many types are there? When will we use them ?
92. How do you load an Image in a Servlet ?
93. What is meant by flickering ?
94. What is meant by distributed Application ? Why we are using that in our applications ?
95. What is the functionality of the stub ?
96. Have you used any version control ?
97. What is the latest version of JDBC ? What are the new features are added in that ?
98. Explain 2 tier and 3 -tier Architecture ?
99. What is the role of the webserver ?
100. How have you done validation of the fields in your project ?
101. What is the main difficulties that you are faced in your project ?
102. What is meant by cookies ? Explain ?
What is the purpose of garbage collection in Java, and when is it used?
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.
2) Describe synchronization in respect to multithreading.
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
>
3) How is JavaBeans differ from Enterprise JavaBeans?
The JavaBeans architecture is meant to provide a format for general-purpose components. On the other hand, the Enterprise JavaBeans architecture provides a format for highly specialized business logic components.
4) In what ways do design patterns help build better software?
Design patterns helps software developers to reuse successful designs and architectures. It helps them to choose design alternatives that make a system reusuable and avoid alternatives that compromise reusability through proven techniques as design patterns.
5) Describe 3-Tier Architecture in enterprise application development.
In 3-tier architecture, an application is broken up into 3 separate logical layers, each with a well-defined set of interfaces. The presentation layer typically consists of a graphical user interfaces. The business layer consists of the application or business logic, and the data layer contains the data that is needed for the application

No comments: