Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

B.E/B.

TECH DEGREE EXAMINATION Nov/Dec 2006


Seventh semester

Computer Science and Engineering


CS 1401 - Internet Programming
(Regulation 2004)
Time: 3 hours Maximum marks: 100

Answer ALL questions


PART A (10 x 2 =20 marks)

1.What do you mean by IRC? Why it is more powerful in the internet?


Internet Relay Chat is a system for chatting that involves a set of rules and convention and
client/server software. It is an open protocol that uses TCP and optionally TLS.
It enables the people all over the world to talk together over the Internet in real-time
sessions in virtual room. Unlike older chat system, IRC is not limited to just two participants.
2. How to avoid the email viruses?
Many of the most common computer viruses are spread through e-mail attachments – the
files that are sent along with an e-mail message. Follow these basic guidelines when dealing
with attachments in an e-mail message.
1. Don’t open any attachment unless you know whom it’s from and you were expecting
it.
2. If you receive an e-mail message with an attachment from someone you don’t know,
delete it immediately.
3. Use anti-virus software and keep it update. Windows Live one care. Scans e-mail
attachments as you open them.
4. If you need to send an e-mail attachment to someone, let them know you’ll be
sending it so they don’t think it’s a virus.
5. Use an e-mail program with spam filtering built-in such as MS Office Outlook 2007,
Windows Live Hotmail or Windows Live Mail.
3. What are the standardized video file formats used on the web? List the safest file formats
1.Real Media
2. MPEG-1 or MPEG-2
3. Apple QuickTime
4. Audio Video Interleave
ts for short video clip, down load and play delivery?

1.Real Media
2. MPEG-1 or MPEG-2
3. Apple QuickTime
4. Audio Video Interleave
ts for short video clip, down load and play delivery?
4.List out any four graphics software which are used frequently on the web?
• Flash Pro
• Photo Shop
• Dream weaver
• Creative Suite 3 Web Editions
5.How do you implement a multiple and multilevel inheritance concept in java?
In java multiple inheritance is implemented only by using interface. A class can implements
more than one interface. Multi level inheritance is perfectly acceptable to use a subclass as a
super class of another.
6.What is the use of finally keyword?
finally keyword is used to handle the Exception. A finally block encloses code that is always
executed at some point after the try block, whether an exception was thrown or not. Finally
block is the right place to close the files, release the network sockets, and perform any other
cleanup processes which are required by the code.
7.. what is runnable interface? How it can implemented in java?
The Runnable interface should be implemented by any class whose instances are intended to
be executed by a thread. The class must define a method of no arguments called run. This
interface is designed to provide a common protocol for objects that wish to execute code
while they are active.
Implementation of Runnable interface in Java includes the following steps.
1. Declare the class as implementing the Runnable interface.
2. Implement the run () method
3. Create the thread and call the start ( ) method to run the thread.
8. Define delegation event model? Write the advantages of it?
Event types are encapsulated in a class hierarchy rooted at java.util.EventObject. An event is
propagated from a "Source" object to a "Listener" object by invoking a method on the
listener and passing in the instance of the event subclass which defines the event type
generated.
Advantages:
1. Provide a more robust framework to support more complex java programs.
2. Support a clean separation between application and GUI code
9. What do you mean by stubs in the context of RMI?
A stubis a Java object that resides on the client machine. Its function is to present the same
interfaces as the remote server. Remote method calls initiated by the client are actually
directed to the stub. The stub works with the other parts of the RMI system to formulate a
request that is sent to the remote machine.
10.What is inner class? Explain with an example?
Inner classes are a type of class and follow most of the same rules
as a normal class. The main difference is an inner class is declared within the curly braces of
a class or even within a method. Inner classes are also classes defined at a scope smaller than
a package.
class MyOuter {
private int x = 7;
public void makeInner () {
MyInner in = new MyInner (); // make an inner instance
in.seeOuter ();
}
class MyInner {
public void seeOuter () {
System.out.println ("Outer x is " + x);
}
}
}

PART B (5 x 16 = 80)

11. (a) (i) Explain Domain name system and sub domains in detail with
suitable example? (8)
• A hierarchical system of naming hosts and placing the TCP/IP hosts into categories.
The DNS is a way of translating numerical Internet addresses into word strings to
computer and network names. For example, the host name rs.internic.net is also
known as 198.41.0.13.
• Any machine on the Internet has its own address, called the Internet Protocol Address
(IP Address). The IP address looks something like this: 123.123.123.123 four
numerical segments with a value range between 0 and 255 (one byte) separated by
dots. Any computer is reachable through its IP address.
• Because users cannot remember these numerical strings of IP addresses, an
alternative system was needed. For this reason, IP addresses were translated into
more logical text strings for humans to remember, such as cs.yale.edu which means
computer science department at Yale University, a U.S. educational institution.
• Thus, the DNS (Domain Name System) was invented a hierarchical domain-based
structure in which the Internet is divided into pieces called domains. The pieces are
categorized as top-level domains and sub-domains. The top-level domains include
generic and country domains.
• The generic domains are com (a commercial enterprise), edu (an educational
institution), gov (a government agency), int (an international institution), mil (the
military institutions), net (a network institution), and org (a nonprofit organization).
The country domains, allocated one per country, look like this: au for Australia, ca for
Canada, uk for the United Kingdom, and us for the United States. The details are
defined in ISO 3166.
Each top-level domain is divided into several sub-domains, with each domain having
control over its own sub-domains. For example, the edu domain covers all of the
educational institutions or sub-domains such as Yale University, Princeton
University, Rutgers University, and Harvard University. Moreover, the country
domains have sub-domains. For example, the uk (the United Kingdom) and the jp
(Japan) domains have two common sub-domains: ac (which stands for academic) and
com (which stands for commercial). Each domain has a particular server with a table
containing all IP addresses and domain names belonging to its domain.
• An organization called the Internic maintains a database having all registered
domains for the world. Anyone can query its database by means of whois. Although
several organizations maintain whois databases, the Internic has the main database.
Any company, institution, or organization wanting to have its own domain name has
to register it with the Internic or one of the other registries.
>
(ii) Discuss spam protection and Usenet group in detail with suitable example. (8)
Spam Protection
Spam Protection helps to shield the email address from spammers. When someone wants to
email you, instead of using the mailto: tag, because SPAM robots look for that tag in html,
which can use a regular link tag instead. This program helps to conceal the address from
spammers, but allowing legitimate visitors to email.

Features:
• Very simple to setup.
• Protects your email address from SPAM Robots.
• Works with any email address.
• No banners on script.
Usenet:
USENET is a worldwide system of discussion groups in which millions of
people participate. There are tens of thousands of different Usenet groups, and anyone on the
Internet may participate for free.
Usenet was originally designed to carry local news between two universities in North
Carolina. For this reason, Usenet groups are often referred to as NEWSGROUPS, even
though, today, they are used as public forums for discussions. Similarly, Usenet itself is
sometimes referred to as THE NEWS or NETNEWS.
Within each newsgroup, people send messages, called ARTICLES, for other people to read.
Once an article is sent to a group, anyone in the world may read it. Each Usenet group has a
unique name. The name consists of two or more parts, separated by periods.
Usenet is one of the oldest computer network communications systems still in
widespread use. It was established in 1980, following experiments from the previous year,
over a decade before the World Wide Web was introduced and the general public got access
to the Internet. It was originally conceived as a "poor man's ARPANET," employing UUCP
to offer mail and file transfers, as well as announcements through the newly developed news
software.
(or)
(b) (i) What are the minimum hardware and software requirements needed to
connect to the internet? (6)
Hardware Requirements
Processor
The Internet keeps pace with advancing technologies. Many web pages now include
multimedia elements and virtual reality. These sites require that the system must be using, at
least, a Pentium or higher processor. However, it can get by with a 486 processor.
Memory
A general rule is that if the system has enough memory to run operating system, it should
have enough for basic Internet use. Windows95 requires 16 MB of RAM to run relatively
smoothly.
Hard Drive
Currently, to run Microsoft's Internet Explorer (4.0), it can get by with about 30 MB of free
hard drive space. This does not include the room needed for other Internet applications.
Using the bigger hard drive it is possible to download and save more contents.
Video Card
While it is true that to read the e-mail the video card is not needed, in order to visit some of
the more graphically rich sites it is essential. The video card should be able to display SVGA
resolution with at least 256 colors.
Sound Card & Speakers
Sound card is not needed to read the e-mail, but if the browser wants to take advantage of
many of the Internet's offerings it will need one. It will need a basic 16-bit sound board and a
cheap set of speakers.
Modem
Last but certainly not least is the modem. Without it, the browser will not be doing anything
on the Internet. 14,400 bps modems are fairly common but the de facto standard has become
28,800 bps (usually seen as 28.8 kbps) modems.
Software Requirements
Two types of software is needed to get on the Internet.
1. An application that is going to uses the resources of the Internet.
2. A browser for surfing the web, an e-mail program, an FTP program. Microsoft Internet
Explorer is an Internet Suite.

(ii) Explain the following terms with suitable example:


1) Online chatting and video conferencing (4)
Online chatting
Online chat can refer to any kind of communication over the Internet, but is
primarily meant to refer to direct one-on-one chat or text-based group chat (formally also
known as synchronous conferencing), using tools such as instant messaging applications—
computer programs, Internet Relay Chat, talkers and possibly MUDs, MUCKs, MUSHes and
MOOes. The expression online chat comes from the word chat which means "informal
conversation".
Video conferencing
In videoconferencing technology, two or more people at different locations can see and hear
each other at the same time, sometimes even sharing computer applications for collaboration.
Videoconferencing offers possibilities for schools, colleges, and libraries to use these
systems for a variety of purposes, including formal instruction (courses, lessons, and
tutoring), connection with guest speakers and experts, multi-school project collaboration,
professional activities, and community events.
Placing a video call is a lot like placing a telephone call. After the connection establishment,
one person can see the other person in color video on a TV screen and may be able to transfer
files or collaborate via options such as document sharing or white boarding.
2) Different compression formats for audio and video files (6) Different compression
formats for audio and video files
The different Audio Compression formats
16-bit PCM
Original source material is uncompressed. 8-bit sampling is possible, but the dynamic range
is much lower; 24-bit and 32-bit also exist but are rarely supported. PCs use the
Microsoft .WAV format; Macs and Unix use the .AIFF format.
ADPCM
ADPCM (Adaptive Differential Pulse Code Modulation) comes in many varieties. There is
the IMA (Interactive Multimedia Association) DVI standard, the ITU (formerly CCITT)
standards G.726 and G.727 which supercede the earlier G.721 and G.723 standards, and
proprietary versions from Microsoft, Creative Labs, Yamaha and Oki. There is also Sub-
Band ADPCM (G.722) which is used for audio on ISDN phone lines.
InterWave
InterWave is a proprietary encoding format created by VocalTec. It is designed specifically
for real-time audio on the Internet and features a friendly user interface and very rapid
encoding times.
The different Video Compression formats

There are several Video Compression formats in use today, including the most popular,
MPEG-1 and MPEG-2.

MPEG-1 is a low quality (think VHS on extended play mode) Video Compression format
that is used for capturing video for various applications.
MPEG-1 is used for capturing video to be played back in computer programs, such as
Microsoft PowerPoint presentations, and for recording video to a CD-R or CD-RW (a
VideoCD) disc.
MPEG-2 is the Video Compression format used for Digital Video Recorders and DVD and
the quality is much better than MPEG-1. When creating DVDs on PC, this is the format to
use for DVD discs.

Other Video Compression formats include, AVI, MPEG-4, DivX, Quicktime, Windows
Media Video (WMV) and RealVideo (RM).
12. (a) (i) discuss the following terms in detail with suitable example (4 + 4)

1. FTP
FTP:
The FTP (File Transfer Protocol) utility program is commonly used for copying files to and
from other computers. These computers may be at the same site or at different sites
thousands of miles apart. FTP is a general protocol that works on UNIX systems as well as a
variety of other (non-UNIX) systems.
For the purposes of this web page, the local machine refers to the machine in which the user
initially logged into, the one on which user type the ftp command. The remote machine is the
other one, the one that is the argument of the ftp command.
A user interface for the standard File Transfer Protocol for ARPANET, FTP acts as an
interpreter to perform desired actions on the remote machine.
Most operating systems and communication programs now include some form of an FTP
utility program, but the commands differ slightly between them.
To connect the local machine to the remote machine, type
ftp machine name
machine name – It is the full machine name of the remote machine
e.g.: srec.edu.If the name of the machine is unknown, user can type

ftp machine number


machine number – It is the net/IP address of the remote machine
e.g.: 129.82.45.181.This command is similar to logging onto the remote machine. If the
remote machine has been reached successfully. FTP responds by asking for a login name and
password. When the user enters login name and password for the remote machine, it returns
the prompt ftp>
and permits the user to access home directory on the remote machine. User should be able to
move around the home directory and to copy files to and from local machine using the FTP
interface commands.
2. Web page editors
Web page editors:
This is a program that the designer uses to create Web pages. It can be something as simple
as the text editor that came with the computer or it can be something that creates the page
right in front of the designer and point him to click away.
If the designer likes to design the pages using HTML then the page will probably use a text
editor of some sort. They come with a wide variety of options including templates, spell
checkers, color coding and much more.
If the page doesn’t use HTML or if the simple page is created quickly, then it will probably
use something more complex. Editors like FrontPage and Composer are easy to use but don't
allow the page to add complex things such as JavaScript and DHTML without using their
text editor option.
WYSIWYG (what- you -see -is -what- you -get) editors are set up so that the users can see
the effects of the tags used in HTML without having to deal with coding "by hand".

(ii) (1) What are the Basic concepts to be considered while creating a new web
page? Give example.
There are basically two ways to make a web page. The first way is to create the page(s)
offline and then upload them to the Internet Service Provider (ISP) via FTP. The second way
is to create the web page(s) online using a Telnet program by accessing the UNIX account.
If the web page(s) are created in offline, it can use any text editing or word processing
document. The document must be saved as a "text", "plain text" or "text only" document.
Otherwise it will not be read properly by a web browser. Once the page(s) are created, the
designer will need to contact the ISP about how to go about uploading them to the server.
Discover the theme or content of the site.
2. Determine what type of tools which must be used to create the web pages.
3. Learn HTML or the editing software
4. Find a place to put the page.
5. Let people know about the site.
<html>
<form action="home.jsp" method="post">
<body>
Welcome to HTML<br>
<table>
<tr><td>UserName</td><td><input type="text" name="uname"></td></tr>

<tr><td>Password</td><td><input type="password"
name="pass"></td></tr>
<tr><td><input type="submit" value="Click"></td></tr>
</table></body>
</html>

(2) Discuss how to block a particular web site and web page? (4+4)
Blocking a website:
Internet Explorer version 5 and later offer the ability for heighten security and privacy. A
web site can be blocked by following the directions below:

1. Load the Internet explorer


2. Click Tools
3. Click Internet Options
4. Click the Privacy tab
5. Under the Privacy window, Click Sites
6. Type in the site addresses that, the website which is to be Blocked and Click OK.
Note that the website address to be typed in all forms. For example, to restrict the site
yahoo.com it should be written as 3 entries as follows.

yahoo.com
www.yahoo.com
http://www.yahoo.com
Blocking Web page without using any software
Step 1 : Browse C:\WINDOWS\system32\drivers\etc
Step 2 : Find the file named “HOSTS”
Step 3 : Open it in notepad
Step 4 : Under “127.0.0.1 localhost” Add 127.0.0.2 www.sitenameyouwantblocked.com ,
and that site will no longer be accessable.
Step 5 : Done!
(2) Discuss how to block a particular web site and web page? (4+4) There are
basically two ways to make a web page. The first way is to create the page(s) offline and then
upload them to the Internet Service Provider (ISP) via FTP. The second way is to create the
web page(s) online using a Telnet program by accessing the UNIX account.
If the web page(s) are created in offline, it can use any text editing or word processing
document. The document must be saved as a "text", "plain text" or "text only" document.
Otherwise it will not be read properly by a web browser. Once the page(s) are created, the
designer will need to contact the ISP about how to go about uploading them to the server.
Discover the theme or content of the site.
2. Determine what type of tools which must be used to create the web pages.
3. Learn HTML or the editing software
4. Find a place to put the page.
5. Let people know about the site.
<html>
<form action="home.jsp" method="post">
<body>
Welcome to HTML<br>
<table>
<tr><td>UserName</td><td><input type="text" name="uname"></td></tr>

<tr><td>Password</td><td><input type="password"
name="pass"></td></tr>

<tr><td><input type="submit" value="Click"></td></tr>


</table></body>
</html>

(2) Discuss how to block a particular web site and web page? (4+4)
Blocking a website:
Internet Explorer version 5 and later offer the ability for heighten security and privacy. A
web site can be blocked by following the directions below:

1. Load the Internet explorer


2. Click Tools
3. Click Internet Options
4. Click the Privacy tab
5. Under the Privacy window, Click Sites
6. Type in the site addresses that, the website which is to be Blocked and Click OK.
Note that the website address to be typed in all forms. For example, to restrict the site
yahoo.com it should be written as 3 entries as follows.

yahoo.com
www.yahoo.com
http://www.yahoo.com
Blocking Web page without using any software
Step 1 : Browse C:\WINDOWS\system32\drivers\etc
Step 2 : Find the file named “HOSTS”
Step 3 : Open it in notepad
Step 4 : Under “127.0.0.1 localhost” Add 127.0.0.2 www.sitenameyouwantblocked.com ,
and that site will no longer be accessable.
Step 5 : Done!
(or)

(b) Create a web site which announces about an international conference on “Net work and
mobile computing” which will be conducted by Anna university on Nov 2006.Following are
the concepts to be incorporated in to your web pages.
i) Audio and video concepts.
ii) Call for paper must be linked and present in the form.
iii) Use web graphics for university logo.
iv) Provide security to see viewers list
v) Play music when the user enters into a home page.
Conference.html
<html>
<head>
<title><font color="#76355" size=14 >Network and Mobile
computing</font></title>
</head>
<body background="C:\Program Files\Apache Software Foundation\Tomcat
5.5\webapps\TwoLevelFullEncryption\Pic\exptextb.jpg">
<marquee><img src="C:\Completed
Projects\OnlineBooking\images\temp02.gif"></marquee>
<blink>Network and Mobile Computing Conference You can also submit the
Paper</blink>
<p>Anna university welcomes you to the Network and Mobile Computing
conference that to be held on Nov 2006.
To see the viewer's list login here</p>
<form action "check.jsp" method="post" >
User name :< input type="text" name="user"><br>
Password :< input type="text" name="pwd"><br>
<input type="submit" value="click">
</form>
<a href="home.html"> Back to home</a>
</body>
</html>
home.html
<html>
<head>
<title>Anna University</title>
</head>
<body>
<h1>Welcome to Anna University</h1>
<embed src="anna.wau" autostart=true>
</embed>
<a href="conference.html">confrence</a>
</body>
</html>
13. (a) (i) Write similarities and dissimilarities of this and super (4)
Similarities of this and super
1. this and super are used to invoke the constructors. Dissimilarities of this and super
2. super () invokes the constructor in the base class whereas this () invokes a constructor
in the same class definition.
3. 'this' is used for pointing the current class instance. ‘super' is used for pointing the
super class instance.
4. super keyword is used for accessing the super class variable.
It can be used with variables or methods. this is instance of a class it cannot be used inside a
static method

(ii) Mention any four uses of packages (4)


The uses of packages are
1. It shows that the classes and interfaces in the package are related.
Often a group of classes and interfaces are related according to functionality so naturally they
should be grouped into a package. An excellent example is the java.io package which groups
a set of classes that all perform input and output functions.
2. User knows where to find the classes they want if they're in a specific package.
If the user looking for a specific class and they know what functionality it provides then the
user can be able to find it in the right package. If you are looking for an InputStreamReader
you will find it in the input and output package, ie: java.io
3. The names of the classes and interfaces won't be in conflict with those of other
programmers.
If the designer decides to implement their own String class and it will be placed in a package
which will be distinguishable from the java.lang.String class that comes with the Java API.
4. Developers can restrict the access to the classes.
When a code or program one package wants to access certain code of another package, it can
restrict the access. For example in a library, then using packages makes access control to
source code much easier.

(iii) Create an interface for adding and subtracting two float numbers. Implement
the interface and demonstrate with suitable main. (8)
interface Calculatable {
public void doAdd (float a, float b);
public void doSub (float a, float b);
}
public class Calculate implements Calculatable {
public void doAdd (float a, float b) {
float a1, b1, c;
a1=a;
b1=b;
c=a1+b1;
System.out.println ("Addition value" +c);
}
public void doSub (float a, float b) {
float a1, b1, c;
a1=a;
b1=b;
c=a1-b1;
System.out.println ("Addition value" +c);
}
public static void main (String args []){
Calculate cal = new Calculate ();
cal.doAdd (2.3f, 4.5f);
cal.doSub (6.5f, 3.2f);
}
}
(or)
(b)(i) What is CLASSPATH? How do you set CLASSPATH? (6)
CLASSPATH
The Classpath is an argument set on the command-line, or through an environment variable,
that tells the Java Virtual Machine where to look for user-defined classes and packages in
Java programs. Specifying where to search for additional libraries in Windows is easily done
by setting the environment variable CLASSPATH, which Java uses to see where it should
find Java programs and libraries.
Setting the class path
The class path can be set using either the -classpath option when calling an SDK tool (the
preferred method) or by setting the CLASSPATH environment variable. The -classpath
option is preferred because it can set individually for each application without affecting
other applications and without other applications modifying its value.
C :> sdkTool -classpath classpath1; classpath2...
-or-
C :> set CLASSPATH=classpath1; classpath2...
where:
sdkTool
A command-line tool, such as java, javac, or javadoc.

(ii)Discuss exception handling mechanism in detail with suitable example? (10)


Exception Handling
A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code. When an exceptional condition arises, an object representing that
exception is created and thrown in the method that caused the error. That method may choose
to handle the exception itself, or pass it on. Exceptions can be generated by the Java run-time
system, or they can be manually generated by the code. Exceptions thrown by Java relate to
fundamental errors that violate the rules of the Java language or the constraints of the Java
execution environment. Manually generated exceptions are typically used to report some
error condition to the caller of a method.
Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.
Program statements that must be monitored for exceptions are contained within a try block.
If an exception occurs within the try block, it is thrown. The code can catch this exception
(using catch) and handle it in some rational manner. System-generated exceptions are
automatically thrown by the Java run-time system. To manually throw an exception, use the
keyword throw. Any exception that is thrown out of a method must be specified as such by a
throws clause. Any code that absolutely must be executed before a method returns is put in a
finally block.
finally creates a block of code that will be executed after a try/catch block has completed
and before the code following the try/catch block. The finally block will execute whether or
not an exception is thrown. If an exception is thrown, the finally block will execute even if
no catch statement matches the exception.

This is the general form of an exception-handling block:


try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
finally {
// block of code to be executed before try block ends
}
A throws clause lists the types of exceptions that a method might throw. This is necessary
for all exceptions, except those of type Error or Runtime Exception, or any of their
subclasses. All other exceptions that a method can throw must be declared in the throws
clause. If they are not, a compile-time error will result.
This is the general form of a method declaration that includes a throws clause:
type method-name (parameter-list) throws exception-list
{
// body of method
}
Example for try and catch
The following program includes a try block and a catch clause which
processes the Arithmetic Exception generated by the division-by-zero error

class Exc2 {
public static void main (String args []) {
int d, a;
try {// monitor a block of code.
d = 0;
a = 42 / d;
System.out.println ("This will not be printed.");
} catch (Arithmetic Exception e) {// catch divide-by-zero error
System.out.println ("Division by zero.");
}
System.out.println ("After catch statement.");
}
}

14. (a) (i) What is the uses of layout manager? List out different layouts available in
JAVA. (4)
Uses of Layout manager
Used to organize the components in a container. A layout manager is an object that
implements the LayoutManager interface and determines the size and position of the
components within a container. Although components can provide size and alignment hints,
a container's layout manager has the final say on the size and position of the components
within the container.
The different layouts of Java are
1. Flow Layout
2. Grid Layout
3. Border Layout
4. Card Layout
5. Grid bag Layout
(ii)Explain any three layout manager in detail with suitable example? (12)
1. Flow Layout
The elements are arranged in a top to bottom and left to right manner. The Flow Layout is the
default layout for Applets (and panels).
import java.applet.Applet;
import java.awt.*;
public class Flow1 extends Applet
{
public void init ()
{
//set Layout (new FlowLayout ());
// this.setLayout (new FlowLayout ());
Label label = new Label ("Name :");
add (label);
TextField tf = new TextField ("Java");
add (tf);
Button b = new Button ("OK");
add (b);
}
}
2. Grid Layout
Elements are arranged in a two dimensional grid form. Each component will have the
same size.
import java.applet.Applet;
import java.awt.*;
public class Grid extends Applet{
public void init () {
setLayout (new GridLayout (5, 3));
for (int row = 0; row < 5; row ++){
add (new Label ("Label” + row));
add (new Button ("Button” + row));
add (new TextField ("TextField” + row));
}
}
}
3. Border Layout
The elements are arranged in North, South, East, West and Center manner. Border
Layout is the default layout for Frame, Window and Dialog.
import java.applet.Applet;
import java.awt.*;
public class Border1 extends Applet {
public void init () {
setLayout (new BorderLayout ());
Label l = new Label ("This is NORTH", Label. CENTER);
l.setBackground (Color. yellow);
Scrollbar sb1 = new Scrollbar ();
Scrollbar sb2 = new Scrollbar ();
add (l, BorderLayout.NORTH);
add (sb1, BorderLayout.WEST);
add (sb2, BorderLayout.EAST);
}
}
(or)
(b) Explain multi threading concept in detail with suitable examples. (16)
A multithreaded program contains two or more parts that can run concurrently. Each part of
such a program is called a thread, and each thread defines a separate path of execution. Thus,
multithreading is a specialized form of multitasking. Multithreading enables the programmer
to write very efficient programs that make maximum use of the CPU, because idle time can
be kept to a minimum. This is especially important for the interactive, networked
environment in which Java operates, because idle time is common.
Advantages of multithreading over multitasking:
• Reduces the computation time.
• Improves performance of an application.
• Threads share the same address space so it saves the memory.
• Context switching between threads is usually less expensive than between
processes.
• Cost of communication between threads is relatively low.
The Main Thread
When a Java program starts up, one thread begins running immediately. This is usually
called the main thread of the program, because it is the one that is executed when the
program begins. The main thread is important for two reasons:
■ It is the thread from which other “child” threads will be spawned.
■ Often it must be the last thread to finish execution because it performs various shutdown
actions.
Creating a Thread
A thread can be created by instantiating an object of type Thread. Java defines two ways in
which this can be accomplished:
■ It can implement the Runnable interface.
■ It can extend the Thread class, itself.
Implementing Runnable
The easiest way to create a thread is to create a class that implements the Runnable
interface. Runnable abstracts a unit of executable code. In the program a thread can be
constructed on ant object by implementing Runnable interface. To implement Runnable, a
class need only implement a single method called run ( ), which is declared like this:
public void run ()
Inside run (), the code that constitutes the new thread is defined. It is
important to understand that run () can call other methods, use other classes, and
declare variables, just like the main thread can. The only difference is that run ()
establishes the entry point for another, concurrent thread of execution within the
program. This thread will end when run ( ) returns.
After a class that implements Runnable is created, the program will instantiate an object of
type Thread from within that class. Thread defines several constructors.

Example for the Thread constructor


Thread (Runnable threadOb, String threadName)
In this constructor, threadOb is an instance of a class that implements the Runnable
interface. This defines where execution of the thread will begin. The name of the new thread
is specified by threadName.
After the new thread is created, it will not start running until the program call its start ( )
method, which is declared within Thread. In essence, start ( ) executes a call to run ( ).The
start ( ) method is written as like this
void start ( )
Extending Thread
The second way to create a thread is to create a new class that extends Thread, and then to
create an instance of that class. The extending class must override the run ( ) method, which
is the entry point for the new thread. It must also call start ( ) to begin execution of the new
thread.
class NewThread implements Runnable {
String name;
Thread t;
NewThread (String threadname) {
name = threadname;
t = new Thread (this, name);
System.out.println ("New thread: " + t);
t.start ();
}
public void run () {
try {
for (int i = 5; i > 0; i--) {
Thread. Sleep (1000);
}
} catch (InterruptedException e) {
System.out.println (name + "Interrupted");
}
System.out.println (name + " exiting.");
}
}
class MultiThreadDemo {
public static void main (String args []) {
new NewThread ("One");
new NewThread ("Two");
new NewThread ("Three");
try {
Thread. Sleep (10000);
} catch (InterruptedException e) {
System.out.println ("Main thread Interrupted");
}
System.out.println ("Main thread exiting.");
}
}
15. (a) discuss the following event listener interfaces with suitable example
(4 X 4=16)
i) Container listener
ii) Window listener
iii) Component listener
iv) Action listener
i) Container listener
The listener is the interface for receiving container events. The class that is interested in
processing a container event either implements this interface (and all the methods it contains)
or extends the abstract ContainerAdapter class (overriding only the methods of interest). The
listener object created from that class is then registered with a component using the
component's addContainerListener method. When the container's contents change because a
component has been added or removed, the relevant method in the listener object is invoked,
and the ContainerEvent is passed to it.
import java.awt.*;
import java.awt.event.*;
public class ContainerEventDemo implements Container Listener {

buttonPanel = new JPanel (new GridLayout (1,1));


buttonPanel.addContainerListener (this);
public void componentAdded (ContainerEvent e) {
displayMessage (" added to ", e);
}
public void componentRemoved (ContainerEvent e) {
displayMessage (" removed from ", e);
}
void displayMessage (String action, ContainerEvent e) {
display. append (((JButton) e.getChild ()).getText ()
+ “was" + action + e.getContainer ().getClass ().getName ()
+ newline);
}
}
ii) Window listener
The listener is the interface for receiving window events. The class that is interested in
processing a window event either implements this interface (and all the methods it contains)
or extends the abstract WindowAdapter class (overriding only the methods of interest). The
listener object created from that class is then registered with a Window using the window's
addWindowListener method. When the window's status changes by virtue of being opened,
closed, activated or deactivated, the relevant method in the listener object is invoked, and the
WindowEvent is passed to it.
import javax.swing.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
public class Test extends JFrame implements WindowListener {
public Test () {
addWindowListener (this);
setSize (100, 100);
setTitle ("test");
setLocation (20, 20);
setVisible (true);
}
public static void main (String [] args) {
Test t = new Test ();
}

public void windowOpened (WindowEvent e) {


public void windowClosing (WindowEvent e) {
System.exit (0);
}
public void windowClosed (WindowEvent e) {
File file = new File ("delete.jar");
if (file.exists ()) {
file.delete ();
}
}
public void windowIconified (WindowEvent e) {
public void windowDeiconified (WindowEvent e) {

public void windowActivated (WindowEvent e) {


}
public void windowDeactivated (WindowEvent e) {
}
}
iii) Component listener
The listener is the interface for receiving component events. The class that is interested in
processing a component event either implements this interface (and all the methods it
contains) or extends the abstract ComponentAdapter class (overriding only the methods of
interest). The listener object created from that class is then registered with a component using
the component's addComponentListener method. When the component's size, location, or
visibility changes, the relevant method in the listener object is invoked, and the
ComponentEvent is passed to it.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ComponentEventDemo implements ComponentListener {
aFrame = new JFrame ("A Frame");
ComponentPanel p = new ComponentPanel (this);
aFrame.addComponentListener (this);
p.addComponentListener (this);
public void componentHidden (ComponentEvent e) {
displayMessage ("componentHidden event from”
+ e.getComponent ().getClass ().getName ());
}
public void componentMoved (ComponentEvent e) {
displayMessage ("componentMoved event from”
+ e.getComponent ().getClass ().getName ());
}
public void componentResized (ComponentEvent e) {
displayMessage ("componentResized event from”
+ e.getComponent ().getClass ().getName ());
}
public void componentShown (ComponentEvent e) {
displayMessage ("componentShown event from”
+ e.getComponent ().getClass ().getName ());
}
}
class ComponentPanel extends JPanel {
ComponentPanel (ComponentEventDemo listener) {
label.addComponentListener (listener);
checkbox.addComponentListener (listener);
}
}
iv) Action Listener
ِ ActionListener is an interface that could be implemented in order to determine how certain
event should be handled. When implementing an interface, all methods in that interface
should be implemented, ActionListener interface has one method to implement named
actionPerformed.
The following example shows how to implement ActionListener:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class ActionDemo extends JFrame implements ActionListener{
public ActionDemo()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 300);
getContentPane().setLayout(new FlowLayout());

JButton b = new JButton("Click me");


getContentPane().add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(this, "Hi !!!");
}
public static void main(String[] args)
{
new ActionDemo().setVisible(true);
}
}

(or)
(b)(i) What is a java bean? Mention the advantages of Java beans (4)
JavaBeans is a portable, platform-independent component model written in the Java
programming language. The JavaBeans architecture was built through a collaborative
industry effort and enables developers to write reusable components in the Java
programming language. Java Bean components are known as beans. Beans are dynamic in
that they can be changed or customized.
Advantages of Java Beans
Software component architecture provides standard mechanisms to deal with software
building blocks. The following list enumerates some of the specific benefits that Java
technology provides for a component developer:
• A Bean obtains all the benefits of Java's "write-once, run-anywhere" paradigm.
• The properties, events, and methods of a Bean that are exposed to an application
builder tool can be controlled.
• A Bean may be designed to operate correctly in different locales, which makes it
useful in global markets.
• Auxiliary software can be provided to help a person configure a Bean. This software
is only needed when the design-time parameters for that component are being set. It
does not need to be included in the run-time environment.
• The configuration settings of a Bean can be saved in persistent storage and restored at
a later time.
A Bean may register to receive events from other objects and can generate events that are
sent to other objects.
(ii) Discuss JAR files and Bean Info interface in detail with suitable example (10)
JAR files
Java Archive (JAR) files are compressed files into which many files can be stored. If the
programmer place many classes that the application, or applet need in a JAR file, the size of
the distributable program will be reduced. Typically a JAR file contains the class files and
auxiliary resources associated with applets and applications.

To create a JAR file, go to the directory where the files are located and type:
jar -cf ajarfile.jar *.*
and every file and directory in the current directory will be in a file called ajarfile.jar.
The jar tool combines multiple files into a single JAR archive file. jar is a general-purpose
archiving and compression tool, based on ZIP and the ZLIB compression format. However,
jar was designed mainly to facilitate the packaging of java applets or applications into a
single archive. When the components of an applet or application (.class files, images and
sounds) are combined into a single archive, they may be downloaded by a java agent (like a
browser) in a single HTTP transaction, rather than requiring a new connection for each piece.
This dramatically improves download times. jar also compresses files and so further
improves download time.
Bean Info interface
A bean implementor who wishes to provide explicit information about their bean may
provide a Bean Info class that implements this Bean Info interface and provides explicit
information about the methods, properties, events, etc, of their bean.
A bean implementor doesn't need to provide a complete set of explicit information. User of a
bean can pick and choose which information they want to provide and the rest will be
obtained by automatic analysis using low-level reflection of the bean classes' methods and
applying standard design patterns. Bean Info classes contain descriptors that precisely
describe the target Bean's features.
BeanInfo defines methods that return descriptors for each property, method, or event that is
to be exposed in a builder tool. Here are the prototypes for these methods:
PropertyDescriptor [] getPropertyDescriptors ();
MethodDescriptor [] getMethodDescriptors ();
EventSetDescriptor [] getEventSetDescriptors ();

Creating a BeanInfo Class


We'll use the ExplicitButton BeanInfo to illustrate BeanInfo class creation. Here are the
general steps to make a BeanInfo class:
1. Name the BeanInfo class. The string "BeanInfo” must be appended to the
target class name. If the target class name is ExplicitButton, then its
associated Bean information class must be named ExplicitButtonBeanInfo
2. Subclass the SimpleBeanInfo class. This is a convenience class the
implements BeanInfo methods to return null, or an equivalent noop value.
3. public class ExplicitButtonBeanInfo extends SimpleBeanInfo
Using this class saves you from implementing all the BeanInfo methods; user
only have to override those methods they need.

(iii) List out any three Java utility packages (2)


The Java utility packages are
1. java.util.jar
2. java.util.concurrent
3. java.util.zip
4. java.util.regex

You might also like