Tuesday, June 10, 2008

Question: What is clipping?

Answer: Clipping is the process of confining paint operations to a limited area or shape.

Question: What is a native method?

Answer: A native method is a method that is implemented in a language other than Java.

Question: Can a for statement loop indefinitely?

Answer: Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;

Question: What are order of precedence and associativity, and how are they used?

Answer: 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

Question: When a thread blocks on I/O, what state does it enter?

Answer: A thread enters the waiting state when it blocks on I/O.

Question: To what value is a variable of the String type automatically initialized?

Answer: The default value of an String type is null.

Question: What is the catch or declare rule for method declarations?

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

Question: What is the difference between a MenuItem and a CheckboxMenuItem?

Answer: The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.

Question: What is a task's priority and how is it used in scheduling?

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

Question: What class is the top of the AWT event hierarchy?

Answer: The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy.

Question: When a thread is created and started, what is its initial state?

Answer: A thread is in the ready state after it has been created and started.

Question: Can an anonymous class be declared as implementing an interface and extending a class?

Answer: An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

Question: What is the range of the short type?

Answer: The range of the short type is -(2^15) to 2^15 - 1.

Question: What is the range of the char type?

Answer: The range of the char type is 0 to 2^16 - 1.

Question: In which package are most of the AWT events that support the event-delegation model defined?

Answer: Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package.

Question: What is the immediate superclass of Menu?

Answer: MenuItem

Question: What is the purpose of finalization?

Answer: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

Question: Which class is the immediate superclass of the MenuComponent class.

Answer: Object

Question: What is serialization ?

Answer: Serialization is the process of writing complete state of java object into output stream, that stream can be file or byte array or stream associated with TCP/IP socket.

Question: What does the Serializable interface do ?

Answer: Serializable is a tagging interface; it prescribes no methods. It serves to assign the Serializable data type to the tagged class and to identify the class as one which the developer has designed for persistence. ObjectOutputStream serializes only those objects which implement this interface.

Question: How do I serialize an object to a file ?

Answer: To serialize an object into a stream perform the following actions:

- Open one of the output streams, for exaample FileOutputStream
- Chain it with the ObjectOutputStream - Call the method writeObject() providingg the instance of a Serializable object as an argument.
- Close the streams

Java Code --------- try{ fOut= new FileOutputStream("c:\\emp.ser"); out = new ObjectOutputStream(fOut); out.writeObject(employee); //serializing System.out.println("An employee is serialized into c:\\emp.ser"); } catch(IOException e){ e.printStackTrace(); }

Question: How do I deserilaize an Object?

Answer: To deserialize an object, perform the following steps:

- Open an input stream
- Chain it with the ObjectInputStream - Call the method readObject() and cast tthe returned object to the class that is being deserialized.
- Close the streams

Java Code try{ fIn= new FileInputStream("c:\\emp.ser"); in = new ObjectInputStream(fIn); //de-serializing employee Employee emp = (Employee) in.readObject(); System.out.println("Deserialized " + emp.fName + " " + emp.lName + " from emp.ser "); }catch(IOException e){ e.printStackTrace(); }catch(ClassNotFoundException e){ e.printStackTrace(); }

Question: What is Externalizable Interface ?

Answer : Externalizable interface is a subclass of Serializable. Java provides Externalizable interface that gives you more control over what is being serialized and it can produce smaller object footprint. ( You can serialize whatever field values you want to serialize)

This interface defines 2 methods: readExternal() and writeExternal() and you have to implement these methods in the class that will be serialized. In these methods you'll have to write code that reads/writes only the values of the attributes you are interested in. Programs that perform serialization and deserialization have to write and read these attributes in the same sequence.

Question: Explain garbage collection ?

Answer: Garbage collection is an important part of Java's security strategy. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects from the memory. The name "garbage collection" implies that objects that are no longer needed by the program are "garbage" and can be thrown away. A more accurate and up-to-date metaphor might be "memory recycling." When an object is no longer referenced by the program, the heap space it occupies must be recycled so that the space is available for subsequent new objects. The garbage collector must somehow determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects. In the process of freeing unreferenced objects, the garbage collector must run any finalizers of objects being freed

Question : How you can force the garbage collection ?

Answer : Garbage collection automatic process and can't be forced. We can call garbage collector in Java by calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.

Question : What are the field/method access levels (specifiers) and class access levels ?

Answer: Each field and method has an access level:

  • private: accessible only in this class
  • (package): accessible only in this package
  • protected: accessible only in this package and in all subclasses of this class
  • public: accessible everywhere this class is available

Similarly, each class has one of two possible access levels:

  • (package): class objects can only be declared and manipulated by code in this package
public: class objects can be declared and manipulated by code in any package

Question: What are different types of inner classes ?

Answer: Inner classes nest within other classes. A normal class is a direct member of a package. Inner classes, which became available with Java 1.1, are four types

  • Static member classes
  • Member classes
  • Local classes
  • Anonymous classes

Static member classes - a static member class is a static member of a class. Like any other static method, a static member class has access to all static methods of the parent, or top-level, class.

Member Classes - a member class is also defined as a member of a class. Unlike the static variety, the member class is instance specific and has access to any and all methods and members, even the parent's this reference.

Local Classes - Local Classes declared within a block of code and these classes are visible only within the block.

Anonymous Classes - These type of classes does not have any name and its like a local class

Java Anonymous Class Example public class SomeGUI extends JFrame { ... button member declarations ... protected void buildGUI() { button1 = new JButton(); button2 = new JButton(); ... button1.addActionListener( new java.awt.event.ActionListener() <------ Anonymous Class { public void actionPerformed(java.awt.event.ActionEvent e) { // do something } } );

Question: What are the uses of Serialization?

Answer: In some types of applications you have to write the code to serialize objects, but in many cases serialization is performed behind the scenes by various server-side containers.

These are some of the typical uses of serialization:

  • To persist data for future use.
  • To send data to a remote computer using such client/server Java technologies as RMI or socket programming.
  • To "flatten" an object into array of bytes in memory.
  • To exchange data between applets and servlets.
  • To store user session in Web applications.
  • To activate/passivate enterprise java beans.
  • To send objects between the servers in a cluster.

Question: what is a collection ?

Answer: Collection is a group of objects. java.util package provides important types of collections. There are two fundamental types of collections they are Collection and Map. Collection types hold a group of objects, Eg. Lists and Sets where as Map types hold group of objects as key, value pairs Eg. HashMap and Hashtable.

Question: For concatenation of strings, which method is good, StringBuffer or String ?

Answer: StringBuffer is faster than String for concatenation.

Question: What is Runnable interface ? Are there any other ways to make a java program as multithred java program?

Answer: There are two ways to create new kinds of threads:

- Define a new class that extends the Thread class
- Define a new class that implements the Runnable interface, and pass an object of that class to a Thread's constructor.
- An advantage of the second approach is that the new class can be a subclass of any class, not just of the Thread class.

Here is a very simple example just to illustrate how to use the second approach to creating threads: class myThread implements Runnable { public void run() { System.out.println("I'm running!"); } } public class tstRunnable { public static void main(String[] args) { myThread my1 = new myThread(); myThread my2 = new myThread(); new Thread(my1).start(); new Thread(my2).start(); }

Question: What is the difference between checked and Unchecked Exceptions in Java ?

Answer: All predefined exceptions in Java are either a checked exception or an unchecked exception. Checked exceptions must be caught using try .. catch() block or we should throw the exception using throws clause. If you dont, compilation of program will fail.

Java Exception Hierarchy
+--------+ | Object | +--------+ | | +-----------+ | Throwable | +-----------+ / \ / \ +-------+ +-----------+ | Error | | Exception | +-------+ +-----------+ / | \ / | \ \________/ \______/ \ +------------------+ unchecked checked | RuntimeException | +------------------+ / | | \ \_________________/ unchecked

Question: Explain garbage collection ?

Answer: Garbage collection is an important part of Java's security strategy. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects from the memory. The name "garbage collection" implies that objects that are no longer needed by the program are "garbage" and can be thrown away. A more accurate and up-to-date metaphor might be "memory recycling." When an object is no longer referenced by the program, the heap space it occupies must be recycled so that the space is available for subsequent new objects. The garbage collector must somehow determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects. In the process of freeing unreferenced objects, the garbage collector must run any finalizers of objects being freed.

Question: How you can force the garbage collection ?

Answer: Garbage collection automatic process and can't be forced. We can call garbage collector in Java by calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.

Question: What are the field/method access levels (specifiers) and class access levels ?

Answer: Each field and method has an access level:

  • private: accessible only in this class
  • (package): accessible only in this package
  • protected: accessible only in this package and in all subclasses of this class
  • public: accessible everywhere this class is available

Similarly, each class has one of two possible access levels:

  • (package): class objects can only be declared and manipulated by code in this package
  • public: class objects can be declared and manipulated by code in any package

Question: What are the static fields & static Methods ?

Answer: If a field or method defined as a static, there is only one copy for entire class, rather than one copy for each instance of class. static method cannot accecss non-static field or call non-static method

Example Java Code

static int counter = 0;

A public static field or method can be accessed from outside the class using either the usual notation:

Java-class-object.field-or-method-name

or using the class name instead of the name of the class object:

Java- class-name.field-or-method-name

Question: What are the Final fields & Final Methods ?

Answer: Fields and methods can also be declared final. A final method cannot be overridden in a subclass. A final field is like a constant: once it has been given a value, it cannot be assigned to again.

Java Code

private static final int MAXATTEMPTS = 10;

Question: Describe the wrapper classes in Java ?

Answer: Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes:

Primitive

Wrapper

boolean

java.lang.Boolean

byte

java.lang.Byte

char

java.lang.Character

double

java.lang.Double

float

java.lang.Float

int

java.lang.Integer

long

java.lang.Long

short

java.lang.Short

void

java.lang.Void

Question: When you declare a method as abstract method ?

Answer: When i want child class to implement the behavior of the method.

Question: Can I call a abstract method from a non abstract method ?

Answer: Yes, We can call a abstract method from a Non abstract method in a Java abstract class

Question: What is the difference between an Abstract class and Interface in Java ? or can you explain when you use Abstract classes ?

Answer: Abstract classes let you define some behaviors; they force your subclasses to provide others. These abstract classes will provide the basic funcationality of your applicatoin, child class which inherited this class will provide the funtionality of the abstract methods in abstract class. When base class calls this method, Java calls the method defined by the child class.

  • An Interface can only declare constants and instance methods, but cannot implement default behavior.
  • Interfaces provide a form of multiple inheritance. A class can extend only one other class.
  • Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
  • A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
  • Interfaces are slow as it requires extra indirection to find corresponding method in the actual class. Abstract classes are fast.

Question: What is user-defined exception in java ?

Answer: User-defined expections are the exceptions defined by the application developer which are errors related to specific application. Application Developer can define the user defined exception by inherite the Exception class as shown below. Using this class we can throw new exceptions.

Java Example : public class noFundException extends Exception { } Throw an exception using a throw statement: public class Fund { ... public Object getFunds() throws noFundException { if (Empty()) throw new noFundException(); ... } } User-defined exceptions should usually be checked.

Question: Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?

Answer: Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.

Question: Can an inner class declared inside of a method access local variables of this method?

Answer: It's possible if these variables are final.

Question: What can go wrong if you replace && with & in the following code: String a=null; if (a!=null && a.length()>10) {...}

Answer: A single ampersand here would lead to a NullPointerException.

Question: What's the main difference between a Vector and an ArrayList

Answer: Java Vector class is internally synchronized and ArrayList is not.

Question:
When should the method invokeLater()be used?

Answer: This method is used to ensure that Swing components are updated through the event-dispatching thread.

Question: How can a subclass call a method or a constructor defined in a superclass?

Answer: Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.

For senior-level developers:

Question: What's the difference between a queue and a stack?

Answer: Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule

Question: You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?

Answer: Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.

Question: What comes to mind when you hear about a young generation in Java?

Answer: Garbage collection.

Question: What comes to mind when someone mentions a shallow copy in Java?

Answer: Object cloning.

Question: If you're overriding the method equals() of an object, which other method you might also consider?

Answer: hashCode()

Question: You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use: ArrayList or LinkedList?

Answer: ArrayList

Question: How would you make a copy of an entire Java object with its state?

Answer: Have this class implement Cloneable interface and call its method clone().

Question: How can you minimize the need of garbage collection and make the memory use more effective?

Answer: Use object pooling and weak object references.

Question: There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?

Answer: If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface.

Question: What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?

Answer: You do not need to specify any access level, and Java will use a default package access level .
What are Servlets and how can they help in developing Web Applications?

"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. Servlets can be embedded in many different servers because the servlet API, which you use to write servlet assumes nothing about the server's environment or protocol. Servlets have become most widely used within HTTP servers; many web servers support the Servlet API.


What is the Advantage of using Servlets over CGI programming?

Servlets are only instantiated when the client first accesses the program. That is, the first time any client hits the URL that is used to access the Servlet, the Servlet engine instantiates that object. All subsequent accesses are done to that instance. This keeps the response time of Servlets lower than that of CGI programs, which must be run once per hit. Also, because a Servlet is instantiated only once, all accesses are put through that one object. This helps in maintaining objects like internal Connection Pooling or user session tracking and lots of other features.

Here are a few more of the many applications for Servlets:

1. Allowing collaboration between people. A Servlet can handle multiple requests concurrently, and can synchronize requests. This allows Servlets to support systems such as on-line conferencing.

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


What is the Jakarta Project ?

The goal of the Jakarta Project is to provide commercial-quality server solutions based on the Java Platform that are developed in an open and cooperative fashion. The flagship product, Tomcat, is a world-class implementation of the Java Servlet 2.2 and JavaServer Pages 1.1Specifications. This implementation will be used in the Apache Web Server as well as in other web servers and development tools." (The Apache Software Foundation).


Where can i find a good tutorial and more details on Servlets?

These URL's are a good starting point if you want to know more about Servlets.


How do I connect to a database from my Servlet?Java includes support for databases, using Java Database Connectivity (JDBC). Most modern databases offer JDBC drivers, which allow you to connect any Java application (including Servlets) directly to your database.

If your database vendor does not offer a JDBC driver, and there are no third party drivers available, you may like to use a JDBC bridge. For example, the ODBC-JDBC bridge allows you to connect to any ODBC data source, which many databases support. Also there are four type of Drivers

Type I : JDBC-ODBC bridge
Type II : native-API partly JavaTM technology-enabled driver
Type III : net-protocol fully Java technology-enabled driver
Type IV : native-protocol fully Java technology-enabled driver

For a list of currently available Database drivers, please visit this page http://industry.java.sun.com/products/jdbc/drivers

Creating a new Connection to Database frequently could slow down your application. Most of the projects use a concept called Connection Pooling. Here when the Servlet starts up, in the init method , a pool of connections are created and are stored in memory (Mostly in a Vector). When a transaction with Database is required, then the next free available connection is retrieved from this Vector and used for that purpose. Once it's work is done, it is again put back into Connections Pool, indicating it is available. Today most of the JDBC Drivers support this feature have inbuilt connection pooling mechanisms.

Please Note : If you are creating your own Connection Pooling, it is strongly recommended to close all the open connections in the destroy method. Else there are chances of your data getting corrupted.


How do I get authentication with myServlet?

Many popular Servlet engines offer Servlet authentication and the API has a call HttpServletRequest.getUserName() which is responsible for returning the username of an authenticated user.


What is a Session Object ?

Session Object is used to maintain a user session related information on the Server side. You can store , retrieve and remove information from a Session object according to your program logic. A session object created for each user persists on the server side, either until user closes the browser or user remains idle for the session expiration time, which is configurable on each server.


How to create Session object and use it for storing information ?

This code will get the Session context for the current user and place values of count1 and count2 into MyIdentifier1 and MyIdentifier2 respectively

HttpSession session = req.getSession(true); //Creating a Session instance

session.putValue ("MyIdentifier1",count1); // Storing Value into session Object
session.putValue ("MyIdentifier2", count2);

session.getValue(MyIdentifier1); // Prints value of Count

session.removeValue(MyIdentifier1); // Removing Valuefrom Session Object


What is the Max amount of information that canbe 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.


What are Cookies and how to use them?

A cookie is a bit of information sent by the Web server that can later be read back from the browser. Limitations for cookies are, browsers are only required to accept 20 cookies per site, 300 total per user , and they can limit each cookie's size to 4096 bytes (4K).

Cookie cookie = new Cookie("userId", "28764"); //Creating new Cookie

response.addCookie (cookie); // sending cookie to the browser

// Printing out all Cookies


Cookie[] cookies = request.getCookies();

if (cookies != null)
{
for (int i=0; i< cookies.length; i++)
{
String name = cookies[i].getName();
String value = cookies[i].getValue();
}
}

Note : If you want to save special characters like "=", or spaces, in the value of the cookie, then makesure you URL encode the value of the cookie , before creating a cookie. Please refer to FAQ on URLEncode and Decoding.


How to confirm that user's browser accepted the Cookie ?

There's no direct API to directly verify that user's browser accepted the cookie. But the quick alternative would be, after sending the required data tothe users browser, redirect the response to a different Servlet which would try to read back the cookie. If this Servlet is able to read back the cookie, then it was successfully saved, else user had disabled the option to accept cookies.


How can i delete or set max duration for which Cookie exists?

You can set the maximum age of a cookie with the cookie.setMaxAge(int seconds) method: Here are different options to this method,

  • Zero means to delete the cookie
  • A positive value is the maximum number of seconds the cookie will live, before it expires
  • A negative value means the cookie will not be stored beyond this browser session (deleted on browser close)

Here is a sample code to delete cookie.

private void deleteCookie(String cookieName)
{
Cookie[] cookies =request.getCookies();

if (cookies != null)
{
for (int i=0; i lt cookies.length; i++)
{
if (cookies[i].getName().equals(cookieName));
cookies[i].setMaxAge(0);
}
}
}


What are the Servlets Equivalents of CGI for commonly requested variables?
SERVER_NAME         request.getServerName();

SERVER_SOFTWARE request.getServletContext().getServerInfo();
SERVER_PROTOCOL request.getProtocol();
SERVER_PORT request.getServerPort()
REQUEST_METHOD request.getMethod()
PATH_INFO request.getPathInfo()
PATH_TRANSLATED request.getPathTranslated()
SCRIPT_NAME request.getServletPath()
DOCUMENT_ROOT request.getRealPath("/")
QUERY_STRING request.getQueryString()
REMOTE_HOST request.getRemoteHost()
REMOTE_ADDR request.getRemoteAddr()
AUTH_TYPE request.getAuthType()
REMOTE_USER request.getRemoteUser()
CONTENT_TYPE request.getContentType()
CONTENT_LENGTH request.getContentLength()
HTTP_ACCEPT request.getHeader("Accept")
HTTP_USER_AGENT request.getHeader("User-Agent")
HTTP_REFERER request.getHeader("Referer")

For more details on these variables please referto this URL http://hoohoo.ncsa.uiuc.edu/cgi/env.html


How can get the entire URL of the current Servlet ?The following code fragment will return the entire URL of the current Servlet

String currentFile = request.getRequestURI();
if (request.getQueryString() != null)
{
currentFile = currentFile + '?' + request.getQueryString();
}

URL currentURL = new URL(request.getScheme(),
request.getServerName(), request.getServerPort(), currentFile);

out.println(URL.toString());


What are different methods in HttpServlet ? Also what are advantages of Get and POST methods?

There are two main methods by which data can be sent to Servlets. They are GET and POST. Here is the over view of sample Servlet and the methods youshould be over riding.

public abstract synchronized class HttpServlet extendsGenericServlet implements Serializable
{
protected void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// If from the Form, the data is submitted using GET method then this method
// is called. Also by default when this Servlet is called from Browser then this
// method is called.
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// If from the Form, the data is submitted using PUT method then this method is called
}

protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// If you must respond to requestsmade by a client that is not using the
// HTTP protocol, you must use service(). You normally should never need
// to override this method, except in special cases.
}
}

If you want to support doPost and doGet from same servlet, then in either doPost or doGet method, which ever is getting called, call the other method using doGet(request, response) or doPost(request,response)

For security reasons if the data being submitted is sensitive, then it's always preferred to use POST method so that the elements don't shown up in URL. When submitted using GET, then all the elements get appended to the URL. If user clicks on a third party click and if that server is logging the Referrer, then the entire URL is saved, which will also have sensitive information.

Also there are limitations of amount of data that can be sent through GET method. Some Operating Systems have a limitation on the Max Length of the URL, which is normally 255 characters. If sending through GET method, then the total length of the target Servlet name and all parameters dataneed to be less than 255 characters.


How do I send email from my Servlet?

You have two options. The first is to write or find a Simple Mail Transfer Protocol (SMTP) implementation in Java. The second is to use the JavaMail API. You can Download the JavaMail from this site at http://java.sun.com/products/javamail


How do I pass arguments to the Servlets?

Arguments to the servlets can be passed at two levels.

  • When a client is invoking the servlet, the client can pass the arguments as part of a URL in form of name/value pairs in the query string portion of the URL. If a tag is used in the html language to invoke the servlet, the arguments can be passed through the param name construct:



  • The server administrator/web-master can pass arguments to the servlet at loading/intialization time by specifying the arguments as part of the server configuration. For Tomcat and JSWDK, edit the conf/web.xml file.

    The required argument (parameter1 in this example ) can be retrieved this way, getServletContext().getAttribute( "paramater1")

How can i set Class Path for my Servlets ?

For developing servlets, just make sure that the JAR filecontaining javax.servlet.* is in your CLASSPATH, and use your normal development tools


Can you provide a sample Servlet ?

Here's the sample implementation of a Servlet to print "Welcome to the World of Servlets." on to the browser

class HelloServlet extends HttpServlet
{
/**
* Handle the HTTP GET method bybuilding a simple web page.
*/

public void doGet (HttpServletRequestrequest, HttpServletResponse response) throws
ServletException,IOException
{
PrintWriterout;

String title= "Hello Servlet";

//set content type and other response header fields first
response.setContentType("text/html");

// then write the data of the response
out =response.getWriter();
out.println(""); <br /> out.println(title); <br /> out.println("");
out.println("

"+ title + "

");
out.println("

Welcometo the World of Servlets.");
out.println("");
out.close();
}
}


How do I get the name of the currently executing script?

Use req.getRequestURI() or req.getServletPath(). The former returns the path to the script including any extra path information following the name of the servlet; the latter strips the extra path info. For example:

URL http://www.javasoft.com/servlets/HelloServlet/jdata/userinfo?pagetype=s3&pagenum=4
getRequestURI servlets/HelloServlet/jdata/userinfo
getServletPath servlets/HelloServlet/
getPathInfo /jdata/userinfo
getQueryString pagetype=s3&pagenum=4

Can you provide me with a List of ISP's who support Servlets ?

Here is the list of all ISP's who supportServlets , http://www.servlets.com/isps/servlet/ISPViewAll


What is URL Encoding and URL Decoding ?

URL encoding is the method of replacing all the spaces and other extra characters into their corresponding Hex Characters and Decoding is the reverse process converting all Hex Characters back their normal form.

For Example consider this URL, /ServletsDirectory/Hello'servlet/

When Encoded using URLEncoder.encode("/ServletsDirectory/Hello'servlet/") the output is

http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2F


This can be decoded back using

URLDecoder.decode("http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2F")


What are Good Ways of Debugging a Servlet ? Are are IDE's which support Servlet Debugging ?

There are couple of Methods. Firstly servers like JRun and others provide separate logs where all your Print requests will print their data into. For example requests to System.out. and System.err go to different log files. If this features is not available or you want to maintain logs separately for each module then you can create a static class called "LogWriter" and call the method inside the try catch loop. The print method in Log Writer will be writing to a custom defined Log File.

try
{ ....
}
catch(Exception exp)
{
LogWriter.print("Debug : The following error occurred at function .... ')
}

Also Inprise JBuilder supports Servlet Debugging. Please refer to JBuilder documentation for details.

Just as a Cautionary note, from your Servlets, never call System.exit(0). The results might be unpredictable. Might close down the entire Server. The Best way is to catch the Exception and either send resultant Error Page to the Browser or Write to a Log file and inform user about the Error.


If i put a Servlet on each servers, and there is a static variable in thisServlet. Do all the instances on these servers share the same static variable? If not, how can I share data among these instances?

No you can't , because on every server there is a different VM running and a static variable is shared only between class instances in the same VM.


How can i create Images Directly on fly and send them to browser, also at run time if i want to write text on top of a image ,how to do it ? You can get the latest image generator package from http://www.acme.com
How can i upload File using a Servlet?

You can show a Browse and Upload Form buttonusing the following code.

multipart/form-data" method=post action="/utils/FileUploadServlet">


It's easy to use a readily available class, which you can easily embed into your servlet for uploading the file. Download the most widely used File Upload package written by Jason Hunter at this URL http://www.servlets.com/cos/


How can i prevent Browser from Caching the Page content ?

Before sending the data to the browser, write thefollowing statements,

response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);

This also helps in case, when user should not beable to see previous pages by clicking the Back button in the browser. (Whenvery sensitive information is being displayed and someone else comes back tomachine and tries to see what data was entered)


How can i reduce the number of writes to Client from Servlet ?

It is always recommended to use StringBuffer instead of String even for Concatenating a group of Strings. Avoid writing every small string to client. Instead store all the strings into a StringBuffer and after sufficient data is available, send this data to Browser.

Here is some sample code,

PrintWriter out =res.getWriter();
StringBuffer sb = new StringBuffer();

//concatenate all text to StringBuffer
sb.append("............. ")

res.setContentLength(sb.length());
out.print(sb);


Can you compare the Performance of Servlets, JSP and Perl Pages ?

Servlets will be faster than Perl CGI ,because the Perl executable needs to launch as a separate process, then Perl needs to initialize itself, then load in the script, then compile the script, and finally execute the script. Here are some Benchmarks for running Servlets and Perl under similar conditions http://www.caucho.com/articles/benchmark.xtp


How can i call another Servlet or JSP from the current Servlet ?

One of the previous methods for calling another servlet was

HelloServlet hello = (HelloServlet)getServletConfig().getServletContext().getServlet("hello");

From Servlet API version 2.1, this method has been deprecated and the preferred method is to use RequestDispatcher. Here is the syntax for it,

getServletContext().getRequestDispatcher("/jsp/hello/hello.jsp").forward(req, res);


How can i write Data submitted from a Applet into a different file , then show users this data on a new page ?

This is one of the most frequently used techniques. From your applet create a URL connection the Servlet and send the data using DataOutputStream. Next in the Service method of Servlet, using PrintWriter, create a new File. On the other end Applet will be waiting for response from Servlet, using DataInputStream. Pass the newly created filename to the Applet. Next From applet call ShowDocument() method with new URL.

Here is some sample code,

URL ticketservlet = new URL( "http://jcom.com/servlet/Ticketservlet ");
URLConnection servletConnection = ticketservlet.openConnection();

// inform the connection that we will send output and accept input
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);

// Don't use a cached version of URL connection.
servletConnection.setUseCaches (false);
servletConnection.setDefaultUseCaches (false);

// Specify the content type that we will send binary data
servletConnection.setRequestProperty ("Content-Type", "application/octet-stream");

// send the student object to the servlet using serialization
ObjectOutputStream ticketOutputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());

// serialize the object , and sending it to servlet , ticketData should implement Serializable interface.
ticketOutputToServlet .writeObject(ticketData);
ticketOutputToServlet .flush();
ticketOutputToServlet .close();

//reading back data from servlet
ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
Vector resultantData = (Vector) inputFromServlet.readObject();
String filename = (String) resultantData.elementAt(0)

//Showing the newly created page from Applet
getAppletContext().showDocument(new URL("http://www.jcom.com/profiles/" + filename));


What are Application Servers , Servlet Engines and Web Servers ? How are they different from each other ?

Initially when the Web started, then all it needed was a Server which would receive the requests for HTML pages or images and send them back to browsers. These are called Web Servers. Then came requests for handling high capacity Database Transactions, supporting latest Java Features like Servlets, JSP, EJB etc. These requests are handled by Application Servers. Normally for a Application Server to exists and process client requests, they need to come through Web servers. All the static data like plain HTML pages etc are placed on Web Server. All the Dynamic Content generators like Servlets, EJB are placed on application server.

Servlet Engines are similar to Application servers, except they support only Servlets and JSP.

Here is the Servlet Engines which support Servlets and JSP , http://java.sun.com/products/servlet/industry.html. Also here is a the list of All Web Servers and Application Servers.

Applications servers are just another level above Servlet Engines. Normally all the Application servers support Servlets and JSP. Not all Servlet Engines support other features like EJB etc, which Application Servers support.


What are the Latest Developments to ServletsAPI ?

Please visit this URL. http://java.sun.com/aboutJava/communityprocess/jsr/jsr_053_jspservlet.html


Is there a Mailing List for Servlets related discussions?

Here is the archive of all the Servlets Interest discussions maintained by JavaSoft http://archives.java.sun.com/archives/servlet-interest.html. You can also subscribe to this mailing list from here.


How do i download a binary file from a Servlet or JSP page ?

Use the Normal Anchor Tag from your page. This is the most preferred way and let the browser handle the downloading part. Here is the Simple syntax for it,

DownloadFile From Here

Another way to have Servlet do this would be, provide a link to Servlet, and from the Servlet call this function ,

response.sendRedirect("/downloads/Profiler.zip");


How do i know when user Session has expired or removed?

Define a class, say SessionTimeoutIndicator,which implements javax.servlet.http.HttpSessionBindingListener. Create a SessionTimeoutIndicator object and add it to the user session. When the session is removed, SessionTimeoutIndicator.valueUnbound() will be called by the Servlet engine. You can implement valueUnbound() to do the required operation.


How can i read data from any URL, which can bea binary data or from a Active Server Page ?

Using the Following code, you can download any data. If it connects to either Servlet or ASP page, then the data get's processed if required and the resultant data is read back.

//Connect to any URL, can be to a image, to a static URL like www.yahoo.com or any ASP page.
URL url = new URL("http://www.aspkit.com/jdata/transaction/transact.asp");

URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
BufferedInputStream in = new BufferedInputStream(stream);
FileOutputStream file = new FileOutputStream("result.txt");
BufferedOutputStream out = new BufferedOutputStream(file);

//Reading Data from the above URL
int i; while ((i = in.read()) != -1){
out.write(i);
}


How can i stress test my Servlets ?

You can use one of the following products to stress test your Servlets.


What is Servlet Changing ?

Servlet Chaining is the process of chaining the output of one Servlet to another Servlet.

You need to configure your servlet engine Java Web server, JRun, , JServ ... for this process to work.

For example to configure JRun for servlet chaining,

  • Select the JSE service (JRun servlet engine) to access to the JSE Service Config panel. You have just to define a new mapping rule where you define your chaining servlet.
  • Let's say /servlets/TicketChainServlet for the virtual path and a comma separated list of servlets as CustomerServlet ,TicketServlet.
  • So when you invoke a request like http://javacommerce.com/servlets/chainServlet, internally the servlet CustomerServlet will be invoked first and its results will be piped into the servlet TicketServlet.

The CustomerServlet servlet code should look like:

public class CustomerServletextends HttpServlet {

public void doGet (HttpServletRequest request, HttpServletResponseresponse) {
PrintWriter out =res.getWriter();
rest.setContentType("text/html");
...
out.println("Customer Name : Tom");
}
}

TicketServlet has to do is to open an inputstream to the request object and read the data into a BufferedReader object.

BufferedReader b = newBufferedReader( new InputStreamReader(req.getInputStream() ) );
String data = b.readLine();
b.close();

Here in data variable you would get "CustomerName : Tom"

Note : Not many Servlet Engines support ServletChaining. Also it has been removed from the standard specifications for Servlets.


How can i make sure User had logged in when accessing Secure Pages ?

At the beginning of each page , place this small code, or include it in a common file

HttpSession session =request.getSession(true);
if (session.getValue("username") == null) {

response.sendRedirect (response.encodeRedirectUrl("LoginPage.jsp?currentURL=productdata.jsp"));
}
else
{
// Go ahead and show the page
}

In LoginPage.jsp once the user has provided the correct logon credentials:

session.putValue("username",currentuser);
response.sendRedirect(response.encodeRedirectUrl(request.getParameter("currentURL")));


Why am i not seeing the most recent updates made to the servlet, from my browser even though i am clicking on Refresh button and removed all the cache from the browser?

This is actually one of the features of Servlet. The first time when the Servlet is invoked, then the init() method is called. So once the Servlet is loaded into memory, it will stay there until the server is restarted. According to specs, the Servlet should reload itself when there is a change in the code or new class is created. But because of performance reasons, most of the Servers don't check for this option and the Same old Servlet is used which is currently in memory for all requests. In JRun, you need to click on the restart button. Any other solutions to this one are welcome. Tomcat requires you to just replace the WAR file.


How can i limit the number of Simultaneous connections to the same Servlet?

This option is configurable on the Server. For example JRun allows you to setup the number of maximum concurrent connections from Admin option.


What is Server Side Push and how is it implemented and when is it useful ?

Server Side push is useful when data needs to change regularly on the clients application or browser , without intervention from client. Standard examples might include apps like Stock's Tracker, Current News etc. As such server cannot connect to client's application automatically. The mechanism used is, when client first connects to Server, (Either through login etc..), then Server keeps the TCP/IP connection open.

It's not always possible or feasible to keep the connection to Server open. So another method used is, to use the standard HTTP protocols ways of refreshing the page, which is normally supported by all browsers.

This will refresh the page in the browser automatically and loads the new data every 5 seconds.


What Servlet engines support sharing of session data across multiple load-balanced web servers, also referred to as Clustering?

The following servers support Clustering,


What is the difference between Multiple Instances of Browser and Multiple Windows. How does this affect Sessions ?

From the current Browser window, if we open a new Window, then it referred to as Multiple Windows. Sessions properties are maintained across all these windows, even though they are operating in multiple windows.

Instead, if we open a new Browser, by either double clicking on the Browser Shortcut icon or shortcut link, then we are creating a new Instance of the Browser. This is referred to as Multiple Instances of Browser. Here each Browser window is considered as different client. So Sessions are not maintained across these windows.



Question: How could Java classes direct program messages to the system console, but error messages, say to a file?

Answer: The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:

Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);

Question: What's the difference between an interface and an abstract class?

Answer: An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.

Question: Why would you use a synchronized block vs. synchronized method?

Answer: Synchronized blocks place locks for shorter periods than synchronized methods.

Question: Explain the usage of the keyword transient?

Answer: This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

Question: How can you force garbage collection?

Answer: You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.


Question: How do you know if an explicit object casting is needed?

Answer: If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:

Object a; Customer b; b = (Customer) a;

When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.

Question: What's the difference between the methods sleep() and wait()

Answer: The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

Question: Can you write a Java class that could be used both as an applet as well as an application?

Answer: Yes. Add a main() method to the applet.

Question: What's the difference between constructors and other methods?

Answer: Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

Question: Can you call one constructor from another if a class has multiple constructors

Answer: Yes. Use this() syntax.

Question: Explain the usage of Java packages.

Answer: This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

Question: If a class is located in a package, what do you need to change in the OS environment to be able to use it?

Answer: You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:

c:\>java com.xyz.hr.Employee

Question: What's the difference between J2SDK 1.5 and J2SDK 5.0?

Answer: There's no difference, Sun Microsystems just re-branded this version.

Question: What would you use to compare two String variables - the operator == or the method equals()?

Answer: I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.