Internet and Java QB 16marks Answers
Internet and Java QB 16marks Answers
DHANALAKSHMI COLLEGE OF
ENGINEERING
CHENNAI
ENGINEERING
QUESTION BANK
PREPARED BY,
Prepared by,
2
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.
Prepared by,
3
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.
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
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 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 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 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.
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)
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).
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.
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.
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
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.
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.
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.
1.Initiation
2.Sharing
3.Updating
Prepared by,
14
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.
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>
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>
value="Reset"></tr>
</table>
</form>
</center>
</body>
</html>
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.
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.
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
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
Prepared by,
24
</helptopic>
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>
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:-
Prepared by,
28
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.
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:
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:
Prepared by,
29
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;
}
Now provide the implementation of the remote interface. For providing the implementation of the
Remote interface, we need to
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();
}
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
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
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.
In this example, we are binding the remote object by the name sonoo.
import java.rmi.*;
import java.rmi.registry.*;
}catch(Exception e){System.out.println(e);}
}
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{
Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
System.out.println(stub.add(34,4));
}catch(Exception e){}
}
}
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 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
Prepared by,
32
Constants Description
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.
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.
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.
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.
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 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.
A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:
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.
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:
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.
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 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.
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
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.
The following table lists the arithmetic operators:
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
Prepared by,
39
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.
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 = 1100 0011
Prepared by,
40
(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
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
Assume Boolean variables A holds true and variable B holds false, then:
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
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.
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
Prepared by,
42
C=C^2
C |= 2 is same as
|= bitwise inclusive OR and assignment operator
C=C|2
Misc Operators
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:
Value of b is : 30
Value of b is : 20
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.
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.*;
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);
}
}
Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101
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 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:
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.
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:
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;
}
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.
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 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{
Prepared by,
51
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.
You can create your own exceptions in Java. Keep the following points in mind when writing your own
exception classes:
If you want to write a runtime exception, you need to extend the RuntimeException class.
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.*;
Prepared by,
52
To demonstrate using our user-defined exception, the following CheckingAccount class contains a
withdraw() method that throws an InsufficientFundsException.
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)
interface Animal {
public void eat();
public void travel();
}
Now, put an implementation in the same package animals:
package animals;
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
Stack 2
Stack 3
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
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
// Database credentials
static final String USER = "username";
static final String PASS = "password";
Prepared by,
58
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//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");
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);
}
Prepared by,
61
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 {
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.
Prepared by,
63
// Database credentials
static final String USER = "username";
static final String PASS = "password";
Prepared by,
64
//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:\>
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:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class ContextApplet extends Applet implements ActionListener{
Button b;
add(b);
b.addActionListener(this);
}
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>
Prepared by,