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("");
out.println(title);
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.
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.