Custom Search

Tuesday, September 4, 2007

Advanced Java interview questions

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++?

A:

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.

 

JSP interview questions

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.

JSP interview questions

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
  1. 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.
  2. What are the different scope values for the <jsp:useBean>? The different scope values for <jsp:useBean> are:
    • page
    • request
    • session
    • application
  3. 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.
  4. 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.
  5. 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.

JDBC interview questions

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:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

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:

Class.forName("jdbc.DriverXYZ");

  1. 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.
  2. 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?);

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

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

  1. What are the different types of Statements?
    Regular statement (use createStatement method), prepared statement (use prepareStatement method) and callable statement (use prepareCall)
  2. 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 ?"); 
  1. 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:

con.setAutoCommit(false);

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

 con.setAutoCommit(false);
PreparedStatement updateSales =
   con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt (1, 50); updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
 PreparedStatement updateTotal =
  con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?"); 
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian"); 
updateTotal.executeUpdate();
con.commit();
 con.setAutoCommit(true);
  1. 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();
  1. 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) 
{
      System.out.println ("n---Warning---n");
      while (warning != null)
       {
        System.out.println("Message: " +  warning.getMessage());
        System.out.println("SQLState: " +  warning.getSQLState());
        System.out.print("Vendor error code: "); 
        System.out.println(warning.getErrorCode());
        System.out.println("");
 warning = warning.getNextWarning();
      }
 }
  1. 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.

  1. 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");
srs.afterLast();
 while (srs.previous())
{
       String name = srs.getString("COF_NAME");
      float price = srs.getFloat("PRICE"); 
      System.out.println(name + " " + price);
 }
  1. 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 =
       DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
Statement stmt =
 con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet uprs =
 stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

Servlet interview questions

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.

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

  1. 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.
  2. Which package provides interfaces and classes for writing servlets? javax
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.

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

  1. 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.
  2. 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.
  3. 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();
    try
   {
      targetURL = new URL(URLString);
   }
    catch (MalformedURLException e)
   {
     // Code for recover from the exception
    }
   context. showDocument (targetURL);
  1. 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.
  2. 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();
  1. 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.
  2. 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.
  3. 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.

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

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.

  1. 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:
 3.                 txtName.setBounds(x,y,width,height);

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.

  1. Which TextComponent method is used to set a TextComponent to the read-only state? - setEditable()
  2. How can the Checkbox class be used to create a radio button? - By associating Checkbox objects with a CheckboxGroup.
  3. What methods are used to get and set the text label displayed by a Button object? - getLabel( ) and setLabel( )
  4. 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.
  5. 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.
  6. 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

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

  1. What are the subclasses of the Container class? - The Container class has three major subclasses. They are:
    • Window
    • Panel
    • ScrollPane
  2. Which object is needed to group Checkboxes to make them exclusive? - CheckboxGroup.
  3. 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.

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

  1. 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).
  2. 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"));
   aWindow.getBounds(50,50,200,200);
    aWindow.show();
  1. Can I create a non-resizable windows? If so, how? - Yes. By using setResizable() method in class Frame.
  2. 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.
  3. 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.

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

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?

J2EE interview questions

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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. What is Applet container? - IManages the execution of applets. Consists of a Web browser and Java Plugin running on the client together.
  11. 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.
  12. 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.
  13. 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.
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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.