You are on page 1of 23

Assignment: MBA – SEM IV

Subject Code: MI0032

Java and Web Design

Set II
Q.1 What are various parameters of an applet tag.

Answer: The Applet tag is used to embed an applet in an HTML document; the Applet tag takes zero
or more parameters.

The Applet Tag

The Applet tag is written the Body tag of an HTML document.

Syntax

<APPLET

CODE = “name of the class file that extends java.applet.Applet”

CODEBASE = “path of the class file “

HEIGHT = “maximum height of the applet, in pixels “

WIDTH = “maximum width of the applet, in pixels “

VSPACE = “vertical space between the applet and the rest of the HTML “

HSPACE = “horizontal space between the applet and the rest of the HTML “

ALIGN = “alignment of the applet with respect to the rest of the web page “

ALT = “alternate text to be displayed if the browser does not support applets “

>

<PARAM NAME=”parameter_name” value=”value_of_parameter”>

……..

</APPLET>

The most commonly used attributes of the Applet tag are CODE, HEIGHT, WIDTH, CODEBASE and
ALT. You can send parameters to the applet using the PARAM tag. The PARAM tag must be written
between <APPLET> and </APPLET>

Example:

<Applet

Code = “clock. class”

Height = 200

Width = 200 >


</applet>

Life Cycle of an Applet

You can describe the life cycle of an applet through four methods. These methods are:

 The init () method.


 The start () method.

 The stop () method.

 The destroy () method.

The init ( ) method

The init () method is called the first time an applet is loaded into the memory of a computer. You can
initialize variables, and add components like buttons and check boxes to the applet in the init ()
method.

The start ( ) method

The start () method is called immediately after the init () method and every time the applet receives
focus as a result of scrolling in the active window. You can use this method when you want to restart
a process, such as thread animation, every time the applet receives the focus.

The stop ( ) method

The stop () method is called every time the applet loses the focus. You can use this method to reset
variables and stop the threads that are running.

The destroy ( ) method

The destroy ( ) method is called by the browser when the user moves to another page. You can use
this method to perform clean-up operations like closing a file.

The following diagram depicts the life cycle of an applet.

It is not mandatory to use any or all the methods of the applet. These methods are called
automatically by the Java environment, and hence, must be declared public. None of the methods
accept parameters. For example,
public void init ()

All but the most trivial applets override a set of methods that provides the basic mechanism by
which the browser or applet viewer interfaces to the applet and controls its execution. Four of these
methods–init( ), start( ), stop( ), and destroy( ) – are defined by Applet. Another, paint( ), is defined
by the AWT Component class. Default implementations for all of these methods are provided.
Applets do not need to override those methods they do not use. However, only very simple applets
will not need to define all of them. These five methods can be assembled into the skeleton shown
here:

// An Applet skeleton.

import java.awt.*;

import java.applet.*;

/*

<applet code="AppletSkel" width=300 height=100>

</applet>

*/

public class AppletSkel extends Applet {

// Called first.

public void init() {

// initialization

/* Called second, after init(). Also called whenever

the applet is restarted. */

public void start() {

// start or resume execution


}

// Called when the applet is stopped.

public void stop() {

// suspends execution

/* Called when applet is terminated. This is the last

method executed. */

public void destroy() {

// perform shutdown activities

Q.2 Write a short note on following topic:

a. Knock Knock Protocol

b. Datagram

Answer: A

The KnockKnockProtocol class implements the protocol that the client and server use to
communicate. This class keeps track of where the client and the server are in their conversation and
serves up the server's response to the client's statements. The KnockKnockServer object contains
the text of all the jokes and makes sure that the client gives the proper response to the server's
statements. It wouldn't do to have the client say "Dexter who?" when the server says "Knock!
Knock!"

All client/server pairs must have some protocol by which they speak to each other; otherwise, the
data that passes back and forth would be meaningless. The protocol that your own clients and
servers use depends entirely on the communication required by them to accomplish the task.

Answer: B

Clients and servers that communicate via a reliable channel, such as a TCP socket, have a dedicated
point-to-point channel between themselves, or at least the illusion of one. To communicate, they
establish a connection, transmit the data, and then close the connection. All data sent over the
channel is received in the same order in which it was sent. This is guaranteed by the channel.

In contrast, applications that communicate via datagrams send and receive completely independent
packets of information. These clients and servers do not have and do not need a dedicated point-to-
point channel. The delivery of datagrams to their destinations is not guaranteed. Nor is the order of
their arrival.
Definition:  A datagram is an independent, self-contained message sent over the network whose
arrival, arrival time, and content are not guaranteed.

The java.net package contains three classes to help you write Java programs that use datagrams to
send and receive packets over the network: DatagramSocket, DatagramPacket, and
MulticastSocketAn application can send and receive DatagramPackets through a DatagramSocket. In
addition, DatagramPackets can be broadcast to multiple recipients all listening to a MulticastSocket.

Writing a Datagram Client and Server

The example featured in this section consists of two applications: a client and a server. The server
continuously receives datagram packets over a datagram socket. Each datagram packet received by
the server indicates a client request for a quotation. When the server receives a datagram, it replies
by sending a datagram packet that contains a one-line "quote of the moment" back to the client.

The client application in this example is fairly simple. It sends a single datagram packet to the server
indicating that the client would like to receive a quote of the moment. The client then waits for the
server to send a datagram packet in response.

Two classes implement the server application: QuoteServer and QuoteServerThread. A single class
implements the client application: QuoteClient.

Let’s investigate these classes, starting with the class that contains the main method for the server
application. Working with a Server-Side Application contains an applet version of the QuoteClient
class.

The QuoteServer Class

The QuoteServer class, shown here in its entirety, contains a single method: the main method for
the quote server application. The main method simply creates a new QuoteServerThread object and
starts it:

import java.io.*;
public class QuoteServer {
    public static void main(String[] args) throws IOException {
        new QuoteServerThread().start();
    }
}

The QuoteServerThread class implements the main logic of the quote server.

The QuoteServerThread Class

When created, the QuoteServerThread creates a DatagramSocket on port 4445 (arbitrarily chosen).
This is the DatagramSocket through which the server communicates with all of its clients.

public QuoteServerThread() throws IOException {


    this("QuoteServer");
}
public QuoteServerThread(String name) throws IOException {
    super(name);
    socket = new DatagramSocket(4445);
 
    try {
        in = new BufferedReader(
                  new FileReader("one-liners.txt"));             
    } catch (FileNotFoundException e)
        System.err.println("Couldn't open quote file. " +
                          "Serving time instead.");
    }

Remember that certain ports are dedicated to well-known services and you cannot use them. If you
specify a port that is in use, the creation of the DatagramSocket will fail.

The constructor also opens a BufferedReader on a file named one-liners.txt which contains a list of
quotes. Each quote in the file is on a line by itself.

Now for the interesting part of the QuoteServerThread: its run method. The run method overrides
run in the Thread class and provides the implementation for the thread. For information about
threads, see Defining and Starting a Thread.

The run method contains a while loop that continues as long as there are more quotes in the file.
During each iteration of the loop, the thread waits for a DatagramPacket to arrive over the
DatagramSocket. The packet indicates a request from a client. In response to the client’s request,
the QuoteServerThread gets a quote from the file, puts it in a DatagramPacket and sends it over the
DatagramSocket to the client that asked for it.

Let’s look first at the section that receives the requests from clients:

byte[] buf = new byte[256];


DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);

The first statement creates an array of bytes which is then used to create a DatagramPacket. The
DatagramPacket will be used to receive a datagram from the socket because of the constructor used
to create it. This constructor requires only two arguments: a byte array that contains client-specific
data and the length of the byte array. When constructing a DatagramPacket to send over the
DatagramSocket, you also must supply the Internet address and port number of the packet’s
destination. You’ll see this later when we discuss how the server responds to a client request.

The last statement in the previous code snippet receives a datagram from the socket (the
information received from the client gets copied into the packet). The receive method waits forever
until a packet is received. If no packet is received, the server makes no further progress and just
waits.

Now assume that, the server has received a request from a client for a quote. Now the server must
respond. This section of code in the run method constructs the response:

String dString = null;


if (in == null)
    dString = new Date().toString();
else
    dString = getNextQuote();
buf = dString.getBytes();

If the quote file did not get opened for some reason, then in equals null. If this is the case, the quote
server serves up the time of day instead. Otherwise, the quote server gets the next quote from the
already opened file. Finally, the code converts the string to an array of bytes.

Now, the run method sends the response to the client over the DatagramSocket with this code:

InetAddress address = packet.getAddress();


int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);

The first two statements in this code segment get the Internet address and the port number,
respectively, from the datagram packet received from the client. The Internet address and port
number indicate where the datagram packet came from. This is where the server must send its
response. In this example, the byte array of the datagram packet contains no relevant information.
The arrival of the packet itself indicates a request from a client that can be found at the Internet
address and port number indicated in the datagram packet.

The third statement creates a new DatagramPacket object intended for sending a datagram message
over the datagram socket. You can tell that the new DatagramPacket is intended to send data over
the socket because of the constructor used to create it. This constructor requires four arguments.
The first two arguments are the same required by the constructor used to create receiving
datagrams: a byte array containing the message from the sender to the receiver and the length of
this array. The next two arguments are different: an Internet address and a port number. These two
arguments are the complete address of the destination of the datagram packet and must be
supplied by the sender of the datagram. The last line of code sends the DatagramPacket on its way.

When the server has read all the quotes from the quote file, the while loop terminates and the run
method cleans up:

socket.close();

The QuoteClient Class

The QuoteClient class implements a client application for the QuoteServer. This application sends a
request to the QuoteServer, waits for the response, and, when the response is received, displays it
to the standard output. Let’s look at the code in detail.

The QuoteClient class contains one method, the main method for the client application. The top of
the main method declares several local variables for its use:

int port;
InetAddress address;
DatagramSocket socket = null;
DatagramPacket packet;
byte[] sendBuf = new byte[256];
First, the main method processes the command-line arguments used to invoke the QuoteClient
application:

if (args.length != 1) {
     System.out.println("Usage: java QuoteClient <hostname>");
     return;
}

The QuoteClient application requires one command-line arguments: the name of the machine on
which the QuoteServer is running.

Next, the main method creates a DatagramSocket:

DatagramSocket socket = new DatagramSocket();

The client uses a constructor that does not require a port number. This constructor just binds the
DatagramSocket to any available local port. It doesn’t matter what port the client is bound to
because the DatagramPackets contain the addressing information. The server gets the port number
from the DatagramPackets and send its response to that port.

Next, the QuoteClient program sends a request to the server:

byte[ ] buf = new byte[256];


InetAddress address = InetAddress.getByName(args[0]);
DatagramPacket packet = new DatagramPacket(buf, buf.length,
                                           address, 4445);
socket.send(packet);

The code segment gets the Internet address for the host named on the command line (presumably
the name of the machine on which the server is running). This InetAddress and the port number
4445 (the port number that the server used to create its DatagramSocket) are then used to create
DatagramPacket destined for that Internet address and port number. Therefore the DatagramPacket
will be delivered to the quote server.

Note that the code creates a DatagramPacket with an empty byte array. The byte array is empty
because this datagram packet is simply a request to the server for information. All the server needs
to know to send a response–the address and port number to which reply–is automatically part of
the packet.

Next, the client gets a response from the server and displays it:

packet = new DatagramPacket(buf, buf.length);


socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println("Quote of the Moment: " + received);

To get a response from the server, the client creates a "receive" packet and uses the
DatagramSocket receive method to receive the reply from the server. The receive method waits until
a datagram packet destined for the client comes through the socket. Note that if the server’s reply is
somehow lost, the client will wait forever because of the no-guarantee policy of the datagram
model. Normally, a client sets a timer so that it doesn’t wait forever for a reply; if no reply arrives,
the timer goes off and the client retransmits.

When the client receives a reply from the server, the client uses the getData method to retrieve that
data from the packet. The client then converts the data to a string and displays it.

Running the Server and Client

After you’ve successfully compiled the server and the client programs, you run them. You have to
run the server program first. Just use the Java interpreter and specify the QuoteServer class name.

Once the server has started, you can run the client program. Remember to run the client program
with one command-line argument: the name of the host on which the QuoteServer is running.

After the client sends a request and receives a response from the server, you should see output
similar to this:

Quote of the Moment:


Good programming is 99% sweat and 1% coffee.

Q.3 What are the different access specifiers in Java? How can we call a superclass constructor?
Explain with a suitable example.

Answer: An access specifier determines which features of a class (the class itself, the data members,
and the methods) may be used by other classes. Java supports three access specifiers.

 public
 private

 protected

The public Access Specifiers

All classes except inner class (class within classes) can have the public access specifier. You can use a
public class, a data member, or a method from any object in any Java program.

Example

public class publicclass

public int publicvaraible;

public void publicmethod ()

{
}

The private Access Specifier

Only objects of the same class can access a private variable or method. You can declare only
variables, methods, and inner classes as private.

Example

private int privatevariable;

The protected Access Specifier

The variables, methods, and inner classes that are declared protected are accessible to the
subclasses of the class in which they are declared.

Example

protected int protectedvariable;

Default Access

If you do not specify any of the above access specifiers, the scope is friendly. A class, variable, or
method that has friendly access is accessible to all the classes of a package.

Consider the following set of classes. Class Y and Z inherit from class X. Class Z belongs to a package
different than that of classes X and Y

A method accessMe () has been declared in class X. The following table shows you the
accessibility of the method accessMe () from classes Y and Z

Access Specifier Class Y Class Z

accessME ( ) is declared asAccessible, as Y is a subclass Accessible, as Z is a subclass


protected (event if it is in another package)

accessMe ( ) is declaredAccessible, as it is in theNot accessible, as it is not in the


without an accesssame package same package
specifier (friendly)

You can access a non-private variable or method using an object of the class as shown below:

Someclass classobject = new someclass ();

classobject.publicvariable;

classobject.protectedmethod ();

Although a subclass includes all of the members of its superclass, it cannot access those members of
the superclass that have been declared as private. For example, consider the following simple class
hierarchy:

/* In a class hierarchy, private members remain

private to their class.

This program contains an error and will not

compile.

*/

// Create a superclass.

class A {

int i; // public by default

private int j; // private to A

void setij(int x, int y) {

i = x;

j = y;

// A’s j is not accessible here.

class B extends A {

int total;
void sum() {

total = i + j; // ERROR, j is not accessible here

class Access {

public static void main(String args[]) {

B subOb = new B();

subOb.setij(10, 12);

subOb.sum();

System.out.println("Total is " + subOb.total);

This program will not compile because the reference to j inside the sum( ) method of B causes an
access violation. Since j is declared as private, it is only accessible by other members of its own class.
Subclasses have no access to it.

Note: A class member that has been declared as private will remain private to its class. It is not
accessibl e by any code outside its class, including subclasses.

A Superclass Variable Can Reference a Subclass Object

A reference variable of a superclass can be assigned a reference to any subclass derived from that
superclass. You will find this aspect of inheritance quite useful in a variety of situations. For example,
consider the following:

class Ref Demo {

public static void main(String args[]) {

BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);

Box plainbox = new Box();

double vol;

vol = weightbox.volume();

System.out.println("Volume of weightbox is " + vol);


System.out.println("Weight of weightbox is " +

weightbox.weight);

System.out.println();

// assign BoxWeight reference to Box reference

plainbox = weightbox;

vol = plainbox.volume(); // OK, volume() defined in Box

System.out.println("Volume of plainbox is " + vol);

/* The following statement is invalid because plainbox

does not define a weight member. */

// System.out.println("Weight of plainbox is " +

plainbox.weight);

Here, weightbox is a reference to BoxWeight objects, and plainbox is a reference to Box objects.
Since BoxWeight is a subclass of Box, it is permissible to assign plainbox a reference to the
weightbox object.

It is important to understand that it is the type of the reference variable – not the type of the object
that it refers to – that determines what members can be accessed. That is, when a reference to a
subclass object is assigned to a superclass reference variable, you will have access only to those
parts of the object defined by the superclass. This is why plainbox can’t access weight even when it
refers to a BoxWeight object. If you think about it, this makes sense, because the superclass has no
knowledge of what a subclass adds to it. This is why the last line of code in the preceding fragment is
commented out. It is not possible for a Box reference to access the weight field, because it does not
define one.

Although the preceding may seem a bit esoteric, it has some important practical applications – two
of which are discussed later in this chapter.

Using super

In the preceding examples, classes derived from Box were not implemented as efficiently or as
robustly as they could have been. For example, the constructor for BoxWeight explicitly initializes
the width, height, and depth fields of Box( ). Not only does this duplicate code found in its
superclass, which is inefficient, but it implies that a subclass must be granted access to these
members. However, there will be times when you will want to create a superclass that keeps the
details of its implementation to itself (that is, that keeps its data members private). In this case,
there would be no way for a subclass to directly access or initialize these variables on its own. Since
encapsulation is a primary attribute of OOP, it is not surprising that Java provides a solution to this
problem. Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the
keyword super.

super has two general forms. The first calls the superclass’ constructor. The second is used to access
a member of the superclass that has been hidden by a member of a subclass. Each use is examined
here.

Using super to Call Superclass Constructors

A subclass can call a constructor method defined by its superclass by use of the following form of
super:

super(parameter-list);

Here, parameter-list specifies any parameters needed by the constructor in the superclass. super( )
must always be the first statement executed inside a subclass’ constructor. To see how super( ) is
used, consider this improved version of the BoxWeight( ) class:

// BoxWeight now uses super to initialize its Box attributes.

class BoxWeight extends Box {

double weight; // weight of box

// initialize width, height, and depth using super()

BoxWeight(double w, double h, double d, double m) {

super(w, h, d); // call superclass constructor

weight = m;

Here, BoxWeight( ) calls super( ) with the parameters w, h, and d. This causes the Box( ) constructor
to be called, which initializes width, height, and depth using these values. BoxWeight no longer
initializes these values itself. It only needs to initialize the value unique to it: weight. This leaves Box
free to make these values private if desired.

In the preceding example, super( ) was called with three arguments. Since constructors can be
overloaded, super( ) can be called using any form defined by the superclass. The constructor
executed will be the one that matches the arguments. For example, here is a complete
implementation of BoxWeight that provides constructors for the various ways that a box can be
constructed. In each case, super( ) is called using the appropriate arguments. Notice that width,
height, and depth have been made private within Box.

// A complete implementation of BoxWeight.


class Box {

private double width;

private double height;

private double depth;

// construct clone of an object

Box(Box ob) { // pass object to constructor

width = ob.width;

height = ob.height;

depth = ob.depth;

// constructor used when all dimensions specified

Box(double w, double h, double d) {

width = w;

height = h;

depth = d;

// constructor used when no dimensions specified

Box() {

width = -1; // use -1 to indicate

height = -1; // an uninitialized

depth = -1; // box

// constructor used when cube is created

Box(double len) {

width = height = depth = len;


}

// compute and return volume

double volume() {

return width * height * depth;

// BoxWeight now fully implements all constructors.

class BoxWeight extends Box {

double weight; // weight of box

// construct clone of an object

BoxWeight(BoxWeight ob) { // pass object to constructor

super(ob);

weight = ob.weight;

// constructor when all parameters are specified

BoxWeight(double w, double h, double d, double m) {

super(w, h, d); // call superclass constructor

weight = m;

// default constructor

BoxWeight() {

super();

weight = -1;

// constructor used when cube is created


BoxWeight(double len, double m) {

super(len);

weight = m;

class DemoSuper {

public static void main(String args[]) {

BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);

BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);

BoxWeight mybox3 = new BoxWeight(); // default

BoxWeight mycube = new BoxWeight(3, 2);

BoxWeight myclone = new BoxWeight(mybox1);

double vol;

vol = mybox1.volume();

System.out.println("Volume of mybox1 is " + vol);

System.out.println("Weight of mybox1 is " + mybox1.weight);

System.out.println();

vol = mybox2.volume();

System.out.println("Volume of mybox2 is " + vol);

System.out.println("Weight of mybox2 is " + mybox2.weight);

System.out.println();

vol = mybox3.volume();

System.out.println("Volume of mybox3 is " + vol);

System.out.println("Weight of mybox3 is " + mybox3.weight);

System.out.println();
vol = myclone.volume();

System.out.println("Volume of myclone is " + vol);

System.out.println("Weight of myclone is " + myclone.weight);

System.out.println();

vol = mycube.volume();

System.out.println("Volume of mycube is " + vol);

System.out.println("Weight of mycube is " + mycube.weight);

System.out.println();

This program generates the following output:

Volume of mybox1 is 3000.0

Weight of mybox1 is 34.3

Volume of mybox2 is 24.0

Weight of mybox2 is 0.076

Volume of mybox3 is -1.0

Weight of mybox3 is -1.0

Volume of myclone is 3000.0

Weight of myclone is 34.3

Volume of mycube is 27.0

Weight of mycube is 2.0

Pay special attention to this constructor in BoxWeight( ):

// construct clone of an object

BoxWeight(BoxWeight ob) { // pass object to constructor

super(ob);
weight = ob.weight;

Notice that super( ) is called with an object of type BoxWeight – not of type Box. This still invokes
the constructor Box(Box ob). As mentioned earlier, a superclass variable can be used to reference
any object derived from that class. Thus, we are able to pass a BoxWeight object to the Box
constructor. Of course, Box only has knowledge of its own members.

Let’s review the key concepts behind super( ). When a subclass calls super( ), it is calling the
constructor of its immediate superclass. Thus, super( ) always refers to the superclass immediately
above the calling class. This is true even in a multileveled hierarchy. Also, super( ) must always be
the first statement executed inside a subclass constructor.

A Second Use for super

The second form of super acts somewhat like this, except that it always refers to the superclass of
the subclass in which it is used. This usage has the following general form:

super.member

Here, member can be either a method or an instance variable.

This second form of super is most applicable to situations in which member names of a subclass hide
members by the same name in the superclass. Consider this simple class hierarchy:

// Using super to overcome name hiding.

class A {

int i;

// Create a subclass by extending class A.

class B extends A {

int i; // this i hides the i in A

B(int a, int b) {

super.i = a; // i in A

i = b; // i in B

void show() {

System.out.println("i in superclass: " + super.i);


System.out.println("i in subclass: " + i);

class UseSuper {

public static void main(String args[]) {

B subOb = new B(1, 2);

subOb.show();

This program displays the following:

i in superclass: 1

i in subclass: 2

Although the instance variable i in B hides the i in A, super allows access to the i defined in the
superclass. As you will see, super can also be used to call methods that are hidden by a subclass.

(5) The abstract class

An abstract class defines common properties and behaviors of other classes. An abstract class is used
as a base class to derive specific classes of the same kind. It defines properties common to the
classes derived from it. The abstract keyword is used to declare such a class. The classes declared
using the abstract keyword cannot be instantiated.

Syntax

abstract class <class_name>

You can also declare abstract methods. Abstract methods have public scope. The code below
declares an abstract method for the class shape.

abstract class shape

public abstract float calculateArea ();


}

The abstract method calculateArea (), given above, is inherited by the subclasses of the shape class.
The subclasses Rectangle, Circle and Hexagon implement this method in different ways.

public class circle extends shape

float radius;

public float calculateArea ()

return radius*22/7;

In the above example, the calculateArea () method has been overridden in the circle class. If the
method is not overridden, the class will inherit the abstract method from the parent class. Any class
that has a abstract method is abstract. Hence, you would not be able to create an object of the circle
class. Therefore, it is necessary to override the calculateArea () method in the circle class.

The final Keyword

A class called password authenticates user login. You do not want anybody to change the
functionality of the class by extending it. To prevent inheritance, use the final modifier.

Example

final class password

You will also find final classes in JDK package. For example, the java.lang.String class has been
declared final. This is done for security reasons. It ensure that any method that refers to the String
class gets the actual String class and not a modified one.

You might also like