You are on page 1of 65

1

DHANALAKSHMI COLLEGE OF
ENGINEERING
CHENNAI

DEPARTMENT OF ELECTRONICS & COMMUNICATION

ENGINEERING

EC2028 INTERNET AND JAVA

ACADEMIC YEAR 2014-2015

QUESTION BANK

PREPARED BY,

Prepared by,
2

DHANALAKSHMI COLLEGE OF ENGINEERING


DEPARTMENT OF ELECTRONICS & COMMUNICATION ENGINEERING
YEAR: IV SEM : VII
PART-B
UNIT-I : INTERNETWORKING WITH TCP / IP

1. Explain why lost TCP acknowledgements do not necessarily force retransmissions. (ND12)(16)

TCP/IP protocol provides facilities to help network managers or users identify network
problems. One of the most frequently used debugging tools invokes the ICMP echo request and
echo reply messages. A host or router sends an ICMP echo request message to a specified
destination. Any machine that receives an echo request formulates an echo reply and returns it to
an original sender. The request contains an operational data area; the reply contains a copy of the
data sent in the request. The echo request and associated can be used to test whether the
destination is reachable and responding.

The command users invoke to send ICMP echo requests is named ping. Sophisticated versions
of ping send a series of ICMP echo request, capture responses, and provide statistics about
datagram loss. They allow the user to specify the length of the data being sent and the interval
between requests. Less sophisticated versions merely send one ICMP echo request and await a
reply.

Transmission Control Protocol: TCP


IP provides a connectionless packet delivery service.
{
Unreliable packet delivery to specific host.
{
UDP adds delivery to multiple ports within a host.
TCP bases a reliable stream delivery service on IP.
{
Delivery to multiple ports within a host (like UDP).
{
Streams
: connections between application programs through which sequences of bytes ow.
{
Reliable
: the sequence of bytes sent is the same as the sequence of bytes received.
Application programming interface (API) to use TCP.
{
Not part of standard: specific to OS/programming lanugage.

Prepared by,
3

Protocol used in most application programs.

2. Give the ARP format and explain how to implement ARP and RARP. (ND12)(16)
ARP and RARP: Address Translation
Though IP packets use IP addresses, hardware addresses must be used to actually transfer data
from one computer to another.

Address Resolution Protocol (ARP) is used to discover what hardware address is associated with
a particular IP address.
o ARP broadcasts an IP address for it's corresponding hardware address. Therefore, ARP
can only be used on networks that support broadcasting.
o The computer that has the corresponding hardware address replys with its hardware
address.
o Every computer maintains an ARP cache that contains the result of recent ARP queries,
which can be viewed with command arp -a.

RARP is used to query a central server to discover a computer's own IP address at boot time.
RARP has been superseded by a newer protocol known as BOOTP, which provides the address-
mapping function of RARP and some other features.

Address Resolution Protocol (ARP):


ARP - is a low-level protocol used to bind addresses dynamically.
ARP allows a host to find a physical address of a target host on the same physical network, given
only its IP address.
ARP hides the underlying network physical addressing. It can be thought of as part of physical
network system and not the internet protocols.

ARP broadcasts special packets with the destinations IP address to ALL hosts.
The destination host (only) will respond with its physical address.
When the response is received, the sender uses the physical address of destination host to send all
packets.

Prepared by,
4

Reverse Address Resolution Protocol (RARP):


RARP functionality supports multiple physical network types.
All machines receive RARP requests but only those authorized to supply RARP services can
respond. Machines supplying RARP services are called RARP servers.
RARP is only used on LANs with a low probability of failure since bootstrapping requires quick
responses.

3. Describe Internet Traffic Management. (ND12) (16)

Internet traffic management, also known as application traffic management, refers to tools that monitor
the flow of Web application traffic over a network. These tools route traffic among multiple devices
within a network, limiting delays and freeing bandwidth.

The F5 BIG-IP product family monitors network traffic for problems that may compromise critical data
and hinder application performance. The BIG-IP product family provides complete network
transparency, enabling automated application security and comprehensive traffic management.

The BIG-IP family of products offers the application intelligence network managers need to ensure
applications are fast, secure and available. All BIG-IP products share a common underlying architecture,
F5's Traffic Management Operating System (TMOS), which provides unified intelligence, flexibility and
programmability. Together, BIG-IP's powerful platforms, advanced modules, and centralized
management system make up the most comprehensive set of application delivery tools in the industry.
4. Explain about various internet applications. (ND12) (16)
Internet is the interconnection of large number of heterogeneous computer networks all over the world
that can share information back and forth. These interconnected network exchange information by using
same standards and protocols
Applications of internet
The internet is treated as one of the biggest invention. It has a large number of uses.
1. Communication: it is used for sending and receiving message from one and other through internet by
using electronic mail. Some of the web sites providing this service are yahoomail.com Hotmail.com
rediffmail.com etc.

Prepared by,
5

2. Job searches: getting information regarding availability of job in different sectors and areas. You can
publish your resume in online for prospective job. Some of the web sites providing this service are
naukri.com, monster.com, summerjob.com, recuritmentindia.com etc.
3. Finding books and study material : books and other study material stored around the world can be
easily located through internet. Latest encyclopaedias are available online.
4. Health and medicine: internet provide information and knowledge about field of health medicine
people can have information about various disease and can receive help .patient can be taken to virtual
check room where they can meet doctors. Some of the web sites providing this service are
5. Travel: one can use internet to gather information about various tourist place . it can be used for
booking Holiday tours , hotels, train and flights. Some of the web sites providing this service
areindiatravelog.com, rajtravel.com, makemytrip.com.
6. Entertainment one can doun lode jokes, songs muvis, latest sports updates through internet Some of
the web sites providing this service arecricinfo.com, movies.com espn.com
7. Shopping : internet is also used for online shopping. By just giving accounts details you can perform
the transaction. You can even pay your bills and perform bank related transaction.
8. Stock market updates : you can sell or buy shares while sitting on computer through internet. Several
websites like ndtvprofit.com, moneypore.com, provide information regarding investment
9. Research: A large number of people are using internet for research purposes you can download any
kind information by using internet
10. Business use of internet: different ways by which intenet can be used for business are:
Information about the product can be provided can be provided online to the the customer .
Provide market information to the business
It help business to recruit talented people
Help in locating suppliers of the product .
Fast information regarding customers view about companies product
Eliminate middle men and have a direct contact with contact with customer .
Providing information to the investor by providing companies back ground and financial information
on web site
5. Explain TCP/IP over ATM networks. (16)

The protocol for classical IP over ATM (sometimes abbreviated as CLIP/ATM) is a well-established
standard spelled out in RFC 1577 and subsequent documents. Windows 2000 provides a full
implementation of this standard.

The IP over ATM approach provides several attractive advantages over ELAN solutions. The most
obvious advantages are its ability to support QoS interfaces, its lower overhead (as it requires no MAC
header), and its lack of a frame size limit. All of these features are discussed in the following sections.

Prepared by,
6

IP over ATM Architecture

IP over ATM is a group of components that do not necessarily reside in one place, and, in this case, the
services are not usually on an ATM switch. In some cases, switch vendors provide some IP over ATM
support, but not always. (For the purposes of this discussion, it is assumed the IP over ATM server
services reside on a Windows 2000 server.)

The core components required for IP over ATM are roughly the same as those required for LANE, as
both approaches require the mapping of a connectionless medium to a connection-oriented medium, and
vice versa. In IP over ATM, these services are provided by an IP ATMARP server for each IP subnet.
This server maintains a database of IP and ATM, and provides configuration and broadcast services, as
described in the following section.

IP over ATM Components

IP over ATM is a very small layer between the ATM protocol and the TCP/IP protocol. As with LANE,
the client emulates standard IP to the TCP/IP protocol at its top edge while simultaneously issuing native
ATM commands to the ATM protocol layers underneath.

IP over ATM is often preferred to LANE because it is faster than LANE. One key reason for this
performance advantage is that IP over ATM adds almost no additional header information to packets as
they are handed down the stack. Once it has established a connection, the IP over ATM client can
generally transfer data without modification.

As with LANE, IP over ATM is handled by two main components: the IP over ATM server and the IP
over ATM client. The IP over ATM server is composed of an ATMARP server and Multicast Address
Resolution Service (MARS). The ATMARP server provides services to map network layer IP unicast
addresses to ATM addresses, while MARS provides similar services for broadcast and multicast
addresses. Both services maintain IP address databases just as LANE services do.

The IP over ATM server can reside on more than one computer, but the ATMARP and MARS databases
cannot be distributed. You can have one IP over ATM server handle ATMARP traffic, and one handle
MARS. If, however, you divided the ATMARP Server between servers, it would effectively create two
different IP networks. All IP over ATM clients in the same logical IP subnet (LIS) need to be configured
to use the same ATMARP server. Traditional routing methods are used to route between logical IP
subnets, even if they are on the same physical network.

IP over ATM Operation

IP over ATM faces the same problems, and relies on the same basic tools and fixes as LANE. In
particular, it faces the issues of address resolution and broadcasting.

In normal ATM, SVC connections are established by sending a connection request containing the ATM
address of the destination endpoint to the ATM switch. Before an IP endpoint can create an SVC in this
manner, the endpoint must resolve the IP address of the destination to an ATM address.

Prepared by,
7

Normally, when an Ethernet host needs to resolve an IP address to an Ethernet MAC address, it uses an
ARP broadcast query frame. As explained earlier, hardware broadcasting is not done in ATM. The
Address Resolution Protocol (ARP) of the ATMARP server resolve IP addresses to ATM addresses.

An ATM endpoint wishing to resolve an IP address sends an ATMARP request to the ATMARP server
for their LIS. The ATMARP request contains the sender's ATM address and IP address and the requested
IP address. If the ATMARP server knows the requested IP address, it sends back an ATMARP response
containing the requested ATM address. If the requested IP address is not found, the ATMARP servers
send back a negative ATMARP reply, unlike the procedure in an ELAN, which would send an
unresolved address to the LANE BUS. This behavior allows an ARP requestor to distinguish between an
unknown address and non-functioning ATMARP server.

The end result is a three-way mapping from the IP address to an ATM address to a VPI/VCI pair. The IP
address and ATM address are required to create a VC. The IP address and VPI/VCI then are required to
send the subsequent cells containing data across the VC.

An ATM endpoint creates SVCs to other ATM endpoints within its LIS. For an ATM endpoint to resolve
an arbitrary IP address, it must be configured with the ATM address of the ATMARP server in its LIS.

Upon startup, an ATM endpoint establishes a VC with the ATMARP server using ATM signaling. As
soon as the VC is opened with the server, the server sends the ATM endpoint an InATMARP request.
When the ATM endpoint sends the response, the ATMARP server has the ATM and IP address of the
new ATM endpoint. In this way, the ATMARP server builds its table of ATM to IP address mappings.

6. Explain the applications of internet. (16)

Applications of Internet

There are many different applications of the internet used commonly across the world. The most
common names are the JAVA, JAVA script and the Flash.

These are the most useful as well as the most frequently used applications which need to be installed on
the computer before the full access of the internet can be guaranteed.

The flash is required for the animated videos and pictures. For example the electronic greeting cards
these days used extensively for various occasions all require the us if the internet application Flash.
Some websites which are used to upload videos online like the most commonly used YouTube also
require the latest flash player to work. Every other website consists of flash content these days and so it
is one of the most useful applications of the internet.

Another mentioned application which is also well-known is the JAVA; java is also needed for the
internet access to a certain extent. For example using the ftp services on the internet, you need to have
the JAVA technology JVM to be able to manage and control the documentation transfers.

Prepared by,
8

These applications are basically used to run the applets on the internet web pages which are made to
work with them, without these tools the internet though can be easily accessed it does not offer all the
features to the user, which might also be some useful information.

The internet applications all reduce the traffic on the network and thus make the server work on a much
optimized level. All the applications are interoperable, and support the cross platforms, both of the OS
servers and the clients.
7. Explain the concept of Sliding Window Protocol. (16)

Sliding Window protocols


Frames have sequence number 0 to maximum 2n - 1 (n bit field).
At any moment, the sender maintains a list of sequence numbers it is permitted to send - these fall within
the sending window. These are frames sent-but-no-ack and frames not-yet-sent.
When new packet from Network layer comes in to send, it is given highest no, and upper edge of
window advanced by 1.

When ack comes in, lower edge of window advanced by 1.

Receiver has receiving window - the frames it is permitted to accept.

Sliding window size 1. Sequence nos. 0 to 7.


(a) At start. Receiver waits for 0.
(b) Sender sends 0.
(c) Receiver receives 0. Waits for 1.
(d) Sender got ack for 0. Hasn't got 1 from its Network layer yet.

Prepared by,
9

More complex Data Link layer, as more freedom about the order in which it sends and receives frames.
Sender may have n unacknowledged frames at any time (window size n).
Needs n buffers to hold them all for possible re-transmit.
If window grows to its maximum size, DA must shut off NA.
This is all hidden from NB - still receives packets in exact same order.

1. Sender window might grow as it receives more frames to send and still has ones un-ack'ed.
Starts with nothing to send, then NA gives it frames to send.
Later, window may shrink as frames are ack-ed and NA has no more.
2. Receiver window constant size.
Receiver window size 1 means will only accept them in order.
Size n means will receive out of order (e.g. receive later ones after earlier frame is lost)
and then must buffer them before sending to NB (must send to NB in order).

e.g. DB has buffers to receive frames 0..7


Receives 1..7 in varying orders. Still waiting on 0. Can't send frames to NB yet.
0 got lost and was re-sent. Eventually gets 0.
Can now send all of 0..7 to NB
and re-use these slots.

e.g. consider frames numbered 0..7 but DB only has 2 buffers


Currently the sliding window is over 4,5
If get 4 can send it to NB and move window to 5,6
If get 5 have to wait for 4, then send both, and advance window to 6,7

8. Explain Karns algorithm. (16)

Karn's Algorithm

TCP adjusts the timeouts in agreement with the Round-Trip-Time (RTT) estimation for the current end-
to-end path. RTT estimation is often called Smoothed-Round-Trip-Time (SRTT) and is obtained by
averaging the measured RTT for the packets sent so far (the details will be described in the next section).
Then, in the original RFC 793 TCP, the retransmit timeout (RTO) is set as twice the SRTT .

A problem arises from the way samples are taken for the calculation of the average: TCP is unable to
distinguish two separate acknowledgements for the same sequence number. Therefore, we have the
following problem:

Left: sender, right: receiver. A timeout occurs before an ACK is received, and PKT1 is retransmitted. The
ack for the first PKT1 arrives a bit later and the source measures a wrong value for the RTT.

Prepared by,
10

That is, sender's TCP has the risk of making the mistake to think that the acknowledgment of a recently
retransmitted packet is one sent for the packet transmitted earlier.

UNIT-II : INTERNET ROUTING


1. Explain in detail, the working mechanism of Link State Protocol. (ND12) (16)
Link-State (SPF) Routing
The main disadvantage of the distance-vector algorithm is that it does not scale well. Besides the
problem of slow response to change mentioned earlier, the algorithm requires the exchange of large
messages. Because each routing update contains an entry for every possible network, message size is
proportional to the total number of networks in an internet. Furthermore, because a distance-vector
protocol requires every router to participate, the volume of information exchanged can be enormous.
The primary alternative to distance-vector algorithms is a class of algorithms known as link state,
link status, or Shortest Path Firstt (SPF). The SPF algorithm requires each participating router to
have complete topology information. The easiest way to think of the topology information is to
imagine that every router has a map that shows all other routers and the networks to which they
connect. In abstract terms, the routers correspond to nodes in a graph and networks that connect
routers correspond to edges. There is an edge (link) between two nodes if and only if the
corresponding routers can communicate directly.

Instead of sending messages that contain lists of destinations, a router participating in an SPF
algorithm performs two tasks. First, it actively tests the status of all neighbour routers. In terms of
the graph, two routers are neighbours if they share a link; in network terms, two neighbours connect

Prepared by,
11

to a common network. Second, it periodically propagates the link status information to all other
routers.

To test the status of a directly connected neighbor, a router periodically exchanges short messages that
ask whether the neighbour is alive and reachable. If the neighbor replies, the link between them is said to
be up. Otherwise, the link is said to be down$. To inform all other routers, each router periodically
broadcasts a message that lists the status (state) of each of its links. A status message does not spec@
routes - it simply reports whether communication is possible between pairs of routers. Protocol
software in the routers arranges to deliver a copy of each link status message to all participating
routers (if the underlying networks do not support broadcast, delivery is done by forwarding
individual copies of the message point-to-point).

Whenever a link status message arrives, a router uses the information to update its map of the
internet, by marking links up or down. Whenever link status changes, the router recomputes routes
by applying the well-known Dijkstras shortest path algorithm to the resulting graph. Dijkstra's
algorithm computes the shortest paths to all destinations from a single source. One of the chief
advantages of SPF algorithms is that each router computes routes independently using the same
original status data; they do not depend on the computation of intermediate machines. Because link
status messages propagate unchanged, it is easy to debug problems. Because routers perform the
route computation locally, it is guaranteed to converge. Finally, because link status messages only
carry information about the direct connections from a single router, the size does not depend on the
number of networks in the internet. Thus, SPF algorithms scale better than distance vector
algorithms.

2. Explain how routing for high speed multimedia traffic done. (ND12) (16)
A Very High Speed Backbone (vBNS)

In 1995, NSF awarded MCI a contract to build a backbone operating at 155 Mbps (OC3 speed) to
replace ANSNET. Called the very high speed Backbone Network Service (vBNS), the new backbone
offered a substantial increase in capacity, and required higher speed processors to route packets.

Commercial Internet Backbones

Since 1995, the Internet has become increasingly commercial, with the percentage of funding from
the U.S. government steadily decreasing. Although vBNS still exists, it is now devoted to networking
research. In its place, commercial companies have created large privately-funded backbones that
carry Internet traffic.
For Example,
Tunnelling across a high-level network such as X.25 requires mapping between the addresses used
by the internet and addresses used by the network. For example, consider the addressing scheme
used by X.25 networks, which is given in a related standard known as X.121. Physical addresses
each consist of a 14-digit number, with 10 digits assigned by the vendor that supplies the X.25
network service. Resembling telephone numbers, one popular vendor's assignment includes an area
code based on geographic location. The addressing scheme is not surprising because it comes from

Prepared by,
12

an organization that determines international telephone standards. There is no mathematical


relationship between such addresses and the addresses used by TCP/IP. Thus, a computer that tunnels
TCP/IP data across an X.25 network must maintain a table of mappings between internet addresses
and X.25 network addresses. Chapter 5 discusses the address mapping problem in detail and gives an
alternative to using fixed tables. Chapter 18 shows that exactly the same problem arises for ATM
networks, which use yet another alternative.

3. Explain IP switching and Resource Reservation. (ND12) (16)


IP SWITCHING
It started with the question: "can switching hardware be exploited to forward IP traffic at higher
speeds?" The assumption underlying the effort is that hardware will be able to switch more packets
per second than to route them. If the assumption is correct, the question makes sense because router
vendors are constantly trying to find ways to increase router perfomance and scale. Ipsilon
Corporation was one of the first companies to produce products that combined IP and hardware
switches; they used ATM, called their technology IP switching, and called the devices they produced
IP switches. Since Ipsilon, other companies have produced a series of designs and names, including
tag switching, layer 3 switching, and label switching. Several of the ideas have been folded into a
standard endorsed by the IETF that is known as Multi-Protocol Label Switching (MPLS)?
Contributors to the open standard hope that it will allow products from multiple vendors to
interoperate.

Resource Reservation
The term Quality Of Service (QoS) refers to statistical performance guarantees that a network
system can make regarding loss, delay, throughput, and jitter. An isochronous network that is
engineered to meet strict performance bounds is said to provide QoS guarantees, while a packet
switched network that uses best effort delivery is said to provide no QoS guarantee. Is guaranteed
QoS needed for real-time transfer of voice and video over IP? If so, how should it be implemented?
A major controversy surrounds the two questions. On one hand, engineers who designed the
telephone system insist that toll-quality voice reproduction requires the underlying system to provide
QoS guarantees about delay and loss for each phone call. On the other hand, engineers who designed
IP insist that the Internet works reasonably well without QoS guarantees and that adding per-flow
QoS is infeasible because routers will make the system both expensive and slow.

The QoS controversy has produced many proposals, implementations, and experiments. Although it
operates without QoS, the Internet is already used to send audio. Technologies like ATM that were
derived from the telephone system model provide QoS guarantees for each individual connection.

4. Explain distance vector routing protocol with an example. (16)


Distance Vector Multicast Routing Protocol
One of the first multicast routing protocols is still in use in the global Internet. Known as the
Distance Vector Multicast Routing Protocol (DVMRP), the protocol allows multicast routers to pass
group membership and routing information among themselves.

Prepared by,
13

DVMRP resembles the RIP protocol described in Chapter 16, but has been extended for multicast. In
essence, the protocol passes information about current multicast group membership and the cost to
transfer datagrams between routers. For each possible (group, source) pair, the routers impose a
forwarding tree on top of the physical interconnections.
When a router receives a datagram destined for an IP multicast group, it sends a copy of the
datagram out over the network links that correspond to branches in the forwarding tree?
Interestingly, DVMRP defines an extended form of IGMP used for communication between a pair of
multicast routers. It specifies additional IGMP message types that allow routers to declare
membership in a multicast group, leave a multicast group, and interrogate other routers. The
extensions also provide messages that carry routing information, including cost metrics.

5. Explain the three phases of path vector protocol. (16)


A path vector protocol is a computer network routing protocol which maintains the path information
that gets updated dynamically. Updates which have looped through the network and returned to the same
node are easily detected and discarded. This algorithm is sometimes used in BellmanFord routing
algorithms to avoid "Count to Infinity" problems.

It is different from the distance vector routing and link state routing. Each entry in the routing table
contains the destination network, the next router and the path to reach the destination.

Path Vector Messages in BGP: The autonomous system boundary routers (ASBR), which participate in
path vector routing, advertise the reachability of networks. Each router that receives a path vector
message must verify that the advertised path is according to its policy. If the messages comply with the
policy, the ASBR modifies its routing table and the message before sending it to the next neighbor. In the
modified message it sends its own AS number and replaces the next router entry with its own
identification.

BGP is an example of a path vector protocol. In BGP the routing table maintains the autonomous
systems that are traversed in order to reach the destination system. Exterior Gateway Protocol (EGP)
does not use path vectors.

It has three phases:

1.Initiation
2.Sharing
3.Updating

6. Explain the following (16)


a. Interior Routing Protocol
Routing protocols are divided into two general groups: interior and exterior protocols. An
interior protocol is a routing protocol used inside - interior to - an independent network system.
In TCP/IP terminology, these independent network systems are called autonomous systems. [9]
Within an autonomous system (AS), routing information is exchanged using an interior protocol
chosen by the autonomous system's administration.

Prepared by,
14

b. Fixed Routing Protocol


Fixed routing is a form of routing that occurs when a router uses a manually-configured routing
entry, rather than information from a dynamic routing protocol to forward traffic. [1] In many
cases, static routes are usually manually configured by a network administrator by adding in
entries into a routing table,

c. Adaptive Routing Protocol


Adaptive routing is the process of locating a clear path from a source point to a destination point
across a network of nodes that could change at any point.

7. Explain Shortest Path Routing algorithm with example. (16)


Link-State (SPF) Routing
The main disadvantage of the distance-vector algorithm is that it does not scale well. Besides the
problem of slow response to change mentioned earlier, the algorithm requires the exchange of large
messages. Because each routing update contains an entry for every possible network, message size is
proportional to the total number of networks in an internet. Furthermore, because a distance-vector
protocol requires every router to participate, the volume of information exchanged can be enormous.
The primary alternative to distance-vector algorithms is a class of algorithms known as link state,
link status, or Shortest Path Firstt (SPF). The SPF algorithm requires each participating router to
have complete topology information. The easiest way to think of the topology information is to
imagine that every router has a map that shows all other routers and the networks to which they
connect. In abstract terms, the routers correspond to nodes in a graph and networks that connect
routers correspond to edges. There is an edge (link) between two nodes if and only if the
corresponding routers can communicate directly. Instead of sending messages that contain lists of
destinations, a router participating in an SPF algorithm performs two tasks. First, it actively tests the
status of all neighbour routers. In terms of the graph, two routers are neighbors if they share a link; in
network terms, two neighbors connect to a common network. Second, it periodically propagates
the link status information to all other routers.

To test the status of a directly connected neighbor, a router periodically exchanges short messages
that ask whether the neighbor is alive and reachable. If the neighbor replies, the link between them is
said to be up. Otherwise, the link is said to be down$. To inform all other routers, each router
periodically broadcasts a message that lists the status (state) of each of its links. A status message
does not spec@ routes - it simpl reports whether communication is possible between pairs of routers.
Protocol software in the routers arranges to deliver a copy of each link status message to all
participating routers (if the underlying networks do not support broadcast, delivery is done by
forwarding individual copies of the message point-to-point). Whenever a link status message arrives,
a router uses the information to update its map of the internet, by marking links up or down.

Prepared by,
15

Whenever link status changes, the router recomputes routes by applying the well-known Dijkstra
shortest path algorithm to the resulting graph. Dijkstra's algorithm computes the shortest paths to all
destinations from a single source. One of the chief advantages of SPF algorithms is that each router
computes routes independently using the same original status data; they do not depend on the
computation of intermediate machines. Because link status messages propagate unchanged, it is easy
to debug problems. Because routers perform the route computation locally, it is guaranteed to
converge. Finally, because link status messages only carry information about the direct connections
from a single router, the size does not depend on the number of networks in the internet. Thus, SPF
algorithms scale better than distance vector algorithms.

UNIT-III : WORLD WIDE WEB

1. Develop a static website in HTML by including all types of text links, image links and
alignment. (ND12) (16)
<!DOCTYPE html>
<html>
<body>

<a href="http://www.w3schools.com">
This is a link</a>
<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">
<p>
<b>This text is bold</b>
</p>
<p>
<strong>This text is strong</strong>
</p>
<p>
<em>This text is emphasized</em>
</p>
<p>
<i>This text is italic</i>
</p>
<p>
<small>This text is small</small>
</p>
<p>This is<sub> subscript</sub> and <sup>superscript</sup>
</p>

</body>
</html>

Prepared by,
16

2. Write a Java script to check whether the given string is palindrome or not. (ND12) (16)
<html>
<body>
<script type="text/javascript">
function checkPalindrome() {
var revStr = "";
var str = document.getElementById("str").value;
var i = str.length;
for(var j=i; j>=0; j--) {
revStr = revStr+str.charAt(j);
}
if(str == revStr) {
alert(str+" -is Palindrome");
} else {
alert(str+" -is not a Palindrome");
}
}
</script>
<form >
Enter a String/Number: <input type="text" id="str" name="string" /><br />
<input type="submit" value="Check" onclick="checkPalindrome();"/>
</form>
</body>
</html>

3. Using a Java script, create a web page with two images loaded in it. Display the relevant
information of the image when the mouse pointer moves over the image. (ND12)(16)
<body>
<img src=home.jpgid=img1 onmouseover=doMouseOver()>
<p>
<a href=link1.html>Rollover link
</a>

Prepared by,
17

<script language=javascript>
Function doMouseOver()
{
Document.getElementById(img1).src=home2.jpg;
}
<img src=home3.jpgid=img2 onmouseover=doMouseOver()>
<p>
<a href=link2.html>Rollover link
</a>
<script language=javascript>
Function doMouseOver()
{
Document.getElementById(img2).src=home3.jpg;
}
</script>
</body>

4. Develop a web page for student details and calculate the total, average, class of the student
using java script. (16)
<html>
<head>
<title>Student Mark List</title>
</head>
<script language="javascript">
function total_1()
{
var m1=parseInt(document.form1.tamil.value);
var m2=parseInt(document.form1.english.value);
var m3=parseInt(document.form1.maths.value);
var m4=parseInt(document.form1.science.value);
var m5=parseInt(document.form1.social.value);
document.form1.total.value=m1+m2+m3+m4+m5;
}
function result_1()
{
var m1=parseInt(document.form1.tamil.value);
var m2=parseInt(document.form1.english.value);
var m3=parseInt(document.form1.maths.value);
var m4=parseInt(document.form1.science.value);

Prepared by,
18

var m5=parseInt(document.form1.social.value);
if(m1>=35 && m2>=35 && m3>=35 && m4>=35 && m5>=35)
{
document.form1.result.value="pass";
}
else
{
document.form1.result.value="fail";
}
}
function disp()
{
document.write("<h1><center><u>STUDENT MARK

LIST</u></center></h1><table

border="0"><tr><td>Name:</td><td>"+document.form1.stuName.va

lue+"</td></tr><tr><td>No:</td><td>"+document.form1.stuNo.valu

e+"</td></tr><tr><td>Tamil:</td><td>"+document.form1.tamil.valu

e+"</td></tr><tr><td>English:</td><td>"+document.form1.english.v

alue+"</td></tr><tr><td>Maths:</td><td>"+document.form1.maths.

value+"</td></tr><tr><td>Science:</td><td>"+document.form1.scie

nce.value+"</td></tr><tr><td>Social</td><td>"+document.form1.so

cial.value+"</td></tr><tr><td>Total:</td><td>"+document.form1.tot

al.value+"</td></tr><tr><td>Result:</td><td>"+document.form1.res

ult.value+"</td></tr></table>");
}
</script>

<body><center><h1>Student Mark List</h1>


<form name="form1">
<table border="2">
<tr><td><label>Name</label></td><td><input type="text"

name="stuName"></td></tr>
<tr><td><label>No</label></td><td><input type="text"

name="stuNo"></td></tr>

Prepared by,
19

<tr><td><label>Tamil</label></td><td><input type="text"

name="tamil"></td></tr>
<tr><td><label>English</label></td><td><input type="text"

name="english"></td></tr>
<tr><td><label>Maths</label></td><td><input type="text"

name="maths"></td></tr>
<tr><td><label>Science</label></td><td><input type="text"

name="science"></td></tr>

<tr><td><label>Social</label></td><td><input type="text"

name="social"></td></tr>

<tr><td><label>Total</label></td><td><input type="text"

name="total" ONFOCUS="total_1()"

ONFOCUS="result_1()"></td></tr>

<tr><td><label>Result</label></td><td><input type="text"

name="result"></td></tr>

<tr><td><input type="submit" name="s" value="Submit"

onclick="disp()"></td><td><input type="reset" name="r"

value="Reset"></tr>
</table>
</form>
</center>
</body>
</html>

5. Explain Web Browsers and its use. (16)


WEB BROWSERS:

A web browser (commonly referred to as a browser) is a software application for retrieving, presenting
and traversing information resources on the World Wide Web. An information resource is identified by
a Uniform Resource Identifier (URI/URL) and may be a web page, image, video or other piece of
content. Hyperlinks present in resources enable users easily to navigate their browsers to related
resources.

Prepared by,
20

Although browsers are primarily intended to use the World Wide Web, they can also be used to access
information provided by web servers in private networks or files in file systems.
The major web browsers are Firefox, Internet Explorer, Google Chrome, Opera, and Safari.

How Do Web Browsers Work?


The World Wide Web is a system of Internet servers that support specially formatted documents. Web
browsers are used to make it easy to access the World Wide Web. Browsers are able to display Web
pages largely in part to an underlying Web protocol called Hyper Text Transfer Protocol (HTTP). HTTP
defines how messages are formatted and transmitted, and what actions Web servers and browsers should
take in response to various commands. It is what allows Web clients and Web servers to communicate
with each other. When you enter a Web address (URL) in your browser, this actually sends an HTTP
command to the Web server directing it to fetch and transmit the requested Web page and display the
information in your browser. All Web servers serving Web sites and pages support the HTTP protocol.

Usage of web browsers:

The usage share of web browsers is the proportion, often expressed as a percentage, of visitors to a
group of Web sites that use a particular Web browser. Web browser usage share varies from region to
region as well as through time.

6. Explain CSS and its types with an example. (16)


What are Style Sheets?
Two forces compete in Web page authoring: content and presentation. When HTML was
first released, the tags were largely focused on content, and they descriptively defined the various
parts of a document: a heading, a paragraph, a list, and so on. Over time, instructions were added
to help with presentation issues at the font level. These instructions included tags for boldface, italic
and typewriter styles.

Then, as graphical browsers became standard equipment, a greatly increased focus on


presentation began. In particular, Netscape introduced proprietary extensions to HTML
that only its browser could render properly. These extensions generally produced
attractive effects on pages, and users began using Netscape en masse. Not to be left
out, Microsoft began producing its own browserInternet Explorerand with it, its own
proprietary HTML extensions. Content authors, who could only watch the new tags
emerge, were frequently left confused and frustrated because it was hard to tell which
browser to write for and how long it would be before the next new set of bells and
whistles became available.

Prepared by,
21

As designers push for more control over page attributes, such as indentation and line
spacing, the evolution of HTML stands at a fork in the road. One path leads to the
continued introduction of proprietary tags by the people making the browsersa path
that will lead HTML into even muddier waters. The other path leads to an explicit
separation of content and presentation by introducing style sheetsdocuments that
provide specifications for how content should look onscreen. By separating these two
otherwise competing forces, HTML is free to evolve as a language that describes
document content and will be less susceptible to seemingly endless extensions by
browser software companies.
The W3C's first stab at separating content and presentation was the Cascading Style
Sheets, level 1 (CSS1) specificationa formal statement on how to specify style
information. In May 1998, the W3C released Cascading Style Sheets, level 2 (CSS2) as
a published recommendation, so you should adhere to that standard when preparing
style sheets

The different types of stylesheets


Stylesheet definitions created with CSS can be inserted into an HTML document in a few different ways.
This tutorial focuses on:
The three types of stylesheets
Creating an internal stylesheet
Creating an external stylesheet
Creating an inline stylesheet
Multiple stylesheets
The three types of stylesheets
There are three types of stylesheets:
Internal - Placed right on the page whose interface it will affect.
External - Placed in a separate file.
Inline - Placed inside a tag it will affect.
Creating an internal stylesheet
Use an internal stylesheet when you want an HTML document to have a unique style. An internal
stylesheet is defined using the <style> tag and goes in the head section of an HTML document.

Prepared by,
22

The <style> tag specifies the content type of a stylesheet with its type attribute which should be set to
"text/css".
Syntax:
<style type="text/css"> styles go here </style>
Example:
<html> <head> <style type="text/css"> p {color: green} </style> </head> <body> <p> The text in this
paragraph will be green. </p> <p> This paragraph too. </p> </body> </html>
The above stylesheet definition specifies that all text declared with the <p> tag should be green.

7. How to create, read and write XML documents? Explain with an example. (16)
Extensible Markup Language (XML) is a markup language that defines a set of rules for
encoding documents in a format that is both human-readable and machine-readable. It is defined in the
XML 1.0 Specificationproduced by the W3C, and several other related specifications, all free open
standards.
The design goals of XML emphasize simplicity, generality, and usability over the Internet. It is a
textual data format with strong support via Unicode for different human languages. Although the design
of XML focuses on documents, it is widely used for the representation of arbitrary data structures, for
example in web services.
Many application programming interfaces (APIs) have been developed to aid software developers
with processing XML data, and several schema systems exist to aid in the definition of XML-based
languages.
XML Document to Check for Validity
<?xml version="1.0" ?>
<?protext objid="I5678" ?>
<!DOCTYPE helptopic [
<!ENTITY doubleclick "Double-click">
]>
<helptopic>
<title keyword="printing,network;printing,shared printer">How to
use a
shared network printer?</title>
<procedure>

Prepared by,
23

<step><action>In <icon>Network Neighborhood</icon>, locate and


double-click the computer where the printer you want to use is
located.
</action>
<tip targetgroup="beginners">To see which computers have shared
printers
attached, click the <menu>View</menu> menu,
click <menu>Details</menu>, &amp; look for printer names or
- 360 -
descriptions
in the Comment column of the Network Neighborhood window.</tip>
</step>
<step>
<action>&doubleclick; the printer icon in the window that
appears.
</action>
</step>
<step>
<action>
To set up the printer, <xref linkend="id45">follow the
instructions</xref>
on the screen.
</action></step>
</procedure>
<rule form="double"/>
<tip>
<p>After you have set up a network printer, you can use it as if
it were
attached to your computer. For related topics, look up
&quot;printing&quot; in the Help Index.
</p>
</tip>

Prepared by,
24

</helptopic>

Simple Xml document:


<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="samp2.xsl"?>
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Return of the Judai</TITLE>
<ARTIST>Judas Priest</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>20.90</PRICE>
<YEAR>1995</YEAR>
</CD>
<CD>
<TITLE>Dangerous</TITLE>
<ARTIST>Michael Jackson</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Sony</COMPANY>
<PRICE>30.00</PRICE>
<YEAR>1992</YEAR>
</CD>
</CATALOG>

Prepared by,
25

/****samp2.xsl ****/
<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<html>
<body>
<table border="2" bgcolor="cyan">
<tr>
<th>Title</th>
<th>Artist</th>
<th>Price</th>
<th>Company</th>
</tr>
<xsl:for-each select="CATALOG/CD">
<tr>
<td><xsl:value-of select="TITLE"/></td>
<td><xsl:value-of select="ARTIST"/></td>
<td><xsl:value-of select="PRICE"/></td>
<td><xsl:value-of select="COMPANY"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet><?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<html>
<body>
<table border="2" bgcolor="cyan">
<tr>

Prepared by,
26

<th>Title</th>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

8. Write a Java script, to find the sum of the digits of a given number. (16)
<HTML><body>
<script>
function find()
{
var sum=0;
var no=parseInt(frm.txt1.value);
while(no>0)
{
sum=sum+no%10;
no=Math.floor(no/10);
}
alert("Sum of digits "+sum);

}
</script>
<form name="frm">
Enter a Number:<input name="txt1" type="text" />
<input name="b1" onclick="find();" type="button" value="display" /></form>
</BODY>
</HTML>

UNIT-IV : INTRODUCTION TO JAVA

1. What is multithreading? Explain with a sample java program. (ND12)(16)


Java is a multithreaded programming language which means we can develop multithreaded program
using Java. A multithreaded program contains two or more parts that can run concurrently and each part
can handle different task at the same time making optimal use of the available resources especially when
your computer has multiple CPUs.

Prepared by,
27

By definition multitasking is when multiple processes share common processing resources such as a
CPU. Multithreading extends the idea of multitasking into applications where you can subdivide specific
operations within a single application into individual threads. Each of the threads can run in parallel. The
OS divides processing time not only among different applications, but also among each thread within an
application.

Multithreading enables you to write in a way where multiple activities can proceed concurrently in the
same program.

Example:-

class RunnableDemo implements Runnable {


private Thread t;
private String threadName;

RunnableDemo( String name){


threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}

public void start ()


{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}

public class TestThread {


public static void main(String args[]) {

RunnableDemo R1 = new RunnableDemo( "Thread-1");


R1.start();

RunnableDemo R2 = new RunnableDemo( "Thread-2");


R2.start();
}
}

Prepared by,
28

This would produce the following result:

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

2. Explain Remote Method Invocation with an example. (ND12)(16)


The Remote Method Invocation (RMI) is an API that provides a mechanism to create distributed
application in java. The RMI allows an object to invoke methods on an object running in another JVM.

The RMI provides remote communication between the applications using two objects stub and skeleton.

RMI uses stub and skeleton object for communication with the remote object.

stub

The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed through
it. It resides at the client side and represents the remote object. When the caller invokes method on the
stub object, it does the following tasks:

1. It initiates a connection with remote Virtual Machine (JVM),


2. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.

skeleton

The skeleton is an object, acts as a gateway for the server side object. All the incoming requests are
routed through it. When the skeleton receives the incoming request, it does the following tasks:

1. It reads the parameter for the remote method


2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.

Prepared by,
29

1) create the remote interface

For creating the remote interface, extend the Remote interface and declare the RemoteException with all
the methods of the remote interface. Here, we are creating a remote interface that extends the Remote
interface. There is only one method named add() and it declares RemoteException.

import java.rmi.*;
public interface Adder extends Remote{
public int add(int x,int y)throws RemoteException;
}

2) Provide the implementation of the remote interface

Now provide the implementation of the remote interface. For providing the implementation of the
Remote interface, we need to

Either extend the UnicastRemoteObject class,


or use the exportObject() method of the UnicastRemoteObject class

In case, you extend the UnicastRemoteObject class, you must define a constructor that declares
RemoteException.

import java.rmi.*;
import java.rmi.server.*;
public class AdderRemote extends UnicastRemoteObject implements Adder{
AdderRemote()throws RemoteException{
super();
}

public int add(int x,int y){return x+y;}


}

3) create the stub and skeleton objects using the rmic tool.

Next step is to create stub and skeleton objects using the rmi compiler. The rmic tool invokes the RMI
compiler and creates stub and skeleton objects.

rmic AdderRemote

4) Start the registry service by the rmiregistry tool

Now start the registry service by using the rmiregistry tool. If you don't specify the port number, it uses a
default port number. In this example, we are using the port number 5000.

Prepared by,
30

rmiregistry 5000

5) Create and run the server application

Now rmi services need to be hosted in a server process. The Naming class provides methods to get and
store the remote object. The Naming class provides 5 methods.

1. public static java.rmi.Remote lookup(java.lang.String) throws


java.rmi.NotBoundException, java.net.MalformedURLException, java.rmi.RemoteException; it
returns the reference of the remote object.
2. public static void bind(java.lang.String, java.rmi.Remote) throws
java.rmi.AlreadyBoundException, java.net.MalformedURLException,
java.rmi.RemoteException; it binds the remote object with the given name.
3. public static void unbind(java.lang.String) throws java.rmi.RemoteException,
java.rmi.NotBoundException, java.net.MalformedURLException; it destroys the remote object
which is bound with the given name.
4. public static void rebind(java.lang.String, java.rmi.Remote) throws
java.rmi.RemoteException, java.net.MalformedURLException; it binds the remote object to the new
name.
5. public static java.lang.String[] list(java.lang.String) throws java.rmi.RemoteException,
java.net.MalformedURLException; it returns an array of the names of the remote objects bound in the
registry.

In this example, we are binding the remote object by the name sonoo.

import java.rmi.*;
import java.rmi.registry.*;

public class MyServer{

public static void main(String args[]){


try{

Adder stub=new AdderRemote();


Naming.rebind("rmi://localhost:5000/sonoo",stub);

}catch(Exception e){System.out.println(e);}
}

6) Create and run the client application


At the client we are getting the stub object by the lookup() method of the Naming class and invoking the
method on this object. In this example, we are running the server and client applications, in the same

Prepared by,
31

machine so we are using localhost. If you want to access the remote object from another machine,
change the localhost to the host name (or IP address) where the remote object is located.

import java.rmi.*;
public class MyClient{

public static void main(String args[]){


try{

Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
System.out.println(stub.add(34,4));

}catch(Exception e){}
}
}

3. Write a brief note on Event class in java. (ND12) (16)

Java has a number of classes that describe different categories of events. The following figure shows the
hierarchy of a Java event class :

The Action Event class

ActionEvent is generated by an AWT component, such as a button, when a component-specific action is


performed.

The action event is generated when a button is pressed, a list item is double-clicked, or a menu item is
selected.

The following syntax shows the declaration of the constructor of the ActionEvent class is:
public ActionEvent(Object source, int id, String command)

The main methods included in the Action Event class are: String getActionCommand

The MouseEvent class

The MouseEvent class extends the java.awt.event.InputEvent class.


The mouse event indicates that a mouse action has occurred on a component.
The mouse events include:
Pressing a mouse button
Releasing a mouse button
Clicking a mouse button
Entering of mouse in a component area
Exiting of mouse from a component area
The mouse event class defines some integer constants that can be used to identify several types of mouse
events.

Prepared by,
32

Given below the various integer constants of the Event class :

Constants Description

MOUSE_CLICKED Identifies the event of mouse clicking.

MOUSE_DRAGGED Identifies the event of dragging of mouse.

MOUSE_MOVED Identifies the event of mouse moving.

MOUSE_PRESSED Identifies the event of mouse pressing.

MOUSE_RELEASED Identifies the event of mouse releasing.

MOUSE_ENTERED Identifies the event of mouse entering an AWT component.

MOUSE_EXITED Identifies the event of mouse exiting an AWT component.

Given below Various methods of the MouseEvent class:

Methods Description

public int getX() Returns the horizontal x coordinate of the mouse position relative to
a source component.

public int getY() Returns the vertical y coordinate of the mouse position relative to a
source component.

public point getPoint() Returns the Point object. The Point object contains the x and y
coordinates
of the mouse position relative to a source component.

public void translatePoint(int x, int y) Translates the coordinates of a mouse event to a new position by
adding x and y offsets.

public int getClickCount() Returns the number of mouse clicks associated with an event.

4. Write short notes on basic concepts of OOPS. (16)


Object-oriented programming (OOP) is a programming paradigm that uses Objects and their
interactions to design applications and computer programs.

There are different types of OOPs are used, they are


1. Object
2. Class
3. Data Abstraction & Encapsulation

Prepared by,
33

4. Inheritance
5. Polymorphism
6. Dynamic Binding
7. Message Passing

1) Object:
Object is the basic unit of object-oriented programming. Objects are identified by its unique name. An
object represents a particular instance of a class. There can be more than one instance of an object. Each
instance of an object can hold its own relevant data.

An Object is a collection of data members and associated member functions also known as methods.

For example whenever a class name is created according to the class an object should be created without
creating object cant able to use class.

The class of Dog defines all possible dogs by listing the characteristics and behaviors they can have; the
object Lassie is one particular dog, with particular versions of the characteristics. A Dog has fur; Lassie
has brown-and-white fur.

2) Class:
Classes are data types based on which objects are created. Objects with similar properties and methods
are grouped together to form a Class. Thus a Class represents a set of individual objects. Characteristics
of an object are represented in a class as Properties. The actions that can be performed by objects
become functions of the class and is referred to as Methods.

For example consider we have a Class of Cars under which Santro Xing, Alto and WaganR represents
individual Objects. In this context each Car Object will have its own, Model, Year of Manufacture,
Colour, Top Speed, Engine Power etc., which form Properties of the Car class and the associated actions
i.e., object functions like Start, Move, Stop form the Methods of Car Class.No memory is allocated when
a class is created. Memory is allocated only when an object is created, i.e., when an instance of a class is
created.

3) Data abstraction & Encapsulation:


The wrapping up of data and its functions into a single unit is called Encapsulation.

When using Data Encapsulation, data is not accessed directly, it is only accessible through the
functions present inside the class.

Data Abstraction increases the power of programming language by creating user defined data types.
Data Abstraction also represents the needed information in the program without presenting the details.

Abstraction refers to the act of representing essential features without including the background details
or explanation between them.

Prepared by,
34

For example, a class Car would be made up of an Engine, Gearbox, Steering objects, and many more
components. To build the Car class, one does not need to know how the different components work
internally, but only how to interface with them, i.e., send messages to them, receive messages from
them, and perhaps make the different objects composing the class interact with each other.

4) Inheritance:
Inheritance is the process of forming a new class from an existing class or base class.

The base class is also known as parent class or super class, the new class that is formed is called derived
class.

Derived class is also known as a child class or sub class. Inheritance helps in reducing the overall code
size of the program, which is an important concept in object-oriented programming.

It is classifieds into different types, they are

Single level inheritance


Multi-level inheritance
Hybrid inheritance
Hierarchial inheritance

5) Polymorphism:
Polymorphism allows routines to use variables of different types at different times. An operator or
function can be given different meanings or functions. Polymorphism refers to a single function or
multi-functioning operator performing in different ways.

Poly, a Greek term, means ability to take more than one form. Overloading is one type of Polymorphism.
It allows an object to have different meanings, depending on its context. When an exiting operator or
function begins to operate on new data type, or class, it is understood to be overloaded.

6) Dynamic binding:
It contains a concept of Inheritance and Polymorphism.

7) Message Passing:
It refers to that establishing communication between one place to another.

5. Explain branching and looping statements of Java with example. (16)

BRANCHING STATEMENTS

The next step up from using the simple operators we saw in Day 2 is to use branching statements in your
code. You use branching statements to make decisions based on the value of your data, and to make the
flow of the program go in different directions accordingly.

There are two branching statements in Javathe if statement, and the switch statement.

Prepared by,
35

The if Statement

When you want to test conditions and execute code accordingly, it's a good idea to use a statement like
the if statement. Here's how you use this statement in general:

if (condition) statement1;
[else statement2;]

If condition evaluates to true, statement1 is executed. Otherwise, if there is an else clause to the
statement, the code in it (statement2) is executed.

In Java, statement1 and statement2 can both be compound statements, which means that they can be
made up of a number of statements enclosed in curly braces, like this:

if (condition){
statement;
statement;
.
.
.
}
else {
statement;
statement;
.
.
.
}

Let's take a look at some examples to see how this works. For example, what if you wanted to find the
absolute value of a number? One way to get an absolute value is to start by checking whether the value
is greater than 0, and if so, just print out the value itself. Listing 3.1 shows how to make that test with an
if statement.

The switch Statement

The switch statement is Java's multiway branch statement, and it provides the same kind of functionality
as an if-else ladder, but in a much easier form. Here's what the switch statement looks like in general:

switch (expression) {
case value1:
statement1;
[break;]
case value2:
statement2;
[break;]
case value3:

Prepared by,
36

statement3;
[break;]
.
.
.
default:
default_statement;
}

LOOPING STATEMENTS

There may be a situation when we need to execute a block of code several number of times, and is often
referred to as a loop.

Java has very flexible three looping mechanisms. You can use one of the following three loops:

while Loop
do...while Loop

for Loop

As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

The while Loop:

A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:

The syntax of a while loop is:

while(Boolean_expression)
{
//Statements
}

When executing, if the boolean_expression result is true, then the actions inside the loop will be
executed. This will continue as long as the expression result is true.

Here, key point of the while loop is that the loop might not ever run. When the expression is tested and
the result is false, the loop body will be skipped and the first statement after the while loop will be
executed.

The do...while Loop:

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least
one time.

Prepared by,
37

Syntax:

The syntax of a do...while loop is:

do
{
//Statements
}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute
once before the Boolean is tested.

If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop
execute again. This process repeats until the Boolean expression is false.

The for Loop:

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute
a specific number of times.

A for loop is useful when you know how many times a task is to be repeated.

Syntax:

The syntax of a for loop is:

for(initialization; Boolean_expression; update)


{
//Statements
}

Here is the flow of control in a for loop:

The initialization step is executed first, and only once. This step allows you to declare and initialize
any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false,
the body of the loop does not execute and flow of control jumps to the next statement past the for loop.

After the body of the for loop executes, the flow of control jumps back up to the update statement.
This statement allows you to update any loop control variables. This statement can be left blank, as long
as a semicolon appears after the Boolean expression.

The Boolean expression is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is
false, the for loop terminates.

6. Explain the various types of operators and expressions. (16)

Prepared by,
38

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into
the following groups:

Arithmetic Operators
Relational Operators

Bitwise Operators

Logical Operators

Assignment Operators

Misc Operators

The Arithmetic Operators:

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.
The following table lists the arithmetic operators:

Assume integer variable A holds 10 and variable B holds 20, then:

Operator Description Example

A + B will give
+ Addition - Adds values on either side of the operator
30

A - B will give
- Subtraction - Subtracts right hand operand from left hand operand
-10

A * B will give
* Multiplication - Multiplies values on either side of the operator
200

/ Division - Divides left hand operand by right hand operand B / A will give 2

Modulus - Divides left hand operand by right hand operand and


% B % A will give 0
returns remainder

++ Increment - Increases the value of operand by 1 B++ gives 21

-- Decrement - Decreases the value of operand by 1 B-- gives 19

The Relational Operators:

There are following relational operators supported by Java language

Assume variable A holds 10 and variable B holds 20, then:

Prepared by,
39

Operator Description Example

Checks if the values of two operands are equal or not, if yes then (A == B) is not
==
condition becomes true. true.

Checks if the values of two operands are equal or not, if values are
!= (A != B) is true.
not equal then condition becomes true.

Checks if the value of left operand is greater than the value of right (A > B) is not
>
operand, if yes then condition becomes true. true.

Checks if the value of left operand is less than the value of right
< (A < B) is true.
operand, if yes then condition becomes true.

Checks if the value of left operand is greater than or equal to the (A >= B) is not
>=
value of right operand, if yes then condition becomes true. true.

Checks if the value of left operand is less than or equal to the value
<= (A <= B) is true.
of right operand, if yes then condition becomes true.

The Bitwise Operators:

Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char,
and byte.

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; now in
binary format they will be as follows:

a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

The following table lists the bitwise operators:

Assume integer variable A holds 60 and variable B holds 13 then:

Prepared by,
40

Operator Description Example

(A & B) will give


Binary AND Operator copies a bit to the result if it exists in both
& 12 which is 0000
operands.
1100

(A | B) will give
| Binary OR Operator copies a bit if it exists in either operand. 61 which is 0011
1101

(A ^ B) will give
Binary XOR Operator copies the bit if it is set in one operand but
^ 49 which is 0011
not both.
0001

(~A ) will give


-61 which is 1100
Binary Ones Complement Operator is unary and has the effect of 0011 in 2's
~
'flipping' bits. complement form
due to a signed
binary number.

A << 2 will give


Binary Left Shift Operator. The left operands value is moved left by
<< 240 which is 1111
the number of bits specified by the right operand.
0000

Binary Right Shift Operator. The left operands value is moved right A >> 2 will give
>>
by the number of bits specified by the right operand. 15 which is 1111

Shift right zero fill operator. The left operands value is moved right A >>>2 will give
>>> by the number of bits specified by the right operand and shifted 15 which is 0000
values are filled up with zeros. 1111

The Logical Operators:

The following table lists the logical operators:

Assume Boolean variables A holds true and variable B holds false, then:

Operator Description Example

Called Logical AND operator. If both the operands are non-zero, (A && B) is
&&
then the condition becomes true. false.

|| Called Logical OR Operator. If any of the two operands are non- (A || B) is true.

Prepared by,
41

zero, then the condition becomes true.

Called Logical NOT Operator. Use to reverses the logical state of its
!(A && B) is
! operand. If a condition is true then Logical NOT operator will make
true.
false.

The Assignment Operators:

There are following assignment operators supported by Java language:

Operator Description Example

C = A + B will
Simple assignment operator, Assigns values from right side operands
= assign value of A
to left side operand
+ B into C

C += A is
Add AND assignment operator, It adds right operand to the left
+= equivalent to C =
operand and assign the result to left operand
C+A

C -= A is
Subtract AND assignment operator, It subtracts right operand from
-= equivalent to C =
the left operand and assign the result to left operand
C-A

C *= A is
Multiply AND assignment operator, It multiplies right operand with
*= equivalent to C =
the left operand and assign the result to left operand
C*A

C /= A is
Divide AND assignment operator, It divides left operand with the
/= equivalent to C =
right operand and assign the result to left operand
C/A

C %= A is
Modulus AND assignment operator, It takes modulus using two
%= equivalent to C =
operands and assign the result to left operand
C%A

C <<= 2 is same
<<= Left shift AND assignment operator
as C = C << 2

C >>= 2 is same
>>= Right shift AND assignment operator
as C = C >> 2

C &= 2 is same
&= Bitwise AND assignment operator
as C = C & 2

^= bitwise exclusive OR and assignment operator C ^= 2 is same as

Prepared by,
42

C=C^2

C |= 2 is same as
|= bitwise inclusive OR and assignment operator
C=C|2

Misc Operators

There are few other operators supported by Java Language.

Conditional Operator ( ? : ):

Conditional operator is also known as the ternary operator. This operator consists of three operands and
is used to evaluate Boolean expressions. The goal of the operator is to decide which value should be
assigned to the variable. The operator is written as:

variable x = (expression) ? value if true : value if false Following is the example:


public class Test {

public static void main(String args[]){


int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}
}

This would produce the following result:

Value of b is : 30
Value of b is : 20

7. Explain Class Libraries and Object Serialization in Java. (16)

The list of classes of package java.lang. These classes are very important to know for a Java programmer.
Click a class link to know more detail about that class. For a further drill, you can refer standard Java
documentation.

SN Methods with Description

Boolean
1
Boolean

Prepared by,
43

Byte
2
The Byte class wraps a value of primitive type byte in an object.

Character
3
The Character class wraps a value of the primitive type char in an object.

Class
4
Instances of the class Class represent classes and interfaces in a running Java application.

ClassLoader
5
A class loader is an object that is responsible for loading classes.

Compiler
6
The Compiler class is provided to support Java-to-native-code compilers and related services.

Double
7
The Double class wraps a value of the primitive type double in an object.

Float
8
The Float class wraps a value of primitive type float in an object.

Integer
9
The Integer class wraps a value of the primitive type int in an object.

Long
10
The Long class wraps a value of the primitive type long in an object.

Math
11 The class Math contains methods for performing basic numeric operations such as the
elementary exponential, logarithm, square root, and trigonometric functions.

Number
12 The abstract class Number is the superclass of classes BigDecimal, BigInteger, Byte, Double,
Float, Integer, Long, and Short.

Object
13
Class Object is the root of the class hierarchy.

Package
14 Package objects contain version information about the implementation and specification of a
Java package.

Process
15 The Runtime.exec methods create a native process and return an instance of a subclass of
Process that can be used to control the process and obtain information about it.

Runtime
16 Every Java application has a single instance of class Runtime that allows the application to
interface with the environment in which the application is running.

Prepared by,
44

RuntimePermission
17
This class is for runtime permissions.

SecurityManager
18
The security manager is a class that allows applications to implement a security policy.

Short
19
The Short class wraps a value of primitive type short in an object.

StackTraceElement
20
An element in a stack trace, as returned by Throwable.getStackTrace().

StrictMath
21 The class StrictMath contains methods for performing basic numeric operations such as the
elementary exponential, logarithm, square root, and trigonometric functions.

String
22
The String class represents character strings.

StringBuffer
23
A string buffer implements a mutable sequence of characters.

System
24
The System class contains several useful class fields and methods.

Thread
25
A thread is a thread of execution in a program.

ThreadGroup
26
A thread group represents a set of threads.

ThreadLocal
27
This class provides thread-local variables.

Throwable
28
The Throwable class is the superclass of all errors and exceptions in the Java language.

Void
29 The Void class is an uninstantiable placeholder class to hold a reference to the Class object
representing the Java keyword void.

Serializing an Object:

The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program
instantiates an Employee object and serializes it to a file.

When the program is done executing, a file named employee.ser is created. The program does not
generate any output, but study the code and try to determine what the program is doing.

Prepared by,
45

Note: When serializing an object to a file, the standard convention in Java is to give the file a .ser
extension.

import java.io.*;

public class SerializeDemo


{
public static void main(String [] args)
{
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try
{
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
}catch(IOException i)
{
i.printStackTrace();
}
}
}

Deserializing an Object:

The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo
program. Study the program and try to determine its output:

import java.io.*;
public class DeserializeDemo
{
public static void main(String [] args)
{
Employee e = null;
try
{
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println("Employee class not found");

Prepared by,
46

c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}

This would produce the following result:

Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101

8. Write short notes on Exception Handling. (16)

An exception is a problem that arises during the execution of a program. An exception can occur for
many different reasons, including the following:

A user has entered invalid data.


A file that needs to be opened cannot be found.

A network connection has been lost in the middle of communications or the JVM has run out of
memory.

Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.

To understand how exception handling works in Java, you need to understand the three categories of
exceptions:

Checked exceptions: A checked exception is an exception that is typically a user error or a problem
that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be
found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
Runtime exceptions: A runtime exception is an exception that occurs that probably could have been
avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the
time of compilation.

Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything about an
error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of
compilation.

Prepared by,
47

Exception Hierarchy:

All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of
the Throwable class. Other than the exception class there is another subclass called Error which is
derived from the Throwable class.

Errors are not normally trapped form the Java programs. These conditions normally happen in case of
severe failures, which are not handled by the java programs. Errors are generated to indicate errors
generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot
recover from errors.

Exceptions Methods:

Following is the list of important medthods available in the Throwable class.

SN Methods with Description

public String getMessage()


1 Returns a detailed message about the exception that has occurred. This message is initialized in the
Throwable constructor.

public Throwable getCause()


2
Returns the cause of the exception as represented by a Throwable object.

public String toString()


3
Returns the name of the class concatenated with the result of getMessage()

public void printStackTrace()


4
Prints the result of toString() along with the stack trace to System.err, the error output stream.

public StackTraceElement [] getStackTrace()


5 Returns an array containing each element on the stack trace. The element at index 0 represents the top of
the call stack, and the last element in the array represents the method at the bottom of the call stack.

public Throwable fillInStackTrace()


6 Fills the stack trace of this Throwable object with the current stack trace, adding to any previous
information in the stack trace.

Catching Exceptions:

A method catches an exception using a combination of the try and catch keywords. A try/catch block is
placed around the code that might generate an exception. Code within a try/catch block is referred to as
protected code, and the syntax for using try/catch looks like the following:

try
{
//Protected code

Prepared by,
48

}catch(ExceptionName e1)
{
//Catch block
}

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs
in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that
occurred is listed in a catch block, the exception is passed to the catch block much as an argument is
passed into a method parameter.

// File Name : ExcepTest.java


import java.io.*;
public class ExcepTest{

public static void main(String args[]){


try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}

This would produce the following result:

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3


Out of the block

Multiple catch Blocks:

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the
following:

try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}

The previous statements demonstrate three catch blocks, but you can have any number of them after a
single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in

Prepared by,
49

the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the
exception passes down to the second catch statement. This continues until the exception either is caught
or falls through all catches, in which case the current method stops execution and the exception is
thrown down to the previous method on the call stack.

Example:

Here is code segment showing how to use multiple try/catch statements.

try
{
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i)
{
i.printStackTrace();
return -1;
}catch(FileNotFoundException f) //Not valid!
{
f.printStackTrace();
return -1;
}

The throws/throw Keywords:

If a method does not handle a checked exception, the method must declare it using the throws keyword.
The throws keyword appears at the end of a method's signature.

You can throw an exception, either a newly instantiated one or an exception that you just caught, by
using the throw keyword. Try to understand the different in throws and throw keywords.

The following method declares that it throws a RemoteException:

import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}

A method can declare that it throws more than one exception, in which case the exceptions are declared
in a list separated by commas. For example, the following method declares that it throws a
RemoteException and an InsufficientFundsException:

import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,

Prepared by,
50

InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}

The finally Keyword

The finally keyword is used to create a block of code that follows a try block. A finally block of code
always executes, whether or not an exception has occurred.

Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter
what happens in the protected code.

A finally block appears at the end of the catch blocks and has the following syntax:

try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}

Example:
public class ExcepTest{

public static void main(String args[]){


int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}
}
}

This would produce the following result:

Prepared by,
51

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3


First element value: 6
The finally statement is executed

Note the following:

A catch clause cannot exist without a try statement.


It is not compulsory to have finally clauses when ever a try/catch block is present.

The try block cannot be present without either catch clause or finally clause.

Any code cannot be present in between the try, catch, finally blocks.

Declaring you own Exception:

You can create your own exceptions in Java. Keep the following points in mind when writing your own
exception classes:

All exceptions must be a child of Throwable.


If you want to write a checked exception that is automatically enforced by the Handle or Declare
Rule, you need to extend the Exception class.

If you want to write a runtime exception, you need to extend the RuntimeException class.

We can define our own Exception class as below:

class MyException extends Exception{


}

You just need to extend the Exception class to create your own Exception class. These are considered to
be checked exceptions. The following InsufficientFundsException class is a user-defined exception that
extends the Exception class, making it a checked exception. An exception class is like any other class,
containing useful fields and methods.

Example:
// File Name InsufficientFundsException.java
import java.io.*;

public class InsufficientFundsException extends Exception


{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}

Prepared by,
52

To demonstrate using our user-defined exception, the following CheckingAccount class contains a
withdraw() method that throws an InsufficientFundsException.

// File Name CheckingAccount.java


import java.io.*;

public class CheckingAccount


{
private double balance;
private int number;
public CheckingAccount(int number)
{
this.number = number;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount) throws
InsufficientFundsException
{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance()
{
return balance;
}
public int getNumber()
{
return number;
}
}The following BankDemo program demonstrates invoking the deposit() and withdraw()
methods of CheckingAccount.// File Name BankDemo.java
public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try
{
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("Sorry, but you are short $"

Prepared by,
53

+ e.getAmount());
e.printStackTrace();
}
}
}

Compile all the above three files and run BankDemo, this would produce the following result:

Depositing $500...

Withdrawing $100...

Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)

UNIT-V : JAVA PROGRAMMING

1. Design an application to illustrate interface and packages. (ND12)(16)


Create a package called animals. It is common practice to use lowercased names of packages to avoid
any conflicts with the names of classes, interfaces.
Put an interface in the package animals:
/* File name : Animal.java */
package animals;

interface Animal {
public void eat();
public void travel();
}
Now, put an implementation in the same package animals:
package animals;

/* File name : MammalInt.java */


public class MammalInt implements Animal{

public void eat(){


System.out.println("Mammal eats");
}

public void travel(){


System.out.println("Mammal travels");
}

public int noOfLegs(){


return 0;
}

public static void main(String args[]){


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

Prepared by,
54

Now, you compile these two files and put them in a sub-directory called animals and try to run as
follows:
$ mkdir animals
$ cp Animal.class MammalInt.class animals
$ java animals/MammalInt
Mammal eats
Mammal travels

2. Create a web application for shopping cart using the appropriate web technologies.(ND12)(16)

To develop a java based, database driven web application, you generally use several technologies and
frameworks that work together to handle different aspects of enterprise applications.

Here are a few hypothetical technology stacks that might be used together:

Stack 1

Tomcat (Web Server / Servlet Container)


Spring (Framework)
Hibernate (ORM)
Oracle (database)
JSP (front end)

Stack 2

GlassFish (Application Server)


EJB (Framework)
JPA (ORM)
MySQL (database)
JSF / PrimeFaces (front end)

Stack 3

JBoss (Application Server)


Seam (Framework)
JPA / EJB (ORM / persistence)
PostgreSQL (database)
JSF / ICEFaces (front end)

Prepared by,
55

Create the Java Classes to Support Shopping Cart - Cart and CartItem

The CartItem class models individual item placed inside the shopping cart. In our e-bookstore, we need to
keep track of the id, title, author, price and quantity ordered.
1package mypkg;
2
3/**
4 * The class CartItem models an item in the Cart.
5 * This class shall not be accessed by the controlling logic directly.
6 * Instead Use Cart.add() or Cart.remove() to add or remove an item from the Cart.
7 */
8public class CartItem {
9
10 private int id;
11 private String title;
12 private String author;
13 private float price;
14 private int qtyOrdered;
15
16 // Constructor
17 public CartItem(int id, String title,

Prepared by,
56

18 String author, float price, int qtyOrdered) {


19 this.id = id;
20 this.title = title;
21 this.author = author;
22 this.price = price;
23 this.qtyOrdered = qtyOrdered;
24 }
25
26 public int getId() {
27 return id;
28 }
29
30 public String getAuthor() {
31 return author;
32 }
33
34 public String getTitle() {
35 return title;
36 }
37
38 public float getPrice() {
39 return price;
40 }
41
42 public int getQtyOrdered() {
43 return qtyOrdered;
44 }
45
46 public void setQtyOrdered(int qtyOrdered) {
47 this.qtyOrdered = qtyOrdered;
48 }
49}

The Cart class stores the items in a List of CartItem. It also provides these public methods:
add(): Add a item into the card. It checks if the id is already in the cart. If so, it adjust the
quantity ordered. Otherwise, it creates a new CartItemand adds to the ArrayList.
update(): Update the quantity order for the given book's id.
remove(): Remove a particular item from the shopping cart, identified via the book's id.
isEmpty(): Return true if the cart is empty.
size(): Return the number of items in the shopping cart.
getItems(): Return all the items of the shopping cart in a List<CartItem>.
clear(): Empty the contents of the shopping cart.

Prepared by,
57

3. Explain JDBC connectivity and the drives with an example. (16)


Creating JDBC Application:
There are following six steps involved in building a JDBC application:
Import the packages . Requires that you include the packages containing the JDBC classes
needed for database programming. Most often, using import java.sql.* will suffice.
Register the JDBC driver . Requires that you initialize a driver so you can open a
communications channel with the database.
Open a connection . Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with the database.
Execute a query . Requires using an object of type Statement for building and submitting an
SQL statement to the database.
Extract data from result set . Requires that you use the appropriate ResultSet.getXXX() method
to retrieve the data from the result set.
Clean up the environment . Requires explicitly closing all database resources versus relying on
the JVM's garbage collection.
Sample Code:
This sample example can serve as a template when you need to create your own JDBC application in
the future.
This sample code has been written based on the environment and database setup done in previous
chapter.
Copy and past following example in FirstExample.java, compile and run as follows:
//STEP 1. Import required packages
import java.sql.*;

public class FirstExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection


System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query


System.out.println("Creating statement...");
stmt = conn.createStatement();

Prepared by,
58

String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);

//STEP 5: Extract data from result set


while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");

//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
Now let us compile above example as follows:
C:\>javac FirstExample.java

Prepared by,
59

C:\>
When you run FirstExample, it produces following result:
C:\>java FirstExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>

4. How to add controls and menus in Java? Explain with example. (16)

This example shows how to construct menus in Java. The main Menu "File" contains three subitems.
Each item can be accessed by a mouse click or by its keyboard mnemonic. Once a subitem is clicked a
message is displayed explaining wich subitem was clicked.

import javax.swing.*;
import java.awt.event.*;
public class Menu extends JFrame{
public Menu()
{
super("Menu example");

JMenu file = new JMenu("File");


file.setMnemonic('F');
JMenuItem newItem = new JMenuItem("New");
newItem.setMnemonic('N');
file.add(newItem);
JMenuItem openItem = new JMenuItem("Open");
openItem.setMnemonic('O');
file.add(openItem);
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('x');
file.add(exitItem);

//adding action listener to menu items


newItem.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("New is pressed");
}
}
);
openItem.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("Open is pressed");
}
}
);
exitItem.addActionListener(

Prepared by,
60

new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("Exit is pressed");
}
}
);
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
bar.add(file);

getContentPane();
setSize(200, 200);
setVisible(true);
}

public static void main(String[] args)


{
Menu app = new Menu();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

5. Write short notes on Swing and Applet in Java. (16)


Following example demonstrates how to go use Swing Applet in JAVA by implementing ActionListener
& by creating JLabels.
import javax.swing.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class SApplet extends Applet implements ActionListener {


TextField input,output;
Label label1,label2;
Button b1;
JLabel lbl;
int num, sum = 0;
public void init(){
label1 = new Label("please enter number : ");
add(label1);
label1.setBackground(Color.yellow);
label1.setForeground(Color.magenta);
input = new TextField(5);
add(input);
label2 = new Label("Sum : ");
add(label2);
label2.setBackground(Color.yellow);
label2.setForeground(Color.magenta);
output = new TextField(20);
add(output);
b1 = new Button("Add");
add(b1);
b1.addActionListener(this);
lbl = new JLabel("Swing Applet Example. ");
add(lbl);
setBackground(Color.yellow);
}

Prepared by,
61

public void actionPerformed(ActionEvent ae){


try{
num = Integer.parseInt(input.getText());
sum = sum+num;
input.setText("");
output.setText(Integer.toString(sum));
lbl.setForeground(Color.blue);
lbl.setText("Output of the second Text Box : "
+ output.getText());
}
catch(NumberFormatException e){
lbl.setForeground(Color.red);
lbl.setText("Invalid Entry!");
}
}
}
Result:
The above code sample will produce the following result in a java enabled web browser.
View in Browser.

Java Swing Example

Below is a java swing code for the traditional Hello World program.

Basically, the idea behind this Hello World program is to learn how to create a java program, compile and
run it. To create your java source code you can use any editor( Text pad/Edit plus are my favorites) or you
can use an IDE like Eclipse.

import javax.swing.JFrame;
import javax.swing.JLabel;

//import statements
//Check if window closes automatically. Otherwise add suitable code
public class HelloWorldFrame extends JFrame {

public static void main(String args[]) {


new HelloWorldFrame();
}
HelloWorldFrame() {
JLabel jlbHelloWorld = new JLabel("Hello World");
add(jlbHelloWorld);
this.setSize(100, 100);
// pack();
setVisible(true);
}

Output

Prepared by,
62

6. Explain JFrame and Frames in Java with sample java program. (16)

A Frame is a top-level window with a title and a border. The size of the frame includes any area
designated for the border. The dimensions of the border area may be obtained using the getInsets
method. Since the border area is included in the overall size of the frame, the border effectively obscures
a portion of the frame, constraining the area available for rendering and/or displaying subcomponents to
the rectangle which has an upper-left corner location of (insets.left, insets.top), and has a size of
width - (insets.left + insets.right) by height - (insets.top + insets.bottom).

A frame, implemented as an instance of the JFrame class, is a window that has decorations such as a
border, a title, and supports button components that close or iconify the window. Applications with a
GUI usually include at least one frame. Applets sometimes use frames, as well.

Example:-

The following FrameDemo code shows how to create and set up a frame.

//1. Create the frame.


JFrame frame = new JFrame("FrameDemo");

//2. Optional: What happens when the frame closes?


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//3. Create components and put them in the frame.


//...create emptyLabel...
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);

//4. Size the frame.


frame.pack();

//5. Show it.


frame.setVisible(true);

Prepared by,
63

7. Design an application to illustrate OPAC search using JDBC connection. (16)

Creating JDBC OPAC Search:


There are following six steps involved in building a JDBC application:
Import the packages . Requires that you include the packages containing the JDBC classes
needed for database programming. Most often, using import java.sql.* will suffice.
Register the JDBC driver . Requires that you initialize a driver so you can open a
communications channel with the database.
Open a connection . Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with the database.
Execute a query . Requires using an object of type Statement for building and submitting an SQL
statement to the database.
Extract data from result set . Requires that you use the appropriate ResultSet.getXXX() method to
retrieve the data from the result set.
Clean up the environment . Requires explicitly closing all database resources versus relying on
the JVM's garbage collection.
Sample Code:
This sample example can serve as a template when you need to create your own JDBC application in
the future.
This sample code has been written based on the environment and database setup done in previous
chapter.
Copy and past following example in FirstExample.java, compile and run as follows:
//STEP 1. Import required packages
import java.sql.*;

public class FirstExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection


System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query


System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);

Prepared by,
64

//STEP 5: Extract data from result set


while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");

//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
Now let us compile above example as follows:
C:\>javac FirstExample.java
C:\>
When you run FirstExample, it produces following result:
C:\>java FirstExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>

8. Write a Java program to establish Applet to Applet Communication. (16)

Prepared by,
65

Applet Communication

java.applet.AppletContext class provides the facility of communication between applets. We provide the
name of applet through the HTML file. It provides getApplet() method that returns the object of Applet.

Syntax:

public Applet getApplet(String name){}

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class ContextApplet extends Applet implements ActionListener{
Button b;

public void init(){


b=new Button("Click");
b.setBounds(50,50,60,50);

add(b);
b.addActionListener(this);
}

public void actionPerformed(ActionEvent e){

AppletContext ctx=getAppletContext();
Applet a=ctx.getApplet("app2");
a.setBackground(Color.yellow);
}
}

myapplet.html
<html>
<body>
<applet code="ContextApplet.class" width="150" height="150" name="app1">
</applet>

<applet code="First.class" width="150" height="150" name="app2">


</applet>
</body>
</html>

Prepared by,

You might also like