Java Applet Basics and Lifecycle Guide
Java Applet Basics and Lifecycle Guide
Methods Description
String
Returns the value of a parameter defined in an
getParameter(String
applet
ParameterName)
Drawback of Applet
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
The [Link] class 4 life cycle methods and [Link] class provides 1 life
cycle methods for an applet.
[Link] class
For creating any applet [Link] class must be inherited. It provides 4 life cycle
methods of applet.
It is important to understand the order in which the various methods shown in the above image
are called. When an applet begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
Let’s look more closely at these methods.
1. init( ) : The init( ) method is the first method to be called. This is where you should
initialize variables. This method is called only once during the run time of your applet.
2. start( ) : The start( ) method is called after init( ). It is also called to restart an applet
after it has been stopped. Note that init( ) is called once i.e. when the first time an applet
is loaded whereas start( ) is called each time an applet’s HTML document is displayed
onscreen. So, if a user leaves a web page and comes back, the applet resumes execution
at start( ).
3. paint( ) : The paint( ) method is called each time an AWT-based applet’s output must
be redrawn. This situation can occur for several reasons. For example, the window in
which the applet is running may be overwritten by another window and then uncovered.
Or the applet window may be minimized and then restored.
paint( ) is also called when the applet begins execution. Whatever the cause, whenever
the applet must redraw its output, paint( ) is called.
The paint( ) method has one parameter of type Graphics. This parameter will contain
the graphics context, which describes the graphics environment in which the applet is
running. This context is used whenever output to the applet is required.
4. stop( ) : The stop( ) method is called when a web browser leaves the HTML document
containing the applet—when it goes to another page, for example. When stop( ) is
called, the applet is probably running. You should use stop( ) to suspend threads that
don’t need to run when the applet is not visible. You can restart them when start( ) is
called if the user returns to the page.
5. destroy( ) : The destroy( ) method is called when the environment determines that your
applet needs to be removed completely from memory. At this point, you should free up
any resources the applet may be using. The stop( ) method is always called
before destroy( ).
[Link] class
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
To run an Applet
1. By html file.
2. By appletViewer tool (for testing purpose).
To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.
//[Link]
import [Link];
import [Link];
public class First extends Applet{
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer [Link]. Now Html file is not required but
it is for testing purpose only.
//[Link]
import [Link];
import [Link];
public class First extends Applet{
public void paint(Graphics g){
[Link]("welcome to applet",150,150);
}
}
/*
<applet code="[Link]" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac [Link]
c:\>appletviewer [Link]
1. Local Applet
2. Remote Applet
[Link] Applet
Local Applet is written on our own, and then we will embed it into web pages. Local Applet
is developed locally and stored in the local system. A web page doesn't need the get the
information from the internet when it finds the local Applet in the system. It is specified or
defined by the file name or pathname. There are two attributes used in defining an applet, i.e.,
the codebase that specifies the path name and code that defined the name of the file that
contains Applet's code.
<applet
codebase = "tictactoe"
code = "[Link]"
width = 120
height = 120>
</applet>
Let's take an example of Local applet to understand how we can create it and embedded it into
web page.
[Link]
[Link] Applet
<applet
codebase = "[Link]
code = "[Link]"
width = 120
height =120>
</applet>
Difference Between Local Applet and Remote Applet
The following table describes the key differences between Local applet and Remote applet.
There is no need to define the Applet's We need to define the Applet's URL
URL in Local Applet. in Remote Applet.
Java Application is just like a Java program that runs on an underlying operating system with
the support of a virtual machine. It is also known as an application program. The graphical user
interface is not necessary to execute the java applications, it can be run with or without it.
Java Applet is an applet is a Java program that can be embedded into a web page. It runs inside
the web browser and works on the client-side. An applet is embedded in an HTML page using
the APPLET or OBJECT tag and hosted on a web server. Applets are used to make the
website more dynamic and entertaining.
The application program The applet does not require the main()
main ()
requires a main() method for its method for its execution instead init()
method
execution. method is required.
An application program is
An applet program is needed to
Program needed to perform some tasks
perform small tasks or part of them.
directly for the user.
Java socket programming provides facility to share data between different computing devices.
1. Sharing resources
2. Centralize software management
3. Protocol – A network protocol is an organized set of commands that define how data is
transmitted between different devices in the same network. Network protocols are the
reason through which a user can easily communicate with people all over the world and
thus play a critical role in modern digital communications. For Example – TCP, FTP, POP,
etc.
4. MAC Address – MAC address stands for Media Access Control address. It is a bizarre
identifier that is allocated to a NIC (Network Interface Controller/ Card). It contains a 48
bit or 64-bit address, which is combined with the network adapter. MAC address can be in
hexadecimal composition. In simple words, a MAC address is a unique number that is used
to track a device in a network.
5. Socket – A socket is one endpoint of a two-way communication connection between the
two applications running on the network. The socket mechanism presents a method of inter-
process communication (IPC) by setting named contact points between which the
communication occurs. A socket is tied to a port number so that the TCP layer can
recognize the application to which the data is intended to be sent.
Network Protocols
As stated earlier, the [Link] package of the Java programming language includes various
classes and interfaces that provide an easy-to-use means to access network resources. Other
than classes and interfaces, the [Link] package also provides support for the two well-known
network protocols. These are:
1. Transmission Control Protocol (TCP) – TCP or Transmission Control Protocol allows
secure communication between different applications. TCP is a connection-oriented
protocol which means that once a connection is established, data can be transmitted in two
directions. This protocol is typically used over the Internet Protocol. Therefore, TCP is also
referred to as TCP/IP. TCP has built-in methods to examine for errors and ensure the
delivery of data in the order it was sent, making it a complete protocol for transporting
information like still images, data files, and web pages.
The [Link] package of the Java programming language includes various classes that provide
an easy-to-use means to access network resources. The classes covered in the [Link] package
are given as follows –
1. CacheRequest – The CacheRequest class is used in java whenever there is a need to store
resources in ResponseCache. The objects of this class provide an edge for the OutputStream
object to store resource data into the cache.
5. InetAddress – The InetAddress class is used to provide methods to get the IP address of
any hostname. An IP address is expressed by a 32-bit or 128-bit unsigned number.
InetAddress can handle both IPv4 and IPv6 addresses.
7. Socket – The Socket class is used to create socket objects that help the users in
implementing all fundamental socket operations. The users can implement various
networking actions such as sending, reading data, and closing connections. Each Socket
object built using [Link] class has been connected exactly with 1 remote host; for
connecting to another host, a user must create a new socket object.
9. Proxy – A proxy is a changeless object and a kind of tool or method or program or system,
which serves to preserve the data of its users and computers. It behaves like a wall between
computers and internet users. A Proxy Object represents the Proxy settings to be applied
with a connection.
10. URL – The URL class in Java is the entry point to any available sources on the internet. A
Class URL describes a Uniform Resource Locator, which is a signal to a “resource” on the
World Wide Web. A source can denote a simple file or directory, or it can indicate a more
difficult object, such as a query to a database or a search engine.
The [Link] package of the Java programming language includes various interfaces also that
provide an easy-to-use means to access network resources. The interfaces included in
the [Link] package are as follows:
1. CookiePolicy – The CookiePolicy interface in the [Link] package provides the classes
for implementing various networking applications. It decides which cookies should be
accepted and which should be rejected. In CookiePolicy, there are three pre-defined policy
implementations, namely ACCEPT_ALL, ACCEPT_NONE, and
ACCEPT_ORIGINAL_SERVER.
4. SocketOption – The SocketOption interface helps the users to control the behavior of
sockets. Often, it is essential to develop necessary features in Sockets. SocketOptions
allows the user to set various standard options.
[Link] package
TCP/IP sockets are used to implement reliable two-way, persistent, point-to-point streaming
connections between hosts on the Internet. The Java I/O system can use sockets to connect to
other programs on the local system or on other systems on the Internet. It is important to note
that the applet establishes a reverse socket connection to the host on which the applet is loaded.
This restriction exists because it is dangerous for applets loaded through a firewall to access
arbitrary systems. There are two types of TCP sockets in Java.
One for the server and one for the client. The ServerSocket class is designed as a "listener",
waiting for a client to connect before doing anything. So ServerSocket is for servers. The
Socket class is for clients. It is designed to connect to a server socket and initiate a protocol
exchange. This is because client sockets are most commonly used in Java applications. Creating
a Socket object implicitly establishes a connection between the client and server. There is no
method or constructor that explicitly exposes details about setting up this connection.
Socket defines multiple instance methods. For example, a Socket can always check for
associated address and port information using the following methods:
The following program provides a simple socket example. Opens a connection to a "whois"
port (port 43) of the InterNIC server, sends command-line argument to the socket, and prints
the returned data. The InterNIC will try find the argument by the registered Internet domain
name, and then send back the IP address and contact information for that site.
[Link]
1. import [Link].*;
2. import [Link].*;
3. public class WhoisClient {
4. public static void main(String[] args) {
5. // no arguments passed, simply return
6. if ([Link] < 1)
7. return;
8. // initializing domainName with the name passed in the argument
9. String domainName = args[0];
10. // specifying the host name
11. String hostname = "[Link]";
12. int port = 43;
13. try (Socket socket = new Socket(hostname, port)) {
14. // getOutputStream( ) returns the OutputStream
15. // associated with the invoking socket
16. OutputStream output = [Link]();
17. PrintWriter writer = new PrintWriter(output, true);
18. // print the domain name
19. [Link](domainName);
20. // getInputStream( ) returns the InputStream
21. // associated with the invoking socket
22. InputStream input = [Link]();
23. BufferedReader reader = new BufferedReader(new InputStreamReader(input));
24. String line;
25. while ((line = [Link]()) != null) {
26. [Link](line);
27. }
28. }
29. catch (UnknownHostException ex) {
30. [Link]("Server not found: " + [Link]());
31. }
32. catch (IOException ex) {
33. [Link]("I/O error: " + [Link]());
34. }
35. }
36. }
Output:
Here is how the program works. First, the socket is constructed to compile the host name
"[Link]" and the port number 43, which is an online site that handles the port 43 whois
requests. In addition, both input and output streams are opened on the socket. Then, the string
is constructed that contains the name of the web site we want to get information. The response
is read by inputting from the socket, and the results are displayed.
stream-based connections between hosts on the Internet. A socket can be used to connect
Java’s I/O system to other programs that may reside either on the local machine or on any
The creation of a Socket object implicitly establishes a connection between the client
and server. There are no methods or constructors that explicitly expose the details of
establishing that connection. Here are two constructors used to create client sockets:
Socket defines several instance methods. For example, a Socket can be examined at any
time for the address and port information associated with it, by use of the following methods:
You can gain access to the input and output streams associated with a Socket by use of
the getInputStream( ) and getOuptutStream( ) methods, as shown here. Each can throw an
IOException if the socket has been invalidated by a loss of connection. These streams are
used exactly like the I/O streams to send and receive data.
Several other methods are available, including connect( ), which allows you to specify a new
connection; isConnected( ), which returns true if the socket is connected to a server; isBound(
),
which returns true if the socket is bound to an address; and isClosed( ), which returns true
if the socket is closed.
socket, and then prints the data that is returned. InterNIC will try to look up the argument
as a registered Internet domain name, and then send back the IP address and contact
information for that site.
// Demonstrate Sockets.
import [Link].*;
import [Link].*;
class Whois {
int c;
// Create a socket connected to [Link], port 43.
// Send request.
[Link](buf);
[Link]((char) c);
}
[Link]();
}
}
If, for example, you obtained information about [Link], you’d get something similar
to the following:
Here is how the program works. First, a Socket is constructed that specifies the host
name "[Link]" and the port number 43. [Link] is the InterNIC web site that
handles whois requests. Port 43 is the whois port. Next, both input and output streams are
opened on the socket. Then, a string is constructed that contains the name of the web site you
want to obtain information about. In this case, if no web site is specified on the command
line, then "[Link]" is used. The string is converted into a byte array and then sent out of
the socket. The response is read by inputting from the socket, and the results are displayed.