<% jquery="yes" fixright="no" google_ads="no" aspage="state" currentpage="jobsbystate" needconn="no" hotemp="yes" techforum="yes" edulist="yes" loclist="no" categorylist="yes" interview="no" infolinks="no" pagetitle="Latest Java Technical Interview Questions for Fresher" pagedesc="Latest Java Technical Interview Questions for Fresher." />
 Yuva Jobs Yuva Jobs Login      New User      Search
Daily Walk-Ins
Send Resume To 1000 Companies
Send Resume To 1000 Consultants
Yuva Jobs
  All Companies List :
| Latest::
     Search the Web      Special Search Engine for Freshers
    Kanbay is recruiting Freshers - Click here to register on their web site for call       Yuva Jobs Team Page Have Updated With Their Team Members Details and Pics      Click Here To Help : Earth Quake's Injured Peoples Need Your Help      Kanbay Papers     All Walkins and Jobs are Updated - 02-01-2005   All Subject's Technical Interview and Aptitude Questions will be on site from 07-01-2005  
Java Technical Questions (Please Scroll Window all java subjects are covered here)

Interview questions for Web application developers

The following set was set in by a reader of the site:

Following are the questions from an interview I attended for in C#, ASP.NET, XML and Sql Server. I will try to add some more as soon as I recollect. Hope these questions will be useful for people attending interviews in this area.

  1. What is the maximum length of a varchar field in SQL Server?

  2. How do you define an integer in SQL Server?

  3. How do you separate business logic while creating an ASP.NET application?

  4. If there is a calendar control to be included in each page of your application, and we do not intend to use the Microsoft-provided calendar control, how do you develop it? Do you copy and paste the code into each and very page of your application?

  5. How do you debug an ASP.NET application?

  6. How do you deploy an ASP.NET application?

  7. Name a few differences between .NET application and a Java application?

  8. Specify the best ways to store variables so that we can access them in various pages of ASP.NET application?

  9. What are the XML files that are important in developing an ASP.NET application?

  10. What is XSLT and what is its use?

Java Web development interview 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
    	SQLWarning warning = stmt.getWarnings();
    	if (warning != null)
    		while (warning != null)
    			System.out.println("Message: " + warning.getMessage());
    			System.out.println("SQLState: " + warning.getSQLState());
    			System.out.print("Vendor error code: ");
    			warning = warning.getNextWarning();
  8. How many JSP scripting elements are there and what are they? - There are three scripting language elements: declarations, scriptlets, expressions.

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

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

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

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

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

EJB interview questions
  1. 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.

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

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

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

  5. 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)

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

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

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

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

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

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

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

  13. Is method overloading allowed in EJB? - Yes you can overload methods

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

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

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

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

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

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

  20. 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".

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

  22. 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)

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

  24. 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.)

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


Good questions asked during Java interview

  1. Is “abc” a primitive value? - The String literal “abc” is not a primitive value. It is a String object. "

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

  3. What modifiers may be used with an interface declaration? - An interface may be declared as public or abstract.

  4. Is a class a subclass of itself? - A class is a subclass of itself.

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

  6. What modifiers can be used with a local inner class? - A local inner class may be final or abstract.

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

  8. Can an exception be rethrown? - Yes, an exception can be rethrown.

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

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

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

  12. What restrictions are placed on method overloading? - Two methods may not have the same name and argument list but different return types.

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

  14. What is the return type of a program’s main() method? - A program’s main() method has a void return type.

  15. What class of exceptions are generated by the Java run-time system? - The Java runtime system generates RuntimeException and Error exceptions.

  16. What class allows you to read objects directly from a stream? - The ObjectInputStream class supports the reading of objects from input streams.

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

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

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

  20. Why are the methods of the Math class static? - So they can be invoked as if they are a mathematical code library.

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

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

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

  24. What are E and PI? - E is the base of the natural logarithm and PI is mathematical value pi.

  25. Are true and false keywords? - The values true and false are not keywords.

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

  27. What happens when you add a double value to a String? - The result is a String object.

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

  29. Which package is always imported by default? - The java.lang package is always imported by default.

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

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

  32. 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).

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

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

  35. 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;

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

  37. What is a transient variable? - transient variable is a variable that may not be serialized.

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

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

  40. What state does a thread enter when it terminates its processing? - When a thread terminates its processing, it enters the dead state.

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

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

  43. Is sizeof a keyword? - The sizeof operator is not a keyword.

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

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

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

  47. Can a for statement loop indefinitely? - Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;

  48. To what value is a variable of the String type automatically initialized? - The default value of an String type is null.

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

  50. What is the range of the short type? - The range of the short type is -(2^15) to 2^15 - 1.

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

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

  53. What is Downcasting ? - Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy

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

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

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

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

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

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

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

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


JDBC and JSP interview questions

  1. What is the query used to display all tables names in SQL Server (Query analyzer)?
    	select * from information_schema.tables
  2. How many types of JDBC Drivers are present and what are they?- There are 4 types of JDBC Drivers
    • JDBC-ODBC Bridge Driver
    • Native API Partly Java Driver
    • Network protocol Driver
    • JDBC Net pure Java Driver

  3. Can we implement an interface in a JSP?- No

  4. What is the difference between ServletContext and PageContext?- ServletContext: Gives the information about the container. PageContext: Gives the information about the Request

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

  6. How to pass information from JSP to included JSP?- Using <%jsp:param> tag.

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

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

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

  10. How do you delete a Cookie within a JSP?
    	Cookie mycook = new Cookie("name","value");
    	Cookie killmycook = new Cookie("mycook","value");
  11. 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.
    	<!--#include file="data.inc"-->

    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 <!–#include file="data.inc"–> is used for including non-JSP files.

  12. 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().

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

  14. What is the fastest type of JDBC driver?- JDBC driver performance will depend on a number of issues:
    • the quality of the driver code,
    • the size of the driver code,
    • the database server and its load,
    • network topology,
    • 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).

  15. How do I find whether a parameter exists in the request object?
    boolean hasFoo = !(request.getParameter("foo") == null
    	|| request.getParameter("foo").equals(""));


    boolean hasParameter =
    	request.getParameterMap().contains(theParameter); //(which works in Servlet 2.3+)
  16. 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.


Advanced EJB interview questions

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

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

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

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

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

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

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

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

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

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

  11. 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)

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

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

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

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

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

  17. 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).”

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

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

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

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

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

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

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

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


Junior Java programmer interview questions

  1. What is the purpose of finalization? - The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

  2. What is the difference between the Boolean & operator and the && operator? - If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.

  3. How many times may an object’s finalize() method be invoked by the garbage collector? - An object’s finalize() method may only be invoked once by the garbage collector.

  4. What is the purpose of the finally clause of a try-catch-finally statement? - The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

  5. What is the argument type of a program’s main() method? - A program’s main() method takes an argument of the String[] type.

  6. Which Java operator is right associative? - The = operator is right associative.

  7. Can a double value be cast to a byte? - Yes, a double value can be cast to a byte.

  8. What is the difference between a break statement and a continue statement? - A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.

  9. What must a class do to implement an interface? - It must provide all of the methods in the interface and identify the interface in its implements clause.

  10. What is the advantage of the event-delegation model over the earlier event-inheritance model? - The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component’s design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model.

  11. How are commas used in the intialization and iteration parts of a for statement? - Commas are used to separate multiple statements within the initialization and iteration parts of a for statement.

  12. What is an abstract method? - An abstract method is a method whose implementation is deferred to a subclass.

  13. What value does read() return when it has reached the end of a file? - The read() method returns -1 when it has reached the end of a file.

  14. Can a Byte object be cast to a double value? - No, an object cannot be cast to a primitive value.

  15. What is the difference between a static and a non-static inner class? - A non-static inner class may have object instances that are associated with instances of the class’s outer class. A static inner class does not have any object instances.

  16. If a variable is declared as private, where may the variable be accessed? - A private variable may only be accessed within the class in which it is declared.

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

  18. What is the % operator? - It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.

  19. When can an object reference be cast to an interface reference? - An object reference be cast to an interface reference when the object implements the referenced interface.

  20. Which class is extended by all other classes? - The Object class is extended by all other classes.

  21. Can an object be garbage collected while it is still reachable? - A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected.

  22. Is the ternary operator written x : y ? z or x ? y : z ? - It is written x ? y : z.

  23. How is rounding performed under integer division? - The fractional part of the result is truncated. This is known as rounding toward zero.

  24. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy? - The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.

  25. What classes of exceptions may be caught by a catch clause? - A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.

  26. If a class is declared without any access modifiers, where may the class be accessed? - A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

  27. Does a class inherit the constructors of its superclass? - A class does not inherit constructors from any of its superclasses.

  28. What is the purpose of the System class? - The purpose of the System class is to provide access to system resources.

  29. Name the eight primitive Java types. - The eight primitive types are byte, char, short, int, long, float, double, and boolean.

  30. Which class should you use to obtain design information about an object? - The Class class is used to obtain information about an object’s design.

Core Java interview questions

  1. Can there be an abstract class with no abstract methods in it? - Yes

  2. Can an Interface be final? - No

  3. Can an Interface have an inner class? - Yes.
    	public interface abc
    		static int i=0; void dd();
    		class a1
    				int j;
    			public static void main(String a1[])
    				System.out.println("in interfia");
  4. Can we define private and protected modifiers for variables in interfaces? - No

  5. 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)

  6. What modifiers are allowed for methods in an Interface? - Only public and abstract modifiers are allowed for methods in interfaces.

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

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

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

  10. 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().

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

  12. How do I convert a numeric IP address like into a hostname like java.sun.com?
    	String hostname = InetAddress.getByName("").getHostName();
  13. Difference between JRE/JVM/JDK?

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

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

  16. Is null a keyword? - The null value is not a keyword.

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

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

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

  20. What are wrapped classes? - Wrapped classes are classes that allow primitive types to be accessed as objects.

  21. 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).

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

  23. What is a native method? - A native method is a method that is implemented in a language other than Java.

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

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

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

  27. What is the range of the char type? - The range of the char type is 0 to 2^16 - 1.

Java interview questions

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

  2. What kind of thread is the Garbage collector thread? - It is a daemon thread.

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

  4. How will you invoke any external process in Java? - Runtime.getRuntime().exec(….)

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

  6. 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, …)

  7. What is the basic difference between string and stringbuffer object? - String is an immutable object. StringBuffer is a mutable object.

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

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

  10. What is the base class for Error and Exception? - Throwable

  11. What is the byte range? -128 to 127

  12. What is the implementation of destroy method in java.. is it native or java code? - This method is not implemented.

  13. What is a package? - To group set of classes into a single unit is known as packaging. Packages provides wide namespace ability.

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

  15. What is a DatabaseMetaData? - Comprehensive information about the database as a whole.

  16. What is Locale? - A Locale object represents a specific geographical, political, or cultural region

  17. How will you load a specific locale? - Using ResourceBundle.getBundle(…);

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

  19. Is JVM a compiler or an interpreter? - Interpreter

  20. When you think about optimization, what is the best way to findout the time/memory consuming process? - Using profiler

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

  22. How will you get the platform dependent values like line separator, path separator, etc., ? - Using Sytem.getProperty(…) (line.separator, path.separator, …)

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

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

  25. What is the significance of ListIterator? - You can iterate back and forth.

  26. What is the major difference between LinkedList and ArrayList? - LinkedList are meant for sequential accessing. ArrayList are meant for random accessing.

  27. What is nested class? - If all the methods of a inner class is static then it is a nested class.

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

  29. What is composition? - Holding the reference of the other class within some other class is known as composition.

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

  31. What are the methods in Object? - clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString

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

  33. 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 … }

  34. What is DriverManager? - The basic service to manage set of JDBC drivers.

  35. 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() ).

  36. Inq adds a question: Expain the reason for each keyword of
    public static void main(String args[])

Basic Java interview questions
  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
J2EE EJB interview questions

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

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

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

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

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

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

  7. What is the need for Clustering? - To scale the application so that it is highly available and has high throughput.

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

  9. What are the types of Scaling? - There are two types of scaling: Vertical Scaling and Horizontal Scaling.

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

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

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

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

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

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

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

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

  18. 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)

  19. Mention some tools to cluster Web Servers? - Web Servers can be clustered using Edge Server or DNS.

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

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

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

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

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

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

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

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

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

  8. Must my bean-managed persistence mechanism use the WebLogic JTS driver? - BEA recommend that you use the TxDataSource for bean-managed persistence.

  9. 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:
    • To keep clustering EJBs simple
    • 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.
    • To ensure that every EJB is available locally
    • To ensure that all classes are loaded in an undeployable way
    • 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.

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

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

  12. 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:
    	$ 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.

  13. What causes Java.io exceptions in the log file of WebLogic Server? - You may see messages like these in the log file:
    (Windows NT)
    	java.io.IOException Connection Reset by Peer
    	java.io.EOFException Connection Reset by Peer
    	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:

    • Click Stop or enter equivalent command or keystrokes
    • Click Refresh or enter equivalent command or keystrokes
    • Send a new HTTP request.

    The messages indicate that WebLogic Server has detected and recovered from an interrupted HTTP request.

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

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

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

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

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

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

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

  21. 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.
    Context c = new InitialContext(); UserTransaction ut = (UserTransaction)
    	// perform multiple operations...
    ut.commit() ...
    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.
  22. 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.

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

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


J2EE with EJB and Weblogic interview questions
Interview questions for Java junior developer position
  1. What gives Java its “write once and run anywhere” nature? - Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platorm specific and hence can be fed to any platform. After being fed to the JVM, which is specific to a particular operating system, the code platform specific machine code is generated thus making java platform independent.

  2. What are the four corner stones of OOP? - Abstraction, Encapsulation, Polymorphism and Inheritance.

  3. Difference between a Class and an Object? - A class is a definition or prototype whereas an object is an instance or living representation of the prototype.

  4. What is the difference between method overriding and overloading? - Overriding is a method with the same name and arguments as in a parent, whereas overloading is the same method name but different arguments.

  5. What is a “stateless” protocol? - Without getting into lengthy debates, it is generally accepted that protocols like HTTP are stateless i.e. there is no retention of state between a transaction which is a single request response combination.

  6. What is constructor chaining and how is it achieved in Java? - A child object constructor always first needs to construct its parent (which in turn calls its parent constructor.). In Java it is done via an implicit call to the no-args constructor as the first statement.

  7. What is passed by ref and what by value? - All Java method arguments are passed by value. However, Java does manipulate objects by reference, and all object variables themselves are references

  8. Can RMI and Corba based applications interact? - Yes they can. RMI is available with IIOP as the transport protocol instead of JRMP.

  9. You can create a String object as String str = “abc"; Why cant a button object be created as Button bt = “abc";? Explain - The main reason you cannot create a button by Button bt1= “abc"; is because “abc” is a literal string (something slightly different than a String object, by the way) and bt1 is a Button object. The only object in Java that can be assigned a literal String is java.lang.String. Important to note that you are NOT calling a java.lang.String constuctor when you type String s = “abc";

  10. What does the “abstract” keyword mean in front of a method? A class? - Abstract keyword declares either a method or a class. If a method has a abstract keyword in front of it,it is called abstract method.Abstract method hs no body.It has only arguments and return type.Abstract methods act as placeholder methods that are implemented in the subclasses. Abstract classes can’t be instantiated.If a class is declared as abstract,no objects of that class can be created.If a class contains any abstract method it must be declared as abstract.

  11. How many methods do u implement if implement the Serializable Interface? - The Serializable interface is just a “marker” interface, with no methods of its own to implement. Other ‘marker’ interfaces are
  12. What are the practical benefits, if any, of importing a specific class rather than an entire package (e.g. import java.net.* versus import java.net.Socket)? - It makes no difference in the generated class files since only the classes that are actually used are referenced by the generated class file. There is another practical benefit to importing single classes, and this arises when two (or more) packages have classes with the same name. Take java.util.Timer and javax.swing.Timer, for example. If I import java.util.* and javax.swing.* and then try to use “Timer", I get an error while compiling (the class name is ambiguous between both packages). Let’s say what you really wanted was the javax.swing.Timer class, and the only classes you plan on using in java.util are Collection and HashMap. In this case, some people will prefer to import java.util.Collection and import java.util.HashMap instead of importing java.util.*. This will now allow them to use Timer, Collection, HashMap, and other javax.swing classes without using fully qualified class names in.

  13. What is the difference between logical data independence and physical data independence? - Logical Data Independence - meaning immunity of external schemas to changeds in conceptual schema. Physical Data Independence - meaning immunity of conceptual schema to changes in the internal schema.

  14. What is a user-defined exception? - Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class.

  15. Describe the visitor design pattern? - Represents an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. The root of a class hierarchy defines an abstract method to accept a visitor. Subclasses implement this method with visitor.visit(this). The Visitor interface has visit methods for all subclasses of the baseclass in the hierarchy.

Java database interview questions
  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.
    	CallableStatement cs =
    		con.prepareCall("{call SHOW_SUPPLIERS}");
    	ResultSet rs = cs.executeQuery();

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

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

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

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

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

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

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

  9. 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:
    • 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.
    • 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.
    • 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.


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

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

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

    1. Create a properly formatted JDBR URL for your database. (See FAQ on JDBC URL for more information). A JDBC URL has the form
    2. Class.forName("my.database.driver");
    3. Connection conn = DriverManager.getConnection("a.JDBC.URL", “databaseLogin","databasePassword");

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

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

  15. How do you get Column names only for a table (SQL Server)? Write the Query. -
    	select name from syscolumns
    		where id=(select id from sysobjects where name='user_hdr')
    		order by colid --user_hdr is the table name
Java Messaging System interview questions
  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:
    • A connection object provided by the JMS server (the message broker)
    • Within a connection, one or more sessions, which provide a context for message sending and receiving
    • Within a session, either a queue or topic object representing the destination (the message staging area) within the message broker
    • 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? -
    1. App server creates the server session and stores them in a pool.
    2. Connection consumer uses the server session to put messages in the session of the JMS.
    3. Server session is the one that spawns the JMS session.
    4. Applications written by Application programmers creates the message listener.

Common JSP interview questions
  1. 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.

  2. Is JSP technology extensible? - Yes. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

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

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

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

  6. 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:
    	<%-- the scriptlet is now commented out
    	out.println("Hello World");

    You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example:

    <!-- (c) 2004 -->

    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
  7. 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 <HTML Tag><Some Headers><Body>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

  8. 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.
    <jsp:useBean id="foo" class="com.Bar.Foo" >
    <jsp:setProperty name="foo" property="today"
    value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>"/ >
    <%-- scriptlets calling bean setter methods go here --%>
    </jsp:useBean >
  9. 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.
    	<%@ page session="true" %>
    	Integer num = new Integer(100);
    	String url =response.encodeURL("hello2.jsp");
    	<a href='<%=url%>'>hello2.jsp</a>
    	<%@ page session="true" %>
    	Integer i= (Integer )session.getValue("num");
    	out.println("Num value in session is "+i.intValue());
  10. 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:
    	public String whereFrom(HttpServletRequest req) {
    	HttpSession ses = req.getSession();
    	return req.getRemoteHost();
    	out.print("Hi there, I see that you are coming in from ");
    	<%= whereFrom(request) %>
    	Another Example
    	<%@page contentType="text/html"%>
    	public void test(JspWriter writer) throws IOException{
    	<%@include file="file1.jsp"%>
    	<%test(out);% >
  11. 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:
    would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds.

  12. 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:
    	//creating a cookie
    	Cookie mycookie = new Cookie("aName","aValue");
    	//delete a cookie
    	Cookie killMyCookie = new Cookie("mycookie", null);
  13. 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.
    	public void doPost (HttpServletRequest request, HttpServletResponse response) {
    	try {
    		govi.FormBean f = new govi.FormBean();
    		String id = request.getParameter("id");
    		//use the id to compute
    		//additional bean properties like info
    		//maybe perform a db query, etc.
    		// . . .
                          ("/jsp/Bean1.jsp").forward(request, response);
    		} catch (Exception ex) {
    	. . .

    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" /
  14. 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:
    • The service() method has to invoke the _jspService() method
    • The init() method has to invoke the jspInit() method
    • 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" %>
  15. 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
    	String blanknull(String s) {
    	return (s == null) ? "" : s;
    	then use it inside your JSP form, like
    	<input type="text" name="shoesize" value="<%=blanknull(shoesize)% >">
  16. 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:
    	<%@ page isErrorPage="true" %>
    	out.println("	");
    	 PrintWriter pw = response.getWriter();
    	out.println(" ");
  17. 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.
    	<%@ page import="java.util.*" %>
    	ServletConfig cfg =null;
    	public void jspInit(){
    	ServletConfig cfg=getServletConfig();
    	for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) {
    	String name=(String)e.nextElement();
    	String value = cfg.getInitParameter(name);
  18. 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:
    	<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %>
    	//declare a "global" reference to an instance of the home interface of the session bean
    	AccountHome accHome=null;
    	public void jspInit() {
    	//obtain an instance of the home interface
    	InitialContext cntxt = new InitialContext( );
    	Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
    	accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
    	//instantiate the session bean
    	Account acct = accHome.create();
    	//invoke the remote methods
    	// etc etc...
Java interview questions
  1. What is the Collections API? - The Collections API is a set of classes and interfaces that support operations on collections of objects

  2. What is the List interface? - The List interface provides support for ordered collections of objects.

  3. What is the Vector class? - The Vector class provides the capability to implement a growable array of objects

  4. What is an Iterator interface? - The Iterator interface is used to step through the elements of a Collection

  5. Which java.util classes and interfaces support event handling? - The EventObject class and the EventListener interface support event processing

  6. What is the GregorianCalendar class? - The GregorianCalendar provides support for traditional Western calendars

  7. What is the Locale class? - The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region

  8. What is the SimpleTimeZone class? - The SimpleTimeZone class provides support for a Gregorian calendar

  9. What is the Map interface? - The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values

  10. What is the highest-level event class of the event-delegation model? - The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy

  11. What is the Collection interface? - The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates

  12. What is the Set interface? - The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements

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

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

  15. What is the difference between yielding and sleeping? - When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.

  16. When a thread blocks on I/O, what state does it enter? - A thread enters the waiting state when it blocks on I/O.

  17. When a thread is created and started, what is its initial state? - A thread is in the ready state after it has been created and started.

  18. What invokes a thread’s run() method? - After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread’s run() method when the thread is initially executed.

  19. What method is invoked to cause an object to begin executing as a separate thread? - The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread.

  20. What is the purpose of the wait(), notify(), and notifyAll() methods? - The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object’s wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object’s notify() or notifyAll() methods.

  21. What are the high-level thread states? - The high-level thread states are ready, running, waiting, and dead

  22. What happens when a thread cannot acquire a lock on an object? - If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object’s lock, it enters the waiting state until the lock becomes available.

  23. How does multithreading take place on a computer with a single CPU? - The operating system’s task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.

  24. What happens when you invoke a thread’s interrupt method while it is sleeping or waiting? - When a task’s interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown.

  25. What state is a thread in when it is executing? - An executing thread is in the running state

  26. What are three ways in which a thread can enter the waiting state? - A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object’s lock, or by invoking an object’s wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

  27. What method must be implemented by all threads? - All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface.

  28. What are the two basic ways in which classes that can be run as threads may be defined? - A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface.

  29. How can you store international / Unicode characters into a cookie? - One way is, before storing the cookie URLEncode it. URLEnocder.encoder(str); And use URLDecoder.decode(str) when you get the stored cookie.

Java GUI designer interview questions
  1. What advantage do Java’s layout managers provide over traditional windowing systems? - Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems.

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

  3. How can the Checkbox class be used to create a radio button? - By associating Checkbox objects with a CheckboxGroup

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

  5. What interface is extended by AWT event listeners? - All AWT event listeners extend the java.util.EventListener interface.

  6. What is a layout manager? - A layout manager is an object that is used to organize components in a container

  7. Which Component subclass is used for drawing and painting? - Canvas

  8. What are the problems faced by Java programmers who dont use layout managers? - Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system

  9. What is the difference between a Scrollbar and a ScrollPane? (Swing) - A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.

J2EE interview questions

Thanks to Sachin Rastogi for contributing these.
  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:
    • Client-tier components run on the client machine.
    • Web-tier components run on the J2EE server.
    • Business-tier components run on the J2EE server.
    • 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:
    • Applets
    • Application clients
    • Java Web Start-enabled rich clients, powered by Java Web Start technology.
    • 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.

Basic Java servlet interview questions

  1. What is the difference between CGI and Servlet?

  2. What is meant by a servlet?

  3. What are the types of servlets? What is the difference between 2 types of Servlets?

  4. What is the type of method for sending request from HTTP server ?

  5. What are the exceptions thrown by Servlets? Why?

  6. What is the life cycle of a servlet?

  7. What is meant by cookies? Why is Cookie used?

  8. What is HTTP Session?

  9. What is the difference between GET and POST methods?

  10. How can you run a Servlet Program?

  11. What is the middleware? What is the functionality of Webserver?

  12. What webserver is used for running the Servlets?

  13. How do you invoke a Servelt? What is the difference in between doPost and doGet methods?

  14. What is the difference in between the HTTPServlet and Generic Servlet? Explain their methods? Tell me their
    parameter names also?

  15. What are session variable in Servlets?

  16. What is meant by Session? Tell me something about HTTPSession Class?

  17. What is Session Tracking?

  18. Difference between doGet and doPost?

  19. What are the methods in HttpServlet?

  20. What are the types of SessionTracking? Why do you use Session Tracking in HttpServlet?

Java AWT interview questions

Thanks to Sachin Rastogi for contributing these.
  1. What is meant by Controls and what are different types of controls? - Controls are componenets that allow a user to interact with your application. The AWT supports the following types of controls:
    • Labels
    • Push buttons
    • Check boxes
    • Choice lists
    • Lists
    • Scroll bars
    • Text components

    These controls are subclasses of Component.

  2. Which method of the component class is used to set the position and the size of a component? - setBounds(). The following code snippet explains this:

    places upper left corner of the text field txtName at point (x,y) with the width and height of the text field set as width and height.

  3. Which TextComponent method is used to set a TextComponent to the read-only state? - setEditable()

  4. How can the Checkbox class be used to create a radio button? - By associating Checkbox objects with a

  5. What methods are used to get and set the text label displayed by a Button object? - getLabel( ) and setLabel( )

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

  7. What is the difference between a Scollbar and a Scrollpane? - A Scrollbar is a Component, but not a Container. A Scrollpane is a Container and handles its own events and performs its own scrolling.

  8. Which are true about the Container class?
    • The validate( ) method is used to cause a Container to be laid out and redisplayed.
    • The add( ) method is used to add a Component to a Container.
    • The getBorder( ) method returns information about a Container’s insets.
    • getComponent( ) method is used to access a Component that is contained in a Container.

    Answers: a, b and d

  9. Suppose a Panel is added to a Frame and a Button is added to the Panel. If the Frame’s font is set to 12-point TimesRoman, the Panel’s font is set to 10-point TimesRoman, and the Button’s font is not set, what font will be used to display the Button’s label?
    • 12-point TimesRoman
    • 11-point TimesRoman
    • 10-point TimesRoman
    • 9-point TimesRoman

    Answer: c.

  10. What are the subclasses of the Container class? - The Container class has three major subclasses. They are:
    • Window
    • Panel
    • ScrollPane

  11. Which object is needed to group Checkboxes to make them exclusive? - CheckboxGroup.

  12. What are the types of Checkboxes and what is the difference between them? - Java supports two types of Checkboxes:
    • Exclusive
    • Non-exclusive.

    In case of exclusive Checkboxes, only one among a group of items can be selected at a time. I f an item from the group is selected, the checkbox currently checked is deselected and the new selection is highlighted. The exclusive Checkboxes are also called as Radio buttons. The non-exclusive checkboxes are not grouped together and each one can be selected independent of the other.

  13. What is a Layout Manager and what are the different Layout Managers available in java.awt and what is the default Layout manager for the panel and the panel subclasses? - A layout Manager is an object that is used to organize components in a container. The different layouts available in java.awt are:
    • FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion.
    • BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container.
    • CardLayout: The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.
    • GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid.
    • GridBagLayout:
      The elements of a GridBagLayout are organized according to a grid.However, the elements are of different sizes and may occupy more
      than one row or column of the grid. In addition, the rows and columns may have different sizes.

    The default Layout Manager of Panel and Panel sub classes is FlowLayout.

  14. Can I add the same component to more than one container? - No. Adding a component to a container automatically removes it from any previous parent (container).

  15. How can we create a borderless window? - Create an instance of the Window class, give it a size, and show it on the screen.
    Frame aFrame = new Frame();
    Window aWindow = new Window(aFrame);
    aWindow.setLayout(new FlowLayout());
    aWindow.add(new Button("Press Me"));
  16. Can I create a non-resizable windows? If so, how? - Yes. By using setResizable() method in class Frame.

  17. Which containers use a BorderLayout as their default layout? Which containers use a FlowLayout as their default layout? - The Window, Frame and Dialog classes use a BorderLayout as their default layout. The Panel and the Applet classes use the FlowLayout as their default layout.

  18. How do you change the current layout manager for a container?
    • Use the setLayout method
    • Once created you cannot change the current layout manager of a component
    • Use the setLayoutManager method
    • Use the updateLayout method

    Answer: a.

  19. What is the difference between a MenuItem and a CheckboxMenuItem?- The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.

Java applet interview questions

Thanks to Sachin Rastogi for sending this set in.

  1. What is an Applet? Should applets have constructors?
    - Applets are small programs transferred through Internet, automatically installed and run as part of web-browser. Applets implements functionality of a client. Applet is a dynamic and interactive program that runs inside a Web page displayed by a Java-capable browser. We don’t have the concept of Constructors in Applets. Applets can be invoked either through browser or through Appletviewer utility provided by JDK.

  2. What are the Applet’s Life Cycle methods? Explain them? - Following are methods in the life cycle of an Applet:
    • init() method - called when an applet is first loaded. This method is called only once in the entire cycle of an applet. This method usually intialize the variables to be used in the applet.
    • start( ) method - called each time an applet is started.
    • paint() method - called when the applet is minimized or refreshed. This method is used for drawing different strings, figures, and images on the applet window.
    • stop( ) method - called when the browser moves off the applet’s page.
    • destroy( ) method - called when the browser is finished with the applet.

  3. What is the sequence for calling the methods by AWT for applets? - When an applet begins, the AWT calls the following methods, in this sequence:
    • init()
    • start()
    • paint()

    When an applet is terminated, the following sequence of method calls takes place :

    • stop()
    • destroy()

  4. How do Applets differ from Applications? - Following are the main differences: Application: Stand Alone, doesn’t need web-browser. Applet: Needs no explicit installation on local machine. Can be transferred through Internet on to the local machine and may run as part of web-browser. Application: Execution starts with main() method. Doesn’t work if main is not there. Applet: Execution starts with init() method. Application: May or may not be a GUI. Applet: Must run within a GUI (Using AWT). This is essential feature of applets.

  5. Can we pass parameters to an applet from HTML page to an applet? How? - We can pass parameters to an applet using <param> tag in the following way:
    • <param name="param1″ value="value1″>
    • <param name="param2″ value="value2″>

    Access those parameters inside the applet is done by calling getParameter() method inside the applet. Note that getParameter() method returns String value corresponding to the parameter name.

  6. How do we read number information from my applet’s parameters, given that Applet’s getParameter() method returns a string?
    - Use the parseInt() method in the Integer Class, the Float(String) constructor or parseFloat() method in the Class Float, or the
    Double(String) constructor or parseDoulbl() method in the class Double.

  7. How can I arrange for different applets on a web page to communicate with each other?
    - Name your applets inside the Applet tag and invoke AppletContext’s getApplet() method in your applet code to obtain references to the
    other applets on the page.

  8. How do I select a URL from my Applet and send the browser to that page? - Ask the applet for its applet context and invoke showDocument() on that context object.
    URL targetURL;
    String URLString
    AppletContext context = getAppletContext();
    	targetURL = new URL(URLString);
    catch (MalformedURLException e)
    	// Code for recover from the exception
    context. showDocument (targetURL);
  9. Can applets on different pages communicate with each other?
    - No, Not Directly. The applets will exchange the information at one meeting place either on the local file
    system or at remote system.

  10. How do I determine the width and height of my application?
    - Use the getSize() method, which the Applet class inherits from the Component class in the Java.awt package. The getSize() method returns the size of the applet as a Dimension object, from which you extract separate width, height fields. The following code snippet explains this:
    Dimension dim = getSize();
    int appletwidth = dim.width();
    int appletheight = dim.height();
  11. Which classes and interfaces does Applet class consist? - Applet class consists of a single class, the Applet class and three interfaces: AppletContext, AppletStub, and AudioClip.

  12. What is AppletStub Interface?

    - The applet stub interface provides the means by which an applet and the browser communicate. Your code will not typically implement this interface.
  13. What tags are mandatory when creating HTML to display an applet?
    1. name, height, width
    2. code, name
    3. codebase, height, width
    4. code, height, width

    Correct answer is d.

  14. What are the Applet’s information methods?
    - The following are the Applet’s information methods: getAppletInfo() method: Returns a string describing the applet, its author, copyright information, etc. getParameterInfo( ) method: Returns an array of string describing the applet’s parameters.

  15. What are the steps involved in Applet development? - Following are the steps involved in Applet development:
    • Create/Edit a Java source file. This file must contain a class which extends Applet class.
    • Compile your program using javac
    • Execute the appletviewer, specifying the name of your applet’s source file or html file. In case the applet information is stored in html file then Applet can be invoked using java enabled web browser.

  16. Which method is used to output a string to an applet? Which function is this method included in? - drawString( ) method is used to output a string to an applet. This method is included in the paint method of the Applet.

Servlet interview questions
  1. What is a servlet?
    Servlets are modules that extend request/response-oriented servers,such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database. Servlets are to servers what applets are to browsers. Unlike applets, however, servlets have no graphical user interface.

  2. Whats the advantages using servlets over using CGI?
    Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with the Java Servlet API, a standard Java extension.

  3. What are the general advantages and selling points of Servlets?
    A servlet can handle multiple requests concurrently, and synchronize requests. This allows servlets to support systems such as online real-time conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.

  4. Which package provides interfaces and classes for writing servlets? javax

  5. What’s the Servlet Interface?
    The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet.Servlets > Generic Servlet > HttpServlet > MyServlet.

    The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

  6. When a servlet accepts a call from a client, it receives two objects. What are they?
    ServletRequest (which encapsulates the communication from the client to the server) and ServletResponse (which encapsulates the communication from the servlet back to the client). ServletRequest and ServletResponse are interfaces defined inside javax.servlet package.

  7. What information does ServletRequest allow access to?
    Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. Also the input stream, as ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and GET methods.

  8. What type of constraints can ServletResponse interface set on the client?
    It can set the content length and MIME type of the reply. It also provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.

  9. Explain servlet lifecycle?
    Each servlet has the same life cycle: first, the server loads and initializes the servlet (init()), then the servlet handles zero or more client requests (service()), after that the server removes the servlet (destroy()). Worth noting that the last step on some servers is done when they shut down.

  10. How does HTTP Servlet handle client requests?
    An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.

JDBC interview questions

Thanks to Sachin Rastogi for sending in Java database interview questions.

  1. What are the steps involved in establishing a JDBC connection? This action involves two steps: loading the JDBC driver and making the connection.

  2. How can you load the drivers?
    Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:


    Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ, you would load the driver with the following line of code:


  3. What will Class.forName 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.

  4. How can you make the connection? To establish a connection you need to have the appropriate driver connect to the DBMS.
    The following line of code illustrates the general idea:

    String url = “jdbc:odbc:Fred";
    Connection con = DriverManager.getConnection(url, “Fernanda", “J8?);

  5. How can you create JDBC statements and what are they?
    A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate. It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object

    Statement stmt = con.createStatement();

  6. How can you retrieve data from the ResultSet?
    JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.

    ResultSet rs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
    String s = rs.getString("COF_NAME");

    The method getString is invoked on the ResultSet object rs, so getString() will retrieve (get) the value stored in the column COF_NAME in the current row of rs.

  7. What are the different types of Statements?
    Regular statement (use createStatement method), prepared statement (use prepareStatement method) and callable statement (use prepareCall)

  8. How can you use PreparedStatement? This special type of statement is derived from class Statement.If you need a Statement object to execute many times, it will normally make sense to use a PreparedStatement object instead. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement’s SQL statement without having to compile it first.
    PreparedStatement updateSales =
    	con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
  9. What does setAutoCommit do?
    When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode:


    Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly.

    PreparedStatement updateSales =
    	con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
    updateSales.setInt(1, 50); updateSales.setString(2, "Colombian");
    PreparedStatement updateTotal =
    	con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");
    updateTotal.setInt(1, 50);
    updateTotal.setString(2, "Colombian");
  10. How do you call a stored procedure from JDBC?
    The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open
    Connection object. A CallableStatement object contains a call to a stored procedure.
    	CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
    	ResultSet rs = cs.executeQuery();
  11. How do I 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:
    SQLWarning warning = stmt.getWarnings();
    if (warning != null)
    	while (warning != null)
    		System.out.println("Message: " + warning.getMessage());
    		System.out.println("SQLState: " + warning.getSQLState());
    		System.out.print("Vendor error code: ");
    		warning = warning.getNextWarning();
  12. How can you move the cursor in scrollable result sets?
    One of the new features in the JDBC 2.0 API is the ability to move a result set’s cursor backward as well as forward. There are also methods that let you move the cursor to a particular row and check the position of the cursor.

    Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

    The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE. The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE. The point to remember here is that if you specify a type, you must also specify whether it is read-only or updatable. Also, you must specify the type first, and because both parameters are of type int , the compiler will not complain if you switch the order. Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in which the cursor moves only forward. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.

  13. What’s the difference between TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE?
    You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopened:
    Statement stmt =
    	con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet srs =
    	stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
    while (srs.previous())
    	String name = srs.getString("COF_NAME");
    	float price = srs.getFloat("PRICE");
    	System.out.println(name + " " + price);
  14. How to Make Updates to Updatable Result Sets?
    Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.
    Connection con =
    Statement stmt =
    	con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
    ResultSet uprs =
    	stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
Java interview questions
  1. What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to an object. For example, a thread only executes a synchronized method after it has acquired the lock for the method’s object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

  2. What are different ways in which a thread can enter the waiting state? A thread can enter the waiting state by invoking its sleep() method, blocking on I/O, unsuccessfully attempting to acquire an object’s lock, or invoking an object’s wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

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

  4. What’s new with the stop(), suspend() and resume() methods in new JDK 1.2? The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

  5. What is the preferred size of a component? The preferred size of a component is the minimum component size that will allow the component to display normally.

  6. What method is used to specify a container’s layout? The setLayout() method is used to specify a container’s layout. For example, setLayout(new FlowLayout()); will be set the layout as FlowLayout.

  7. Which containers use a FlowLayout as their default layout? The Panel and Applet classes use the FlowLayout as their default layout.

  8. What state does a thread enter when it terminates its processing? When a thread terminates its processing, it enters the dead state.

  9. What is the Collections API? The Collections API is a set of classes and interfaces that support operations on collections of objects. One example of class in Collections API is Vector and Set and List are examples of interfaces in Collections API.

  10. What is the List interface? The List interface provides support for ordered collections of objects. It may or may not allow duplicate elements but the elements must be ordered.

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

  12. What is the Vector class? The Vector class provides the capability to implement a growable array of objects. The main visible advantage of this class is programmer needn’t to worry about the number of elements in the Vector.

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

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

  15. What is an Iterator interface? The Iterator interface is used to step through the elements of a Collection.

  16. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? Unicode requires 16 bits, 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

  17. What is the difference between yielding and sleeping? Yielding means a thread returning to a ready state either from waiting, running or after creation, where as sleeping refers a thread going to a waiting state from running state. With reference to Java, when a task invokes its yield() method, it returns to the ready state and when a task invokes its sleep() method, it returns to the waiting state
  18. What are wrapper classes? Wrapper classes are classes that allow primitive types to be accessed as objects. For example, Integer, Double. These classes contain many methods which can be used to manipulate basic data types

  19. Does garbage collection guarantee that a program will not run out of memory? No, it doesn’t. 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. The main purpose of Garbage Collector is recover the memory from the objects which are no longer required when more memory is needed.

  20. Name Component subclasses that support painting? The following classes support painting: Canvas, Frame, Panel, and Applet.

  21. What is a native method? A native method is a method that is implemented in a language other than Java. For example, one method may be written in C and can be called in Java.

  22. How can you write a loop indefinitely?

    for(;;) //for loop
    while(true); //always true

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

  24. What is the purpose of finalization? The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. For example, closing a opened file, closing a opened database Connection.

  25. What invokes a thread’s run() method? After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread’s run() method when the thread is initially executed.

  26. What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars.

  27. What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar.

  28. What is the Properties class? The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.

  29. What is the purpose of the Runtime class? The purpose of the Runtime class is to provide access to the Java runtime system.

  30. What is the purpose of the System class? The purpose of the System class is to provide access to system resources.

  31. What is the purpose of the finally clause of a try-catch-finally statement? The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. For example,

    //some statements
    // statements when exception is cought
    //statements executed whether exception occurs or not

  32. What is the Locale class? The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.

  33. What must a class do to implement an interface? It must provide all of the methods in the interface and identify the interface in its implements clause.

JSP interview questions
  1. What is JSP? Describe its concept. JSP is a technology that combines HTML/XML markup languages and elements of Java programming Language to return dynamic content to the Web client, It is normally used to handle Presentation logic of a web application, although it may have business logic.

  2. What are the lifecycle phases of a JSP?
    JSP page looks like a HTML page but is a servlet. When presented with JSP page the JSP engine does the following 7 phases.
    1. Page translation: -page is parsed, and a java file which is a servlet is created.
    2. Page compilation: page is compiled into a class file
    3. Page loading : This class file is loaded.
    4. Create an instance :- Instance of servlet is created
    5. jspInit() method is called
    6. _jspService is called to handle service calls
    7. _jspDestroy is called to destroy it when the servlet is not required.

  3. What is a translation unit? JSP page can include the contents of other HTML pages or other JSP files. This is done by using the include directive. When the JSP engine is presented with such a JSP page it is converted to one servlet class and this is called a translation unit, Things to remember in a translation unit is that page directives affect the whole unit, one variable declaration cannot occur in the same unit more than once, the standard action jsp:useBean cannot declare the same bean twice in one unit.

  4. How is JSP used in the MVC model? JSP is usually used for presentation in the MVC pattern (Model View Controller ) i.e. it plays the role of the view. The controller deals with calling the model and the business classes which in turn get the data, this data is then presented to the JSP for rendering on to the client.

  5. What are context initialization parameters? Context initialization parameters are specified by the <context-param> in the web.xml file, these are initialization parameter for the whole application and not specific to any servlet or JSP.

  6. What is a output comment? A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as un-interpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.

  7. What is a Hidden Comment? A comment that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or “comment out” part of your JSP page.

  8. What is a Expression? Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed.

  9. What is a Declaration? It declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as semicolons separate them. The declaration must be valid in the scripting language used in the JSP file.

  10. What is a Scriptlet? A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables or methods to use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects or any object declared with a <jsp:useBean>.

  11. What are the implicit objects? List them. Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects are:
    • request
    • response
    • pageContext
    • session
    • application
    • out
    • config
    • page
    • exception

  12. What’s the difference between forward and sendRedirect? When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container And then returns to the calling method. When a sendRedirect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

  13. What are the different scope values for the <jsp:useBean>? The different scope values for <jsp:useBean> are:
    • page
    • request
    • session
    • application

  14. Why are JSP pages the preferred API for creating a web-based client program? Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.

  15. Is JSP technology extensible? Yes, it is. JSP technology is extensible through the development of custom
    actions, or tags, which are encapsulated in tag libraries.

  16. What is difference between custom JSP tags and beans? Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. Custom tags and beans accomplish the same goals – encapsulating complex behavior into simple and accessible forms. There are several differences:
    • Custom tags can manipulate JSP content; beans cannot.
    • Complex operations can be reduced to a significantly simpler form with custom tags than with beans.
    • Custom tags require quite a bit more work to set up than do beans.
    • Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page.
    • Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.
Java interview questions
  1. What is a class? A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind.

  2. What is a object? An object is a software bundle of variables and related methods.An instance of a class depicting the state and behavior at that particular time in real world.

  3. What is a method? Encapsulation of a functionality which can be called to perform specific tasks.

  4. What is encapsulation? Explain with an example. Encapsulation is the term given to the process of hiding the implementation details of the object. Once an object is encapsulated, its implementation details are not immediately accessible any more. Instead they are packaged and are only indirectly accessible via the interface of the object

  5. What is inheritance? Explain with an example. Inheritance in object oriented programming means that a class of objects can inherit properties and methods from another class of objects.

  6. What is polymorphism? Explain with an example. In object-oriented programming, polymorphism refers to a programming language’s ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes. For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results. Polymorphism is considered to be a requirement of any true object-oriented programming language

  7. Is multiple inheritance allowed in Java? No, multiple inheritance is not allowed in Java.

  8. What is interpreter and compiler? Java interpreter converts the high level language code into a intermediate form in Java called as bytecode, and then executes it, where as a compiler converts the high level language code to machine language making it very hardware specific

  9. What is JVM? The Java interpreter along with the runtime environment required to run the Java application in called as Java virtual machine(JVM)

  10. What are the different types of modifiers? There are access modifiers and there are other identifiers. Access modifiers are public, protected and private. Other are final and static.

  11. What are the access modifiers in Java? There are 3 access modifiers. Public, protected and private, and the default one if no identifier is specified is called friendly, but programmer cannot specify the friendly identifier explicitly.

  12. What is a wrapper class? They are classes that wrap a primitive data type so it can be used as a object

  13. What is a static variable and static method? What’s the difference between two? The modifier static can be used with a variable and method. When declared as static variable, there is only one variable no matter how instances are created, this variable is initialized when the class is loaded. Static method do not need a class to be instantiated to be called, also a non static method cannot be called from static method.

  14. What is garbage collection? Garbage Collection is a thread that runs to reclaim the memory by destroying the objects that cannot be referenced anymore.

  15. What is abstract class? Abstract class is a class that needs to be extended and its methods implemented, aclass has to be declared abstract if it has one or more abstract methods.

  16. What is meant by final class, methods and variables? This modifier can be applied to class method and variable. When declared as final class the class cannot be extended. When declared as final variable, its value cannot be changed if is primitive value, if it is a reference to the object it will always refer to the same object, internal attributes of the object can be changed.

  17. What is interface? Interface is a contact that can be implemented by a class, it has method that need implementation.

  18. What is method overloading? Overloading is declaring multiple method with the same name, but with different argument list.

  19. What is method overriding? Overriding has same method name, identical arguments used in subclass.

  20. What is singleton class? Singleton class means that any given time only one instance of the class is present, in one JVM.

  21. What is the difference between an array and a vector? Number of elements in an array are fixed at the construction time, whereas the number of elements in vector can grow dynamically.

  22. What is a constructor? In Java, the class designer can guarantee initialization of every object by providing a special method called a constructor. If a class has a constructor, Java automatically calls that constructor when an object is created, before users can even get their hands on it. So initialization is guaranteed.

  23. What is casting? Conversion of one type of data to another when appropriate. Casting makes explicitly converting of data.

  24. What is the difference between final, finally and finalize? The modifier final is used on class variable and methods to specify certain behaviour explained above. And finally is used as one of the loop in the try catch blocks, It is used to hold code that needs to be executed whether or not the exception occurs in the try catch block. Java provides a method called finalize( ) that can be defined in the class. When the garbage collector is ready to release the storage ed for your object, it will first call finalize( ), and only on the next garbage-collection pass will it reclaim the objects memory. So finalize( ), gives you the ability to perform some important cleanup at the time of garbage collection.

  25. What is are packages? A package is a collection of related classes and interfaces providing access protection and namespace management.

  26. What is a super class and how can you call a super class? When a class is extended that is derived from another class there is a relationship is created, the parent class is referred to as the super class by the derived class that is the child. The derived class can make a call to the super class using the keyword super. If used in the constructor of the derived class it has to be the first statement.

  27. What is meant by a Thread? Thread is defined as an instantiated parallel process of a given program.

  28. What is multi-threading? Multi-threading as the name suggest is the scenario where more than one threads are running.

  29. What are two ways of creating a thread? Which is the best way and why? Two ways of creating threads are, one can extend from the Java.lang.Thread and can implement the rum method or the run method of a different class can be called which implements the interface Runnable, and the then implement the run() method. The latter one is mostly used as first due to Java rule of only one class inheritance, with implementing the Runnable interface that problem is sorted out.

  30. What is deadlock? Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread waiting for a resource which is held by the other waiting thread. In Java, this resource is usually the object lock obtained by the synchronized keyword.

  31. What are the three types of priority? MAX_PRIORITY which is 10, MIN_PRIORITY which is 1, NORM_PRIORITY which is 5.

  32. What is the use of synchronizations? Every object has a lock, when a synchronized keyword is used on a piece of code the, lock must be obtained by the thread first to execute that code, other threads will not be allowed to execute that piece of code till this lock is released.

Java networking and algoritms interview questions
  1. What is the protocol used by server and client ?

  2. Can I modify an object in CORBA ?

  3. What is the functionality stubs and skeletons ?

  4. What is the mapping mechanism used by Java to identify IDL language ?

  5. Diff between Application and Applet ?

  6. What is serializable Interface ?

  7. What is the difference between CGI and Servlet ?

  8. What is the use of Interface ?

  9. Why Java is not fully objective oriented ?

  10. Why does not support multiple Inheritance ?

  11. What it the root class for all Java classes ?

  12. What is polymorphism ?

  13. 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 ?

  14. 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?

  15. What are virtual functions ?

  16. Write down how will you create a binary Tree ?

  17. What are the traverses in Binary Tree ?

  18. Write a program for recursive Traverse ?

  19. What are session variable in Servlets ?

  20. What is client server computing ?

  21. What is Constructor and Virtual function? Can we call Virtual function in a constructor ?

  22. Why we use OOPS concepts? What is its advantage ?

  23. What is the middleware ? What is the functionality of Webserver ?

  24. Why Java is not 100 % pure OOPS ? ( EcomServer )

  25. When we will use an Interface and Abstract class ?

  26. What is an RMI?

  27. How will you pass parameters in RMI ? Why u serialize?

  28. What is the exact difference in between Unicast and Multicast object ? Where we will use ?

  29. What is the main functionality of the Remote Reference Layer ?

  30. How do you download stubs from a Remote place ?

  31. What is the difference in between C++ and Java ? can u explain in detail ?

  32. I want to store more than 10 objects in a remote server ? Which methodology will follow ?

  33. What is the main functionality of the Prepared Statement ?

  34. What is meant by static query and dynamic query ?

  35. What are the Normalization Rules ? Define the Normalization ?

  36. What is meant by Servlet? What are the parameters of the service method ?

  37. What is meant by Session ? Tell me something about HTTPSession Class ?

  38. How do you invoke a Servlet? 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. Have you used threads in Servlet ?

  41. Write a program on RMI and JDBC using StoredProcedure ?

  42. How do you sing an Applet ?

  43. In a Container there are 5 components. I want to display the all the components names, how will you do that one ?

  44. Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA ?

  45. Tell me the latest versions in JAVA related areas ?

  46. What is meant by class loader ? How many types are there? When will we use them ?

  47. How do you load an Image in a Servlet ?

  48. What is meant by flickering ?

  49. What is meant by distributed Application ? Why we are using that in our applications ?

  50. What is the functionality of the stub ?

  51. Have you used any version control ?

  52. What is the latest version of JDBC ? What are the new features are added in that ?

  53. Explain 2 tier and 3 -tier Architecture ?

  54. What is the role of the webserver ?

  55. How have you done validation of the fields in your project ?

  56. What is the main difficulties that you are faced in your project ?

  57. What is meant by cookies ? Explain ?

Large collection of Java interview questions
  1. What is the difference between an Abstract class and Interface ?

  2. What is user defined exception ?

  3. What do you know about the garbage collector ?

  4. What is the difference between C++ & Java ?

  5. Explain RMI Architecture?

  6. How do you communicate in between Applets & Servlets ?

  7. What is the use of Servlets ?

  8. What is JDBC? How do you connect to the Database ?

  9. In an HTML form I have a Button which makes us to open another page in 15 seconds. How will do you that ?

  10. What is the difference between Process and Threads ?

  11. What is the difference between RMI & Corba ?

  12. What are the services in RMI ?

  13. How will you initialize an Applet ?

  14. What is the order of method invocation in an Applet ?

  15. When is update method called ?

  16. How will you pass values from HTML page to the Servlet ?

  17. Have you ever used HashTable and Dictionary ?

  18. How will you communicate between two Applets ?

  19. What are statements in JAVA ?

  20. What is JAR file ?

  21. What is JNI ?

  22. What is the base class for all swing components ?

  23. What is JFC ?

  24. What is Difference between AWT and Swing ?

  25. Considering notepad/IE or any other thing as process, What will happen if you start notepad or IE 3 times?
    Where 3 processes are started or 3 threads are started ?

  26. How does thread synchronization occurs inside a monitor ?

  27. How will you call an Applet using a Java Script function ?

  28. Is there any tag in HTML to upload and download files ?

  29. Why do you Canvas ?

  30. How can you push data from an Applet to Servlet ?

  31. What are 4 drivers available in JDBC ?

  32. How you can know about drivers and database information ?

  33. If you are truncated using JDBC, How can you know ..that how much data is truncated ?

  34. And What situation , each of the 4 drivers used ?

  35. How will you perform transaction using JDBC ?

  36. In RMI, server object first loaded into the memory and then the stub reference is sent to the client ? or whether a stub reference is directly sent to the client ?

  37. Suppose server object is not loaded into the memory, and the client request for it , what will happen?

  38. What is serialization ?

  39. Can you load the server object dynamically? If so, what are the major 3 steps involved in it ?

  40. What is difference RMI registry and OSAgent ?

  41. To a server method, the client wants to send a value 20, with this value exceeds to 20,. a message should be sent to the client ? What will you do for achieving for this ?

  42. What are the benefits of Swing over AWT ?

  43. Where the CardLayout is used ?

  44. What is the Layout for ToolBar ?

  45. What is the difference between Grid and GridbagLayout ?

  46. How will you add panel to a Frame ?

  47. What is the corresponding Layout for Card in Swing ?

  48. What is light weight component ?

  49. Can you run the product development on all operating systems ?

  50. What is the webserver used for running the Servlets ?

  51. What is Servlet API used for connecting database ?

  52. What is bean ? Where it can be used ?

  53. What is difference in between Java Class and Bean ?

  54. Can we send object using Sockets ?

  55. What is the RMI and Socket ?

  56. How to communicate 2 threads each other ?

  57. What are the files generated after using IDL to Java Compilet ?

Java Swing interview questions

1) Can a class be it’s own event handler? Explain how to implement this.

Answer: Sure. an example could be a class that extends Jbutton and implements ActionListener. In the actionPerformed method, put the code to perform when the button is pressed.

2) Why does JComponent have add() and remove() methods but Component does not?
Answer: because JComponent is a subclass of Container, and can contain other components and jcomponents.

3) How would you create a button with rounded edges?
Answer: there’s 2 ways. The first thing is to know that a JButton’s edges are drawn by a Border. so you can override the Button’s paintComponent(Graphics) method and draw a circle or rounded rectangle (whatever), and turn off the border. Or you can create a custom border that draws a circle or rounded rectangle around any component and set the button’s border to it.

4) If I wanted to use a SolarisUI for just a JTabbedPane, and the Metal UI for everything else, how would I do that?
Answer: in the UIDefaults table, override the entry for tabbed pane and put in the SolarisUI delegate. (I don’t know it offhand, but I think it’s "com.sun.ui.motiflookandfeel.MotifTabbedPaneUI" - anything simiar is a good answer.)

5) What is the difference between the ‘Font’ and ‘FontMetrics’ class?
Answer: The Font Class is used to render ‘glyphs’ - the characters you see on the screen. FontMetrics encapsulates information about a specific font on a specific Graphics object. (width of the characters, ascent, descent)

6) What class is at the top of the AWT event hierarchy?
Answer: java.awt.AWTEvent. if they say java.awt.Event, they haven’t dealt with swing or AWT in a while.

7) Explain how to render an HTML page using only Swing.
Answer: Use a JEditorPane or JTextPane and set it with an HTMLEditorKit, then load the text into the pane.

8) How would you detect a keypress in a JComboBox?
Answer: This is a trick. most people would say ‘add a KeyListener to the JComboBox’ - but the right answer is ‘add a KeyListener to the JComboBox’s editor component.’

9) Why should the implementation of any Swing callback (like a listener) execute quickly?
A: Because callbacks are invoked by the event dispatch thread which will be blocked processing other events for as long as your method takes to execute.

10) In what context should the value of Swing components be updated directly?
A: Swing components should be updated directly only in the context of callback methods invoked from the event dispatch thread. Any other context is not thread safe?

11) Why would you use SwingUtilities.invokeAndWait or SwingUtilities.invokeLater?
A: I want to update a Swing component but I’m not in a callback. If I want the update to happen immediately (perhaps for a progress bar component) then I’d use invokeAndWait. If I don’t care when the update occurs, I’d use invokeLater.

12) If your UI seems to freeze periodically, what might be a likely reason?
A: A callback implementation like ActionListener.actionPerformed or MouseListener.mouseClicked is taking a long time to execute thereby blocking the event dispatch thread from processing other UI events.

13) Which Swing methods are thread-safe?
A: The only thread-safe methods are repaint(), revalidate(), and invalidate()

14) Why won’t the JVM terminate when I close all the application windows?
A: The AWT event dispatcher thread is not a daemon thread. You must explicitly call System.exit to terminate the JVM.

Java interview questions

Q1: What are the advantages of OOPL?
Ans: Object oriented programming languages directly represent the real life objects. The features of OOPL as inhreitance, polymorphism, encapsulation makes it powerful.

Q2: What do mean by polymorphisum, inheritance, encapsulation?
Ans: Polymorhisum: is a feature of OOPl that at run time depending upon the type of object the appropriate method is called. Inheritance: is a feature of OOPL that represents the "is a" relationship between different objects(classes). Say in real life a manager is a employee. So in OOPL manger class is inherited from the employee class.
Encapsulation: is a feature of OOPL that is used to hide the information.

Q3: What do you mean by static methods?
Ans: By using the static method there is no need creating an object of that class to use that method. We can directly call that method on that class. For example, say class A has static function f(), then we can call f() function as A.f(). There is no need of creating an object of class A.

Q4: What do you mean by virtual methods?
Ans: virtual methods are used to use the polymorhism feature in C++. Say class A is inherited from class B. If we declare say fuction f() as virtual in class B and override the same function in class A then at runtime appropriate method of the class will be called depending upon the type of the object.

Q5: Given two tables Student(SID, Name, Course) and Level(SID, level) write the SQL statement to get the name and SID of the student who are taking course = 3 and at freshman level.
Ans: SELECT Student.name, Student.SID
FROM Student, Level
WHERE Student.SID = Level.SID
AND Level.Level = "freshman"
AND Student.Course = 3;

Q6: What are the disadvantages of using threads?
Ans: DeadLock.

Q7: Write the Java code to declare any constant (say gravitational constant) and to get its value
Ans: Class ABC
static final float GRAVITATIONAL_CONSTANT = 9.8;
public void getConstant()
system.out.println("Gravitational_Constant: " + GRAVITATIONAL_CONSTANT);

Q8: What do you mean by multiple inheritance in C++ ?
Ans: Multiple inheritance is a feature in C++ by which one class can be of different types. Say class teachingAssistant is inherited from two classes say teacher and Student.

Q3: Can you write Java code for declaration of multiple inheritance in Java ?
Ans: Class C extends A implements B

Java and Perl Web programming interview questions
  1. Q1: How can we store the information returned from querying the database? and if it is too big, how does it affect the performance? In Java the return information will be stored in the ResultSet object. Yes, if the ResultSet is getting big, it will slow down the process and the performance as well. We can prevent this situation by give the program a simple but specific query statement.

  2. Q2: What is index table and why we use it? Index table are based on a sorted ordering of the values. Index table provides fast access time when searching.

  3. Q3: In Java why we use exceptions? Java uses exceptions as a way of signaling serious problems when you execute a program. One major benefit of having an error signaled by an exception is that it separates the code that deals with errors from the code that is executed when things are moving along smoothly. Another positive aspect of exceptions is that they provide a way of enforcing a response to particular errors.

  4. Q4: Write a code in Perl that makes a connection to Database.

    use DBI; my $dbh = DBI->connect(’dbi:mysql:test’,'root’,'foo’)||die "Error opening database: $DBI::errstrn"; print"Successful connect to databasen";

    $dbh->disconnect || die "Failed to disconnectn";

  5. Q5: Write a code in Perl that select all data from table Foo?

    use DBI; my ($dbh, $sth, $name, $id); $dbh= DBI->connect(’dbi:mysql:test’,'root’,'foo’) || die "Error opening database: $DBI::errstrn"; $sth= $dbh->prepare("SELECT * from Foo;") || die "Prepare failed: $DBI::errstrn"; $sth->execute() || die "Couldn’t execute query: $DBI::errstrn"; while(( $id, $name) = $sth->fetchrow_array) { print "$name has ID $idn"; } $sth->finish();

    $dbh->disconnect || die "Failed to disconnectn";

Java software engineering interview questions

Question 1: What is the three tier model?
Answer: It is the presentation, logic, backend

Question 2: Why do we have index table in the database?
Answer: Because the index table contain the information of the other tables. It will
be faster if we access the index table to find out what the other contain.

Question 3: Give an example of using JDBC access the database.
Class.forName("register the driver");
Connection con = DriverManager.getConnection("url of db", "username","password");
Statement state = con.createStatement();
state.executeUpdate("create table testing(firstname varchar(20), lastname varchar(20))");
state.executeQuery("insert into testing values(’phu’,'huynh’)");
catch(Exception e)

Question 4: What is the different of an Applet and a Java Application
Answer: The applet doesn’t have the main function

Question 5: How do we pass a reference parameter to a function in Java?
Answer: Even though Java doesn’t accept reference parameter, but we can
pass in the object for the parameter of the function.
For example in C++, we can do this:

void changeValue(int& a)
void main()
int b=2;

however in Java, we cannot do the same thing. So we can pass the
the int value into Integer object, and we pass this object into the
the function. And this function will change the object.

JSP interview questions

Q: What are the most common techniques for reusing functionality in object-oriented systems?
A: The two most common techniques for reusing functionality in object-oriented systems are class inheritance and object composition.
Class inheritance lets you define the implementation of one class in terms of another’s. Reuse by subclassing is often referred to as white-box reuse.
Object composition is an alternative to class inheritance. Here, new functionality is obtained by assembling or composing objects to get more complex functionality. This is known as black-box reuse.

Q: Why would you want to have more than one catch block associated with a single try block in Java?
A: Since there are many things can go wrong to a single executed statement, we should have more than one catch(s) to catch any errors that might occur.

Q: What language is used by a relational model to describe the structure of a database?
A: The Data Definition Language.

Q: What is JSP? Describe its concept.
A: JSP is Java Server Pages. The JavaServer Page concept is to provide an HTML document with the ability to plug in content at selected locations in the document. (This content is then supplied by the Web server along with the rest of the HTML document at the time the document is downloaded).

Q: What does the JSP engine do when presented with a JavaServer Page to process?
A: The JSP engine builds a servlet. The HTML portions of the JavaServer Page become Strings transmitted to print methods of a PrintWriter object. The JSP tag portions result in calls to methods of the appropriate JavaBean class whose output is translated into more calls to a println method to place the result in the HTML document.


Java and networking interview questions

QUESTION: What is a JavaBean? (asked by Lifescan inc)
ANSWER: JavaBeans are reusable software components written in the Java programming language, designed to be manipulated visually by a software develpoment environment, like JBuilder or VisualAge for Java. They are similar to Microsoft’s ActiveX components, but designed to be platform-neutral, running anywhere there is a Java Virtual Machine (JVM).

QUESTION: What are the seven layers(OSI model) of networking? (asked by Caspio.com)
ANSWER: 1.Physical, 2.Data Link, 3.Network, 4.Transport, 5.Session, 6.Presentation and 7.Application Layers.

QUESTION: What are some advantages and disadvantages of Java Sockets? (asked by Arashsoft.com)
Advantages of Java Sockets:

Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications.

Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information.

Disadvantages of Java Sockets:

Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network

Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

Since the data formats and protocols remain application specific, the re-use of socket based implementations is limited.

QUESTION: What is the difference between a NULL pointer and a void pointer? (asked by Lifescan inc)
ANSWER: A NULL pointer is a pointer of any type whose value is zero. A void pointer is a pointer to an object of an unknown type, and is guaranteed to have enough bits to hold a pointer to any object. A void pointer is not guaranteed to have enough bits to point to a function (though in general practice it does).

QUESTION: What is encapsulation technique? (asked by Microsoft)
ANSWER: Hiding data within the class and making it available only through the methods. This technique is used to protect your class against accidental changes to fields, which might leave the class in an inconsistent state.

Advanced enterprise Java interview questions

1) 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.


Advanced Java interview questions

Q:In Java, what is the difference between an Interface and an Abstract class?

A: An Abstract class declares have at least one instance method that is declared abstract which will be implemented by the subclasses. An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior.

Q: Can you have virtual functions in Java? Yes or No. If yes, then what are virtual functions?

A: Yes, Java class functions are virtual by default. Virtual functions are functions of subclasses that can be invoked from a reference to their superclass. In other words, the functions of the actual object are called when a function is invoked on the reference to that object.

Q:Write a function to reverse a linked list p in C++?


Link* reverse_list(Link* p)
if (p == NULL)
return NULL;

Link* h = p;
p = p->next;
h->next = NULL;
while (p != null)
Link* t = p->next;
p->next = h;
h = p;
p = t;

return h;

Q:In C++, what is the usefulness of Virtual destructors?

A:Virtual destructors are neccessary to reclaim memory that were allocated for objects in the class hierarchy. If a pointer to a base class object is deleted, then the compiler guarantees the various subclass destructors are called in reverse order of the object construction chain.

Q:What are mutex and semaphore? What is the difference between them?

A:A mutex is a synchronization object that allows only one process or thread to access a critical code block. A semaphore on the other hand allows one or more processes or threads to access a critial code block. A semaphore is a multiple mutex.


Java Web programming interview questions


What is a Servlet?

Answer: Servlets are modules of Java code that run in a server application (hence the name "Servlets", similar to "Applets" on the client side) to answer client requests.


What advantages does CMOS have over TTL(transitor transitor logic)? (ALCATEL)


  • low power dissipation
  • pulls up to rail
  • easy to interface

How is Java unlike C++? (Asked by Sun)


Some language features of C++ have been removed. String manipulations in Java do not allow for buffer overflows and other typical attacks. OS-specific calls are not advised, but you can still call native methods. Everything is a class in Java. Everything is compiled to Java bytecode, not executable (although that is possible with compiler tools).


What is HTML (Hypertext Markup Language)?


HTML (HyperText Markup Language) is the set of "markup" symbols or tags inserted in a file intended for display on a World Wide Web browser. The markup tells the Web browser how to display a Web page’s words and images for the user.


Define class.

Answer: A class describes a set of properties (primitives and objects) and behaviors (methods).


Basic Java interview questions

1. Why do you prefer Java?

Answer: write once ,run anywhere.

2. Name some of the classes which provide the functionality of collation?

Answer: collator, rulebased collator, collationkey, collationelement iterator.

3. Awt stands for? and what is it?

Answer: AWT stands for Abstract window tool kit. It is a is a package that provides an integrated set of classes to manage user interface components.

4. why a java program can not directly communicate with an ODBC driver?

Answer: Since ODBC API is written in C language and makes use of pointers which Java can not support.

5. Are servlets platform independent? If so Why? Also what is the most common application of servlets?

Answer: Yes, Because they are written in Java. The most common application of servlet is to access database and dynamically construct HTTP response


© Copyright 2004, Yuva Jobs | GauravJain.net | For Sales or Ads On Yuva Jobs.com Contact Gaurav Jain : sapgaurav@yahoo.com