Download as pdf or txt
Download as pdf or txt
You are on page 1of 169

BSC0231

ANNAMALAI UNIVERSITY
DIRECTORATE OF DISTANCE EDUCATION

B.Sc COMPUTER SCIENCE


THIRD YEAR

INTERNET AND JAVA PROGRAMMING


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Copyright Reserved
(For Private Circulation Only)
Internet and Java Programming

Table of content
Page No.
Unit – I

1.0) Introduction 1
1.1) Objective 1
1.2) Content 2
1.2.1 Protocols 2
1.2.1.1 Transmission Control Protocol / Internet Protocol (TCP/IP) 2
1.2.1.2 File Transfer Protocol (FTP) 2
1.2.1.3 Hypertext Transfer Protocol (HTTP) 3
1.2.1.4 Telnet 3
1.2.1.5 Wide Area Information Service (WIAS) 3
1.2.2 World Wide Web (WWW) 4
1.2.2.1 Web Address 4
1.2.2.2 Web Page 4
1.2.3 Web Site 4
1.2.3.1 Connecting To Internet 5
1.2.3.2 Dial up Connections 5
1.2.3.3 Host/Terminal connec tion (Shell Accounts) 5
1.2.3.4 Long Distance Dial, Connection Services or Public Data Network 5
1.2.3.5 Individual Computer TCP/IP Link 5
1.2.3.6 Dialup or on demand TCP/IP link through your LAN 6
1.2.4 Browsers 6
1.2.4.1 Terminal-Based Browsers 6
1.2.4.2 WWW Line Mode Browsers 6
1.2.4.3 “Lynx” Full Screen Browser 6
1.2.5 Internet Services 6
1.2.5.1 File Transfer Protocol (FTP) 6
1.2.5.2 mailto 7
1.2.5.3 UseNet 7
1.2.5.4 Internet Service Provider (ISP) 7
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
1.2.5.5 Web Browsing / Net Surfing
1.2.5.6 Uniform Resource Locator (URL)
8
8
1.2.5.7 Hypertext Markup Language (HTML) 8
1.2.5.8 World Wide Web (WWW) 8
1.2.5.9 Domain Name 8
1.2.5.10 E-mail 8
1.2.6 E-mail 9
1.2.7 E-Mail Mailing Lists 10
1.2.7.1 Net-Happenings 10
1.2.7.2 On-line Public Access Catalogs (OPAC) 10
1.2.7.3 Gopher Jewels 10
1.2.7.4 Gopher Jewels Talk 10
1.2.7.5 NEWNIR-L 10
1.2.7.6 SICLIST 11
1.2.7.7 New List Mailing List 11
1.2.7.8 comp.infosystems.www.users 11
1.2.7.9 comp.society.privacy 11
1.2.7.10 soc.couples 11
1.2.7.11 soc.feminism 11
1.2.7.12 soc.men 11
1.2.8 News Groups 11
1.2.9 FTP 12
1.2.10 WWW Search Tools 12
1.2.11 Internet Chatting 13
1.2.12 Internet Conferencing 13
1.2.13 Search Engines 13
1.2.14 Tools for creating web sites 13
1.2.14.1 Java 14
1.2.14.2 JavaScript 14
1.2.14.3 HTML 14
1.2.15 Creating Web Sites 14
1.2.15.1 Web Pages 14
1.2.15.2 Web Sites 15
1.2.15.3 Web Directories 15
1.2.16 Security 15
1.3) Revision Points 16
1.4) In-text Questions 16
1.5) Summary 16
1.6) Terminal Exercises 17
1.7) Supplementary Materials 18
1.8) Assignment 18
1.9) Suggested Reading 18
1.10) Learning Activities 18
1.11) Keywords 18

ANNAMALAI
ANNAMALAI UNIVERSITY
Unit - II UNIVERSITY
2.0) Introduction 19
2.1) Objective 19
2.2) Content 19
2.2.1 Overview of JAVA 19
2.2.1.1 What is Java Virtual Machine? 21
2.2.2 Data Types 21
2.2.2.1 Integers 21
2.2.2.2 Primitive Data Types 22
2.2.2.3 Boolean Literals 22
2.2.2.4 Char Literals 23
2.2.2.5 Integral Literals 24
2.2.2.6 Floating-Point Literals 24
2.2.2.7 String Literals 24
2.2.3 Variables 25
2.2.3.1 Variables and Initialization 25
2.2.4 Arrays 26
2.2.4.1 Copying Arrays 26
2.2.4.2 Copying an array variable 27
2.2.5 Operators 27
2.2.5.1 Increment and Decrement Operators 29
2.2.5.2 Relational and Boolean Operators 30
2.2.5.3 Bitwise Operators 30
2.2.5.4 Mathematical Functions and Constants 31
2.2.6 Control Structures 32
2.2.6.1 Switch Statement 32
2.2.6.2 Do/While Statement 33
2.2.6.3 while statement 34
2.2.6.4 If Statement 35
2.2.6.5 If / Else statement 36
2.2.6.6 For Loop statement 37
2.3) Revision Points 38
2.4) In-text Questions 38
2.5) Summary 39
2.6) Terminal Exercises 39
2.7) Supplementary Materials 40
2.8) Assignment 40
2.9) Suggested Reading/Reference Books 40
2.10) Learning Activities 40
2.11) Keywords 40

Unit – III

3.0 Introduction 41
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
3.0.1 Classes
3.1 Objective
41
41
3.2 Content 41
3.2.1 The General Form of a Class 41
3.2.1.1 A Simple Class 42
3.2.2 Methods 44
3.2.2.1 Introduction 44
3.2.2.2 Returning a Value 46
3.2.2.3 Adding a Method that Takes Parameters 48
3.2.3 Inheritance 50
3.2.3.1 Understanding Inheritance 50
3.2.3.2 Building an Inheritance Hierarchy 51
3.2.3.3 Types of Inheritance 52
3.2.3.4 Defining a Subclass 52
3.2.3.5 Multilevel Inheritance 54
3.2.3.6 Use of Super 54
3.2.3.7 Method Overriding 56
3.2.3.8 Converting Objects and Simple Variables 58
3.2.4 Packages and Interfaces 58
3.2.4.1 Introduction 58
3.2.4.2 Accessing Java Package Members 59
3.2.4.3 Including a Package 59
3.2.4.4 Including Sub-Packages 60
3.2.4.5 java.lang 61
3.2.4.6 Creating a Package 64
3.2.4.7 Setting of CLASSPATH 65
3.2.5 Interfaces 66
3.2.6 Modifiers 68
3.2.6.1 Other Modifiers 68
3.2.7 Access Specifiers 72
3.2.7.1 Types of Access Specifiers 72
3.3) Revision Points 74
3.4) In-text Questions 74
3.5) Summary 74
3.6) Terminal Exercises 75
3.7) Supplementary Materials 75
3.8) Assignment 76
3.9) Reference Books 76
3.10) Learning Activities 76
ANNAMALAI
ANNAMALAI UNIVERSITY
3.11) Keywords UNIVERSITY 76

Unit – IV

4.0) Introduction 77
4.1) Objective 77
4.2) Content 77
4.2.1 Exception Handling 77
4.2.1.1 Understanding the Exception Handling 77
4.2.1.2 Exceptions in Java 78
4.2.1.3 Try and Catch 78
4.2.1.4 The finally Statement 79
4.2.1.5 The Error Class 87
4.2.1.6 Declaring Exceptions 88
4.2.1.7 Runtime Exceptions 88
4.2.2 Multithreading 89
4.2.2.1 Introduction to Thread 89
4.2.2.2 Multithreading 89
4.2.2.3 Creating and Managing Threads 89
4.2.2.4 Thread Synchronization 91
4.2.3 Input and Output 93
4.2.3.1 Introduction 93
4.2.3.2 InputStream Class 94
4.2.3.3 OutputStream Class 94
4.2.3.4 Byte Array I/O 95
4.2.3.5 File I/O 97
4.2.3.6 FileInputStream Class 97
4.2.3.7 Filtered I/O 98
4.2.3.8 Buffered I/O 99
4.2.3.9 The Reader and write class 100
4.2.3.10 The RandomAccessFile Class 101
4.2.4 String Handling 101
4.2.4.1 Substrings 102
4.2.4.2 String Editing 102
4.2.4.3 Testing Strings for Equality 103
4.2.5 The Utility classes 104
4.2.5.1 Introduction 104
4.2.5.2 The Enumeration Interface 104
4.2.5.3 Vector 106
4.2.5.4 Stack 107
4.2.5.5 Hashtable 108
4.2.6 Introduction to Networking 110
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
4.2.6.1 Protocols
4.2.6.2 Socket
110
110
4.2.6.3 Client/Server 110
4.2.6.4 Internet Address 110
4.2.6.5 Domain Naming Service 111
4.2.6.6 Inet Address 111
4.2.6.7 Datagram 111
4.2.6.8 TCP/IP 112
4.2.6.9 URL 113
4.3) Revision Points 114
4.4) In-text Questions 115
4.5) Summary 115
4.6) Terminal Exercises 116
4.7) Supplementary Materials 117
4.8) Assignment 117
4.9) Suggested Reading 117
4.10) Learning Activities 117
4.11) Keywords 117

Unit – V

5.0) Introduction 119


5.0.1 Introduction to Applet 119
5.1) Objective 119
5.2) Content 119
5.2.1 Applets 119
5.2.1.1 Inline Applets with HTML 120
5.2.1.2 Standard Applet Methods 121
5.2.1.3 Life Cycle Of Applet Class 122
5.2.1.4 Running the Applet Viewer 124
5.2.1.5 Java application Vs applets 125
5.2.1.6 Restrictions on a Java Applet 125
5.2.1.7 Pop -up Windows in Applets 126
5.2.1.8 Applet Attributes for Positioning 126
5.2.1.9 The Class Applet 127
5.2.2 Abstract Windowing Toolkit 128
5.2.2.1 Introduction to Swing 128
5.2.2.2 Using the Abstract Windowing Toolkit 129
5.2.2.3 AWT Components 129
5.2.2.4 Laying Out an User Interface 130
5.2.3 Working with windows 131
5.2.3.1 Introduction 131
5.2.3.2 The AWT Classes 132
5.2.3.3 Window Fundamentals 132
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
5.2.3.4 Working with Frame Windows
5.2.3.5 Hiding and Showing a Window
133
134
5.2.3.6 Setting a Window Title 134
5.2.3.7 Handling Events in a Frame Window 135
5.2.3.8 Creating Window program 135
5.2.4 Graphics 135
5.2.4.1 Introduction 135
5.2.4.2 Displaying Graphics 136
5.2.4.3 Displaying Graphics Primitives 136
5.2.4.4 Loading images 139
5.2.5 Layout Managers 139
5.2.5.1 Introduction 139
5.2.5.2 The GridLayout Manager 141
5.2.5.3 Border Layout 141
5.2.6 Menus 143
5.2.6.1 Using Menus 143
5.2.6.2 Dialog Boxes 145
5.2.6.3 FileDialog 145
5.2.6.4 Text Controls 147
5.2.7 Images 147
5.2.7.1 Introduction 147
5.2.7.2 Displaying the Images 148
5.2.7.3 Drawing the Image 149
5.2.7.4 Drawing to a Hidden Screen 150
5.2.8 Animation in Java 151
5.2.8.1 Introduction 151
5.2.8.2 Painting and Repainting 151
5.2.8.3 Flicker and How to Avoid It 155
5.2.8.4 Reducing flicker using Double-buffering 155
5.2.8.5 Animation using Images 156
5.2.8.6 Creating applets with Double-Buffering 157
5.2.9 Swing Class Library 158
5.2.9.1 Introduction 158
5.2.9.2 Reasons to choose swing are overwhelming 158
5.3) Revision Points 159
5.4) In-text Questions 159
5.5) Summary 159
5.6) Terminal Exercises 160
5.7) Supplementary Materials 161
5.8) Assignment 161
5.9) Suggested Reading 161
5.10) Learning Activities 161
5.11) Keywords 161

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Internet and Java Programming

Unit – I
1.0) Introduction
The Internet was originally formed in 1969 as a military network called ARPAnet
(Advanced Research Projects Agency Network),as part of the department of defense. The
network opened to non-military users in the 1970's.The term Internet was first used by California
computer scientist VINTCERF in 1982. An English scientist TIM BERNERS-LEE working at
European nuclear research center in Geneva, develops the World Wide Web (WWW), and its
Uniform Resource Locator (URL), Hyper Text Markup Language (HTML), Hyper Text
Transfer Protocol (HTTP) standards. This web produces enormous success.
In 1990, the original Arpanet is disbanded, leaving the Internet in its place. The Internet
is fully opened to commercial traffic. That is, commercial providers were first permitted to sell
Internet connection to individuals, usage of network exploded. The first Internet Service
Providers (ISPs) offers in expensive public Internet access via the telephone network. Million of
new users came on with in months and a new era of computer communication begins. Email or
electronic mail uses the Internet to transmit massages between users with in unique addresses. In
1996 the number of host computer on the Internet reaches 10 million. As personal computing,
put machines in to offices and homes across world application. Such as www, e-commerce and
email begin to change the way we live, work, and business.
The heart of the Internet consists of computers known as routers, connected by high-
speed backbone links, using fibre-optic and other cable and satellite links. The routers are
connected, in turn, with thousands of smaller networks and millions of individual computer.
Large companies and government and academic institutions often have direct Internet access via
computers called Internet servers at their Internet Service Provider. Data is sent around the
Internet by means of ‘packet switching’. Whether it takes the form of email, web pages or
computer files, the information is split up into small ‘packets’, each of which is digitally
‘labelled’ with its destination address.
Email – or Electronic Mail – uses the Internet to transmit message between users with
unique addresses. Messages are created and routed between computers with special software
until they reach the correct address.
In 1993 MARC ANDREESSEN and ERIC BINA developed web pages. The java
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
programming language enables more complex web pages. Begin in 2002, the Internet has about
95 million Host computers, about 25 million web sites and more than 1 billion web pages.

1.1) Objective
The objective of this lesson is to provide the basic knowledge and understanding about
Internet and its concepts in detail. The content of this lesson starts with introduction to Internet,
Protocols, World Wide Web, Connecting to Internet, Intranet, Browsers, Internet Services, E-
Mail, Mailing list, News groups FTP, Search tools, Chatting and Conferencing. It also provides
the basics of creating and Maintenance of Website and Security.

Page 1
Internet and Java Programming
Towards end of this lesson student can understand the Internet paradigm. They can get
the clear idea about basics of Internet and its terminology.

1.2) Content
1.2.1 Protocols
The word protocol comes out of diplomatic language. These protocols are nothing but the
rules that the network all uses to understand each other. There are various types of protocols
are set of technique specification.

The most commonly used protocols are:

 Transmission control protocol/Internet protocol (TCP/IP)

 File transfer protocol (FTP)

 Hypertext transfer protocol (HTTP)

 TELNET

 Wide area information service (WAIS)

1.2.1.1 Transmission Control Protocol / Internet Protocol (TCP/IP)


This TCP/IP protocol is a collection of protocol or a rule that governs the way data
travels from one machine to another machine across the network. This TCP/IP is an common
protocol that provides reliable transfer of data. This protocol is responsible for assembling data
passed from higher layer application to standard packets.

TCP/IP is the protocol that enables communication across a network, be it an intranet,


extranet or the Internet. TCP/IP comprises of two protocols: the Transmission Control Protocol
(TCP) and Internet Protocol (IP).

1.2.1.2 File Transfer Protocol (FTP)


This is popularly known as (FTP) file control protocol is simply a method of transferring
file on the Internet using FTP, you can both send (upload) and receive (download) files from
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
FTP sites on the Internet. There are some of the important FTP terms to know they are ASCII,
Client, Binary, Archie, pub, put, etc.,

File transfer protocol is one of the basic services on the Internet. Until 1995 it accounted
for more traffic on the Internet than any other service. This FTP simply means sending a file (not
a message) from one computer to another .FTP is a part of TCP/IP protocol and it is very
powerful tool. You can use FTP with your web browser, or you can use an FTP client program.
In either case, an FTP address starts out with “ftp://”. For example, the address of an FTP site at
university of Hawaii is ftp://ftp.hawaii.edu.

Page 2
Internet and Java Programming
1.2.1.3 Hypertext Transfer Protocol (HTTP)

This transfers a hypertext between two or more computers. This HTTP is based of client
and server principle. Hyper text is a text that is specially coded using a standard system called
Hypertext Markup Language (HTML). These codes are use to make links. Links can be textual
or graphical.

Hypertext transfer protocol allows computer A (client) to establish a connection to


computer B (server) and make a request and the server accepts the connection and send the
response. Hypertext transfer protocol request identifies the resource that the client is inserted in
and tell the server what “action” to take on the resource in an single sentence HTTP is defined as
“underlying system where by web document are transferred over the Internet.”

The underlying system whereby web documents are transferred over the Internet, an
hypertext interconnected web of text information, wherein any given word or phrase any link to
another point in the document or to another document.

1.2.1.4 Telnet

This telnet is a protocol that enables one computer to establish a connection to another
computer. This protocol can provide access to many resources around the world, such as library
catalogs, database, Internet tools and applications.

This telnet is one of the simplest tools of the Internet This telnet also operates on client
and server principle. People are in one location frequently wanted to use a computer in another
location on a business trip and want to check the mail. This telnet is an Internet tool that let you
transfer from your “own workstation out into Cyberspace”

1.2.1.5 Wide Area Information Service (WIAS)

Wide Area Information Service (WIAS) (pronounced as “WAYZ”). This is an Internet


searching tool. WIAS is based on Z39.50 standard this Z39.50 was the first demonstration on the
Z39.50 information retrieved protocol in use outside the library automation community. This has
several overlapping meanings.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Wide area information service has the capacity to simultaneous searching more than one
database. After search they typed into the client interface. Then user can choose which database
should be used to complete the search. Once the search has been executed all terms containing
words appearing in search phrase will be returned to user .The search phrase appear on the index
of selected database.

For Example search “Internet address” WIAS will retrieve all items from the chosen
database that contain the word “Internet” even the items have nothing to do with “address” and
vice-versa. The table 1.1 shows all common protocols:

Page 3
Internet and Java Programming

Protocol Names
HTTP Hypertext Transfer Protocol (web pages)
SHTTP Secure Hypertext transfer protocol
FTP File transfer protocol
WAIS Wide area information service
TELNET Telnet session
MAILTO Electronic mail
Table 1.1: Protocols
1.2.2 World Wide Web (WWW)
Basically the World Wide Web (www) was originally developed at CERN, (high energy
physical research center in swizz). The ultimate home page for CERN (http://info-cern.com) The
World Wide Web is an Internet navigation tools that helps to find a retrieve Information using
links to other web pages. This www produces new era of computers. This World Wide Web is
also referred to as the www or w3 or simply the web. This World Wide Web is a nonlinear with
no top or no bottom.
What is Non-linear?
Non–linear means you do not have to follow a hierarchical path to information recourses.
Internet has grown explosively in the 1990’s there are more than 40 million server computer on
the Internet, each providing some type of information or services. World Wide Web is the
newest Internet service has accelerated the growth of the Internet by giving it an easy to use,
point and click, graphical interface. This World Wide Web is done many things to its million of
users. WWW is used as a market place, art gallery, Library, education institutions etc. Here there
are some of the web terms to know:

1.2.2.1 Web Address


The location of a page on the World Wide Web, which usually looks like
http://www.aol.com. Web addresses are officially known as URL’s, which stands for Uniform
Resource Locator.

ANNAMALAI
ANNAMALAI UNIVERSITY
1.2.2.2 Web Page
UNIVERSITY
A document on the World Wide Web, created using html and seen with a web browser.
A web page can contain text, pictures, sounds, software files, movies, and more. Each web page
has a unique web address that describes how to get to it. A home page is a specific kind of web
page, usually the main page on a web site.

1.3.3 Web Site


A collection of web pages is called Website. World wide web (also www, web) the
world wide web uses the Internet to create a network of information, made up of documents
(“web pages”) containing text, sounds, pictures, movies, and more, tied together with hyperlinks
so that all this information is just a few click of the mouse away.

Page 4
Internet and Java Programming
1.2.3 Connecting To Internet

1.2.3.1 Dial up Connections


If you have a computer, some communication software, a telephone line, and a modem
(modulator/demodulator). You can connect to the Internet. The major ways that you can link to
the net using dialup are:

 Host/Terminal connection (Shell Accounts)


 Individual computer TCP/IP link
 Dial up or on-demand TCP/IP link through your LAN.

1.2.3.2 Host/Terminal connection (Shell Accounts)

In Host/Terminal connection, your computer acts as if it were a terminal directly


connected to some Internet host. VT100 terminal is a lowest common denominator of emulation:
the simplest to implement, and a terminal that can display visual information.
a) Local Dial
This local number host dial connection is the least expensive type available. (This kind of
connection is not available in all areas) with an access point that is a local telephone call from
your geographical location, a telephone connected that does not incur measured time costs, and a
flat rate Internet service you may stay connected to your providing system for long periods
without incoming charges.
1.2.3.3 Long Distance Dial, Connection Services or Public Data Network
Since you are not located where you can reach a service provider with a local call, you
will need to consider whether a long distance call, a connection service this service is best for
your connection. Some national wide service provides offer1-800 or1-900 service and essentially
passes through their cost to you. This can be more expensive then simple long distance .A
connection service is one that offers local or 800/900 accesses then once you are connected, lets
you use telnet to connect from the terminal server to Internet service.

Another connection method is that of a public data network like computer service packets
network or sprint net. Be sure and investigate how fast these connections are because they might

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
not offer the type of service that will serve your needs.

1.2.3.4 Individual Computer TCP/IP Link


This allows you computer to function as an Internet host. Whatever software you select to
run, providing only these links are taken either “SLIP” (serial link Internet protocol) or
“PPP”(point to point protocol). Both Hyperlinks will handle dial up. Both can take advantage of
frequency software technique that condense or compress. The chameleon sampler on companion
disk2 is a TCP/IP software packages that includes both SLIP and PPP.

Page 5
Internet and Java Programming
1.2.3.5 Dialup or on demand TCP/IP link through your LAN
This dial-up link through LAN is an intermediate step between individual dialup and
dedicated high-speed link. It is therefore somewhat like having a direct link. The main different
between this type of connection and one to your individual computer is that the TCP/IP software
runs on the LAN service and your connection is to the server a LAN for purpose for this
discussion includes pc based networks. A TCP/IP connection through a LAN either on a dialup
connection or a direct connection is the most common type of IP connection much more than a
personal dial up IP connection. It may also dial up in to the network on the regular schedule to
exchange electronic mail.

1.2.4 Browsers
If you have a host account on someone else’s system, try typing lynx or www. at main
system prompts. Finding web client consist of ;
 Terminal Based Browsers
 www.line mode browser
 Lynx full screen browser

1.2.4.1 Terminal-Based Browsers


Probably we find these installed on your host-based account; If not, consult your local
system administrator to get them installed.

1.2.4.2 WWW Line Mode Browsers


The CERN line mode browser is a character based www browser. It is developed for on
host that supports VT100 terminal emulation. Binaries are available for most UNIX varieties and
many other platform as www*.tar.Z.

1.2.4.3 “Lynx” Full Screen Browser


This is an Hyper text Browser for VT100s using full screen, arrow keys, highlighting,
and so on. It is much preferred over the www line mode browser, code is available by
anonymous FTP from ftp2.cc.ukans.edu
1.2.5 Internet Services

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The Internet is a worldwide collection of computer network connecting
academic Government, commercial and individual sites. This provides a access of
communication services and information resources to million of users around the world. This
Internet service includes direct Communication (email chat), online -conferencing (UseNet
news), distribution information resource (World Wide Web), remote login (Telnet), and many
others. Other various Internet services are explained below:

1.2.5.1 File Transfer Protocol (FTP)


File Transfer Protocol (FTP) was devised as a means of passing binary files back and
forth over the Internet. An FTP client shows files and directories on a local and a remote
machine and facilitates the exchange of files between the two.

Page 6
Internet and Java Programming
Many popular Web browsers are programmed to perform as FTP clients but only in one
direction. You can transfer a file from a remote server to your machine through a Web browser,
but you can't use it to send files. It's rare for a Web surfer to send a file, so the inability to send is
not a serious end user issue. To set up an FTP download link on one of your pages, you set it up
much like a link to another Web page except you use an FTP URL rather than a Web URL.

Note: Be sure to include the size of the file when you put up an FTP link so that users can have a
sense of how long it will take to download the file.

1.2.5.2 mailto

A mailto URL gives users a point-and-click way to send you electronic mail. When users
click the hypertext feedback, their browsers open a mail window where they can compose their
messages.

Note: To send a mail message using Netscape Navigator, select File, New Mail Message.

Netscape Navigator provides a built-in electronic mail program for sending and receiving
messages. E-mail links set up with a mailto attribute are a great way to collect feedback on your
Web pages or Web site. Even if you are not looking for opinions, it's still a good idea to give
visitors some means of contacting you in case there is a problem loading or viewing your pages.

Note: Before you use Netscape Navigator to send e-mail, you need to specify the mail server you
use. To do this, select Options, Mail and News Preferences, click the Servers tab, and enter the
name or IP address of your outgoing mail (SMTP) server.

1.2.5.3 UseNet

UseNet newsgroups are forums for discussion on a particular topic. Internet users with a
Usenet client and access to a news server can read and post responses to any newsgroup they
find interesting with over 7,000 newsgroups to choose from, there's bound to be at least one that
pertains to content on your Web pages.

You can establish hypertext links on a Web page that will take users to a Usenet
newsgroup via their browser's newsreader feature. Microsoft Internet Explorer also has an

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
associated newsreader. You set up a link to a newsgroup just like any other in this chapter,
except that you use a news URL:

1.2.5.4 Internet Service Provider (ISP)

This ISP provides Internet access. The customer can be business, individual and
organizations the two common types of Internet access are dialup shell account and slip / point-
to-point account. In this account the entire user has all direct to the Internet through ISP.
Additional services that can be offered by ISP include web hosting, domain name, name service
and proprietary on line services.

Page 7
Internet and Java Programming
1.2.5.5 Web Browsing / Net Surfing
Web Browsing is also called as net surfing. This net surfing is the process of visiting a
different web site on the Internet hosted by the various companies, organization, education
institution, individuals, magazines etc.

1.2.5.6 Uniform Resource Locator (URL)

Uniform Resource Locator is called URL. URL provides a standard hierarchical way of
identifying and locating Internet resources on the World Wide Web (www). This URL includes
letters, numbers, and punctuations.

1.2.5.7 Hypertext Markup Language (HTML)

Hyper text markup language is the set standard codes or Tags. HTML has been derived
from the SGML (Standard Generalized Markup Language) standard. In addition HTML
document are portable and they can be viewed with any web browser on any type of computer.

This transfers a hypertext between two or more computers. This HTTP is based of client
and server principle. Hypertext is a text that is specially coded using a standard system called
Hypertext Markup Language (HTML). These codes are use to make links. Links can be textual
or graphical.

1.2.5.8 World Wide Web (WWW)

World Wide Web is a system based on hypertext and HTTP, for providing, organizing,
and accessing a wide variety of recourses (text, image and sound) that are available via in the
Internet. This www produces great success.

Basically this World Wide Web (www) was originally developed at CERN,(high energy
physical research center in swizz). The ultimate home page for CERN (http://infocern.com) The
World Wide Web is an Internet navigation tools that helps to find a retrieve information using
links to other web pages. This www produced new era of computers. This World Wide Web is
also referred to as the www or w3 or simply the web. This World Wide Web is a nonlinear with
no top or no bottom.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
1.2.5.9 Domain Name

This domain name is to identify and locate computer connected to Internet .The domain
name must be unique, no two organization on the Internet can have the same name.

1.2.5.10 E-mail

Email – or Electronic Mail – uses the Internet to transmit message between users with
unique addresses. Messages are created and routed between computers with special software
until they reach the current address. Electronic mail or email as popularly known, this electronic
mail is the System that allows user to send and receive messages and data through the Internet.

Page 8
Internet and Java Programming
1.2.6 E-mail

The Internet is a valuable tool for accessing information and also opens a whole new
world of communication to it users. Electronic mail or e-mail involves transmission of messages
over communication networks. The messages can be notes or files. Some electronic-mail systems
are confined to a single computer or network, but others have gateways to other computer
systems, enabling users to send electronic mail anywhere in the world. Companies that are fully
computerized make extensive use of e-mail because it is fast, flexible and reliable.
Electronic communication, because of its speed and broadcasting ability, is
fundamentally different from paper-based communication. Because the turnaround time can be
fast, email is more conversational than traditional paper-based media.

Most e-mail systems include a rudimentary text editor for composing and editing
messages. A message is sent to the recipient by specifying the recipient's address. An address is a
text string of the form mailbox@site. The second part (after @ sign) is a string identifying a
particular site on the Internet; the first part (before @ sign)is a string identifying a particular
mailbox at that site. For example, consider a mail id like abc_def@yahoo.com. In this case,
abc_def is the username and yahoo.com is the website.

Every Internet site has an Internet Protocol (IP) address, specified as four decimal
numbers (each in the range 0-255) separated by dots. The transport service sends the site name
string to a Domain Name Server (DNS), which translates the name into an IP address. The
transport service then starts up an Internet connection to the given IP address and asks the
destination site to deliver mail to the given mailbox.

A message can be sent to several users at once. This is called broadcasting. The sent
messages are stored in electronic mailboxes of the recipient. The recipient has to check the
mailbox to see if mail has been received and can decide on whether to save it or remove it off the
mailbox.

Once the user drafts a message and specifies the recipients mail IDs, e-mail software
transfers a copy of the message to each recipient. In most systems, two separate pieces of
software are required. A user interacts with an e-mail interface program when composing or
reading messages. The underlying e-mail system contains a mail transfer program that handles
the details of sending a copy of the message to a remote computer. When a user finishes

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
composing a message, the e-mail interface places the message in a queue that the mail transfer
program handles.

The mail transfer program waits for a message to be placed on its queue and then
transfers a copy of the message to each recipient. When a mail transfer program contacts a server
on a remote machine, it forms a TCP connection over which it communicates. Once the
connection is in place, the two programs follows the Simple Mail Transfer Protocol (SMTP) that
allows the sender to identify itself, specify recipients and transfers an e-mail message. The server
places a copy of the message in the recipient's mailbox.

Page 9
Internet and Java Programming
Different e-mail systems use different formats and there are some emerging standards
that make it possible for users on all systems to exchange messages. An important e-mail
standard is MAPI. The CCITT standards organization has developed the X.400 standard, which
attempts to provide a universal way of addressing messages.

1.2.7 E-Mail Mailing Lists


Here are some mailing lists to join of new services to be delivered directly to your e-mail
inbox.

1.2.7.1 Net-Happenings
The" list for users who want to know everything that's new on the Net and that's
happening to the Net. List owner Gleason Sackman forwards thousands of bytes of information
a day to keep up with the ever-changing Internet environment. This list has a digest option that
will allow you to receive the postings in big gulps rather than dribs and drabs; but be warned
even in Digest form it generates a large amount of mail. This list is essential to Gopher or Web
administrators and others who serve as the Internet expert for their community. To subscribe,
send a subscription message to: majordomo@is.internic.net and include either subscribe net-
happenings or subscribe net-happenings digest in the body of your message, depending upon
which you'd like to receive.

1.2.7.2 On-line Public Access Catalogs (OPAC)


A discussion focusing on computer systems those libraries make available to their
patrons. You do not need to be a librarian to join the list. This is a great list for getting help with
specific computer problems related to OPACs (On-line Public Access Catalogs) CD-ROMs, and
databases. The discussion is library-oriented but may be of help to professionals in many other
areas.

1.2.7.3 Gopher Jewels


This mailing list sends out a small amount of daily traffic on interesting Gopher finds.
Usually there are no more than five messages per day. This list is perfect for those who would
like to see what's good and new in gopher space or who are maintaining a Gopher server that
includes out side resources.

1.2.7.4 Gopher Jewels Talk


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Since the Gopher Jewels list is limited to postings about interesting Gopher sites, Gopher
Jewels-Talk supplies a place for people to ask questions about Gopher or discuss issues. It's
mainly for Internet neophyte. Who are looking for a friendly place to post a Gopher question and
neglect flamed by the "experts".

1.2.7.5 NEWNIR-L
Announcements of new Network Information Retrieval services and OPACs (On-line
Public Access Catalogs) are made here and include WWW, Gopher or WAIS servers and
CWISes. Another high-traffic list like Net-Happenings, but without the extra "information
technology" postings.

Page 10
Internet and Java Programming
1.2.7.6 SICLIST
The Dartmouth SIGLIST is a subject-organized list of both Internet and Bitnet's
discussion lists that is updated monthly. Various computer formats are available and most are
searchable. FTP: dartcmsl.dar.tmouth.edu in directory SIGLISTS.

1.2.7.7 New List Mailing List


New-List is an announcement service for new mailing lists on the Internet and Bitnet.

1.2.7.8 comp.infosystems.www.users
This heavy-traffic group discusses ways to use the World Wide Web, new Web servers
and services.

1.2.7.9 comp.society.privacy
This group discusses privacy and networking subjects such as credit card information and
bank accounts on the Internet, how to make an anonymous posting on the Internet, e-mail
privacy cases, and phone taps.

1.2.7.10 soc. couples


Being in a short- or long-term relationship offers much in the way of joy, pleasure, and
emotional satisfaction, but it also offers the chance for major arguments and other problems. This
is where you can talk about the relationship you're in with others who are also in relationships.

1.2.7.11 soc. feminism


This is a moderated newsgroup for the discussion of feminist issues. Both men and
women are encouraged to post to it, and discussion is not limited to the pro-feminist viewpoint.
This group differs from soc. women in that moderation keeps out the flames and in appropriate
cross-posts. In addition, there are subjects appropriate for soc. women but not soc. feminism (for
example, the sporadic "where do I find comfortable shoes?” discussion that turns up in soc.
women or discussions of women's health that aren't related to policy).

1.2.7.12 soc. men

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
This group discusses similar issues to soc. women, but from the male perspective. Topics
include equal rights, child support, and custody of children, relationships, and so on. In addition,
there are often topics specific to men including shaving in the shower, post-workout skin care,
and similar. Both men and women are active participants in this group.

1.2.8 News Groups

Newsgroups are electronic discussion forums for users to meet and exchange ideas. They
serve a good source of answers and information for questions, installation problems and
programming issues for many products.

Page 11
Internet and Java Programming
When a person posts his queries or comment in the Newsgroup, the members of the
group reply to it. The reply may or may not lead to other questions or doubts and this in turn are
answered. Thus the entire process leads to a chain of related postings.

Newsgroups were popular long before the World Wide Web exploded onto the scene.
Newsgroups are organized based on the topics. They originate from many sources and are hosted
on many systems, known collectively as the Usenet network, the original name given to this
service. The system administrator at any given ISP fixes the time limit of availability of the
posting.

1.2.9 FTP
FTP stands for File Transfer Protocol. It is a widely used method for copying files from
one system to another on the Internet. FTP is the method of choice for file movement across the
Internet. FTP is a two-way protocol in that files can be sent and received and both these
processes can be controlled. With FTP the files in a directory can be listed and uploading or
downloading files to and from that directory is possible.

The transfer of publicly available information is one of the most widespread uses of the
file transfer capability on the Internet. Many organizations connected to the Internet provide
openly accessible file transfer sites with information that anyone can obtain. Files are stored in
"open" areas of computers. Using FTP to connect to those systems can access these files. An
FTP client program is required if a web browser without built-in FTP capability has to be used to
upload files to a remote server.

When an FTP program is run, by specifying a relevant login name and password, the user
is presented with a directory structure. The user can navigate the directory structure and
depending on the system, pull files off the server or put files on to the server. The files will then
be copied from one location to the other. FTP specifies three modes for data transmission:

1. Stream mode: It treats the file as a sequence of bytes. This mode can be used with any type of
data type.
2. Block mode: The file is transmitted as a number of block. Each block is preceded by a header,
which contains the size of the block and a description. The descriptor also has a bit that indicates
whether the data is reliable. This bit is used when voluminous data, such as geologic or
atmospheric data being read off a medium, results in a media error.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
3. Compressed mode: It is used to transfer files efficiently and utilize network bandwidth
optimally. The compression is fairly simple, where a string of x replications of a data byte is
compressed into 2 bytes

1.2.10 WWW Search Tools


WWW Search tools refer to the various web sites available in the Internet to help in
gathering information related to a topic. The search tools websites displays the various links
where information related to a topic under search can be gathered. These search tools are also
referred to as search engines.

Page 12
Internet and Java Programming
The search engines searches a database of the full text of web pages selected from the
billions of web pages residing on servers. When a link provided in a search engine's search
results is clicked, the server sends the current version of the page.

Search engine databases are selected and built by computer robot programs called
spiders. After spiders find pages, they pass them on to another computer program for "indexing."
This program identifies the text, links and other content in the page and stores it in the search
engine database's files so that the database can be searched by keyword

1.2.11 Internet Chatting

This means that user exchange typed text with other user’s who is just like a user, are
sitting in front of their computers, typing anyway. The sense of immediacy and involvement can
be addictive. User can count on the interacting with the diverse group of people. For example,
because most IRC (Internet Relay Chat) networks are international in scope, you’ll find
yourself chatting any way with people from the other countries.

1.2.12 Internet Conferencing

Apart from chatting, it provides to meet people virtually- possible seeing and hearing
each other. This technology makes it possible to have virtual meeting, called Videoconference,
among far-flung people. It is sometimes said that transportation and communication are having a
race, and whichever wins will make the other obsolete. Virtual meeting could be used for remote
school, getting special medical opinions from distant specialists, and numerous other
applications.

1.2.13 Search Engines

Search engines and directories are Web searching features. A directory is meant for
browsing. It is organized in a particular manner for easy and productive browsing. Search
engines allow us to type in keywords that we want to find. The engine searches for a matching
word and gives list of hyperlinks to web sites. Directories may or may not contain search
engines. The largest directories have a built-in search engine, which is more convenient as both
browsing through the directory and using the search engine is possible. The directories that come
with the built-in engines are Yahoo, Lycos and Excite. On the other side, the search engines

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
alike.AltaVista, Open text, Inktoim and WWW worm do not have a directory.

A search engine without a directory is like a library without a card catalog in other words;
a search engine helps the user in finding a site of interest. Whereas a directory without a engine
is like a library with no librarians. The user has to browse on his own. Some of the well-known
web directories like Yahoo, Lycos, Excite and web crawlers are discussed briefly.
1.2.14 Tools for creating web sites
Various languages and tools are designed for the distributed Internet applications.

Page 13
Internet and Java Programming
1.2.14.1 Java
Java is one of the languages designed for distributed applications on the Net. It was
incorporated from Sun Microsystems in 1991. Java is a platform-independent programming
language. The Web is more interactive with the addition of forms and image maps. Java is a
coding language. The small programs that create animation, multimedia, real-time games and
multi-user games are called applets. These are downloaded over the Net and executed by a web
browser in a web page. Java language was used in several projects of Sun Microsystems. It was
later paired with hot lava. Hot Java was written in the yearl994. It is mainly written to download
and run applets. It also stands as an example for the complex application that can be written in
Java. To run and view Java applets we need a Java-capable browser.

1.2.14.2 JavaScript
JavaScript is an object based programming language from Sun Microsystems
incorporated into the web browser Netscape Navigator. It enhances the functionality of the web
browser that is used. Java Script is a scripting language and is developed by Netscape. It is a tool
that is associated with the Internet and World Wide Web. This tool is used to add functionality
and interactivity to Web pages.

1.2.14.3 HTML

HTML stands for Hyper Text Markup Language. It is an application of Standard


Generalized Markup Language (SGML). It is a simple language, which is used to define and
describe the layout of a Web page. It provides structuring and layout controls to manage the
appearance of a document. HTML also supports Multimedia and document links/It consists of
special codes which when embedded in text adds formatting and linking information. The special
characters, which separate HTML text from our ordinary text, is the left and right brackets.
These brackets contain instructions known as TAGS. These tags are not case sensitive.

1.2.15 Creating Web Sites

1.2.15.1 Web Pages


A web page is the basic part of the World Wide Web. The information displayed on the
web page includes graphics, video and audio. Several web pages link together to form the World
Wide Web. We can host our own web pages through services like America Online, Internet shell
account and SLIP/PPP account. Most of the providers allow creation of individual web pages. To
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
create a web page, the procedure followed is

 Create the pages as files on the disk by using either a text editor or a HTML editor.

 Test the pages with Netscape and other browsers to check if they work correctly.

 Upload them to the Internet service provider's computer and file them in the proper place.

 The pages must be updated frequently to become more interesting.


Note: Web pages are stored as text files, a combination of both text and HTML commands.

Page 14
Internet and Java Programming
1.2.15.2 Web Sites
The web site is a very common terminology in the WWW. The web pages that represent
the online home of their author are called home pages. Home pages can be more than one page.
The multipage destinations are referred to as sites. A site refers to a particular location on the
web. It can even be a single page.

1.2.15.3 Web Directories


The web browser delivers maps to virtually everything on the Internet. The web maps are
called directories. A directory is used to find a site of interest. To get more information about the
site there are some specialized tools. There are many directories available for searching the Net.
They are unique and accurate. Though the directories have different contents, all of them work
similarly. The directories add new web pages to their databases. Directories consist of many
levels and provide maps of the WWW. The number of levels depends on the directory we are
using and also the topic of interest we start with. Some of them can have as many as eight levels
below the top level. The top level gives us the broadest overview of the Net.

1.2.16 Security
There are two kinds of security related to the Internet installation.

 Protecting organization from outsiders

 Protecting it from insiders.

Smart Defense
Defending your self from outsiders is easier. Sensitive data about organization should be
kept off. The server that is connected to the Internet. Internet is very open environment. There is
a lot of very interesting work being done on data encryption Technologies, on private key etc.

These technologies become more mature and more trusted in next several years. It does
not mean that you cannot on Internet. It means that data should be connected on Internet. Many
installation use firewall to protect their Internet networks from unwanted instruction. Firewalls
are so named because they protect what is behind them from being burned. It is possible to send
e-mail into the IBM network and to send e-mail out of IBM Internet network. The most IBM
employees who use the Internet have personal accounts outside the IBM.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Trouble from within

The large danger to any Internet and server system comes from the people who access to
it internally. Many really bright computer users feel that anything they can explore or do not they
should be allowed to it. All changes should be logged.
Care should be taken in training people about security concern. This means teaching all your
staff how to protect their own data as well as make sure your system administrator are thrust
worthy.

Page 15
Internet and Java Programming

1.3) Revision Points


Protocol
On the Internet "protocol" usually refers to a set of rules that define an exact format for
communication between systems. Some of the examples are: TCP/IP, FTP, HTTP etc.,

World Wide Web (WWW)


A hypertext-based, distributed information system originally created by researchers at CERN,
the European Laboratory for Particle Physics, to facilitate sharing research information. The Web
presents the user with documents, called web pages, full of links to other documents or
information systems. Selecting one of these links, the user can access more information about a
particular topic. Web pages include text as well as multimedia

E-mail
The exchange of electronic messages and computer files between computers that are connected
to the Internet or some other computer network.

FTP
The protocol used on the Internet for exchanging files. FTP uses the Internet's TCP/IP protocols
to enable data transfer. FTP is most commonly used to download a file from a server using the
Internet or to upload a file to a server.

Search Engines
Search Engines permits searching of documents and databases accessible on the Internet. It can
be set up to search only content within one Web site or to search the entire Internet.

1.4) Intext Questions


1. Explain about Internet and its applications
2. What is protocol? Explain any 2 protocols in detail
3. Write about E-mail and Search Engines with examples
4. Write about the available web development tools with examples
5. What is web security and why it’s needed?
1.5) Summary
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
 The Internet was originally formed in 1969 as a military network called
ARPAnet(Advanced Research Projects Agency Network)

 Email – uses the Internet to transmit message between users with unique addresses.
Messages are created and routed between computers with special software until they
reach the correct address.

 The protocols are nothing but the rules that the network all uses to understand each other.

Page 16
Internet and Java Programming
 The TCP/IP protocol is a collection of protocol or a rule that governs the way data travels
from one machine to another machine across the network.

 The most commonly used protocols are:

o Transmission control protocol/Internet protocol (TCP/IP)

o File transfer protocol (FTP)

o Hypertext transfer protocol (HTTP)

o TELNET

o Wide area information service (WAIS)

 The World Wide Web is an Internet navigation tools that helps to find a retrieve
Information using links to other web pages.

 Web addresses are officially known as URL’s, which stands for uniform resource locator.

 A document on the world wide web, created using html

 The Internet is a worldwide collection of computer network connecting


academic Government, commercial and individual sites.

1.6) Terminal Exercises


1. The Internet was originally formed in 1969 as a military network called
__________
2. The term Internet was first used by __________________
3. The heart of Internet consist of computer called ___________
4. Transmission Protocol are also known as _________
a) File Transfer b) Telnet c) Internet d) Gopher

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
5. FTP is used for _____________
a) Uploading b) Downloading c) both d) None
6. Html have been derived from SGML (TRUE/FALSE)
7. World Wide Web is also referred to as W3 (TRUE/FALSE)
8. There are two kinds of security related to Internet installation. What are they?
9. Web browsing are also called as ___________
10. The Internet is the world wide connection of computer network (TRUE/FALSE)

Page 17
Internet and Java Programming
1.7) Supplementary Materials
1. Margret Levine Young, "Internet: The Complete Reference" Tata Mcgarw Hill
Publishing Company Limited, New Delhi, Millennium Edition, 1999.

2. Douglas E. Corner, "The Internet", PHI, New Delhi, Second Edition, 1997.

1.8) Assignment
1. Discuss about the Advantages and Disadvantages of Internet
2. Prepare a case study about Search Engines and its importance

1.9) Suggested Reading


1. http://www.kn.pacbell.com/wired/internet/internet-basics.htm
2. http://www.webcurrent.com/tcrc/basics/html/internet.html
3. http://web-hosting.candidinfo.com/ftp-tutorial.asp
4. http://www.answers.com/topic/world-wide-web

1.10) Learning Activities


An individual or small group can enrich the following
1. E-Mail
2. Internet Chatting
3. Internet Conferencing
4. Web Security

1.11) Keywords
WWW - World Wide Web
URL - Uniform Resource Locator
HTML - Hyper Text Markup Language
ANNAMALAI
ANNAMALAI UNIVERSITY
HTTP UNIVERSITY
- Hyper Text Transfer Protocol
ISP - Internet Service Providers
Email - Electronic Mail
FTP - File Transfer Protocol

Page 18
Internet and Java Programming

Unit - II
2.0) Introduction
In the earlier lesson, we have seen the basics of Internet, protocols, WWW and
connection to Internet and Intranet browsers. We also looked into E-Mailing and doing FTP’s.
We also had chance to go through the conferencing creations. Above all we made ourselves
familiar with the security of websites.
Going further down this Unit II, we will be discussing the overview of Java, and the
various data types that have been using in Java. Finally, we make you familiar with the most
important concepts of Arrays and control statements. Let us discuss all these topics in detail.

2.1) Objective
The objective of this lesson is to furnish you the introduction and overview of Java
programming language. Java is the efficient and elegant language for Internet programming.
The content of this lesson starts with overview and basic data types, variables, arrays, operators
and control structures in Java.
Towards end of this lesson student will get the idea and basic knowledge about java
programming language and its efficiency.

2.2) Content
2.2.1 Overview of JAVA
Java is an object-oriented, multi-threaded programming language developed by Sun
Microsystems in 1991. It is designed to be small, simple and portable across different platforms
as well as operating systems.
The popularity of java is due to its unique technology that is designed on the basis of
three key elements. They are the usage of applets, powerful programming language constructs
and rich set of significant object classes.

When a program is complied, it is translated into machine code or processor instructions


that are specific to the processor. In the Java development environment there are two parts: a
Java complier and a Java interpreter. The complier generates bytecode (asset of instructions that

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
resemble machine code but are not specific to any processor) instead of machine code and the
interpreter executes the Java program.

Much of the characteristics of java is inherited from C and C++ languages. Infact, several
of java defining characteristics comes from its predecessors. By the end of 1980 and the early of
1990 object oriented programming using C++ took hold. Within few years the World Wide Web
and the Internet would reach critical mass. And this event would precipitate another revolution in
programming.
James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike Sheridian conceived
Java at Sun Microsystems, Inc in 1991. This version was first called as “OAK” but was renamed
as “Java” in 1995.

Page 19
Internet and Java Programming

Java is a portable, platform-neutral language that could be used to produce code that
would run on a variety of CPU’s under different environments. This concept and effort
ultimately led to the creation of Java. First Java was designed, tested and refined by real working
programmers. It is a language grounded in the needs and experiences of the people who advise it.
Thus java is also a programmer’s language. Secondly, java is cohesive and logically consistent.
Third except the constraints imposed by the Internet environment java gives the programmer full
control. While it is true that java is influenced by C++, it is not an enhanced version of C++. Java
was not designed to replace C++. Java was designed to solve a certain set of problems.
Java can be used to create two types of programs: Applications and Applets. An
application is a program that runs on your computer under the operating system of that computer.
That is an application created by java is more or less like one created using C or C++. An Applet
is an application designed to be transmitted over the Internet and executed by a java compatible
web browsers. An applet is actually a java program dynamically downloaded across the network.
The important difference is that an applet is an intelligent program not just an dynamically
change.
The coding in Java is slightly different from conventional interpreted systems. This
change lies in the method for creating a Java program:
 The user writes code in Java.
 The source code is stored in files with the extension 'Java'.
 This source code file is compiled to create a 'class' file.
 This 'class' file contains the 'bytecode'.
It is this byte code that is executed on the target computer. Java was brought into this
world of computing in 1991 by Sun Microsystems of USA. However, Java hit the market in the
year 1995. When the first version of Java was introduced, it was called as Java Alpha.
Generally, the Alpha versions of Software applications and programming languages are
released to developers to be reviewed, provide the comments and fix the errors in the software.
The final version of Java released for implementation was Java Alpha 3 with the following
features.
 It was an object-oriented programming language.
 It was general-purpose in nature. Thus, it is not intended or restricted to a particular area
of programming.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
 Java has syntax similar to that of C and C++. However, Java is said to be simpler because
it has many semantic features.
The original name of this platform independent programming language was not Java as it
is called today. James Gosling, one of the inventors of this programming language, originally
called it Oak.
Java was originally designed to develop software for consumer electronic devices like
toasters, TVs, VCRs, etc. A team of people from Sun Microsystems called the Green Project
demonstrated the use of this new language for electronic devices by making use of small touch
sensitive screens to control the working of these electronic devices.

Page 20
Internet and Java Programming

The Green Project Team consisted of James Gosling, Guy Steel, Bill Joy, Frank Yellin,
Patrick Naughton, Richard Tuck, Arthur van Hoff and some other colleagues. The ‘Green
Project' team developed the language 'Oak' to be able to build software for the small-distributed
systems that would be embedded into the consumer devices.
2.2.1.1 what is Java Virtual Machine?
Java Virtual Machine is nothing but a software concept, based on the idea of an
imaginary computer, which has a logical set of instructions and those instructions, which define
the operations of the computer. It can be thought as a mini operating system. It forms a layer of
abstraction where, the underlying hardware platform, the operating system and the compiled
code is concerned. JVM is not targeted to a particular environment.
2.2.2 Data Types
Data types are nothing but define the type of data. For example age, salary is the types of
data which will have only numerics. The set of data, which will hold only alphabets, are name,
country etc.
Java is strongly typed language. This means that every variable must have the types
declared. There are eight primitive types in Java. Four of them are integer types; two are
floating-point number types; one is the character type and finally the boolean type to have true
or false values.
Note: Java has an arbitrary precision arithmetic package. However. "Big numbers", as they are
called, are Java objects and not a new Java type.
2.2.2.1 Integers
The integer datatypes are storing integer values. There are four types of integer types in
Java. Each of these can hold a different range of values. The values can either be positive or
negative. Depending on the range of values that it should hold, the type of integer is chosen. If
the value becomes too large, it will be truncated. The ranges of values are shown below:
Type Storage Requirement Range (inclusive)
Type Size Range
int 4 bytes -2,147,483,648 to 2,147,483,647
(just over 2 billion)
short 2 bytes -32,768 to 32,767
ANNAMALAI
ANNAMALAI UNIVERSITY
1ong
UNIVERSITY 8 bytes (-9,223,372,036,854,775,808L to
9,223,372,036,854,775,8071 )
byte byte (-128 to 127 s)

Table 2.1: Data Types

In most situations, the int type is the most practical. The byte and the short types are
mainly intended for specialized applications, such as low-level file handling, or for large arrays
when storage space is at a premium.

Page 21
Internet and Java Programming

Under Java, the ranges of the integer types do not depend on the machine on which you
will be running the Java code. This a major pain for the programmer who wants to move
software from one platform to another, or even between operating systems on the same platform.
In contrast, C and C++ programs use the most efficient integer type for each processor. As a
result, a C program that runs well on a 32-bit processor may exhibit integer overflow on a 16-bit
system. Since Java programs must run with the same result on all machines, the ranges for the
various types are fixed.
 Float
Float is used to store numbers with decimal part. There are two floating point data types
in Java namely, the float (32 bits, single precision) and the double (64 bits, double precision).
 Character
It is used to store single characters. The char type has 16 bits of precision and it is
unsigned.
 Boolean
Boolean data types hold either a true or a false value. These are not stored as numeric
values.
 Long
Long is a signed 64-bit type and is useful fo those occasions where an int type is not large
enough to hold the desired value. The range of a long is quite large. This makes it useful, when
big whole numbers are needed.
Long integer numbers have a suffix L (for example, 400000000 OL). Hexadecimal
numbers have a prefix 0x (for example, OxCAFE). Octal numbers have a prefix for example,
010 is 8.This can be confusing, and we recommend against the use of octal constant.

2.2.2.2 Primitive Data Types


Java’s primitive data types are listed below:
 boolean
 char
 byte
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
 short
 int
 long
2.2.2.3 Boolean Literals
The only valid literals of boolean type are true and false. This datatype is practically used
to hold values like yes or no, true or false, male or female etc.
1. boolean isBig = true;
2. boolean isLittle = false;

Page 22
Internet and Java Programming

2.2.2.4 Char Literals


The char type is integral but unsigned. A single character enclosed within single quotes
expresses character literals. Java characters are stored in Unicode, which is a 16-bit encoding. If
the most significant nine bits of a char are all 0, then the encoding is the same as seven-bit
ASCII. The list of special codes that represent non-printable characters shown below:

Escape Meaning
\n New line
\t Tab
\b Backspace
\r Return
\\ Backslash
\’ Single quote
\” Double quote
\ddd Octal
\xdd Hexadecimal
\udddd Unicode character
Table 2.2: Special Codes
The two floating-point types literals they are
 float
 double
These types conform to the IEEE 754 specification. Many mathematical operations can
yield results that have no expression in numbers infinity, for example. To describe such non-
numerical situations, both doubles and floats can take on values that are hit patterns that do not
represent numbers rather, these patterns represent non-numerical values. The patterns are defined
in the Float and Double classes and may be referenced as
 Float.NaN
 F1oat.NEGATIVE_INFINITY
 F1oat.POSITIVE_INFINITY
 Doubte.NaN

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
 Double.NEGATIVE_INFINITY
 Double.POSITIVE.INFINITY )
NaN stands for "Not a Number”. The code fragment below shows the use of these constants:
1. doubled = -10.0 / 0.0;
2. if (d =sss Double. NEGATIVE_INFINITY)
3. System, output int (1n d just exploded: d);
In this code fragment, the test on line 2 passes, so line 3 is executed. All the numerical
primitive types (that is, all except boo1ean and char) are signed.

Page 23
Internet and Java Programming

2.2.2.5 Integral Literals


Integral literals may be expressed in decimal, octal, or hexadecimal. The default is
decimal. To indicate octal, prefix the literal with 0 (zero). To indicate hexadecimal, prefix the
literal with Ox or OX; the hex digits may be upper- or lowercase. The value twenty-eight may
thus be expressed six ways:

 28
 034
 Oxic
 OxIC
 OXIc
 OXIC
By default, an integral literal is a 32-bit value. To indicate a long (64-bit) literal, append
the suffix L to the literal expression. (The suffix can be lowercase, but then it looks so much like
a 1 that your readers are bound to be confused.)

2.2.2.6 Floating-Point Literals

A floating-point literal expresses a floating-point numerical value. In order to be


interpreted as a floating-point literal, a numerical expression must contain one of the following:

 A decimal point: 1.414

 The letter E or e, indicating scientific notation: 4.23E+21

 The suffix F or f, indicating a 32-bit float literal: 1.828f

 The suffix D or d, indicating a 64-bit double literal: 1234d

A floating-point literal with no F or D suffix defaults to a 64-bit double literal.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
2.2.2.7 String Literals

A string is a combination of characters. String literals are a set of characters that are
enclosed within double quotes. As they are real objects, it is possible to concatenate, modify and
test them. For example “String Example” represents a string. Strings can contain character
constants and Unicode characters.

When a string literal is declared Java automatically creates an instance of the class string
and initializes it with the value specified. A string literal is a run of text enclosed in double
quotes.

Page 24
Internet and Java Programming

Example:
Strings = “Characters”
"in strings are 16-bit Unicode.” these are used to store long strings.
2.2.3 Variables
In java, every variable has a type you declare a variable by placing the type first,
followed by the name of the variable.

Examples:
double salary;
int vacation days;
char yeschar;
long earthpolution;
boolean done;
Notice the semicolon at the end of each declaration. The semicolon is necessary because
a declaration is a complete Java statement.
The rules for a variable name are as follows:
A variable name must begin with a letter, and must be a sequence of letters or digits Note
that the terms "letter" and "digit" are much broader in Java than in most of the languages. A letter
is defined as 'A'-'Z', 'a'-'z', '_', or any Unicode character that denotes a letter in a language. All
characters in the name of a variable are significant and case is also significant .The length of a
variable name is essentially unlimited.

2.2.3.1 Variables and Initialization


Java supports variables of two different lifetimes:
 A member variable of a class is created when the instance is created, and is accessible
from any method in the class
 An automatic variable of a method is created on entry to the method, exists only
during execution of the method, and is only accessible within the method.
All member variables that are not explicitly assigned a value upon declaration are
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
automatically assigned an initial value. The initialization value for member variables depends on
the member variable's type. A member value may be initialized in its own declaration line:

class HasVariables {

int x = 20;

static int y = 30;


}

Page 25
Internet and Java Programming

When this technique is used, non-static instance variables are initialized just before the
class constructor is executed; here x would be set to 20 just before invocation of any Has
Variables constructor. Static variables are initialized at class load time; here y would be set to 30
when the Has Variables class is loaded.
Automatic Variables also known as local variables are not initialized by the system every
automatic variable must be explicitly initialized before being used.
For example, the following method will not compile:
public-int wrong( )
{

int i ;

return i+ 5;
}
2.2.4 Arrays
An array is a data structure that stores a collection of values of the same type. Then
access each individual value through an integer index. For example, if a is an array of integers,
then a [I] is the ith integer in the array.

It can declare an array variable by specifying the array type-which is the element type
followed by [] and the array variable name. For example, here is the declaration of an array a of
integers:
Int[] a;

However, this statement only declares the variable a. It does not yet initialize a, with an
actual array. Can use the new operator to create the array.
Int[] a = new int [100];

This statement sets up an array that can hold 100 integers. The array entries are
numbered form 0 to 99 (and not 1 to 100). Once the array is created, you can fill the entries in an
array, For example, by using a loop:
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Int[] a = new int [100];
For (int I = 0; I <100; I++)
A [a] = I; // fills the array with 0 to 9

2.2.4.1 Copying Arrays


One array variable can be copied into another, but then both variables refer to the same
array:

Int[] luckyNumbers = smallPrimes;


luckyNumbers[5] = 12; // NOW SMALLPRIMES [5] is also 12

Page 26
Internet and Java Programming

Following figure shows the result. If actually want to copy all values of one array into
another, you have to use the array copy method in the system class.
The syntax for this call is:
System.arraycopy(from, formIndex, to, toIndex, count);
The two array must have sufficient space to hold the copied elements.
2.2.4.2 Copying an array variable
For example the following statements, whose result is illustrated in set up two arrays and
then copy the four entries of the first array to the second array. The copy the last four entries of
the first array to the second array. The copy stats at position 2 in the source array and copies 4
entries, starting at position 3 of the target.

Figure 2.1: Copying Arrays


Int[] smallPrimes = {2, 3, 5, 7, 11, 13,};
Int[] luckyNumbers = {1001, 1002, 1003, 1004, 1005, 1006, 1007};
System.arraycopy (smallPrimes, 2, luckyNumbers, 3, 4);
For (int I = 0; I < luckNumbers.length; I++)
System.out.println(I + “:” + luckyNubers[I]);
The output is
0: 1001
1: 1002
2: 1003
3: 5

ANNAMALAI
ANNAMALAI UNIVERSITY
4:
5:
6:
7
11
13
UNIVERSITY
2.2.5 Operators
The usual arithmetic operators + - * / are used in Java for addition, subtraction,
Multiplication, and division. The / operator denotes integer division if both arguments are
integers, and floating-point division otherwise. Integer remainder (that is, the mod function) is
denoted by %. For example, 15/2 is^7,15 % 2 is 1, and 15.0 / 2 is 7.5.
Notice that integer division by 0 raises an exception, whereas floating-point division by 0
yields an infinite or NaN result.

Page 27
Internet and Java Programming

Arithmetic operators can be used in the variable initializations:


int n = 5;
int a = 2 * n; // a is 10 Comment
There is a convenient shortcut for using binary arithmetic operators in an assignment.

Figure 2.2: Copying Arrays

For example:

X+=4

is equivalent to

x = x + 4;

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
(In general, place the operator to the left of the = sign, such as *=- or %=.)

Note: One of the stated goals of the Java programming language is portability. A computation
should yield the same results no matter on which virtual machine it executes. For arithmetic
computations with floating-point numbers, it is surprisingly difficult to achieve this portability.
The double type uses 64 bits to store a numeric value, but some processors use 80 bit floating-
point registers. These registers yield added precision in intermediate steps of a computation.

For example, consider the computation:

double w.= x * y / z;

Page 28
Internet and Java Programming

Many Intel processors compute x * y and leave the result in an 80-bit register, then divide
by z and finally truncate the result back to 64 bits. That can yield a more accurate result, and it
can avoid exponent overflow. But the result may be different from a computation that uses 64
bits throughout. For that reason, the initial specification of the Java virtual machine mandated
that all intermediate computations must be truncated. The numeric community hated it. Not only
can the truncated computations cause overflow, they are actually over than the more precise
computations because the truncation operations take time. For that reason, the Java programming
language was updated to recognize the conflicting demands for optimum performance and
perfect reproducibility. By default, virtual machine designers are now permitted to use extended
precision for intermediate computations. However, methods tagged with the strict fp keyword
must use strict floating-point operations that yield reproducible results.

For example, you can tag main as.

public static strict fp void main(String[] args)

Then all instructions inside the main method use strict floating-point computations. If you
tag a class as strict fp, then all of its methods use strict floating-point computations.

2.2.5.1 Increment and Decrement Operators

Programmers, of course, know that one of the most common operations with a numeric
variable is to add or subtract 1. Java, following in the footsteps of C and C++, has both increment
and decrement operators: x++ adds 1 to the current value of the variable x, and x- - subtracts 1
from it.
For example, the code

int n = 12;
n++;
changes n to 13. Because these operators change the value of a variable, they cannot be applied
to numbers themselves. For example, 4++ is not a legal statement.
There are actually two forms of these operators you have seen the "postfix” form of the
operator that is placed after the operand. There is also a prefix form, ++n. Both change the value

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
of the variable by l. The difference between the two only appears when they are used inside
expressions. The prefix form does the addition first; the postfix form evaluates to the old value
of the variable.
int m = 7;
int n = 7;
int a = 2 * ++m; // now a is 16, m is 8
int b = 2 * n++; // now b is 14, n is 8

Many programmers against using + + inside other expressions as this often leads to
Confuse code and annoying bugs.

Page 29
Internet and Java Programming

While it is true that the ++ operator gives the C++ language its name, it also led to the
first joke about the language. C++ haters point out that even the name of the language contains a
bug: "After all, it should really be called ++C, since we only want to use a language after it has
been improved”.

2.2.5.2 Relational and Boolean Operators


Java has the full complement of relational operators. The relational operators determine
The relationship that one operand has to the other. Specifically, they determine equality and
ordering. The relational operators are shown below:

Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Table 2.3: Operators
Example:
Int a=4;
Int b=1;

Boolean (c= =a<b);

Java, following C++, uses && for the logical "and" operator and || for the logical "or"
operator. As you can easily remember from the (! = ) Operator, the exclamation point 1 is the
logical negation operator. The && and || operators are evaluated in “short circuit” fashion. This
means that when you have an expression like:

A && B

Once the true value of the expression has been determined to be false, the value for the
expression b is not calculated.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
2.6.3 Bitwise Operators

When working with any of the integer types, you have operators that can work directly
with the bits that make up the integers. This means that you can use masking techniques to get at
individual bits in a number. The bitwise operators are
&(And)
||(Or)
^(Xor)
~(Not)

Page 30
Internet and Java Programming

these operators work on bit patterns. For example, if n is an integer variable, then

int fourthBitFromRight = ( n & 8) / 8;

gives you a one if the fourth bit from the right in the binary representation of n is one, and a zero
if not. Using & with the appropriate power of two lets you mask out all but a single bit.

2.2.5.4 Mathematical Functions and Constants


The Math class contains an assortment of mathematical functions that may occasionally
need, depending on the kind of programming that you do.
To take the square root of a number, you use the sqrt method:
Double x = 4
Double y = Math.sqrt (x);
System.out.println(y); // prints 2.0
The Java programming language has no operator for raising a quantity to a pow; pow
method should be used in the Math class.
Syntax:
Double y = Math.pow(x,a);
Sets y to be x raised to the power a (x2).
The Math class supplies the usual trigonometric functions
 Math.sin
 Math.cos
 Math.tan
 Math.atan
 Math.atan2
And the exponental function and its inverse, the natural log:
 Math.exp
ANNAMALAI
ANNAMALAI UNIVERSITY
 Math.log
UNIVERSITY
Finally, there are two constants
 Math.PI
 Math.E
That denotes the closest possible approximations to the mathematical constants (pi) and e.

Page 31
Internet and Java Programming

2.2.6 Control Structures


Control structures play a vital role in the java programming. This consists of various
statements. The statements are described below:

2.2.6.1 Switch Statement


The switch statement dispatches control to the different parts of code based on the value
of single variable or expression. The value of expression is compared with each of the literal
values in the case statements. If they match, the following code sequence is executed. Otherwise
an optional default statement is executed. Java switch statement is exactly like the switch
statement in C and C++.
Syntax:
Switch (Expression) {
Case <Value1>:
//statements
Break;
Case <Value2>:
Break;
Case <Value2>:
//statements
Break;
...
...
Default:
//Default Statement
}
For example:
Class ExampleSwitch {

Public static void main (string args[]){


For(int I=0; I<6; I++)
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
switch (I) {
Case 0:
System.out.println(“I is zero”);
Break;
Case 1:
System.out.println(“I is one”);
Break;
Case 2:
System.out.println(“I is two”);
Break;

Page 32
Internet and Java Programming

Case 3:
System.out.println(“I is zero”);
Break;
Default:
System.out.println(“I is Greater than 3.”);
}
}
}
Output:
I is Zero
I is One
I is Two
I is Three
I is greater than 3

Figure 2.3: Flow Chart


2.2.6.2 Do/While Statement
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
This statement executes the block and only then tests the condition. if user want to make
sure a block is executed at least once, user will need to move the tests on to the bottom. This is
done with the help of Do/While loop only.
Syntax:
do {
<Statement1>
<Statement2>
-------------------
} while (condition);

Page 33
Internet and Java Programming

Figure 2.4: Flow Chart


Example:

Class ExampleDoWhile {
Public static void main (String args []) {
Int n=10;

Do {
System.out.println(“check” + n)
n--;
} while (n >0)
}
}

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
2.2.6.3 while statement

This loop executes only the body of the loop while condition is true.

Syntax:
while (condition){
Statement1
Statement2

}

Page 34
Internet and Java Programming

Example:

Class ExampleWhile{
Public static void main(string args[]){
Int n = 10;

While(n > 0) {
System.out.println(“Check” + n);
n--;
}
}
}

output :
Check 10
Check 9
Check 8
Check 4
Check 6
Check 5
Check 4
Check 3
Check 2
Check 1

2.2.6.4 If Statement

The condition must be surrounded by parameters in java, as in most programming


languages, often want to execute multiple statement when single condition is true.

Syntax:

if(<condition>)
{

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
statement1
statement2
….
}
For example:

if (yoursales >= target)


{
performance = “satisfactory”;
bonus = 100;
}

Page 35
Internet and Java Programming

Figure 2.5: Flow Chart


2.2.6.5 If / Else statement
The If / Else statement will execute the code within if block when the given condition is
true. Suppose if the condition is false, the statements within else block are executed.
Syntax:
If (condition)
{
statement1
statement2

}
else
{
statement1
statement2

ANNAMALAI
ANNAMALAI UNIVERSITY
Example:
}
UNIVERSITY
if (yoursales >=target)
{
performance = “satisfactory”;
bonus = 100 + 0.01* (yoursales – target);
}else
{
performance = “unsatisfactory”;
bonus=0;
}

Page 36
Internet and Java Programming

Figure 2.6: Flow Chart


2.2.6.6 For Loop statement
For loop is a determinate loop this is very general construct to support iteration that is
controlled or similar variable that is updated after every iterations.
Syntax:
For (initialization; condition; iteration)
{
// body of loop
}

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Figure 2.7: Flow Chart
The following example prints the number from 1 to 10 on the screen using for loop. Here
the I is initialized to 1 and printed. Then the value of I is incremented by 1 until it reaches 10.
Example:
For(int I =1; I<=10; I++ ){
System. Out.println(I); }

Page 37
Internet and Java Programming

2.3) Revision Points


Java Virtual Machine
A JVM is a piece of software that is responsible for running Java programs. A new JVM is
started whenever you type in java program name on the command line. It is called a virtual
machine since it is software that emulates a physical computer. Java programs have built to be
run on this virtual machine, allowing them to be run on any real machine that has a JVM.

Data types
A data type is a name or label for a set of values and some operations, which can be performed
on that set of values.

Primitive Type
A primitive type is predefined by the language and is named by a reserved keyword. Primitive
values do not share state with other primitive values. There are eight primitive data types
supported by the Java programming language.

Variables
Variables are data identifiers. Variables are used to refer to specific values that are generated in a
program. In other words values that you want to keep around. Program data is often easier to
understand and manipulate if each datum has its own name.

Arrays
An array is a data structure that stores a collection of values of the same type. Then access each
individual value through an integer index

Operators
Java provides a rich set of operators for manipulating program data. Most of these were taken
directly from C/C++, but you must be careful because there are some significant differences to
keep in mind.

2.4) Intext Questions


1. Java is general-purpose language. Discuss.
2. Explain Java Virtual Machine.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
3. Explain the features of Java.
4. Write about the data types available in java
5. Explain any 5 primitive types in java
6. What is an array? Explain with example
7. Explain about increment and decrement operators
8. What is control structure? Explain any two of them with example

Page 38
Internet and Java Programming

2.5) Summary

 Java is an object-oriented, multi-threaded programming language developed by Sun


Microsystems in 1991.

 The complier generates bytecode (asset of instructions that resemble machine code but
are not specific to any processor) instead of machine code and the interpreter executes the
Java program.

 When Java program is complied, it is translated into (machine code or processor


instructions that are specific to the processor) instead of machine code and the interpreter
executes the Java program.

 Most of the characteristics of java are inherited from C and C++ languages.

 The source code is stored in files with the extension 'Java'.

 The source code file is compiled to create a 'class' file.

 The 'class' file contains the 'bytecode'.

 Java Virtual Machine is nothing but a software concept, based on the idea of an
imaginary computer, which has a logical set of instructions and those instructions, which
define the operations of the computer.

 Data types are nothing but define the type of data.

 The integer datatypes are storing integer values.

 There are four types of integer types: int, short, long, byte

2.6) Terminal Exercises


1. Java was conceived by_____________
a) James Gosling b) Andersen c) Tim Berners Lee d) Vintcerf
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
2. Java is Object Oriented Language (True/False)

3. The green project team developed language called OAK (True/False)

4. The floating point literals express a floating point _________ value

5. Automatic variable are also called as _____________ variable

6. Java programming language is not portable (True/False)

Page 39
Internet and Java Programming

7. Which among this considered to be bitwise operator

a) + b) ! c) * d) %

8. In control statement condition should be surrounded by ____________

9.__________ statement is also called Multiple statement.

10. The first version of java language called _________.

2.7) Supplementary Materials


1. Patrick Naughton and Herbert Schildt, "The Complete reference JAVA2" Tata
McGraw Hill Publishing Limited, NewDelhi, 1999.

2. C. Xavier, "Programming with JAVA2", Scitech Publications (India) Pvt. Limited


2000

2.8) Assignment
1. Discuss the platform independent ability of Java
2. Case Study: Java with other programming languages

2.9) Suggested Reading/Reference Books


1. Head First Java By Sierra, Bates, Kathy Sierra, Bert Bates
2. http://www.unix.org.ua/orelly/java-ent/jnut/ch02_04.htm
3. http://javaspecs.com/specs/sp_0011.html
4. http://journals.ecs.soton.ac.uk/java/tutorial/java/javaOO/variables.html

2.10) Learning Activities


An individual or small group can enrich the following
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
1. JVM
2. Operators

2.11) Keywords
Byte code - is a sort of intermediate code that is more abstract than machine code.

JVM - Java Virtual Machine

Page 40
Internet and Java Programming

Unit – III
3.0) Introduction
3.0.1 Classes

The class is the logical construct upon which the entire Java language is built because it
defines the shape and nature of an object. As such, the class forms the basis for object-oriented
programming in Java. Any concept, which is implemented in a Java program, must be
encapsulated with in a class because the class is so fundamental to Java. Here is the introduction
to the basic elements of a class and learn how a class can be used to create objects. This topic
describes also to learn about methods, constructors, and the keyword.

Class Fundamentals
Classes have been used a basic in java. This primarily exists simply to encapsulate the
main () method, which has been used to demonstrate the basics of the Java syntax. As user will
see, classes are substantially more powerful than the limited ones presented so far.

Perhaps the most important thing to understand about a class is that it defines a new data
type. Once defined, this new type can be used to create objects of that type. Thus, a class is a
template for an object, and an object is an instance of a class. Because an object is an instance of
a class, user will often see the two words object and instance used interchangeably.

3.1) Objective
The objective of this lesson is to award the power of java’s object oriented programming
concept. It starts with classes, which attain the OOP’s encapsulate mechanism. It further
provides the skill and knowledge about methods, inheritance, packages, interfaces and data
structures. It discusses the access specifier in detail.

Towards end of this lesson, students should have a comprehensive knowledge of the Java
programming environment and Java’s object oriented ability. Students will have the ability to
develop small programs using Java

3.2) Content
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
3.2.1 The General Form of a Class

When programmer defines a class, he declares its exact form and nature. Programmers do
this by specifying the data that it contains and the code that operates on that data. While every
simple class may contain only code or only data, most real-world classes contain both. A class
code defines the interface to its data.

A class is declared by use of the class keyword. The classes that have been used up to this
point are actually very limited examples of its complete form. As we will see, classes can (and
usually do) get much more complex.

Page 41
Internet and Java Programming

The general form of a class definition is shown here:


class classname {
type instance-variable1;
type instance-variable2;
//...
type instance-variableN;
type methodnamel(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list){
// body of method
}
}
The data, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined with in a class are
called members of the class. In most classes, the instance variables are acted upon and accessed
by the methods defined for that class. Thus, it is the methods that determine how a class' data can
be used.
Variables defined within a class are called instance variables because each instance of the
class (that is, each object of the class) contains its own copy of these variables.
Thus, the data for one object is separate and unique from the data for another. All
methods have the same general form as main(), which have been using thus far. However, most
methods will not be specified as static or public. Notice that the general form of a class does not
specify a main() method. Java classes do not need to have a main() method. One can only specify
one if that class is the starting point for their program. Further, applets don't require a main()
method at all.
3.2.1.1 A Simple Class

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Lets begin our study of the class with a simple example. Here is a class called Box that
defines three instance variables: width, height, and depth. Currently, Box does not contain any
methods (but some will be added soon).
Example:
class Box
{
double width;
double height;
rouble depth;
}

Page 42
Internet and Java Programming

As stated, a class defines a new type of data. In this case, the new data type is called Box.
This name will be used to declare objects of type Box. It is important to remember that a class
declaration only creates a template; it does not create an actual object. Thus the preceding code
does not cause any objects of type Box to come into existence.

The following statement is used to create a Box object

Box mybox = new Box();


// Create a Box object called mybox

After this statement executes, mybox will be an instance of Box. Thus, it will have,
“physical” reality. Again, each time when an instance of a class is created, an object is created
that will contain its own copy of each instance variable defined by the class. Thus, every Box
object will contain its own copies of the instance variables width, height, and depth. The dot (.)
operator is used to access these variables. This operator links the name of the object with the
name of an instance variable.

For example, the following statement is to assign the width variable of mybox, the value
100,

mybox.width = 100;

This statement tells the compiler to assign the copy of width that is contained with in the
mybox object the value of 100. In general, the dot operator is used to access both the instance
variables and the methods within an object. Here is a complete program that uses the Box class:

Example:

/* A program that uses the box class*/

call this file Box


{
double width;
double height;
double depth;
}
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
This class declares an object of type Box.

class BoxDemo
{
Public static void main (string agrs[])
{
Box mybox =newbox();
double vol;

Page 43
Internet and Java Programming

// Compute vol of box


vol=mybox.width *mybox.height*mybox.depth;

system.out.println ("volume is "+vol);


}
}

//*assigning instance variable


mybox.width = 20;
mybox.height = 40;
mybox.depth = 30;

File containing this program BoxDemo.java, since the main() method is in the class
called BoxDemo. The java compiler automatically puts each class into its own class file. It is
necessary for Box and the Demo class to actually be in the same source, put each class in own
file.
3.2.2 Methods

3.2.2.1 Introduction
A method is a large one because Java gives them so much power and flexibility.
However, there are some fundamentals that user need to learn now so that user can begin to add
methods to the classes.

This is the general form of a method:

type name(parameter-list)
{
// body of method
}

Here, type specifies the type of data returned by the method. This can be any valid type,
including class types that are created. If the method does not return a value, its return type must
be void. The name of the method is specified by name. This can be any legal identifier other than
those already used by other items within the current scope. The parameter-list is a sequence of
type and identifier pairs separated by commas. Parameters are essentially variables that receive
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
the value of the arguments passed to the method when it is called. If the method has no
parameters, then the parameter list will be empty.

Methods that have a return type other than void return a value to the calling routine using
the following form of the return statement:

Syntax:
return value;

Here, value is the value returned.

Page 44
Internet and Java Programming

Adding a method to the Box Class although it is perfectly fine to create a class that
contains only data, it rarely happens. Most of the time methods are used to access the instance
variables defined by the class. In fact, methods define the interface to most classes. This allows
the class implementer to hide the specific layout of internal data structures behind cleaner
method abstractions. In addition to defining methods that provide access to data, User can also
define methods that are used internally by the class itself.
Lets begin by adding a method to the Box class. It may have occurred while looking at
the preceding programs that the computation of a box's volume was something that was best
handled by the Box class rather than the BoxDemo class.
After all, since the volume of a box is dependent upon the size of the box, it makes sense
to have the box class compute it. To do this, an user must add a method to Box as shown:
// This program includes a method inside the box class.
class Box
{
double width;
double height;
double depth;
// display volume of a box
void volume()
{
System.out.print("Volume is ");
System.out.printin(width * height * depth);
}
}
class BoxDemo3
{
public static void main(String args[])
{
Box myboxl = new Box() ;
Box mybox2 = new Box() ;

// assign values to myboxl's instance variables


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
myboxl.width = 20;
myboxl.height = 40;
myboxl. depth =30;
/* assign different values to mybox2/s
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9 ;

Page 45
Internet and Java Programming

// display volume of first box


myboxl.volume() ;

// display volume of second box


mybox2.volume() ;
}
}

Volume is 3000
Volume is 162

Look closely at the following two lines of code:

my box 1.volume() ;
mybox2.volume() ;

The first line here invokes the volume() method on myboxl. That is, it calls volume()
relative to the myboxl object, using the object's name followed by the dot operator. Thus, the call
to myboxl.volume() displays the volume of the box defined by myboxl, and the call to
mybox2.volume() displays the volume of the box defined by mybox2. Each time volume() is
invoked, it displays the volume for the specified box.

The following discussion will help to get familiar with the concept of calling a method.
When myboxl.volume() is executed, the Java run-time system transfers control to the code
defined inside volume(). After the statements inside volume() have executed, control is returned
to the calling routine, and execution resumes with the line of code following the call. In the most
general sense, a method is Java's way of implementing subroutines.

There is something very important to notice inside the volume() method: the instance
variables width, height, and depth are referred to directly, without preceding them with an object
name or the dot operator. When a method uses an instance variable that is defined by its class, it
does so directly, without explicit reference to an object and without use of the dot operator. This
is easy to understand about it. A method is always invoked relative to some object of its class.
Once this invocation has occurred, the object is known. Thus, within a method, there is no need
to specify the object a second time. This means that width, height, and depth inside volume()
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
implicitly refer to the copies of those variables found in the object that invokes volume().

3.2.2.2 Returning a Value

While the implementation of volume() does move the continuation of a box's volume
inside the Box class where it belongs, it is not the best way to do it. For example, what if another
part of the program wanted to know the volume of a box, but not display its value? A better way
to implement volume () is to have it compute the volume of the box and return the result to the
caller.

Page 46
Internet and Java Programming

Example:
// Now, volume() returns the volume of a box.
class Box
{
double width;
double heights;
double depth;

// compute and return volume


double volume()
{
return width * height * depth;
}

class BoxDemo4
{
public static void main(String args[])
{
Box mybox1 = new Box() ;
Box mybox2 = new Box() ;
double vol;
}

// assign values to myboxl's instance variables


myboxl.width = 20;
myboxl.height = 40;
myboxl.depth = 30;

// assign different values to mybox2’s

//instance variables
mybox2.width = 6;
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
mybox2.height = 12;
mybox2.depth = 18 ;

// get volume of first box


vol = myboxl.volume();
System.out.println("Volume is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume is " + vol);
}

Page 47
Internet and Java Programming

As shown in the program, when volume() is called, it is put on the right side of an
assignment statement. On the left is a variable, in this case vol, that will receive the value
returned by volume(). Thus, after vol = myboxl.volume(); executes, the value of
myboxl.volume() is 3,000 and this value then is stored in vol. There are two important things to
understand about returning values.
 The type of data returned by a method must be compatible with the return type
specified by the method. For example, if the return type of some method is boolean,
integer cannot be returned.
 The variable receiving the value returned by a method (such as vol, in this case) must
also be compatible with the return type specified for the method.
3.2.2.3 Adding a Method that Takes Parameters
While some methods do not need parameters, most do. Parameters allow a method to be
generalized. That is, a parameterized method can operate on a variety of data and / or be used in
a number of slightly different situations. To illustrate this point, lets use a very simple example.
Here is a method that returns the square of the number 10:
Example:
int square()
{
return 20 * 20;
}
While this method does, indeed, return the value of 20 squared, its use is very limited.
However, when this method is modified to take a parameter, it becomes much more useful.
int square(int j)
{
return j * j;
}

Now, square() will return the square of whatever value it is called with. That is, square()
is now a general-purpose method that can compute the square of any integer value, rather than
just 20.

ANNAMALAI
ANNAMALAI UNIVERSITY
Example: UNIVERSITY
int x, y;
x = square(3); // x equals 9
x = square(4); // x equals 16
y = 5;
x = square(y); // x equals 25

In the first call to square(), the value 3 will be passed into parameter j. In the second call,
i will receive the value 4. The third invocation passes the value of y, which is 5 in this example.
As these examples show, square() is able to return the square of whatever data it is passed.

Page 48
Internet and Java Programming

It is important to keep the two terms parameter and argument straight. A parameter is a
variable defined by a method that receives a value when the method is called. For example, in
square(), i is a parameter. An argument is a value that is passed to a method when it is invoked.
For example, square(l00) passes 100 as an argument. Inside square(), the parameter i receives
that value.
Parameterized method can be used to improve the Box class. In the preceding examples,
the dimensions of each box had to be set separately by use of a sequence of statements, such as:
myboxl. width =20;
myboxl.height = 40;
myboxl.depth = 30;

While this code works, it is troubling for two reasons. First, it is clumsy and error prone.
For example, it would be easy to forget to set a dimension. Second, in well-designed Java
programs, instance variables should be accessed only through methods defined by their class. In
the future, the behavior of a method can be changed, but the behavior of an exposed instance
variable cannot be changed.
Thus a better approach to setting the dimensions of a box is to create a method that the
dimension of a box in its parameters and sets each instance variable separately. The following
program implements this concept.

Example:

// This program uses a parameterized method.

class Box
{
double widths-
double height;
double depth;

// compute and return volume


double volume()
{
return width * height * depth;
ANNAMALAI
ANNAMALAI UNIVERSITY
} UNIVERSITY
// sets dimensions of box
void setDim(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
}

Page 49
Internet and Java Programming

class BoxDemo5
{
public static void main(String args[])
{
Box my box 1 = new Box() ;
Box mybox2 = new Box() ;
double vol;
// initialize each box
myboxl.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
// get volume of first box
vol = myboxl.volume();
System.out println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume() ;
System.out.println("Volume is ." + vol);
}
}
the setDim( ) method is used to set the dimension of each box.
For example , when
Mybox1.setDim (10 ,20 ,15);
Is executed,
10 is copied in to parameter (p)
20 is copied in to h
15 is copied in to d.
Inside setDim the value of w, h, and d are then assigned to width, height, and depth.
3.2.3 Inheritance

3.2.3.1 Understanding Inheritance


Inheritance is one of the corner stone of OOP. Since it allows the creation of
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
hierarchical classification. Using this inheritance, a general class can be created and that
defines traits common to a set of related items. Other, more specific classes unique to it can
inherit this class. In the terminology of java, a class that is inherited is called super class. The
class that does not inheriting is called a subclass.
In other word, the final selling point to object-oriented programming is called inheritance.
Inheritance is the way one object can inherit behavior and attributes from other objects that are
similar to it.

When user start creating objects to use in other programs, he will find that some new
objects like other objects that have already been developed.

Page 50
Internet and Java Programming

Layman could create a new ErrorCorrectionModem object by copying the statements of


the Modem object and revising them. However, if most of the behavior and attributes of
ErrorCorrectionModem are the same as those of Modem, this is a lot of unnecessary work. It also
means that Layman will have to maintain two separate programs if something need to be
changed or debugged later. Through inheritance, a programmer can create a new class of objects
by defining only how it is different from an existing class. Layman could make
ErrorCorrectionModem inherit from Modem, and all he would have to write are the things that
make error-correction modems different than previous modems.
The way a class of objects inherits from another class is through the extends statement.
The following is a skeleton of an ErrorCorrectionModem class that inherits from the Modem
class:

class ErrorCorrectionModem extends Modem


{
// program goes here
}

3.2.3.2 Building an Inheritance Hierarchy


Inheritance enables a variety of related classes to be developed without a lot of redundant
work. It can be passed down from one class to another class to another Class. This system of
classes is called a class hierarchy, and all of the standard classes that are used in the Java
programs are part of a hierarchy.
Knowledge of subclasses and superclasses will be easier to understand an inheritance
hierarchy. A class that inherits from another class is called a subclass, and the class that is
inherited from is called a superclass are already explained above.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Figure 3.1: Modem

Page 51
Internet and Java Programming

In the preceding WarGames example, the Modem class is the superclass of the
ErrorCorrectionModem class, and ErrorCorrectionModem is the subclass of Modem class can
have more than one class that inherits from it in the hierarchy—another sub class of Modem
could be ISDNModem, since ISDN modems Java behavior and attributes that make them
different from error-correcting modems there were a subclass of ErrorCorrectionModem such as
InternalErrorCorrectionModem, it would inherit from all classes above it in the hierarchy-both
ErrorCorrectionModem and Modem.

In many cases, java programmers do not use complicated class hierarchies. However, the
classes that are part of the standard Java language make full use of inheritance. Understanding it
is essential to making the most of the classes that are part of the Java Language.

3.2.3.3 Types of Inheritance

The inheritance allows subclasses to inherit all the variables and methods of their parent
classes. There are different types of inheritance like:

 Single inheritance (only one super class)


 Multiple inheritance (several super classes)
 Hierarchical inheritance (one super class, many subclasses)
 Multilevel inheritance (Derived from derived class)

Java does not directly support multiple inheritances. However, this concept is
implemented using a secondary inheritance path in the form of ‘interface’.

3.2.3.4 Defining a Subclass

A subclass is defined as follows:

class subclassname extends superclassname


{
variables declaration;
methods declaration;
}

The keyword ‘extends’ signifies that the properties of the superclassname are extended
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
to the subclassname. The subclass will now contain its own variables and methods as well as
those of the superclass. Inheritance is very useful in situations when more properties have to be
added to an existing class without modifying it.
The following program creates a new class called Hall, which inherits the members of the
class Room. The class Hall apart from inheriting the members of class Room, includes a
constructor, an extra method volume() and an instance variable height.

Page 52
Internet and Java Programming

Example:

class Room
{
int length;
int breadth;
Room ()
{
length = 14;
breadth = 12;
}
int area()
{
return (length * breadth);
}
}
class Hall extends Room // Inheriting Room
{
int height;
Hall (int z)
{
height = z;
}
int volume ( )
{
return (length * breadth * height);
}
}
class InherTest
{
public static void main (String args[])
{
Hall room1 = new Hall(10);
int area1 = room1.area(); // superclass method
int volume1 = room1.volume(); // baseclass method
System.out.println("Area1 = "+ area1);

}
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
System.out.println("Volume1 "+ volume1);

}
Output:
Area1 = 168
Volume = 1680

In the above program, subclass object is created. This will first call the super class
constructor and then the constructor in the derived.

Page 53
Internet and Java Programming

The object room1 of the subclass Hall then calls the method area defined in the super
class as well as the method volume defined in the subclass itself. Finally, it prints these values.

This particular program makes use of three classes. The base class (Room), the Derived
class (Hall) and another class InherTest. The InherTest class is the class that contains the main
method. Hence program should be saved with the filename as InherTest.java.

3.2.3.5 Multilevel Inheritance

A common requirement in object-oriented programming is the use of a derived class as a


super class. Java supports this concept and uses it extensively in building its class library. This
concept allows building a chain of classes.

The class A serves as a base class for the derived class B, which in turn serves as a base
class for the derived class C. The chain ABC is known as inheritance path.

A derived class with multilevel base classes is declared as follows:

class A
{
.......
.......
}
class B extends A // First level
{
........
........
}
class C extends B // Second level

{
.......
.......

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
3.2.3.6 Use of Super

A subclass object calls the constructor of the super class as well as the subclass. In
addition to this, the subclass constructor uses the keyword super to invoke the constructor
method of the superclass.

For example, if values are assigned to the instance variable of the super class by passing
these values through the superclass constructor, the superclass constructor may not be called at
all, the default constructor of the super class will be called automatically. In such case super
keyword is used along with the number of arguments equal to that in the superclass constructor
that has to be called. The following program uses this concept.

Page 54
Internet and Java Programming

Example:

class Room
{
int length;
int breadth;

Room (int x,int y)


{
length = 14;
breadth = 12;
}
int area()
{
return (length * breadth);
}
}
class Hall extends Room // Inheriting Room
{
int height;
Hall (int x, int y, int z)
{
super (x,y); // pass value
height = z;
}
int volume ( )
{
return (length * breadth * height);
}
}
class InherTest
{
public static void main (String args[])
{
Hall room1 = new Hall(10, 12, 13);
int area1 = room1.area(); // superclass method
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
int volume1 = room1.volume(); // baseclass method
System.out.println("Area1 = "+ area1);
System.out.println("Volume1 "+ volume1);
}
}

Output:
Area1 = 168
Volume1 2184

Page 55
Internet and Java Programming

The keyword super is used subject to the following conditions:

 ‘Super’ keyword may only be used within a subclass constructor method.


 The call to super class constructor must appear as the first statement within
subclass constructor.
 The parameters in the super class must match the order and type of the instance
variable declared in the super class.
3.2.3.7 Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type signature
as its methods in super class then the method in the subclass is said to be overriding. When
overridden method is called using the subclass object, it will always refer to the version defined
by the subclass. The version of the method defined by the super class will be hidden. The
following example demonstrates this property.
Example:
class Base
{
Base()
{
System.out.println("Constructor of super class");
}
void fun1()
{
System.out.println("Function inside Super class is called");
}
}
class Sub extends Base
{
Sub()
{
System.out.println("Constructor of sub class");
}
void fun1()
{

} ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
System.out.println("Function inside Sub class is called");

}
class MethodOverloadingDemo
{
public static void main (String args[])
{
Sub s=new Sub();
s.fun1();
}
}

Page 56
Internet and Java Programming

Output:
Constructor of super class
Constructor of sub class
Function inside Sub class is called

In the above program, the object of class Sub calls the method fun1(). Since this method
has been overridden in the Sub class, only the method in the derived class will be called.
However, if the method had not been overridden in the derived class, the method fun1() in the
base class will only be called. This is shown in the following example.

Example:

class Base
{
Base()
{
System.out.println("Constructor of super class");
}
void fun1()
{
System.out.println("Function inside Super class is called");
}
}
class Sub extends Base
{
Sub()
{
System.out.println("Constructor of sub class");
}
/* void fun1()
{
System.out.println("Function inside Sub class is called");
}*/
}
class MethodOverloadingDemo
{
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
public static void main (String args[])
{
Sub s=new Sub();
s.fun1();
}
}
Output:
Constructor of super class
Constructor of sub class
Function inside Super class is called

Page 57
Internet and Java Programming

3.2.3.8 Converting Objects and Simple Variables

One of the most common tasks that need to be accomplished in Java is to convert
information from one form into another. There are several types of conversions that can be done:

 Converting an object into another object.

 Converting a simple variable into another type of variable.

 Using an object to create a simple variable.

 Using a simple variable to create an object.

Simple variables are the basic data types are already seen in the beginning of this chapter.
These types include int, float, char, long, and double. When using a method or an expression in a
program, the right type of information must be used which is expected by these methods and
expressions. A method that expects a string object must receive a string object, for instance. If a
floating-point number passed as an argument to a method, which holds an integer argument, an
error would occur when this method is executed.

Converting information into a new form in a program is called casting. Casting produces
a new value that is a different type of variable or object than its source. There is no need to
change the value of a variable or object when it is cast. Instead, a new variable or object is
created in the format as per the need.

3.2.4 Packages and Interfaces

3.2.4.1 Introduction

Reusability of code is one of the most important requirements in the software industry.
Reusability saves time, effort and also ensures consistency. For example, a class once defined
and then used repeatedly will ensure that all applications using a particular class will have
identical behavior.

The main requirement for reusability to be successful is the ability of the program to

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
incorporate the reusable code easily in a given application. In Java, “Packages” will be used to
reuse the existing code.
Consider the class "Circle" that calculates the following for a circle:

 Area

 Circumference

In Java, all reusable code is put into packages. A package is a collection of classes,
interfaces and/or other packages. Packages are essentially a means of organizing classes together
as groups.

Page 58
Internet and Java Programming

In short, packages are useful for the following purpose:

 Packages allow to organize the classes into smaller units (such as folders) and make it
easy to locate and use the appropriate class file.

 It helps to avoid naming conflicts. When working with a number of classes, it


becomes difficult to decide on names of the classes & methods. At times if a user
wants to use the same name, which belongs to another class. A Package basically
hides the classes and avoids conflicts in names.

 Packages allow protecting the classes, data and methods in a larger way than on a
class-to-class basis.

 Package names can be used to identify the classes.

Packages need not be only a collection of classes and interfaces. They can also contain
other packages, each level representing a smaller, more specific grouping of classes.

3.2.4.2 Accessing Java Package Members

Consider a class 'My_Class' to be defined inside the package 'My_Package'. To access


this class, use the notation:

Example:

My_Package.My_Class

Thus, members of the package are accessed using the "dot notation". The same holds true for
members of sub-packages also:

Example:

My_Package,My_Sub_Package.My_Class

3.2.4.3 Including a Package


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
To be able to use the members of a package, the packages should be included explicitly
in the Java program. This is done using the 'import' statement as shown:

For Example:

import package_name.*;

The above line includes all classes / interfaces that are found in the package. To include a
specific class / interface found in a package use the notation:

Page 59
Internet and Java Programming

For Example:
import package_name.class_ name;
Discuss and explain why exactly do we require importing a package. What will happen if
a package is not included in the program? The above statement imports only the specified
member and not the other class members. Thus, user may include all or only some of the
members in a package.
3.2.4.4 Including Sub-Packages
Include all classes/interfaces to be found in specified package but not any sub-packages
or their members. Consider the following Hierarchy:

Figure 3.2: Hierarchy

ANNAMALAI
ANNAMALAI UNIVERSITY
For Example:
UNIVERSITY
Import Main_package.*; (Refer above figure)
We will include the classes:
 Class_l
 Class_2
 Class_3

in the Java program but not the sub-packages 'Sub_Package_1, 'Sub_Package_2' and
‘Sub_Package_3'. To include the members of a particular sub package use the notation:

Page 60
Internet and Java Programming

Syntax:
import package_name. sub_package_name. *;
Example:

import Main_Package.Sub_Package_3.*;

We will include the classes:

 Class_31

 Class_32

Thus, it is necessary to import classes of each package or sub-package individually.

Syntax:

import Main_Package.*;

For Example:

will include all the packages inside the Main_Package

import MainPackage.SubPackage1*; Class 11 Class12

import MainJPackage.Sub_Package2.Class_21; Class21

import MainPackage.Sub_Package3.Class_32; Class32

into the Java program.

There are three packages that are essential to any Java program:
 java.lang
 java.io
ANNAMALAI
ANNAMALAI UNIVERSITY
 java.util UNIVERSITY
3.2.4.5 java.lang
The package 'java.lang' contains classes that form the base of the design of the
programming language in Java. One of the most important classes defined in this package is
"Object" and it represents the root of the class hierarchy. Java does not have 'free' methods, i.e.
methods not belonging to any class. All methods in Java must always belong to some class. Data
type conversion functions are required very often. These functions have to be associated with a
class in Java. Thus, Java defines Wrapper classes that enable us to treat even primitive data types
as objects.

Page 61
Internet and Java Programming

Some variables that are declared by using the primitive Java data types are not objects
and cannot be created and accessed using methods. These primitive types cannot be subclassed
either. To solve this problem, the java.lang package defines the "wrapper" classes. These classes
enhance the properties of methods such as class conversion, equity checks, hash codes and value
testing. The constructors used for the wrapper classes allow objects to be created and then
converted to primitive values and strings.

This package also holds 'wrapper' classes such as Boolean, Character, Integer, Long,
Float, and Double. The primitive datatypes of int, char etc. are not objects, but still placed in this
package because many a times there is a necessity to treat them as objects. For example, when a
particular datatype is converted to another.

Other classes found in this package include:

 Math - Provides commonly used mathematical functions such as sine, cosine, and square
root.

 String & String Buffer - Encapsulate commonly used operations on character strings.

Mention the cases where the above classes will be used like the string classes will be useful to
use methods like compareTo( ) and equals( ).

Java.io

Java uses a 'stream' for all its input and output operations. A 'Stream' is a sequence of
bytes read or written over a period of time. The package 'java.io' has two very important abstract
classes:

 InputStream - This class defines the basics, which deals with the required classes used
for input operations.

 OutputStream - This class is the basis for all classes that deal with output operations.

Since these are abstract classes, they cannot be used directly but must be inherited. All
I/O stream classes are derived from either of these classes. Using classes derived from
InputStream and OutputStream, user can only read from and write to files respectively. The
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
same classes for both read and write operations cannot be used.
The exception to this rule is the class RandomAccessFile. This is the class used to handle
files that allow random access and is capable of mixed reading and writing operations on a file.
The basic input output methods like println( ) do not require to have import statements as these
methods are built in the compiler itself.
In addition, there are two other interfaces:
 DataInput
 DataOutput

Page 62
Internet and Java Programming

These classes are used to transfer data other than bytes or characters. For example, these
classes are used to handle data such as long integers, floating-point numbers and strings.
java.util
The package 'java.util’, as the name indicates, contains classes and interfaces that provide
additional utility but may not be vital. One of the most important classes in this package is the
class Date. This class provides a means to conveniently represent and/or manipulate date and
time information. In Java, dates may be constructed from any of the following six components:

 Year
 Month
 Day of month
 Hour
 Minute
 Second
Given a date, any of these six components (including the day of the week) can be
determined. In addition, the class also enables us to account for time zones, thus saving time to
write a code for the purpose. One of the interesting classes in this package is the class Random.
This class provides several methods that can be used for generating random numeric values of
various primitive types. In Java, the size of an array is fixed. However, Java provides us with the
ability to change the size of an array through the class Vector. This class also has methods that
enable adding, removing and searching for items within an array.

Thus, packages are nothing but Java files to be found in the respective sub-directory.
Thus, the line of code:

import java.awt.*;

means include all classes to be found in the sub-directory 'java\awt’ at

c:\windows\java\classes\..

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The following shows the legal and illegal declarations where packages are concerned.

Legal:

Package mypackage;
Import java.io*;
class ABC
{
…..
…..
}

Page 63
Internet and Java Programming

Illegal:
Import java.io*;
Package mypackage;
class ABC
{
…..
…..
}

Note: This means that while creating packages the package declaration must be made before the
import statements.
While importing a package
 A specific file or the entire package can be imported.
import java.mypackage.calculate
import java.mypackage.*;
The Java Virtual Machine keeps a track of all the elements present in the package that is
imported.

3.2.4.6 Creating a Package

Before creating a package, it is important to note that all the members of the package are
to be defined as public, if they need to be accessed from outside the package.
// First declare the package
package mypackage;

public class calculate {

public double volume(double height, double width, double depth ){

Return (height*width*depth);
}

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

public int divide(int x, int y){


return (x / y);
}
}
All the members of the package need to be defined as public, if they need to be accessed
from outside. To use this package, do the following steps:

Page 64
Internet and Java Programming

 Import the class to be used


 Import the entire package
 Refer to its members
Finally compile this file. It can be compiled with -d option whereby it creates a folder
with the package name and places the class file into this folder.
For Example:
Javac -d c:\JavaProgs\mypackage Calculate.java
The above command when issued ensures that the compiler creates a folder called mypackage in
our JavaProgs directory and stores the Calculate.class into this folder.
The following example shows how to use a packageimport java.io.*;
import mypackage.Calculate;

class PackageDemo
{
public static void main(String args[j)
{
Calculate calc=new Calculate();
int sum = calc.add(10,20);
double vol = calc.volume(10.3f,13.2f,32.32f);
int div = calc.divide(20,4);
System.out.println('The addition is :”+ sum);
System.out.println(“'The Volume is : '+ vol);
System.out.println(“The division is : "+ div);
}
}
If a class is used from a different package without using the import statement for that
package, then the class name with the package name should be used.
mypackage.Calculate calc=new mypackage.Calculate();
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
3.2.4.7 Setting of CLASSPATH
The compiler and the interpreter search for the classes in the current directory and the zip
file that consists of JDK class files. This means that the JDK class files and the current directory
are automatically set in the CLASSPATH. However, in some cases, the CLASSPATH must be
set.
A CLASSPATH is a list of directories, which the compiler and the interpreter use, to
search for the respective class file. Generally setting the CLASSPATH environment is not
advisable as it is long lived. Setting the CLASSPATH at runtime is preferable as it sets the path
for the current execution.

Page 65
Internet and Java Programming

Syntax:
javac -classpath c:\JavaProgs Packagedemo.java
The order of entries in the classpath is very important. When the code is executed, the
Java Virtual Machine looks out for the class by searching the entries in classpath in the same
order as mentioned, until it finds one.

3.2.5 Interfaces
Inheritance plays a very important role in saving the time and energy of programmers by
reusing the existing code. Most real life programs make use of something called multiple
inheritances. In multiple inheritances, methods and properties can be inherited from several
different classes. Java does not support multiple inheritances. However seeing the importance of
multiple inheritances, Java introduces the concept of interface.
An Interface is a kind of class, which contain methods and variables. The difference lies
in the way of defining the abstract methods by the concept of interfaces. Also in interfaces, data
fields only contain constants. Classes have the ability to define objects, while interfaces define a
set of methods and constants to be implemented by another object. Interfaces enable to define a
certain set of functionality without having any idea as to how this property of the function will be
later defined.
For Example:
class Demo implements Mycalc
The above statement shows the relationship provided by interface. A class can implement
as many interfaces as it needs, in addition to extending a class.
For Example:
class Point extends Applet implements Runnable, ActionListener. Now need to do is to
separate the interfaces with a comma after the keyword implements.
In short, an interface is a template of behavior (in form of methods) that other classes
need to implement. This means that the body of the method is empty. The program given below
will explain the purpose.
public interface myinterface
{
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
public void add(int x,int y);
public void volume(int x, int y , int z);
}
Compile it like as follows:
javac -d c:\JavaProgs\mypackage my interface. Java
When the above command is executed, a directory by the name "mypackage" is created
and inside it will reside the ".class" file of myinterface. If the directory already exists, it will just
overwrite the current directory with the new contents.

Page 66
Internet and Java Programming

Interfaces cannot extend classes but can extend other interfaces. If an interface is
implemented to extend another interface then the methods in the new interface as well as in the
old interface has to be replaced. In the above example, the methods have just been declared and
not defined. These methods have to be defined in the class that implements this interface, i.e.,
now need to specify the behavior of the method. All methods in the interfaces have to be of type
public. It is illegal to use any other standard modifiers, such as protected, private etc., when
declaring the methods in an interface.
For Example:
The following example shows the implementation of the interface.
import java.io.*;
import mypackage.*;
class demo implements myinterface
{
public void add(int x, int y)
{
System.outprintInC' "+(x+y));
public void volume(int x, int y, int z)
{
System.outprintIn(“ “ +(x*y*z));
}
public static void main(String args[])
{
demo d= new demo( );
d.add(10,20);
d.volume(10,10,10);
}
}
Compile the code with the following command.
javac -classpath c:\mypackage demo.java
Interfaces are also used to define a set of constants that can be used by the classes. The
code given below, displays this property.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
public interface myconstants
{

public static final double price = 1450.00;


public static final int counter = 5;
}

Hence, Interfaces helps to declare a set of properties without having the knowledge as to
how these properties are to be implemented. This, which will be later, defined by the class that
implements it.

Page 67
Internet and Java Programming

3.2.6 Modifiers
Modifiers are keywords that give additional meaning to code and classes. There are 2
types or categories of modifiers
 Access modifier
 Non access modifier
The features of a class, such as
 the class itself
 its instance variables
 its methods and constructors
are accessible or not acceptable from other classes depending upon which access modifier is
used. The Access modifiers are
 Public
 Protected
 Private
 Public access modifier
A class's features are available to other classes within the same package or in a different
package, only when the public access modifier is used. The public access modifier, as its name
suggests, makes the class features publicly available to any class.
 Protected access modifier
The protected access modifier restricts access to a class's features to a certain extent.
Unlike public access modifier, protected access modifier allows access to the class itself,
subclasses and all the classes present in the different packages. Protected access modifiers are
used when user want to restrict the access to certain features of a class.
 Friendly access modifier
Friendly is not a key word, but in absence of any modifier for class or variable or method,
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
they get this modifier. They become friendly i.e. it can access from any class in the same
package. Even if a class in another package inherits this class, it cannot access its friendly
method or variable.
3.2.6.1 Other Modifiers
 Static
 Final
 Abstract
 Native and Volatile

Page 68
Internet and Java Programming

Other Modifiers - Static


Static modifier is a different kind of a modifier. It can be used with a variable, a method
or a block of code. A Static variable or method or block of code in the class is not instance
specific i.e. it can be used with the Classname and there is no need to create an object of the class
to access he static feature of the class. The following example shows how static variable of a
class can be accessed

class StaticModifier
{
static int i = 10;
intj;
StaticModifierO
{
J-20;
}
}

Note: User can access static variables with an object, but there is no meaning in doing that
because the value contained in the static variable is same for all the objects.

Some important points regarding static variables or methods


 static variables of a class are accessed by static methods only.
 static methods of a class are invoked by static methods only.

 static method does not have 'this’


 static method can not be overridden by non-static method
Other Modifiers - Final
Java provides a unique modifier named 'final'. Here is how it operates:
 A method declared ' final’ cannot be overridden in the subclass
 A variable defined as 'final' is a constant
 A class declared as being 'final' cannot be subclassed.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Thus the modifier 'final' is added to a class when its specification is frozen. The final
modifier is used with variables and methods and classes. This modifier when used with

 variable - indicates that once a value is assigned, it can not be changed.


 method - indicates that method body can not be changed.
 Class - indicates that this class can not be subclassed

Page 69
Internet and Java Programming

The following program shows use of final modifier


class FinalDemo
{

public static void main(String args[])


{
final int noChange = 20;
noChange = 30;
System.out.println(" Value of noChange = "+ noChange);
}
}

When programmer compiles this program, he will get the following error message

FinalDemo.java: 5 : can't assign a value to a final variable : noChange


noChange =30;
1 error.

Other Modifiers - Abstract

The abstract modifier can be used with classes and methods. This keyword when used
with:

 Class - indicates that the class cannot be instantiated.

 Method - indicates that the implementation of the method must be provided in the
subclass of this abstract class.

In the following circumstances a class becomes abstract

 When one or more methods of a class are abstract

 When the class is a subclass of an abstract class and does not provide any implementation
details or method body to any of the abstract methods

 When a class implements an interface and does not provide implementation details or
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
method body to any of the abstract methods.

The following code shows an example of abstract methods

abstract class Employee


{
int basic = 2000;
abstract void salary( );
}

Page 70
Internet and Java Programming

class Manager extends Employee


{
void salary()
{
System.out.println(“Salary = "-basic);
}
}
class Worker extends Employee
{
void salary( );
{
System.out.printIn("Salary = "+basic*2);
}
}
class AbstractDemo
{
public static void main(String args[])
{
Manager m == new ManagerQ;
System.out.println(“Manager");
m.salary( );
Worker w = new Worker();
System.out.println(”Worker");
w.salary( );
}
}

The output of the above program is

Manager
Salary = 70000
Worker
Salary=4000
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
In the above program, the method salary is an abstract method and hence the class Employee is
also declared as abstract. The class Manager and Worker inherit class Employee and provide
implementation details for the method salary.

 Other Modifiers - Native

The modifier native can be used only with methods. The word indicates that the body of
the method will be provided elsewhere i.e. outside Java Virtual Machine. So native code is
written in a language other than Java and is compiled for the native machine.

Page 71
Internet and Java Programming

 Other Modifiers - Synchronized


The modifier synchronized is used to control multithreaded programs. This is explained
in detail in the topic Multithreading.

 Other Modifiers - Volatile


This modifier is used only with variables and it indicates that the value of the variable
may be changed.

3.2.7 Access Specifiers


One of the most popular modifiers as applied to a class, method or variable are access
specifies. These are keywords that when applied to a method or variable decide the visibility and
access of the particular element.

Visibility defines whether the user realizes there is such a member in the class at all while
access decides who can use the element.

 The Need For Access Control


A given class may define many methods and variables; however, other members of a
class define several of these for internal use. In such a situation it would be advisable to hide
members meant for internal use from the user of the class.

For example, a class that calculates area and circumference of a circle might use a
method to calculate the value of pi. This method need not be accessible to the user and so must
be hidden.

Another situation is that when a class Cylinder is created by inheriting from Circle, it
must not be able to access the method that calculates the value of pi while the user of the class
still cannot. Thus, the method that calculates pi is visible and accessible to the members within
the class.

3.2.7.1 Types of Access Specifiers

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
There are three main types of access specifiers:
 Private
 Public
 Protected
Private Members
When a member of a class is declared as being private, only the members of the same
class can access it. The users of the class cannot access the private members, neither can the
inherited classes.

Page 72
Internet and Java Programming

Example:

public class circle


{
private double pi * 22.00/7.00;

public double area(double r)


{
return pi*r*r;
}
public double volume(double r, double h)
{
return pi*r*r*h;
}

public double circumference(double r)


{
return 2 * pi * r;
}
}

The variable 'pi' can be accessed only by the members of the class 'Circle* and no one
else. Any variable/method created in a class has the default access specifier as 'private’.

Public Members

As opposed to 'private' members, 'public' members of a class are available to all. All sub-
classes can access 'public' members, as can all the users of the class. Thus, in the above class
'Circle', all the methods are accessible from everywhere. Members of other packages can access
these members as well.

Protected Members

Protected member are those that are accessible to any class within a package. However,
when accessed from outside a package, only the subclass of a class, in which they are declared,
can access the protected member.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Here are some rules that govern the use of access specifier:
 A method declared in a class without an access specifier is an implicitly declared a
private method
 Methods that are declared public in a superclass must also be public in the subclass.
 Methods that are specified to be private cannot be inherited at all.
 Local variable cannot have access specifier attached.

Page 73
Internet and Java Programming

3.3) Revision Points


Class
A class defined as logical construct. A class consists of a collection of types of encapsulated
instance variables and types of methods, possibly with implementation of those types together
with a constructor function that can be used to create objects of the class.
Method
The term method refers to a piece of code that is exclusively associated either with a class or
with an object. A method usually consists of a sequence of statements to perform an action, a set
of input parameters to parameterize those actions, and possibly a return value.
Inheritance
Inheritance is a mechanism a class to derive data and behavior from another class. This supports
reuse and maintainability.
Package
A set of Java classes organized for convenience in the same directory. Package is a name space
for collection of classes and interfaces. Using ‘import’ keyword we can use the package in our
programs or applications.
Interface
It is a Java language’s keyword, which is used to declare a class-like structure. An interface can
declare attributes and methods, but it cannot provide method implementations. Any class
implementing the interface is required to define the interface's method bodies.

Access Specifiers
Access specifiers in Java can access the Scope of variables. There are four levels of access
specifiers in Java. They are Public, Private and Protected.

3.4) Intext Questions


1. Explain about classes with example
2. Write a note about methods
3. What is inheritance? And explain types of inheritance
4. Explain the term CLASSPATH

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
5. Explain about packages and interfaces
6. What are modifiers? Explain any 3 of them
7. Write about access specifiers
8. Explain final
3.5) Summary
 Classes have been used a basic java programming
 This primarily exists simply to encapsulate the main () method, which has been used to
demonstrate the basics of the Java syntax.

Page 74
Internet and Java Programming

 Class is declared by use of the class keyword.


 Parameters allow a method to be generalized.
 Inheritance is one of the corner stone of OOP.
 It allows the creation of hierarchical classification.
 Inheritance is the way one object can inherit behavior and attributes from other objects
that are similar to it.
 Inheritance enables a variety of related classes to be developed without a lot of
redundant work.
 Knowledge of subclasses and superclasses will be easier to understand a inheritance
hierarchy.
 A class that inherits from another class is called a subclass, and the class that is inherited
from is called a superclass.
 Converting an object into another object.
 Converting a simple variable into another type of variable.
 Using an object to create a simple variable.
 Using a simple variable to create an object.

3.6) Terminal Exercises


1. The data, or variables, defined within a class are called _________________
2. In java, method can be any valid type (true/false)
3. Inheritance is one of the corner stone of ______________
4. Inheritance can be passed down from one class to another class to another
Class (true/false)
5. Package is the collection of ___________ and_____________

6. Name the three packages that are essential to any Java program?
7. Boolean, Character, Integer, and Double holds_______________class
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
8. Name any two interfaces?
9. Java does not support multiple inheritance.(true/false)
10. An Interface is a kind of Class which contain __________ and ____________

3.7) Supplementary Materials


1. “Java: The Complete Reference, J2SE TM” By Herbert Schildt
2. “Sams Teach Yourself Java 2 in 24 Hours” By Rogers Cadenhead

Page 75
Internet and Java Programming

3.8) Assignment
1. Develop small applications using Java and test access specifiers behavior
2. Case Study: Java’s object oriented ability
Access Specifiers

3.9) Reference Books


1. “Core Java 2” By Cay S., Horstmann, Gary Cornell
2. “Java Programming for the Absolute Beginner” By Joseph P. Russell

3.10) Learning Activities


An individual or small group deepens the following:
1. Inheritance
2. Packages and Interfaces

3.11) Keywords
Instance variables - The data, or variables, defined within a class are called.

Parameters - A value or object, which is used to transfer information to or


from subprograms

super - used to invoke the constructor method of the super class.

Casting - Converting information into a new form in a program

Wrapper classes - enable us to treat even primitive data types as objects.

InputStream - This class defines the basics, which deals with the required
classes used for input operations.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
OutputStream - This class is the basis for all classes that deal with output
Operations.

CLASSPATH - a list of directories, which the compiler and the interpreter use, to
search for the respective class file.

Overriding - In a class hierarchy, when a method in a subclass has the same


name and type signature as its methods in super class then the
method in the subclass is said to be overriding

Page 76
Internet and Java Programming

Unit – IV
4.0) Introduction
This Session starts with an introduction to Errors and the causes of Errors in the Java
programming Language. It also goes on to explain the Exceptions and handling Exceptions in
Java. The session also covers how to make use of the try() and catch() block. It then goes on to
explain how different exception handling techniques can be used in a Java program. This chapter
also includes a description on the Error class. It also explains the runtime Exception that occurs
in Java.

4.1) Objective
The objective of this lesson is to provide you the skill and knowledge about Java’s more
powers such as Exception Handling, Multithreaded Programming, I/O Streams, String Handling
and Utility classes. Content of this lesson starts with exception handling technique in Java and it
completely provides all in detail. It also provides the Java Networking.

Towards end of this lesson student can understand and the Java’s ability and they can
develop a complete Java applications their own.

4.2) Content
4.2.1 Exception Handling
4.2.1.1 Understanding the Exception Handling

Whenever an Error is encountered while executing a program, an Exception is said to


have occurred. An Exception can also be termed as a special type of error. It arises at run time in
a code sequence. Mostly, due to abnormal conditions that occur at the time of running the
program.

It is essential that a programmer foresees these conditions and takes care of them by
writing proper error messages to be flashed when the program encounters an error. If these
conditions are not dealt with properly, the running program can be terminated abruptly.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
When an exception is occurred, an object, which represents that exception is created and
passed to the method where the exception has occurred. This object contains detailed information
about the exception, which can be retrieved and processed. Exceptions can be thrown by run-
time environment such as IllegalAccessException or EmptyStackException etc. or it can be
manually generated by the code. Throwable class provided in the language is the super class of
Exception class, which in turn is a super class of individual exceptions.

Error and exception handling is used to foresee and identify error conditions and perform
processing to take care of their impact.

Page 77
Internet and Java Programming

For Example:
A program segment in C
fp = fopen( “xyz.txt”, "rw”);
Now, if the file "xyz.txt” does not exist, an exception occurs.
In programming languages such as C, errors can be dealt with in the normal running of a
program. A large portion of a well-written program is concerned with what to do when things go
wrong. When looking at a program written in a language like C, in which you are forced to
handle errors with the help of return codes, the actual algorithm being used in a procedure
becomes difficult to see, as there is an error checking code inserted every few lines.
Excellent exception handling mechanism minimizes the chances of a system crash or
abrupt termination of programs. This feature of Java language makes it a robust language.
4.2.1.2 Exceptions in Java
Java provides an exception-handling model that allows you to check for errors where it is
relevant to do so. It implements a catch and throw model of exception handling similar to the one
used in C++. Using this model, you only have to pay attention to exceptional conditions where it
makes sense to do so. Instead of returning errors from a method using the normal return value or
parameter mechanism, Java provides an exception handling facility.

Errors and other exceptional conditions are treated as distinct from the normal flow of
control in the program, which, after all, they are. When an error occurs, an exception is thrown.
Exceptions climb the chain of calls until they are caught or until the program exits.

The catch and throw method of exception handling offers two big advantages:

 An error condition can be dealt with only where it makes sense instead of dealing with
it at every level between where it occurs and where it needs to be dealt with.

 Code can be written as if the error message for a particular error, which you expect to
occur, works, when the particular error is caught.

4.2.1.3 Try and Catch

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The fundamental language support for the catch and throw method of exception handling
is the try / catch block. Look at the try block listed below:
try
{
doFileProcessing();
displayResults();
}catch (Exception e)
{
System.err.println("Error :” + e.getMessage( ) ;
}

Page 78
Internet and Java Programming

Any error that occurred during the execution of doFileProcessing( ) or display Results( )
would be caught by catch( ) and processed as specified. If an error occurred during
doFileProcessing( ), the method displayResults( ) would never get called, and the execution
would proceed directly to the catch block. If, instead of having (Exception e), we had a more
specific error class, (such as LookupException e), the actual error would have to be an instance
of the LookupException or one of its subclasses that is to be caught. Otherwise, the error would
pass through this try / catch block and continue to climb the call chain until it encounters a catch
that matched it until the program is terminated. (The code given above uses the System object,
which provides standard input and output streams for reading character data and for printing
output).
You can also use multiple catchQ blocks together and process various exception types
differently.
This is listed in the code given below.
try
{
doFiIeProcessing ();
displayResults();
}
catch (LookupException e)
{
handleLookupException (e);
}
catch (Exception e)
{
System.err.println( "Error: " + e.getMessage ( ) );
}
In this case, a LookupException would be caught and processed by the first catch and any
other type of exception would be handled by the second catch.
4.2.1.4 The finally Statement
Exceptions can cause control to leave the current method without completing the
method’s execution. If there is a cleanup code such as the code required to close files at the end

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
of the method, it will never get called. To deal with this, Java provides the finally statement. The
finally statement can be used in conjunction with a try() block. Basically, it ensures that if an
exception has occurred, any cleanup work, which is necessary, is taken care of. This is because
the code in a finally statement is guaranteed to run whether an exception occurs or not.

Example:

try
{
doSomethingThatMightThrowAnException ( );
}

Page 79
Internet and Java Programming

finally
{
cleanup ();
}
If the doSomethingThatMightThrowAnException() throws an exception, the cleanup ()
method will still be called and then the exception will continue to travel up the call chain. If an
exception is not thrown, cleanup () will get called and execution will proceed after the finally
statement
The following is the model of an exception-handling block
try
{
//place code which is expected to throw an exception
)
catch(Exceptloop el)
{
// if exception is thrown in the try block which of type el 9 then perform

//necessary actions here else go to next catch block


}
catch(Exception e2)
{
// if exception thrown in the try block is of type e2, then perform necessary
//actions here else go to next catch block
}
catch(Exception eN)
{
// if exception is thrown in the try block of type eN, then perform necessary
//actions here else go to next catch block
}
finally
{
//Finally executes this block whether an exception is thrown or not
}
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Following are the different types of exceptions your code can throw
RuntimeException
ArithmeticException
IllegalArgumentException
ArrayIndexOutOfBoundsException
NullPointerException
SecurityException

Page 80
Internet and Java Programming

NoSuchElementException
ClassNotFoundException
AWTException
DataFormatException
SQLException
lOException
UnKnownHostException
SocketException
EOFException
MalformedURLException
FileNotFoundException
IllegalAccessException
NoSuchMethodException
 We need to handle each exception separately
Whenever an exception occurs, in the program in which proper exception handling
mechanism is not provided, the program aborts, leaving all the resources previously allocated in
the same state. This can lead to resource leak. To avoid this, in a proper exception handling
mechanism we can return all the resources which are previously allocated by the system to the
system. So each exception must be handled separately by keeping in mind when they might
possibly occur.
An example of this is when we deal with file I/O. We open a file and while writing to the
file if lOException occurs, program aborts without closing the file. This may damage the file and
the resources allocated to the file may not return to the system.
 Try Block
The try block consists of a set of executable statements that can possibly throw exception
while executing them. A method, which may throw an exception, can also be included in the try
block. A try( ) block can be followed by one or more catch blocks where exception thrown in the
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
try block is caught. On the other hand, a try() block may not be followed by a catch() block, as
seen in the block given below.

int demo = 0;
try
{
System.out.println(20/demo);
}
//The statement

System.out.println(20/demo);

Page 81
Internet and Java Programming

This program will throw an exception because we are trying to divide a number by zero.
When we compile the program where the above code exists, the program will get successfully
compiled, but when we run the program, the execution of the program will be terminated. This is
because an exception is thrown at run time. Now, this exception can be caught in the catch block
and a message can be printed which will give the details of the exception. Now, think of a code
for the catch( ) block to trap the above exception.
We can have nested try blocks in the program as follows
try
{
statement 1;
statement 2;
try
{
statement3;
statement4;
}
catch(Exception e)
{
}
}catch(Exception e) {}
}
When nested try blocks are used, the inner try block is executed first and any exception
thrown in that block is caught in the following catch blocks. If a matching catch block is not
found with the inner block, then catch blocks of outer try block are inspected. If a matching catch
block is found, then the exception is handled in that block otherwise Java Runtime Environment
handles the exception. We will see an example of try blocks and nested try blocks later.
 Catch Block
The Catch block, as the name suggests, catches the exceptions thrown in the try block.
Without the try block no catch block can exist. We can have multiple catch blocks covering
different types of exceptions. Following is the syntax of the catch block.
try
{
ANNAMALAI
ANNAMALAI UNIVERSITY
}
UNIVERSITY
catch(Exceptiontype e)
{
}
Here, e is the object for the class Exception and with this object we can print details of the
exception. Specifying the Exception type as 'Exception', in the method
catch(Exceptiontype e)
ensures that we can catch any type of exception. Hence, when the type of exception be thrown is
not known then we can use the class 'Exception' to catch that exception.

Page 82
Internet and Java Programming

Following is a simple example of try / catch block

class TryClass
{
public static void main(String args[])
{
int demo = 0;
try
{
System.out.println(20/demo);
}
catch(ArithmeticException a)

System.out.println("Can not divide by zero");

}
}
}

The output of the above program is

Cannot divide by zero

In the above program, we are trying to divide a number by zero, which is not a valid
arithmetic operation. Hence, an exception is thrown which is caught in the catch block provided.
Since we were aware of the type of exception (ArithmeticException) that could occur it has
given a statement in the catch block, which will print a message. Here, we can use 'a' an object of
ArithmeticException to print details of what exceptional operation is performed. These are
provided by the system. Try this by adding following statement in your program

System.out.println(a.getMessage());

 Throws Clause

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The throw Statement (one of the Exception conditions) In Java, when an error condition
arises in a program, we send an exception up the call chain by using the throw keyword. Using
throw in Exception Handling:

TableEntry entry == fileLooknp (name, filename);


if (entry = = null)
{
throw new FileLookupFailureException (name, filename);
}

Page 83
Internet and Java Programming

The Java Exception class implements the throwable interface and provides some useful
features for dealing with exceptions. Specifically, the Exception class:

1. Provides a slot for a message.


2. Contain a stack race

It is often useful to create your own exception classes for special case exception handling
within your program. Creating a subclass of the Exception class normally does this. The
advantage of subclassing the Exception class is that, the new exception type can be caught
separately from other Throwable types, as in the LookupException.

We could simply define LookupException as:

public class LookupException extends Exception


{
//Throwable
}

This would allow us to catch and specifically process a LookupException, without regard
to other possible exceptions.

For Example:

import java-io.*;

public class ThrowsDemo


{
public static void main(String[] args) throwslOException,NumberFormatException
{
double aimedAmount;
double interest= 7.5;
double payment;
int years=0;
double balance=0;

InputStreamReader isr = new InputStreamReader(System.ln);


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
BufferedReader br = new BufferedReader(isr);

System.out.println("Amount to be expected at the time of retirement: ");


aimedAmount = Double.valueOf(br.readLine()).doubleValue();
System.out.println("(t)”);

System.out.println('Your contribution each year:”);


payment = Double. valueOf(br.readLineO).doubleValue( );
System.out.println(" “);

Page 84
Internet and Java Programming

while(balance<aimedAmount)
{
balance == (balance+payment)*(1+(interest/100));

years++;
}
System.out.println('You can retire in (t +years -(-" years.")));
}
}

When above program is run, if we enter characters instead of number, main method will
throw NumberFormatException. Throws clause or keyword is used to indicate that main method
may throw lOException or NumberFormatException. Some in-built methods like readLine() in
the above example throw an exception, which has to be caught. When we use these types of
methods, we can use throws clause.

 Throw keyword

Throw keyword is used to indicate that exception has occurred. The operand of throw is
an object of a class, which is derived from class Throwable. Following is an example of throw
keyword.

class ArraySizeException extends NegativeArraySizeException


{
ArraySizeExceptionO
{
superC'You have passed illegal array size");
}
}

class ThrowDemo
{
intsize, array [];
ThrowDemo(int s)
{
size = s;
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
try
{
checkSize();
}

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

Page 85
Internet and Java Programming

void checkSizeQ throws ArraySizeException


{
if(size < 0)
throw new ArraySizeExceptionO;
array == new int[3j;
for(inti=0;i<3;i-H-)
array [i] =i+l;

}
public static void main(String args[j)
{
newThrowDemo(Integer.parse!nt(args[0]));
}
}

When you run the above program by passing any negative number from command line,
the output of the above program will be as follows:

ArraySizeException: passing illegal array size

The created class called ArraySizeException, which is a subclass of


NegativeArraySizeException. By creating an object of this class, we are printing exception
message. The method checkSize is expected to throw ArraySizeException, which is indicated by
throws clause. In this method, we are checking size of array in the if construct. If size is negative
then object of a class ArraySizeException is created. The method call is enclosed in the try /
catch block where we are printing value of object of class ArraySizeException. The method call
needs to be enclosed within try block so that in the corresponding catch block we can print the
value.

 Finally Block

Finally block is the block in which we find statements which return resources to the
system and other statements for printing any message. Typically, these statements include

 Closing a file

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
 Closing a resultset (used in Database programming)

 Closing the connection established with the database.

This block is optional but when included is placed after the last catch block of a try(). The
Finally block is always executed no matter whether exception is thrown or not. If in a try block, a
return or a break statement is used, then on executing that statement, the control comes to first
statement of the finally block.

Page 86
Internet and Java Programming

Syntax:

Try
{
//statements
}
catch(ExceptionType e)
{
//stattements
}
catch(ExceptionType e)
{
//stattements
}
finally
{
//stattements
}

 Finally executed

This means that the finally block is executed no matter whether the exception is thrown
in the try block or not. In the Finally block, we have set String object 'name' set to null. By
setting the object to null, we are making the object ready for garbage collection thereby returning
the resources to system.

4.2.1.5 The Error Class


There is another high-level class in the Java runtime system that implements the
Throwable interface-the Error class. The runtime system uses the Error class for catastrophic
failures that a program is not expected to be able to recover from.

A catch block such as the following is designed to catch all exceptions:

catch (Exception e)

ANNAMALAI
ANNAMALAI UNIVERSITY
{
UNIVERSITY
//stattements
}

The catch block will not catch errors from the Error class, which is the desired behavior.
If a program actually needs to trap errors, the following catch block will do:

catch (Error e)
{
//stattements
}

Page 87
Internet and Java Programming

4.2.1.6 Declaring Exceptions

In Java, the exceptions, which a method can throw, are considered part of its public
interface. Users of a method need to know the exceptions it might throw so they can be prepared
to handle them. Java requires that a method definition include a list of the exceptions the method
throws.

For Example:

public static void exceptionExample( )


{
throws ExampleException,

LookupException
}

In the above example, the exceptionExample() declaration includes the throws keyword,
which is followed by a list of the exceptions this method might throw. In this case,
ExampleException and LookupException.

Defining the exceptions that a method throws in the method declaration has one
significant implication on the code you write. If you write a method that calls another method
that can throw an exception, you must make sure the calling method does at least one of two
things:

1. Declares itself capable of throwing the same exception as the called method.
2. Includes a try/catch block to make sure the exception does not pass through to its
caller.

4.2.1.7 Runtime Exceptions

There are a handful of common exceptions that can occur anywhere in a program. These
include exceptions such as:

 OutOfMemoryException
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
 NullPointerException

 ArrayIndexOutOfBoundsException

These are referred to as runtime exceptions. Any exception that is a subclass of


RuntimeException can be thrown from anywhere. Although you can declare them in a method
declaration you do not have to explicitly declare the runtime exceptions.

Page 88
Internet and Java Programming

4.2.2 Multithreading

4.2.2.1 Introduction to Thread


A Thread is a unique property of Java. Java language and the Java Virtual Machine are
built up with many features of a threaded system. It is an integral part of Java.

4.2.2.2 Multithreading
A thread is the smallest unit of executable code that performs a particular task Java
supports multithreading. An application can contain multiple threads. Each thread is specified a
particular task which is executed concurrently with the other threads. This capability of working
with multiple thread is called Multithreading.

Multithreading allows you to write efficient programs that make the maximum use of the
CPU, by keeping the idle time to a minimum. Each part of the program is called a thread, and
each thread defines a different path of execution. It is a specialized form of multitasking.

Multitasking is running multiple programs simultaneously, with each program having at


least one thread in it. A single processor executes these programs. Though it may appear that the
programs are executed simultaneously, the processor actually switches between the tasks.

4.2.2.3 Creating and Managing Threads


When you execute your Java programs, there is already one thread that is running and it
is the main thread. This main thread is important for two reasons:
 It is the thread from which child threads will be created.
 It is the last thread to finish execution. The moment the main thread stops executing, the
program is terminated.
Though this main thread is created automatically with the program execution, it can be
controlled through a thread object.
a. Two ways of working with threads:
 Declare the class to be a sub-class of Class Thread where you need to override the run
method of Class Thread.
Syntax:
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Class Mydemo extends Thread
{
// class definition
public void run( )
{
// implementation
}
}

 Declare the class that implements Runnable. Then define the run( ) method.

Page 89
Internet and Java Programming

Syntax:

class Mydemo implements Runnable


{
// class definition

public void run( )


{
// implementation
}
}

b. Daemon Threads

A Java program is terminated only after all the threads die. There are two types of threads
in a Java program

 User threads

 Daemon threads

The threads that are created by the Java Virtual Machine on your behalf are called
daemon threads. It is identical to the user threads. The daemon threads are merely created to
serve the user threads. After a user thread has been terminated, the Java Virtual Machine checks
for any other user threads remaining. If there are some threads left, then the Java Virtual
Machine schedules the next thread execution and so on. However, if there are no user threads,
and only a daemon thread exists, the JVM will exit and the program will be terminated. If the
user threads do not exist, then there is no point for the daemon thread to continue, as there is
nothing to serve. Hence, the JVM just exits.

Java provides a garbage collector thread that reclaims dynamically allocated memory that
is no longer needed. This thread runs as a low priority thread that may be the only thread left
running in the JVM. And since all the other threads have terminated, there is no more work to be
done and so the JVM can exit. Therefore, the garbage collection is marked as a daemon thread.
The thread class has two methods that deal with daemon threads.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
 public void setDaemon(boolean )
 public boolean isDaemon( )

c. Thread Scheduling and Setting the Priorities


Most of the Java programs work with multiple threads. The CPU is capable of running
only one thread at a time. When there are more that two threads in a program, that are of equal
priority, each thread wants the CPU time and the threads compete with each other to access this
resource. It is the programmer, or the Java Virtual Machine or the operating system that need to
ensure that the CPU is shared between the threads. This is referred to as the scheduling of
threads.

Page 90
Internet and Java Programming

Every thread in Java has its own priority. This priority is in the range Thread. MIN-
PRIORITY, which contains a constant of 1 and Thread. AX-PRIORITY, which contains a
constant of 10. By default, a thread has a priority of Thread. NORM-PRIORITY, a constant of 5.
Every new thread that is created, inherits the priority of the thread that creates it.

There are no specific implementations of the Java Virtual Machine as to the scheduling of
threads.Some Java platforms support the concept of time slicing. In this, every thread receives a
small portion of processor time, which is called a quantum. The thread can perform its task
during this quantum. After the time period is over, even if the thread has not finished its
execution, the thread is given no more time to continue and the next thread of equal priority takes
the charge of the processor time. The Java scheduler does this, where all equal high-priority
threads are time sliced.

The priority of the thread can be adjusted with the available method called setPriority( )
that takes an integer as an argument. This value has to be within the range of 1 to 10, else, the
method throws an exception called as IllegalArgumentException.

4.2.2.4 Thread Synchronization


While working with multiple threads, it may so happen that more than one thread wants
to access the same variable at the same time. For example, one thread might try to read the data
while the other tries to change the data. In this case the data may get corrupted. In such cases,
what we need to do is, allow one thread to finish its task completely (changing the value) and
then allow the next thread to execute. This can be attained with the help of the synchronized
method. This method tells the system to put a lock around a particular method.
Every object with a synchronized method is a monitor that lets only one thread at a time
to execute. After execution, the lock on the object is released and the next priority thread starts
running.
The following program demonstrates the working of synchronized method.

Example:

class ThreadDemo
{
ThreadSyn tl,t2,t3;

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
public ThreadDemo( )
{
Obj ob == new Obj( );
tl = new ThreadSyn(ob);
tl.startO;
t2 = new ThreadSyn(ob);
t2.start();
t3 = new ThreadSyn(ob);
t3.start0;

Page 91
Internet and Java Programming

public static void main(String args[])


{
new ThreadDemoQ;
}
}
class ThreadSyn extends Thread
{
Objobj 1;

ThreadSyn(Obj obj)
{
objl = obj;
}
public void run( )
{
int count = 0;
while(count<5)
{
try
{
thread.sleep(100);
}
catch(interrupted execution e)
{
count=obj1.getcount( );
system.out.println(“ count=”+count);
}
}
}
Thread group
Thread group is a class that handles the group of threads. All threads in java virtual
machine belongs to default thread group user defined threads also belongs to default thread
group allocated by JVM. Every thread group has parent thread group. Thus they exist on the
hierarchy of a tree.System thread group is the root of all the thread groups.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Thread group class has follows:
Constructor:
Public thread group(string str)
Str is the name of the new thread group. This constructor creates a new thread group with current
threads thread group as it parent.
Public thread group(threadgroup tgroup,string str). Here tgroup is specified parent thread
group. Public final string getname( ). Returns the name of the thread group. Public final
threadgroup getparent( ). Return the parent of the thread group.

Page 92
Internet and Java Programming

Following diagram shows execution flow of try / catch/ and finally block

Figure 4.1: Try Block


4.2.3 Input and Output
4.2.3.1 Introduction
The literal meaning of stream is a waterway or flow. In technical terms, a stream is a path
by which the data travels in a program. We are definitely aware of one way of sending data using
streams. We have used system input stream all the while. In this chapter we will see how to
create and use input and output stream (I/O). Along with this we will also learn about the various
streams.

a. Concept of Streams

Streams are pipelines for sending and receiving information in Java programs. When a
stream of data is being sent or received, we refer to it as writing and reading a stream. When a
stream is read or written, the other threads are blocked. While reading or writing a stream if an
error occurs, an IOException is thrown. Hence, the stream statements must consist of a try-catch
block. The java.lang.System class defines standard input and output stream. These are the major
classes of byte streams provided by Java. We have been using output streams to output data to
display the results on the screen. The I/O stream consist of the following classes:

System.out class: The standard output stream is used to typically display the
Output on the screen.

System.in class: The standard input stream usually comes from the keyboard
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
and is used for reading characters of data.

System.err class: This is the standard error stream.

The major InputStream and OutputStream classes provide a variety of I/O capabilities.
Both these classes have subclasses for performing I/O through memory buffers, files, pipes, etc.
The InputStream subclasses perform the input, while the OutputStream subclasses perform the
output.
Although system streams are very beneficial, they are not powerful enough to use when
dealing with substantial I/O. The java.io package has to be imported for this purpose.

Page 93
Internet and Java Programming

4.2.3.2 InputStream Class


The InputStream Class is an abstract class. It defines how data is received. Importance is
not given to where the data comes from, but fact is that it is accessible.
The InputStream class provides a number of methods for reading and inputting streams of
data; these methods help in creating, reading and processing input streams. The table below
depicts the various methods that operate on InputStream class.

Method Name Syntax Description

Read() The most important method of Input Stream


Read

It reads bytes of data from a stream. If no


AStream.read() data is available it blocks the method.

When a method is blocked, the thread


executing waits until the data is available.
This method also reads into an array of
Byte barray=new byte bytes. It returns the actual number of bytes
[1024] read when the end of the stream is reached.
It throws an IO Exception If an error occurs.

This method returns the number of bytes


that can be read without blockage. It returns
the number of available byte. It is not
Available Available()
reliable method for performing input
processing.

This method closes the input stream


Close Close()

It releases the resources associated with the


stream. It is a good practice to close the
stream so as to ensure that the stream
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Astream.close()
processing is properly terminated. It throws
an IO Exception if an error occurs.

Table 4.1: Input Stream Methods


4.2.3.3 OutputStream Class
OutputStream is also an abstract class. It basically defines the way in which all the
streams are written. It provides a set of methods that help in creating, writing and processing
output streams.

Page 94
Internet and Java Programming

The table below depicts the various methods that operate on the OutputStream class.

Method Name Syntax Description


Write () This is most fundamental
operation in the output
stream class

write (int) This method writes a bytes


// write a single byte
Write
write(byte[]) This actually blocks until
//writes a particular session of an session of an array.
array of byte

byte mbyte = System.in.read(); It also writes keyboard


//read array of bytes. character.

Flush() This method flushes the


Flush stream
Close()output stream.close(); This method closes the
// close the stream stream. It is use to release
Close any associated with the
stream.

Table 4.2: Output Stream Methods

4.2.3.4 Byte Array I/O

The Byte Array I/O uses ByteArrayInputStream and ByteArrayOutputStream classes.


These classes make use of memory buffers. It is not necessary to use them together.

a. ByteArrayInputStream Class

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
This class creates an input stream from the memory buffer which is nothing but an array
of bytes. It provides two constructors to create the input stream. This class does not support any
new methods; on the contrary, it overrides methods of InputStream like read( ), skip( ), available(
) and reset(). We have already seen these methods in the previous sections.

b. ByteArrayOutputStream Class

This class creates an output stream on a byte array. It also provides additional capabilities
for the output array to grow so as to accommodate the new data that is written. This class also
provides two methods namely, toByteArray( ) and toString( ). This is to convert the stream to a
byte array or string object.

Page 95
Internet and Java Programming

The ByteArrayOutputStream class provides two constructors. One takes an integer


argument used to set the output byte array to an initial size. The second one does not take any
argument and sets the output buffer to a default size. This class provides some additional
methods, which are not declared in the OutputStream.
The methods are:

Method Name Description

To reset the output buffer so as to


Reset() enable writing to restart at the
beginning of the buffer.

Size() To return the current number of bytes


that has been written to the buffer.
To write the constant of the output
Writeto()
buffer to the specified output stream.

Table 4.3: ByteArrayOutputStream


The program below depicts Byte Array Input Output classes.
For Example:
import java.lang. System;
import java.io.*;
public class byteexam
{
public static void main(String args[]) throws lOException
{
ByteArrayOutputStream os = new ByteArrayOutputStream( );
String s = "Welcome to Byte Array Input Output classes";
for(int i=0; i<s.length( );i++)
outStream.write(s.charAt(i));
System.out.println(Output Stream is: " -+ os);
System.out.println(Size of output stream is: "+ os.size( ));
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
ByteArrayInputStream in;
in = new ByteArrayInputStream(os.ByteArray( ));
int ibuf == in.available();
System.out.println("Input Stream has:” + ib + "available bytes");
byte ibuf[ ] = new byte[ib];
int byrd = in.read(ibuf, 0, i);
System.out.println(byrd + "bytes were read");
System.out.println("They are: " + new String(ibuf));
}
}

Page 96
Internet and Java Programming

The output of the program is:


Output Stream is: Welcome to Byte Array Input Output Classes
Size of output stream is: 41
Input Stream has 41 available bytes
41 bytes were read
They are: Welcome to Byte Array Input Output Classes

4.2.3.5 File I/O


Java supports file Input and Output with the help of File, FileDescriptor, FileInputStream
and FileOutputStream classes. Direct or random access input/output is supported using File,
FileDescriptor and RandomAccessFile classes. There is also another class called File class that
provides access to file and directory objects. It also supports a number of operations on files and
directories.
a. File Class
This class is used to access file and directory objects. The files are named using the file-
naming conventions of the host operating system. These conventions are encapsulated using the
File class constants. This class provides constructors for creating files and directories. They take
absolute and relative file paths and file and directory names. All common file and directory
operations are performed using the access methods provided by the File class.
These methods
 Allow the creating, deleting and renaming of files.
 They provide access to the file's pathname.
 They determine whether a file object is a file or directory.
 They also check the read and write access permissions.
Just like access methods, the directory methods also allow creating, deleting, renaming
and listing of directories. These methods allow directory trees to cross by providing access to the
parent and sibling directories.

b. FileDescriptor Class
This class provides access to the file descriptors that are maintained by the operating
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
system when files and directories are being accessed. This class does not provide any visibility
into the Specific information maintained by the operating system. It provides only one method
called Valid ( ) method, which helps to determine whether a file descriptor object is currently
valid or not.

4.2.3.6 FileInputStream Class

This class allows the input to be read from a file in the form of a stream. Objects of this
class are created using a filename string or File or a FileDescriptor object as an argument. This
class overrides methods of InputStream class. Along with this it also provides two new methods
such as fnalize( ) and getFD( ).

Page 97
Internet and Java Programming

The finalize( ) method is used to close a stream while being processed by the Java
garbagecollector. The getFD() method is used to obtain access to the FileDescriptor associated
with the input stream.

a. FileOutputStream Class

This class allows output to be written to a file stream. Objects of this class are created in
a manner similar to that of class FileInputStream using a filename string or File or a
FileDescriptor object as an argument. This class overrides the method of OutputStream class and
provides two methods such as finalize( ) and getFD( ).

The program below shows the use of FileInputStream and FileOutputStream and File
classes. It writes to an output file and then reads the file to verify if the output was correctly
written.

For Example:

import java.lang.*;
import j ava.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.io.IOExceptiod;

public class fileioexam


{
public static void main(String args[ ]) throws lOException
{
//creating an output file abc.txt
FileOutputStream os = new FileOutputStream”abc.txt”);
String s = "Welcome to File Input Output Stream";
for(int i = 0; i < s.length( ); ++i)
os.write(s.charAt(i));
os.close( );}

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
4.2.3.7 Filtered I/O

A Filter is a type of stream that modifies the way an existing stream is handled. The
filtered input and output streams classes provided by Java help in filtering I/O in a number of
ways. These filters are basically used to adapt streams to a specific program needs.

The filter sits between an input stream and an output stream. It performs some special
processing on the bytes transferred from input to output. The filters can be combined to perform
a sequence of filtering options where one filter acts as the output of another.

Page 98
Internet and Java Programming

a. FilterInputStream Class
This is an abstract class. It is the parent of all filtered input stream classes. This class
provides the capability of creating one stream from another. One stream can be read and
provided as the output to another stream. This is made possible by using the 'in' variable. This
variable is used to maintain a separate object of the class InputStream. The FilterInputStream
class is designed in such a way that it allows multiple chained filters to be created. This is done
using several layers of nesting. Each class in turn accesses the output of the previous class with
the help of the ‘in’ variable.

b. FilterOutputStream Class

This class is the supplement to the FilterInputStream class. It is the parent of all filtered
output stream classes. This class is similar to the FilterInputStream class in the sense that it
maintains the object of class OutputStream as an 'out' variable. The data written to this class can
be modified as needed to perform filtering operations, and then forwarded to the OutputStream
object.

4.2.3.8 Buffered I/O

A Buffer is a storage place where data is kept. By storing the data in a buffer, we can get
it from the buffer instead of going back to the original source of the data. Java uses buffered
input and output to temporarily cache data read from or written to a stream. This helps programs
to read or write small amounts of data without adversely affecting the performance of the system.

While performing buffered input, large number of bytes are read at a single time and
stored in an input buffer. When the program reads the input stream, the input bytes are read from
the input buffer.
Output buffering is also performed in a similar manner. When something is written to a
stream by a program, the output data is stored in an output buffer. The data is stored until the
buffer becomes full or the output stream is flushed. Finally the buffered output is forwarded to
the output stream's destination.
The filters operate on the buffer (which is located between the program and the
destination of the buffered stream).
a. BufferedInputStream Class

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
This class supports input buffering by automatically creating and maintaining a buffer.
Hence programs can read data from the stream one byte at a time without affecting the
performance of the system. Since BufferedInputStream class is a filter, it can be applied to
discretionary objects of the InputStream class and can also be combined with other input files.

This class makes use of several variables to implement input buffering. These variables
are declared as protected and hence cannot be accessed directly by the program. This class
defines two constructors. One allows the size of an input buffer to be specified whereas the other
does not. But both the constructors take an object of class InputStream as an argument. This class
overrides the access methods provided by the InputStream and does not introduce any new
methods.

Page 99
Internet and Java Programming

b. BufferedOutputStream Class
This class performs output buffering in a manner corresponding to the
BufferedInputStream class. This class also defines two constructors. It allows us to specify the
size of the output buffer in a constructor as well as provide a default buffer size. It overrides all
the methods of OutputStream and does not introduce any methods.

4.2.3.9 The Reader and write class


These are abstract classes. They are at the top of the class hierarchy that supports reading
and writing of Unicode character streams. Java 1.1 actually introduced these classes.
a. Reader Class
This class supports methods such as:
 read()
 reset()
 skip()
 mark()
 markSupported()
 close()

In addition to the above methods, it also supports a method called 'ready ()'. This returns
a boolean value that indicates whether the next read operation will succeed without blocking.

b. Writer Class

It supports the following methods:

 write()

 flush()

 close()
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
c. The PrinterWriter Class

The PrintStream class implements an output. This class has additional methods, which
helps in printing basic types of data.The PrinterWriter class is a replacement for the PrintStream
class. This in fact improves the PrintStream by using a platform-dependent line separator to print
lines instead of the (\ n) character. This class also provides better support for Unicode characters
as compared to the PrintStream. The printed output is flushed and tested for any errors using the
checkError( ) method. To set an error condition, the setError( ) method is used. PrintWriter class
also provides support for printing primitive data types, character arrays, strings and objects.

Page 100
Internet and Java Programming

4.2.3.10 The RandomAccessFile Class


This class provides the capability to perform I/O to specific locations within a file. The
name RandomAccess is due to the fact that data can be read or written to random locations
within a file instead of a continuous storage of information. The seek( ) method supports random
access. As the result, the pointer corresponding to the current file can-be set to any location
within the file permissions. This allows files to be accessed in read-only or read-write modes. An
argument 'r' or 'rw' is passed to the RandomAccessFile indicating the read-only and read-write
access to files.
This method include
 Seek( )
 getfile pointer( )
 length( )
This class implements both Datalnput and DataOutput. Hence, I/O can be performed
using primitive data types. Along with this, RandomAccessFile supports basic file read/write.
This class introduces several new methods other than those inherited from Datalnput and
DataOutput.

4.2.4 String Handling


Strings are sequences of characters, such as "Hello". Java does not have a built-in string
type. Instead, the standard Java library contains a predefined class called, naturally enough.
String. Each quoted string is an instance of the String class:
For Example:
String e = ""; // an empty string
String greeting = "Hello";

Concatenation

Java, like most programming languages, allows you to use the + sign to join (concatenate) two
strings together.

For Example:
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
String expletive = "Expletive";
String PG13 = "deleted";
String message = expletive + PG13;

The above code makes the value of the string variable message " Expletivedeleted".
(Note the lack of a space between the words: the + sign joins two strings together in the order
received, exactly as they are given.

When you concatenate a string with a value that is not a string, the latter is converted to a
string. As you will see in Chapter 5, every Java object can be converted to a string.

Page 101
Internet and Java Programming

For Example:
int age =13; .
String rating = "PG" + age;)
sets rating to the string " PG13 ".
This feature is commonly used in output statements; for example,
system.out.println("The answer is " + answer);
is perfectly acceptable and will print what one would want (and with the correct spacing because
of the space after the word is).

4.2.4.1 Substrings
Extract a substring from a larger string with the substring method of the String class.
For Example:
String greeting = "Hello";
String s = greeting.substring(0, 4);
It creates a string consisting of the characters "Hello”. Java counts the characters in
strings in a peculiar fashion: the first character in a string has position 0, just as in C and C++.
(In C, there was a technical reason for counting positions starting at 0, but that reason has long
gone away, and only the nuisance remains. For example, the character ' H' has position 0 in the
string "Hello", and the charters for position 4. The second parameter of substring is the first
positions not want to copy. In our case, we want to copy the characters in position 0, 1, 2, and 3
(from position 0 to position 3 inclusive). As substring counts it, ins from position 0 inclusive to
position 4 exclusive.

There is one advantage to the way substring works: it is easy to compute the length of the
substring. The strings, substring (a, b) always has b – a characters.

For example, the substring "Hello" has length 4-0=4.

4.2.4.2 String Editing


To find out the length of a string, use the length method.
ANNAMALAI
ANNAMALAI UNIVERSITY
For Example:
UNIVERSITY
String greeting = "Hello";

int = greeting, length (); // is 5

Just as char denotes a Unicode character. String denotes a sequence of Unicode


characters. It is possible to get at individual characters of a string.

s.charAt (n) returns the Unicode character at position n, where n is between 0 and s.
length 0-1.

Page 102
Internet and Java Programming

For Example:
char last = greet ing.charAt(4); // fourth is 'o'/
However, the String class gives no methods that let you change a character in an existing
string. If you want to turn greet ing into " Hell", you cannot directly change the last position of
greeting into a ' !'. If you are a C programmer, this will make you feel pretty helpless. How are
you going to modify the string? In Java, it is quite easy take the substring that you want to keep,
and then concatenate it with the characters that you want to replace.
For Example:
greeting = greeting.substring(0, 4) + "!";
This changes the current value of the greet ing variable to " Hell” Since you cannot
change the individual characters in a Java string, the documentation refers to the objects of the
String class as being immutable. Just as the number 3 is always 3, the string "Hello" will always
contain the character sequence 'H', 'e', '1', '1', 'o'. You cannot change these values You can, as you
just saw however, change the contents of the string variable greeting and make it refer to a
different string, just as you can take a numeric variable currently holding the value 3 hold the
value 4.
It would seem simpler to change the characters than to build up a whole new string from
scratch. Well, yes and no. Indeed, isn't efficient to generate a new string that holds the
concatenation of "Hell” and " I". But immutable strings have one great advantage: The compiler
can arrange that strings are shared.
4.2.4.3 Testing Strings for Equality
To test whether or not two strings are equal, use the equa1s method; the expression
s.equals(t)
returns true if the strings s and t are equal, false otherwise. Note that s and t can be string
variables or string constants.
For Example:
"Hello". equals (command)
is perfectly legal. To test if two strings are identical except for the upper / lower-case letter
distinction, use the equalsIgnoreCase method.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
"Hello" .equalsIgnoreCase ("hello" )
Do not use the = = operator to test if two strings are equally only determines whether or
not the strings are stored in the same location. Sure, if strings are in the same location, they must
be equal j But it is entirely possible to store multiple copies of identical strings in different
places.
String greeting = "Hello"; //initialize greeting to a string
if (greeting == "Hello") . . .
// probably true

Page 103
Internet and Java Programming

if (greeting.substring(0, 4) === "Hell") . . .


// probably false
If the virtual machine would always arrange for equal strings to be shared, then you could
use = = for testing equality. But only string constants are shared, not strings that are the result of
operations like + or substrings Therefore, never use = = to compare strings or you will have a
program with the worst kind of bug—an intermittent one that seems to occur randomly.
4.2.5 The Utility classes
4.2.5.1 Introduction
The Java library includes an assortment of utility classes. These classes are used
throughout the core Java packages and are also available for use in programs that user write.
Their uses include storing collections of objects, generating pseudorandom numbers,
manipulating date and time, and tokenizing strings. The utility classes are stored in the java.util
package. The classes found in java.util are listed here:
 BitSet
 Date
 Dictionary
 Hashtable
 Observable
 Properties
 Random
 Stack
 Vector
java.util also defines these interfaces:
 Enumeration
 Observer
This utility class presents an overview of each of these classes and interfaces.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
4.2.5.2 The Enumeration Interface
The Enumeration interface defines the methods by which you can enumerate (obtain one
at a time) the elements in a collection of objects. Enumeration specifies the two methods shown
here:
1. Boolean has MoreElements( )
2. Object nextElement( )

Page 104
Internet and Java Programming

When implemented, has MoreElements() must return true while there are still more
elements to extract, and false when all of the elements have been enumerated. nextElement()
returns the next object in the enumeration as a generic Object reference That is, each call to
nextElement() obtains the next object in the enumeration. The calling routine must cast that
object into the object type held in the enumeration. The following example uses a class called
Enum to implement an Enumeration of Integer objects. The EnumerateDemo class creates an
instance of Enum, iterates through its values, and displays each. Notice that Enum doesn't
actually contain data; it simply returns the sequence of Integers it constructs. However, the
implementations of has MoreElements() and nextElement() still fulfill the requirements specified
by Enumeration.

// Implement enumeration.
Import java.util.enumeration;

class enum implements enum{


private int count = 0;
private boolean more =true;

public boolean hasmore elements()


{
return more;
}

public object nextelement() {


count++;
if(count>4)
more = false;
return new integer(count=0);
}
}

class enum demo


{
public static void main(string rgs[]) {
enumeration enum =new enum( );
}
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
While (enum.hasmore elements())

{
system.out.println(enum.next element();

}
}
}

Page 105
Internet and Java Programming

4.2.5.3 Vector
In Java, arrays are of a fixed length. Once created, they cannot grow or shrink. This
means that the user must know in advance how many elements an array will hold. But sometimes
you may not know until run time precisely how large an array that the programmer need. To
handle this situation, Java defines the Vector class. In essence, a vector is a variable-length array
of object references That is, a vector can dynamically increase or decrease in size. Vectors are
created with an initial size. When this sizes exceeded, the vector is automatically enlarged. When
objects are removed, the vector may be shrunk.
Here are the Vector constructors:
 Vector( )
 Vector(int size)
 Vector(int size, int incr)

The first form creates a default vector. A default vector has an initial size of 10. The
second form creates a vector whose initial capacity is specified by size. The third form creates a
vector whose initialize capacity is specified by size and whose increment is specified by incr.
The increment specifies the number of elements to allocate each time a vector is resized upward.
In all three forms, the vector is initially empty All vectors start with an initial capacity.

Once this initial capacity has been reached, the next time you attempt to store an object in
the vector, the vector will automatically allocate space for that object, plus extra room for
additional objects. By allocating more than just the required memory, the vector reduces the
number of allocations that must take place. This is important because allocations are costly in
terms of time.

The amount of extra space allocated during each reallocation is determined by the
increment that user specify when he create the vector. If user do not specify an increment, then
the vector's size is doubled by each allocation cycle. Usually, programmer or user will want to
specify an increment value.

Vector defines these data members:

int capacityIncrement;
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
int elementCount;
Object elementData[ ];

The increment value is stored in capacityIncrement. The number of elements currently in


the vector is stored in elementCount, and the array that holds the vector is stored in elementData.

Vector defines several methods and implements the Cloneable interface.Once you have
instantiated a vector ,an user can addan element to it by calling add elementAt( ). To determine if
the vector contains a specific location,call elementAt( ).To determine if a vector contains a
certain element,call contains( ).To obtain the first element in a vector ,call firstElement( ) and so
on. Here are few methods and descriptions as follows:

Page 106
Internet and Java Programming

Methods Descriptions
The object specified by element is added to
Final void addElement
vector.
Final int capacity( ) Return the capacity of a vector.

Object clone Return the duplicate of the invoking vector.

Final object firstElement Return the first element in a vector


Return the number of elements currently in a
Final int size( )
vector.
String to string( ) Return the string equivalent of the vector.
Table 4.4: Final Methods
4.2.5.4 Stack
Stack is a subclass of vector that implements a standard last-in first out stack. Stack only
defines the default constructor, which creates an empty stack. Stack includes all of the methods
defined by the vector and adds several of its own
To put an object on the top of the stack,call push( ).To remove and return the top
element,call pop().An empty stackException is thrown if you call pop() when the invoking stack
is empty. The empty method will return true if there is nothing on the stack. The search method
will determine if any object exists on the stack and return the number of pops that would be
required to bring it to the top of the stack.
a. Dictionary
Dictionary is an abstract class that represents a key / value storage repository. A key is a
name that the user uses to retrieve a value at a later date. If an user got key and value, can store
in the Dictionary object. Once the value is stored, user can retrieve it by using its key. Thus, a
dictionary can be thought of as a list of key / value pairs.
The Abstract method defined by dictionary:
Method Purpose
Return the enumeration of the values contained
Enumeration elements( ) in a dictionary
Return the object that contains the value
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Object get(obj.key) associated with key.

Return true if the dictionary is empty and false


Boolean is empty( ) if it contains atleast one key.

Return the enumeration of the keys contained


Enumeration key( ) in the dictionary.
Int size( ) Return the number of entries in the dictionary.

Table 4.5: Abstract Method

Page 107
Internet and Java Programming

It is easy to use dictionary. To add a key and value, use put method.Dictionary is a Super
class of Hashtable.

4.2.5.5 Hashtable
A Hashtable instance can be used to store arbitrary objects, which are indexed by any
other arbitrary object. A hashtable stores information using a mechanism called hashing. In
hashing, the informational content of a key is used to determine a unique value, called its hash
code. The hash code is then used as the index at which the data associated with the key is stored.
When using a Hashtable, you specify an object that is used as keys and the value (that is, data)
that you want linked to that key.The key is then hashed, and the resulting hash code is used as
the index .
 Hashtable()
 Hashtable(int size)
 Hashtable(int size, float fillRatio)
The first version is the default constructor. The second version creates a table that has
Initial size specified by size. The third version creates a hash table that has an initial size
specified by size and a fill ratio. This ratio must be between 0.0 and 1.0, and it determines how
full the hash table can be before it is resized upward. Specifically when the number of elements
is greater than the capacity of the hash table multiplied by its fill ratio, the hash table is
explained.

a. BitSet
A bitset class creates a special type of array that holds bit values. This array can increase
in size an needed. This makes it similar to a vector of bits. The BitSet constructors are shown
here:
 BitSet( )
 BitSet(int size)
BitSit implements the Cloneable interface and defines the methods

Method Description
Returns the current state of the bit at the
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Boolean get(int index) specified index.

Object clone( ) Duplicates the invoking BitSet object.

Int hashCode( ) Returns the hash code for the invoking object.

Void set(int index) Sets the bit specified by index.


Returns the number of bits in the invoking
Int size( )
BitSet object.
Table 4.6: BitSet Methods

Page 108
Internet and Java Programming

b. Date
The Date class represents a date and time. There are several constructors for Date
objects. The default, Date( ), initializes the object with the current date and time. Three more
constructors offer increasing levels of specificity.
Following are their general forms:
Date(int year, int month, intdayOf month)
Date(int year, int month, intdayOf month, inthours, intminutes)
Date(int year, int month, intdayOf month, inthours, intminutes, intseconds)
An user can also construct a date object by specifying the number of milliseconds that
have elapsed since mid night, January 1, 1970, using this constructor.
c. Date(long milliseconds)
Finally, user can set the date using a string that contains the date, using this form:
d. Random
The Random class is a generator of pseudorandom numbers. These are called
pseudorandom numbers because they are simply uniformly distributed sequences. Random
defines the following constructors:
 Random( )
 Random(long seed)
If programmer initialize a Random object with a seed, programmers define the starting
point for the random sequence. If user use the same random sequence. If they want to generate
different sequences, specify different seed values. The easiest way to do this is to use the current
time to seed a Random object. This approach reduces the possibility of getting repeated
sequences.
The methods defined by Random are shown bellow:
Method Description
Double nextDouble( ) Returns the next double random number
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Float nextFloat( ) Returns the next float random number
Int nextInt( ) Returns the next Int random number
Long nextLong( ) Returns the next long random number
Double nextGaussian( ) Returns the next gaussian random number

Table 4.7: Random Methods

Finally, nextGaussian( ) returns a double value center at 0.0 with a standard deviation of
1.0. known as a bell curve. Float and double are uniformly distributed 0.0 and 0.1 respectively.

Page 109
Internet and Java Programming

4.2.6 Introduction to Networking


A Network is a set of computers and peripherals, which are physically connected
together. Networking enables sharing of resources and communication. Internet is a network of
networks. Java applets can be downloaded from a website. This is one of the main attractions of
Java. Networking in Java is possible through the use of java.net package. The classes within this
package encapsulate the socket model developed by Berkeley Software Division.
The following sections introduce various terms used generally while discussing
networking.

4.2.6.1 Protocols
Communication between computers in a network or a different network requires certain
set of rules called protocols. Java networking is done using TCP/IP protocol. Some of the
different kinds of protocols available are HTTP (Hyper Text Transfer Protocol-enables
interaction with the Internet), FTP (File Transfer Protocol-enables transfer of files between
computers), SMTP (Simple Mail Transfer Protocol-provides e-mail facility) and NNTP
(Network News Transfer Protocol-acts as a bulletin board for sharing news).

4.2.6.2 Socket
Sockets can be understood as a place used to plug in just like electric sockets. In case of
electric sockets, if a toaster’s plug is plugged into a socket, communication starts at that time. It
is essential that they should follow a set of rules to communicate called Protocols. Assuming that
the toaster has been plugged in the socket at the kitchen, the power grid of the house should
know the point of communication or the address of the socket. A network socket can be similarly
understood. Here TCP/IP as protocol for communication and IP addresses are the addresses of
the sockets.
TCP/IP assigns specific ports to some protocols. A few examples are port number 21 is
assigned for FTP, 23 is assigned for Telnet, 25 is assigned for e-mail, 80 for HTTP and so on.

4.2.6.3 Client/Server
A computer, which requests for some services from another computer, is called a client.
The one that processes the request is called as Server. A server waits till one of its clients makes
a request. It can accept multiple connections at a time to the same port number. Multithreading is

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
used to serve multiple users at he same time.

4.2.6.4 Internet Address


Every computer connected to a network has a unique IP address. It is similar to every
student of a batch having unique id. An IP address is a 32-bit number which has four numbers
separated by periods. It is possible to connect to the Internet either directly or by using Internet
Service Provider. By connecting directly to the Internet, the computer is assigned with a
permanent IP address. In case connection is made using ISP, it assigns a temporary IP address
for each session. A sample IP address is given below.

Page 110
Internet and Java Programming

4.2.6.5 Domain Naming Service


It is very difficult to remember a set of numbers to connect to the Internet. The Domain
Naming Service (DNS) is used to overcome this problem. It maps one particular IP address to a
string of characters.

4.2.6.6 Inet Address


There are classes provided in Java to enable networking. They are found in the java.net
package. Inet Address is one such class, which is used to encapsulate the Ip address and the
DNS. To create an instance of InetAddress class, factory methods are used as there are no visible
constructors available for this class. Factory methods are conventions where static return an
instance of that class.

4.2.6.7 Datagram
Datagram is a type of packet that represents an entire communication. There is
nonecessity to have connection or disconnection stages when communicating using datagrams.
This is less reliable than communication using TCP/IP.
There are two classes in Java, which enable communication-using datagrams.
DatagramPacket is the class, which acts as the data container, and DatagramSocket is a
mechanism used to send or receive DatagramPackets.
a. DatagramPacket
A DatagramPacket object can be created as follows.
Constructors
DatagramPacket(byte data[], int size)
The above constructor takes a byte array and its size as its parameter.
DatagramPacket(byte data[], int size, InetAddress I, int port)

In addition to the byte array and its size, the above constructor takes the InetAddress and
the port as its parameter.

b. DatagramSocket
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The class DatagramPacket does not provide methods to send or receive data. This job is
take up by the DatagramSocket class. Listed below are its constructors and some of its methods.

Constructors
The creation of a DatagramSocket object throws a SocketException, which must be
handled.
There are two constructors of DatagramSocket class. The first constructor does not take
any parameters and is created as given below:

Page 111
Internet and Java Programming

DatagramSocket s = new DatagramSocket();


The next constructor is given as follows.
datagramSocket s = new DatagramSocket (int port);

4.2.6.8 TCP/IP

TCP/IP sockets are the most reliable, bi-directional, stream protocols. It is possible to
send arbitrary amounts of data using TCP/IP. Sockets are used for data communication using this
protocol. There are two kinds of sockets in Java – a server and a client. The server to wait for the
client uses the ServerSocket class and the client connects to the server using Socket class.

a. Socket Class

A Socket object establishes connection between the client and the server. Given below
are its constructors and some of the methods associated with it.

Constructors

The first constructor takes the hostname and port as its parameter to create a Socket
object. Creation of a Socket object throws an UnknownHostException or an IOException,
which must be caught.

Socket s = new Socket (InetAddress a, int port);

b. ServerSocket Class

The ServerSocket object waits for the client to make a connection. An object of this class
registers itself as having an interest in the client connections. Apart from using the methods listed
above, this class has accept() method which is used to wait for a client to initiate
communications. The normal Socket object is used for further transfer of data.

Constructors

There are two types of constructors available. The first constructor accepts a port number
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
as parameter to create a ServerSocket object on that port. Creation of this object throws an
IOException, which must be caught and handled.

ServerSocket ss = new ServerSocket (int port);

The next constructor accepts a port and maximum queue length as parameters. The queue
length indicates the maximum number of client connections that the system can have before
refusing further connections.

ServerSocket ss = new ServerSocket (int port, int maxqu);

Page 112
Internet and Java Programming

4.2.6.9 URL

URL stands for Uniform Resource Locator and it points to resource files on the Internet.
The term Web is often used when there is discussion about the Internet. The Web is a collection
of higher level protocols and file formats. An important aspect of a Web is its ability to locate
files on the Internet. The URL helps in locating such files using their addresses on the Net. Java
provides URL class that provides an API to access information across the Internet.

a. Components of URL

The URL has four components: the protocol, IP address or the hostname, port number
and actual file path. The protocols may be http, smtp, nntp, ftp or gopher. The most commonly
used protocol of the web is the hypertext transfer protocol (HTTP). The IP address is delimited
on the left by double slashes (//) and on the right by a slash(/) or a colon. The third component,
port, is optional and is delimited on the left by a colon and on the right by a slash. The last
component specifies the actual file path.

Given below is an example of an URL.

http://www.musics.com:80/root/htmlfiles/index.html

http is the protocol, www.musics.com is the host name, 80 is the port number and the file
index.html is stored under root/htmlfiles directory.

Constructors
There are four constructors and creation of a URL object throws a
MalformedURLException. The first constructor takes the urlname as parameter and creates an
object. This is the most commonly used constructor to create the URL object.
URL u = new URL(String urlname);
The next constructor takes the name of the protocol, host name, port number and the file
path as parameters.
URL u = new URL (String protocolname, String hostname, int port, String path);

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The third constructor accepts three parameters as given below.
URL u = new URL (String protocolname, String hostname, String path);
The last constructor accepts the URL object and a string.
URL u = new URL (URL urlobj, String urlspecifier);
URL Connection
URL connection is general-purpose class, which provides methods to know more about
the remote resource.

Page 113
Internet and Java Programming

4.3) Revision Points


Exception Handling
Exception handling is a programming language construct or computer hardware mechanism
designed to handle runtime errors or exceptions, which occur during the execution of a program.
Multithreading
A thread is the smallest unit of executable code that performs a particular task Java supports
multithreading. An application can contain multiple threads. Each thread is specified a particular
task which is executed concurrently with the other threads. This capability of working with
multiple threads is called Multithreading.
Synchronization
Synchronization is a mechanism to ensure only one thread has access to the resource in a shared
resource at any given point of time. A synchronized method acquires the monitor of an object
when it is invoked for that object. During the execution of a synchronized method, the object is
locked so that no other synchronized method can be invoked.
I/O Stream
Streams are pipelines for sending and receiving information in Java programs. When a stream of
data is being sent or received, we refer to it as writing and reading a stream.
String Handling
The String Handling is an ability to manipulate alphanumeric data, such as names, addresses,
text, etc. Typical functions include the ability to handle arrays of strings, to left and right align
and center strings and to search for an occurrence of text within a string.
Utility Classes
These classes are used throughout the core Java packages and are also available for use in
programs that user write. Their uses include storing collections of objects, generating
pseudorandom numbers, manipulating date and time, and tokenizing strings. The utility classes
are stored in the java.util package.
Vector
A vector is a variable-length array of object references that is; a vector can dynamically increase
or decrease in size.
Stack
Stack is a subclass of vector that implements a standard last-in first out stack. Stack only defines
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
the default constructor, which creates an empty stack. Stack includes all of the methods defined
by the vector and adds several of its own
Hashtable
A Hashtable instance can be used to store arbitrary objects, which are indexed by any other
arbitrary object.
Networking
A Network is a set of computers and peripherals, which are physically connected together.
Networking enables sharing of resources and communication. Networking in Java is possible
through the use of java.net package.

Page 114
Internet and Java Programming

4.4) Intext Questions

1. What is an Exception?
2. When the Exception object is created?
3. What is the difference between throw and throws?
4. List any three Java’s Built in Exceptions?
5. Define the term multithreading?
6. What is Synchronization?
7. Discuss the InputStream class and OutputStream class?
8. Write a notes about PrinterWriter Class
9. What is String Handling? and how java achieves it?
10. What is vector? Explain it with example
11. Write a note about HashTable
12. Write a brief notes about Java Networking
4.5) Summary

 Error is encountered while executing a program, an Exception is said to have occurred.

 Exception occurs mainly, due to abnormal conditions that occur at the time of running the
program.

 The fundamental language support for the catch and throw method of exception handling
is the try / catch block.

 The finally statement can be used in conjunction with a try() block.

 Finally block is the block in which we find statements which return resources to the
system and other statements for printing any message.

 ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
These are the Runtime Exceptions:

o OutOfMemoryException

o NullPointerException

o ArrayIndexOutOfBoundsException

 Java language and the Java Virtual Machine are built up with many features of a threaded
system.

Page 115
Internet and Java Programming

 A thread is the smallest unit of executable code that performs a particular task

 Thread Synchronization - This method tells the system to put a lock around a particular
method.

 A hashtable stores information using a mechanism called hashing.

 Networking, one of the main attractions in Java, is possible through the use of java.net
package.

 Communication between the computers in a network or a different network requires


certain set of rules called protocols.

 A computer, which requests for some services from another computer, is called a client
and the one, which processes the request, is called the server.

 Domain Naming Services (DNS) is used to map one particular IP address to a string of
characters.

 InetAddress is class, which is used to encapsulate the IP address and the DNS.

 Datagram is a type of packet that represents an entire communication.

 Datagram packet is the class, which acts as the data container, and DatagramSocket is a
mechanism used to send or receive DatagramPackets.

 TCP/IP sockets are the most reliable, bi-directional, stream protocols. The server to wait
for the client uses the ServerSocket class and the client to connect to the server uses the
Socket class.

 The URL class helps in locating files on the Net using their addresses. URLConnection
calss is a general-purpose class that provides methods to know more about the remote
resource.

4.6) Terminal Exercises


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
1. Name any two exception handling in java programming?

2. Why do we need to handle each exception separately?

3. The try block consists of a set of ____________statements.

4. Exception can be caught in the catch block (true/false)

5. When nested try blocks are used, the inner try block is executed first(true/false)

Page 116
Internet and Java Programming

6. Give any two uses of Throw keyboard?

7. Define the term “Stream”?

8. In Java, Exception class implements ____________interface.

9. Explain the term “array size exception”?

10. What is multi threading?

4.7) Supplementary Materials

1. Head First Java By Sierra, Bates, Kathy Sierra, Bert Bates


2. Patrick Naughton and Herbert Schildt, "The Complete reference JAVA2" Tata
McGraw Hill Publishing Limited, NewDelhi, 1999.

4.8) Assignment
1. Develop an application using Java with exception handling feature

2. Discuss Multithreading and its applications

4.9) Suggested Reading


1. http://www.unix.org.ua/orelly/java-ent/jnut/

2. http://www.oreilly.com/catalog/javanut/excerpt/index.html

3. Data Structures and the Java Collections Framework by William Collins

4.10) Learning Activities


An individual or small group can enrich the following

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
1. Collection Framework

2. Networking

4.11) Keywords
Error - An Error, that indicates serious problems that a reasonable
application should not try to catch.

Exception - Programmers can handle the exception. Exception is thrown


when something goes wrong in the execution of a program

Page 117
Internet and Java Programming

Thread - A thread is the smallest unit of executable code that performs a


particular task

Daemon threads - The threads that are created by the Java Virtual Machine on your
behalf are called daemon threads.

Streams - they are pipelines for sending and receiving information in Java
programs.

String - It is a Java object. It consists of a collection of characters

Client - A computer, which requests for some services from another


computer.

Server - The one that processes the request is called as Server

DNS - Domain Naming Service

Datagram - Datagram is a type of packet that represents an entire


communication.

Socket - This java object establishes connection between the client and the
server

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Page 118
Internet and Java Programming

Unit – V
5.0) Introduction
5.0.1 Introduction to Applet
Applets are small applications that are accessed on an Internet server, transported over
the internet, automatically installed and run as a part of the Web document. After an applet
arrives on the client, it has limited access to resources, so that it can produce an arbitrary
multimedia user interface and run complex computations without introducing the risk of viruses
or breaching data integrity.

Every applet is implemented by creating a subclass of the Applet class (Applet class is
inside package java.applet). The following figure shows the inheritance hierarchy of the Applet
class. This hierarchy determines much of what an applet can do and how.
java.lang.Object
|
+----java.awt.Component
|
+----java.awt.Container
|
+----java.awt.Panel
|
+----java.applet.Applet

5.1) Objective
The Objective of this lesson is to provide you the knowledge on Applet. It guides you
Java’s GUI development environment. The content of the lesson starts with Applets, Abstract
Windowing Toolkit. It develop you skills and knowledge to Work with Windows, Graphics,
Layout Managers and Menus. It also provides you to develop the applications using Images and
Animation in Java. This lesson gives the introduction and knowledge about Swing Class
Library.

Towards end of this lesson student can acquire the GUI application programming
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
development skill using Java. After finishing this lesson you can develop a complete application
using Java programming language.

5.2) Content
5.2.1 Applets

An applet is nothing more (or less) than a Java class that inherits from the Java API's
Applet class and implements certain methods that need to be present for the applet to handle its
appearance and to respond to events passed to the applet. For the most part, supporting applets in
a browser is an all-or-nothing proposition, so if browser is able to view applets, it supports the
JDK.

Page 119
Internet and Java Programming

5.2.1.1 Inline Applets with HTML

When a browser loads an HTML page, it starts to format the text. If it is a graphical
browser, it lays out the text around any graphical elements that are embedded in the page (as
indicated by the IMG or FIG tags). Some browsers, like Netscape, may allow the HTML page to
have some additional control over layout and formatting issues, but for the most part, these
decisions are supposed to be made by the browser and the user. As an HTML page loads, when
the browser sees certain tags that suggest the display of inline elements such as images, the
browser requests that the server send the data for those elements in order that they might be
properly displayed.

An inline element is an element that is drawn right onto the Web page, as opposed to
appearing in a separate window, with the page's text wrapping around it. The most common
inline element is the image, usually a GIF or JPEG bitmap file. Netscape 2.0 and a few other
browsers allow a number of different types of objects to be inlined on the page.

A Java applet is handled with HTML as a type of inline element. The browser reads the
HTML file and sees that it needs to load the data associated with this element. The applet
element also tells the browser how much display space, in terms of pixel height and width, to
reserve to' the applet. Many browsers (especially the Java-capable ones) are multithreaded, so the
browser will continue dealing with rest of the HTML data in one thread, while creating a new
thread to load the inline element's data. In the case of the applet, this data is a Java class.

For a browser to load a Java class, it needs to implement a Java class. The class loader
loads the class that is indicated by the HTML applet tag over the network; once that class is
loaded, it uses the class loader to load any other classes it needs, pulling those down over the net
if necessary. Java-enabled browsers also keep all the Java API classes in a local file on the hard
drive, so that these are available for the applet to use. It is also up to the applet to load any
images, sounds, or other data that it needs.

The applet at this point is talking directly to the browser to handle these requests, so that
you usually would not see any reference to these other files used by the applet in the HTML
page's source. Note that entire applet loading is taking place in a separate thread, so that while
this is happening, the browser is continuing to load and lay out the other traditional HTML page
elements. When the applet has finished loading and initializing, the browser asks it to draw itself;

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
from then on the applet has the responsibility for managing its display area.

Let's take a look at the HTML code for a page that loads an applet:

<HTML>

<HEAD>

<TITLE>Applets</TITLE>

</HEAD>

Page 120
Internet and Java Programming

<BODY>

<H1>

My HIML page

</H1>

<P>

This is a sample html page.

Cool applets soon...

<APPLET CODE=MyApplet.class WIDTH=100 HEIGHT=100>

</APPLET>

more text

<P>

</BODY>

</HTML>

When the browser hits the applet tag, it will load the indicated applet class and create an
applet object. This illustration is presented to develop a conceptual model of how applet loading
works; it does not necessarily reflect the actual technical implementation that a particular
browser might use. The process is called the HTML loader and applet loader represents the
internal mechanisms in the browser for handling these activities.

5.2.1.2 Standard Applet Methods

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The first step in the creation of an applet is to make it a subclass of JApplet, a class that's
part of the corn. sun. java.swing package. This package is called Swing, and it provides a set of
classes for the creation of a graphical user interface, graphics, and visual elements of a computer
program. An applet is treated as a visual window inside. Web page. So JApplet is part of Swing
along side clickable buttons, scrollbars, and other components of a program's user interface.

JApplet is a subclass of Applet, a class in the java.applet package. Being part of hierarchy
enables the applets to use all the behavior and attributes they need to be run as part of a World
Wide Web page. Before writing any other statements in applets, it will be able to interact with a
Web browser, load and unload them-selves, redraw their window in response to changes in the
browser window, and handle

Page 121
Internet and Java Programming

In applications, programs begin running with the first statement inside the main( ) block
statement and end with the last closing bracket ( }) that closes out the block. There is no main()
method in a Java applet, so there is no set starting place for the program. Instead an applet has a
group of standard methods that are handled in response to specific events as the applet runs.
 Applet method to be handled
 The program is loaded for first time
 Request the applet window to be redisplayed.
 The program is stopped by the browser
 The program restart after a stop.
 Program is unloaded as it finishes running.

An applet's class inherits all of the methods that are handled automatically when needed:
init( ), paint ( ), start ( ), stop( ), and destroy ( ). However, none of these methods do anything. To
do new activities the methods with new version has to be overridden The two methods you will
override most often are paint ( ) and init( ).

5.2.1.3 Life Cycle Of Applet Class


a. The paint ( ) Method
The paint () method should be a part of almost every applet written because you can't
display anything without it. Whenever something needs to be displayed or redisplayed on the
applet window, the paint () method handles the task. You also can force paint () to be handled
with the following statement:
Syntax:
paint ( );
The repaint ( ) method can be used inside any method of the applet's class, but avoid
calling it inside the paint ( ) method. This causes a quick-running loop that makes the Java
interpreter run inefficiently and might cause the Web browser running the applet to crash.
Aside from the use of repaint (), the main time the paint () method is handled is when
something changes in the browser or the operating system running the browser. Unlike other

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
methods, paint () takes an argument.
The following is an example of a simple paint () method:
public class paint(Graphics screen)
{
// display statements go here
}
The argument is a Graphics object. The methods of a related class, Graphics2D, are used
to display text, graphics, and other information. If Graphics or Graphics2D object is used in
applet, the following import statements have to be added before the class statement at the
beginning of the source file:

Page 122
Internet and Java Programming

Syntax:
import java.awt.Graphics;
import java.awt.Graphics2D;
In order for start( ) to be handled a second time or more, the applet has to stop execution
at some point. The stop( ) method is called when an applet stops execution. This event can occur
when a user leaves the Web page containing the applet and continues to another page. It also can
occur when the stop( ) method is called directly in a program. In the programs, start( ) and stop( )
will have the most use in animation.
b. The init() Method
This method is also a good place to set up fonts, colors, and the screen's background
color. The init () method is handled once—and only once—when the applet is run. As a result,
it's an ideal place to set up values for any objects and variables that are needed for the applet to
run successfully. Variables and objects should not be created inside an init() method because
they will only exist within the scope of that method.
c. The start () and stop() Methods
At any point when the applet program starts running, the start () method will be handled.
When a program first begins, the init () method is followed by the start () method. After that, in
many instances there will never be a cause for the start () method to be handled again. In order
for start () to be handled a second time or more, the applet has to stop execution at some point.
The stop() method is called when an applet stops execution. This event can occur when a
user leaves the Web page containing the applet and continues to another page. It also can occur
when the stop() method is called directly in a program.
In the programs, start () and stop() will have the most use in animation.
d. The destroy( ) Method
This method is used in rare instances when something has been changed during a
program and it should be restored to its original state. It is another method that will be used more
often with animation than with other types of programs. The destroy () method is an opposite of
sorts to the init () method. It is handled just before an applet completely closes down and
completes running.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
e. Using the drawString() Method
The drawString () method is similar in function to the System output. println() method
that displays information to the system's standard output device. Text is displayed in an applet
window by using the drawString () method of the Graphics2D class or the same method in the
Graphics class, The Graphics2D class is used in BigDebtApplet because it provides better results
for the display of text and graphics.
Before using the drawString () method of the qraphics2D class, Graphics2D object must
be available that represents the applet window.
The paint ( ) method of all applets includes a Graphics object as its only argument. This
object represents the applet window.

Page 123
Internet and Java Programming

As you might suspect, you use casting to convert a Graphics object into a Graphics2D
object. Graphics2D is a subclass of Graphics, which makes the following statement possible:
Example:
Graphics2D screen2D = (Graphics2D)screen;
This statement casts a Graphics object named screen into a Graphics2D object named
screen2D. A statement like this can be seen often in the paint () method of applets.
The following three arguments are sent to drawString ():
 The text to display, which can be several different strings and variables strung
together with the + operator
 The x position (in an (x,y) coordinate system) where the string should be displayed3.
The y position where the string should be displayed.
The (x,y) coordinate system in an applet is used with several methods.

5.2.1.4 Running the Applet Viewer

To execute the applet, carry out the following two steps:

1. Compile your source files into class files


2. Create an HTML file that tells the browser which class files to load how to size the
applet.
It is customary (but not necessary) to give the HTML file the same name the applet class
inside. So, following this tradition, we will call the file helloWorldApplet.html. Here are the
contents of the file:
Syntax: <APPLET CODE="applet.class " WIDTH=300 HEIGH=300
// Display content
</APPLET>
import java.awt.*;
import javax.swing.*;
public class .......
ANNAMALAI
ANNAMALAI UNIVERSITY
{ UNIVERSITY
public void init();
{
container content pane = get content pane;
label =new label("Not a hello, world applet", swing constants.center);
content pane.add(label);
}

Page 124
Internet and Java Programming

NotHelloWorldApplet.html source:
<APPLET CODE="NotHelloWorldApplet.class" WIDTH=300 HEIGH=300

</APPLET>

Before viewing the applet in a browser, it is a good idea to test it in the viewer program
that is a part of the Java SDK. To use the appletviewer, enter appletviewer
NotHelloWorldApplet.html at the command line for the applet viewer. The program is the same
of the HTML file, not the class file.

5.2.1.5 Java application Vs applets


It is easy to convert a graphical Java application (that is, an application that uses the
AWT and that can be started with the java command-line intcinterpreter) into an applet that can
be embedded in a web page. Essentially, all of the user interface code can stay the same.
Here are the specific steps for converting an application to an applet.
 Make an HTML page with the appropriate tag to load the applet code
 Supply a subclass of the JApplet class. Make this class public; otherwise the applet
cannot be loaded
 Eliminate the main method in the application. Do not construct a frame window for
the application. Your application will be displayed inside the browser
 Move any initialization code from the frame window constructor to the init method of
the applet. You don't need to explicitly construct the applet object
 Remove the call to setsize; for applets, sizing is done with the width and height
parameters in the actual HTML file
 Remove the call to setDefault closeOperation. An applet cannot be closed; it
terminates when the browser exits
 Do not call show .The applet is displayed automatically.

5.2.1.6 Restrictions on a Java Applet

Some of the most popular browsers in the world today are the Netscape Navigator and
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
the Internet Explorer. The following are some of the restrictions placed by these browsers on the
Java Applets:

 Applets are not allowed to read from or write to files on the local system
 Applets can communicate only with the server on which they are originally resident and with
no other server either on the Net or on the client's local network
 Applets are not allowed to execute any applications on the local computer neither are they
allowed to load any DLLs.

Page 125
Internet and Java Programming

5.2.1.7 Pop -up Windows in Applets


An applet sit in the web page, in a frame of a size that is fixed by the width and height
value in the applet tag of HTML page. Many program wonder whether they can a pop up
window to make better use of the available space. It is in deeded possible to create a pop up
frame. Here is a sample applet with a single button labeled calculator. When clicked on the
button, a calculator pops up in separate window. The pop-up is easy to do. Simply use a JFrame,
but don't call setDefault-close Operation.

Example:

frame = new CalculatorFrame() ;


frame.setTitle('Calculator") ;
frame.setSize(200, 200);
When the user clicks the button, toggle the frame so that it is shown if it is not visible and
hidden. When clicked on the calculator button, the dialog box pop and float over the web page.
Clicking again on the button, the calculator goes away.
jbutton caclButton = new jbutton ("calculator");
calcbutton .addAction list enter
actionlistener ( )
{
public void actionPerformed(ActionEvent evt)
{

if (frame. isVisible ()) frame. setVisible (false);

else frame.show();

}
}

In early browser versions, that message was very ominous: "Untrusted Java Applet
Window." Every successive version of the SDK watered down the warning a bit-
"Unauthenticated Java Applet Window," or "Warning: Java Applet Window." Now it is simply
"Java Applet Window."

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
This message is a security feature of all web browsers. The browser wants to make sure
that the applet does not launch a window that the user might mistake local application.

5.2.1.8 Applet Attributes for Positioning

What follows are short discussions of the various attributes that can be used within the
APPLET tag to position your applet. For those familiar with HTML many of these attributes are
similar to those used with the IMG tag for image placement on a web page.

Page 126
Internet and Java Programming

WIDTH, HEIGHT
These attributes are required and give the width and height of the applet, measured in pixels.
In the applet viewer, this is the initial size of the applet can resize any window that the applet
viewer creates. In a browser, applet cannot be resized. You will need to make a good guess
about how much space your applet requires to show up well for all users.
ALIGN
This attribute specifies the alignment of the applet. There are two basic choices. The applet
can be a block with text flowing around it, or the applet can be inline, floating inside a line
of text as if it were an oversized character. The first two values (LEFT and RIGHT) make
the text flow Kind the applet. The others make the applet flow with the text. Choices are
described below.
Applet positioning attributes
Attributes What it Does
Place the applet at the left margin of
Left
the page text
Place the applet at the right margin of
Right
the page text

Place the bottom of the applet at the


Bottom bottom of the text.

Places the top of the applet with the top


TOP of the Current line.

Places the top of the applet with the top


TEXTTOP of the text in a current line

Places the middle of the applet with the


Middle
baseline of the current line

Places the middle of the applet with the


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
ABSMIDDLE middle of the current line.

Table 5.1: Applet Positioning Attributes

5.2.1.9 The Class Applet

The first step in writing a Java Applet is to derive a class from the class 'Applet' that is a
part of the Java API. This class provides us with the basic functionality required to run a Java
Applet. The class 'Applet' has been defined in the package 'java.applet'. The first line of code:

Page 127
Internet and Java Programming

import j ava.applet.*;
This code imports all the members of the package 'java.applet’ into the current
application. When a Java program is compiled, the resultant class file (which contains the byte
code) has the same name as the Java source file. Java requires that the name of the Java source
file is the same as that of the class, which is derived from the 'Applet'.
The 'Applet' derived class i.e. Our_Applet, is the class that encapsulates most of the
behavior required of the Java Applet. This class must be declared as ‘public’; otherwise the
browser will not be able to interact with this class. This is because, the called the access specifier
'public' indicates that all can access the class.
5.2.2 Abstract Windowing Toolkit
Abstract Windowing Toolkit:
The basic set of Java classes that can be used to display and control a graphical user
interface, which has been extended by the Swing windowing classes. Generally, it is called as
AWT.
5.2.2.1 Introduction to Swing
Java classes that can expand on the Abstract Windowing Toolkit's ability to display and
control a graphical user interface.
When java 1.0 was introduced, it contained a class library, which sun called the Abstract
Window Toolkit (AWT), for basic GUI programming. The way the basic AWT library deals
with user interface elements is to delegate their creation and behavior to the native GUI toolkit
on each target platform (Windows, Solaris and so on..) for example, if you used the original
AWT to put a text box on a Java window, an underlying "Peer" text box actually handled the text
input.
The peer-based approach worked well for simple applications, but it soon became
apparent that it was fiendishly difficult to write a high-quality portable graphics library that
depended on native user interface elements. User interface elements such as menus, scrollbars,
and text fields can have subtle differences in behavior on different platforms. It was hard,
therefore, to give users a consistent and predictable experience with this approach. More
expressingly, there were different bugs in the AWT user interface library on the different
platforms. Developers complained that they needed to test their applications on each platform, a
practice derisively called "write once, debug everywhere."
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
In 1996, Netscape created a GUI library they called the IFC (Internet Foundation Classes)
that used an entirely different approach. User interface elements, such as buttons, menus, and so
on, were painted onto blank windows.

Reasons to choose swing are overwhelming


 Swing has a much richer and more convenient set of user interface elements.
 Swing depends far less on the underlying platform; it is therefore less prone to platform-
specific bugs.
 Swing will give a consistent user experience across platforms.

Page 128
Internet and Java Programming

User interaction with your programs is by far the most important aspect of creating Java
applets and applications. If your interface is bad, people will not want to use your program.
Come up with a unique interface, however, and you could have the next "killer" app. But keep in
mind that creating those awesome interfaces requires you to start with some foundation.

It is that Java foundation. Learning about all the different tools at your disposal will
allow you to build cool interfaces and keep your users happy.

5.2.2.2 Using the Abstract Windowing Toolkit

The Abstract Windowing Toolkit (AWT) is Java's component package. This package
contains all of the programming tools you'll need to interact with the user.

 The AWT contains a number of familiar user interface elements.


 The AWT features a number of familiar components.
 The AWT inherits all its user interface components from Component.

5.2.2.3 AWT Components


Components are the building blocks of the AWT. The end-user interacts directly with
these components. The components provided by the AWT are
 Drawing canvases (Canvas)
 Check boxes and radio buttons (Checkbox)
 Menus (Menu, MenuBar, Menultem)
 Popup choices (Choice)
 Pushbuttons (Button)
 Scroll bars (Scrollbar)
 Scrolling lists (List)
 Text areas (TextArea)
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
 Text fields (TextField)
 Text labels (Label)
a. Containers
You need more than just components are needed to create a good user interface. The
components need to be organized into manageable groups. That's where containers come in.
Containers hold, or contain, components. To use a component, it must be placed within a
container. A component without a container is like a refrigerator magnet without a refrigerator.

Page 129
Internet and Java Programming

The container classes defined in the AWT are:


 Applet

 Dialog

 FileDialog

 Frame

 Panel

 Window

5.2.2.4 Laying Out an User Interface

Even though you have containers as a place to neatly store your UI components, you still
need a way to organize the components within a container. That's where the layout managers
come in. Each container is given a layout manager that decides where each component should be
displayed. The layout manager in the AWT are:

 FlowLayout

 BorderLayout

 GridLayout

 CardLayout

 GridBagLayout

Java is an object-oriented language, and the Java classes take advantage of this
completely. Because of that, some of the methods discussed in this and the following sections
may not be in the classed being discussed but rather inherited from a base class.

a. Buttons
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Buttons are a simple mechanism, but they are one of the workhorses of any graphical
interface. You find buttons on toolbars, dialog boxes, windows, and even in other components
such as scroll bars.

Creating Buttons:
The only thing you have to decide when creating a button is whether or not you want the
button to be labeled. There are no other options for buttons. To create an unlabeled button, use
the following syntax:
Button myButton = new Button();

Page 130
Internet and Java Programming

Creating a labeled button is an equally simple task:


Button myButton = new Button(“Press Me" );
Once you have created a button, you need to add it to a container. Since your applet is already a
container, you can add a button directly to your container or layout:
Button myButton = new Button( "Press Me" );
add( myButton);
To change the label of your button, use setLabel:
myButton.setLabel( "Pull Me!");
To get the label for your button, use getLabel:
String button label = myButton.getLabel();
b. CheckBoxes and Radio buttons:
Check boxes are similar to buttons except that they are used as "yes-no" or "on-off
switches. Every time you click a check box it changes from "off to "on" or from "on" to "off." A
close cousin to the check box is the radio button. Radio buttons are also "on-off switches, but
they are arranged in special mutually exclusive groups where only one button in the group can be
on at a time. Imagine what a radio would sound like if you could have more than one station on
at a time!
Creating Check Boxes
A check box has two parts-a label and a state. The label is the text that is displayed next
to the check box itself, while the state is a Boolean variable that indicates whether or not the box
is checked. By default, the state of a check box is false, or "off."
To create a check box with no label, use the following syntax:
Checkbox myCheckbox = new Checkbox();
To create a check box with a label, use the following syntax;
Checkbox myCheckbox = new Checkbox("check me if you like Java", null, true);
You can also create a check box while setting its state using the following syntax:
Checkbox myCheckbox = new Checkbox ("check me if you like Java", null, true);

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
5.2.3 Working with windows
5.2.3.1 Introduction
The Abstract Window Toolkit (AWT) provides support for applets. AWT contains
numerous classes and methods that allow you to create and manage windows. A full description
of the AWT is very wast. Therefore it is not possible to describe in detail every method, instance
variable, or class . AWT will create their own applets or stand-alone programs. A user can be
able to explore other parts of the AWT on their own. In this topic, you will learn to create and
manage windows, manage fonts, output text, and utilize graphics. AWT explains further aspects
of Java's event-handling mechanism. Although the main purpose of the AWT is to support applet
windows, it can also be used to create stand-alone windows that run in a GUI environment, such
as Windows 95/NT.

Page 131
Internet and Java Programming

5.2.3.2 The AWT Classes


The AWT classes are contained in the java.awt package. The AWT also defines two
interfaces: LayoutManager and MenuContainer. These define the nature of the interface that
must be implemented by all layout managers and menus, respectively.

Methods Description
The border layout manager. Border layouts
Borderlayout use five components: North, South, East, West,
and Center.
Button Creates a push button control.
Canvas A blank, semantics-free window.
The card layout manager. Card layouts emulate
Cardlayout
index cards Only the one on top is showing.
Checkbox Creates a check box control.
CheckboxGroup Creates a group of check box controls.
CheckboxMenuItem Creates an on/off menu item.
Choice Creates a pop-up list.
An abstract subclass of Component that can
Container
hold other components.
Dialog Creates a dialog window.
Table 5.2: AWT Controls

5.2.3.3 Window Fundamentals


The AWT defines windows according to a class hierarchy that adds functionality and
specificity with each level. The two most common windows are those derived from panel, which
is used by applets, and those derived from Frame, which creates a standard window. Much of the
functionality of these windows is derived from their parent classes. Thus, a description of the
class hierarchies relating to these two classes is fundamental to their understanding. Class
hierarchy for Panel and Frame is given below. Let us look at each of these classes now.
a. Component
Component is an abstract class that encapsulates all of the attributes of a visual
component. All of the user interface elements that are displayed on the screen and that interact
with the user are subclasses of Component. It defines almost a hundred public methods which are
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
responsible for managing events, such as mouse and keyboard input, positioning and sizing the
window, and repainting. A Component object is responsible for remembering the current
foreground and background colors, and the currently selected text font.

b. Container

The Container class is an abstract subclass of Component. It has additional methods that
allow other Component objects to be nested within it. Other Container objects can be stored
inside of a Container (since they are themselves instances of Component). This makes for a
multileveled containment system. A container is responsible for laying out (that is, positioning)
any components that it contains. It does this through the use of various layout manager

Page 132
Internet and Java Programming

c. Panel

The Panel class is a concrete subclass of Container. It doesn't add any new methods; it
simply implements Container. A Panel may be thought of as a recursively nestable, concrete
screen component. Panel is the superclass for Applet. When screen output is directed to an
applet, it is drawn on the surface of a Panel object. In essence, a Panel is a window that does not
contain a title bar, menu bar, or border. This is why you don't see these items when an applet is
run inside a browser. When you run an applet using an applet viewer, it is the applet viewer that
provides the title and border.
Other components can be added to a Panel object by its add() method. Once these
components have been added, you can position and resize them manually using the move(),
resize(), or reshape() methods.
d. Window
The Window class creates a top-level window. A top-level window is not contained
within any other object; it sits directly on the desktop. Generally, this will not create Window
objects directly. Instead, should use a subclass of Window called Frame.
e. Frame
Frame encapsulates what is commonly thought of as a "window." It is a subclass of
Window and has a title bar, menu bar, borders, and resizing comers. If you create a Frame object
from within an applet, it will contain a warning message to the user that an applet window has
been created. If the applet is executed from within a browser, the message will be "Untrusted
Java Applet Window." If the applet is run in an applet viewer, then the message will be
"Warning: Applet Window." This message warns users that the window they see was started by
an applet and not by software running on their computer. (An applet that could masquerade as a
host-based application could be used to obtain passwords and other sensitive information without
the user's knowledge.) When a program, rather than an applet creates a Frame window, a normal
window is created.
f. Canvas
Although it is not part of the hierarchy for applet or frame windows, there is one other
type of window that you will find valuable: Canvas. Canvas encapsulates a blank window upon
one can draw

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
5.2.3.4 Working with Frame Windows
After the applet, the type of window you will most often create is derived from Frame.
An user will use it to create child windows within applets and top-level or child windows for
applications. As mentioned, it creates a standard-style window.

Frame supports these two constructors:


 Frame()
 Frame(String title)

Page 133
Internet and Java Programming

The first form creates a standard window that does not contain a title. The second form
creates one with the title specified by title. Notice that a user cannot specify the dimensions of
the window. Instead, he must set the size of the window after it has been created. There are
several, methods to use when working with Frame windows.

a. Setting the Window Dimensions

To set the dimensions of the window, use either version of resize(), shown here:

Syntax:
void resize(int newWidth, int newHeight)

Void resize(Dimension newSize)

The new size of the window is specified by newWidth and newHeight, or by the
Dimension object newSize. The dimensions are specified in terms of pixels. Then obtain the
current size of a window by calling size(), shown here:

Dimension size()

This method returns the current size of the window contained within the width and height
fields of a Dimension object.

5.2.3.5 Hiding and Showing a Window

Once a Frame window has been created, it will not be visible until user call show(). To
hide a window (that is, remove it from view), call hide(). These methods are shown:

 void hide()

 void show()

5.2.3.6 Setting a Window Title

One can change the title in a frame window using setTitle(), which has this general form:

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Void SetTitle(string newTitle)

Here, new Title is the new title for window.

Creating a Frame Window in an Applet While it is possible to simply create a window by


creating an instance of Frame, must seldom do so, because user will not be able to do much with
it. For example, Programmer will not be able to receive or process events that occur within it or
easily output information to it. Most of the time, he will create a subclass of Frame. Lets override
Frame's methods and event handling.

Page 134
Internet and Java Programming

Creating a new frame window from within an applet is actually quite easy. First, create a
subclass of Frame. Override any of the standard window methods, such as init(), start(), stop(),
and paint(). You must also override handleEvent() so that it hides the window when the window
destroy event is received.

Once you have defined a Frame subclass, you can create an object of that class. This
causes a frame window to come into existence, but it will not be initially visible. Make it visible
by calling show( ). When created, the window is given a default height and width. Now, set the
size of the window explicitly by calling the resize( ) method.

Note: Frame windows are given a default size when they are created.

The following applet creates a subclass of Frame called SampleFrame. A window of this
subclass is instantiated within the init() method of AppletFrame. Notice that SampleFrame calls
Frame's constructor. This causes a standard frame window to be created with the title passed in
title. This example overrides the applet window's start( ) and stop( ) methods so that they show
and hide the child window, respectively. This causes the window to be removed automatically.

5.2.3.7 Handling Events in a Frame Window

Since Frame is a subclass of Component, it inherits all the capabilities defined by


Component. This means that one can use and manage a frame window that they create just like
they manage their applet's main window. For example, one can override Paint() to display
output, call repaint() when they need to restore the window, and override all event handlers.
Whenever an event occurs in a window, the event handlers defined by that window will be
called. Each window handles its own events. For example, the following program creates a
window that responds to mouse events. The main applet window also responds to mouse events.
One you experiment with this program, they will see that mouse events are sent to the window in
which the event occurs.

5.2.3.8 Creating Window program

Creating applets is the common use for java’s AWT. It is possible to create stand alone
AWT based applications, to over do this, Simply create an instance

ANNAMALAI
ANNAMALAI UNIVERSITY
5.2.4 Graphics
UNIVERSITY
5.2.4.1 Introduction

Fractals are an area of mathematics dealing with fractional dimensions. Probably recall
from high school geometry that a line is a one-dimensional object, a square is two-dimensional, a
cube is three dimensional, and so forth. This all has to do with the traditional, comfortable world
of Euclidean geometry, where two parallel lines never meet and the sum of the three angles in a
triangle will always equal 180[degrees]Fractals deal with a whole other spectrum of dimensions,
one in which a line might have a dimension not of 1, but of, say, 1.3756.

Page 135
Internet and Java Programming

Around the turn of the century, mathematicians and philosophers began conceiving
strange, abstract worlds where the common sense rules governing the Euclidean Universe were
no longer true. The notion of fractional dimensions was conceived at that time, but it wasn't until
well into the age of computers nearly 60 years later that it became practical to investigate the
subject. The man who first applied computers to the subject, and who coined the term fractal,
was Dr. Benoit Mandelbrot, of the IBM Research Labs.
Although fractals have proven themselves to be of practical value in everything from CGI
special effect in the Hollywood movies to fabulously efficient digital image compression
technique, we're interested in one kind of fractal-a Mandelbrot Set-far the following reasons:
 The Mandelbrot Set is easy to code.
 The Mandelbrot Set presents an interesting picture.
 The program to plot a Mandelbrot Set is sufficiently compute-intensive to yield
interesting benchmark results about Java.

5.2.4.2 Displaying Graphics

Java provides a wide range of tools for creating and displaying graphics. The majority of
Java's graphics methods are contained in the Graphics class.

a. Using Java's Graphics Class


Java's Graphics class provides methods for manipulating a number of graphical features
including the following:

 Creating Graphics Primitives


 Displaying Colors
 Displaying Text
 Displaying Images
 Creating flicker-free animation

5.2.4.3 Displaying Graphics Primitives:

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Java's Graphics class provides you with methods that make it easy to draw 2-D graphics
primitives. You can draw any 2-D graphics primitive including:

 Lines
 Rectangles
 Ovals
 Arcs
 Polygons

Page 136
Internet and Java Programming

a. Drawing Lines

Perhaps the simplest graphics primitive is a line. In Java's Graphics class, drawLine
provides a single method for drawing lines. Below is the complete definition of the drawLine
method.

Syntax:

Public abstract void drawLine(int xl,int yl,int x2, int y2);

The drawLine method takes two pairs of coordinates-xl, yl and x2, y2-and draws a line
between them. The applet in Listing 44.1 uses the drawLine method to draw some lines.

Example:

Listing Source Code for DrawLines.java import java.awt.Graphics;

// This applet draws a pair of lines using the Graphics class

public class DrawLines extends java.applet.Applet


{
public void paint(Graphics g)
{
// Draw a line from the upper-left corner to the point at (400, 200)
g.drawLine(0, 0, 400, 200);

// Draw a line from (20, 170) to (450, 270)


g.drawLine(20, 170,450,270);
}
}

b. Drawing Rectangles

Java's Graphics class provides six methods for drawing rectangles. They are shown
below:

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Method Description
DrawRect() Draw a rectangle
FillRect() Fill a rectangle
DrawRoundRect() Draw a rectangle with rounded corners
FillRoundRect() Fill a rectangle with rounded corners
Draw3Drect() Draw a 3-D rectangle
Fill3DRect() Fill a 3-D rectangle.

Table 5.3: Drawing Rectangle Methods

Page 137
Internet and Java Programming

To draw a simple rectangle using the drawRect method, use the complete definition
below.

Public void drawRect(int x, int y, int width, mt height);

Pass the x and y applet window coordinates of the rectangle's upper-left corner along
with the rectangle's width and height to the drawRect method. For instance, let's say that you
want to draw a rectangle that is 300 pixels wide (width = 300) and 170 pixels high (height =
170). You also want to place the rectangle with its upper-left corner 150 pixels to the right of the
left edge of the applet's window (x = 150) and 100 down from the window's top edge (y = 100).
To do this, fill in the drawRect method's arguments as
Follows:
g.drawRect(150, 100,300, 170);

The drawRect method call above assumes that you've created an object from the Graphics
class . Source Code for OneRectangle.java

For Example:

import java.awt.Graphics;

public class OneRectangle extends java.applet.Applet


{

public void paint(Graphics g)


{

g.drawRect(150, 100.300, 170);

The rectangle displayed by this applet was created with the drawRect method. Use the
fillRect method if you want to draw a solid rectangle. The following is the complete definition of
ANNAMALAI
ANNAMALAI UNIVERSITY
fillRect. UNIVERSITY
public abstract void fillRect(int x, int y, int width, int height);

As seen, fillRect takes the same parameters as drawRect. The rectangle at the left of the
figure is drawn with drawRect and the one of the right is drawn with fillRect. You will find
TwoRectangles applet's code below.

The left rectangle was drawn with drawRect and the one on the right, was drawn with
fillRect. Source Code for TwoRectangles.java

Page 138
Internet and Java Programming

For Example:
import java.awt.Graphics;
public class TwoRectangles extends java.applet. Applet
{
public void paint(Graphics g)
{
g.drawRect(20,20,200,100);
g.fillRect(240,20,200,100);
}
}

5.2.4.4 Loading images


Loading the dancing doll images is nearly identical to the way you have loaded images
before. The only difference is that you needed to load more than one images. You need to create
an instant variable that holds an array of image objects. There are three dancing doll images so
you will create an array for three image objects.
Image images doll[] = new image[3];
Now load the images in an overloaded init method. You can conveniently use a “for”
statement to load the images because each image has an identical name followed by a number.
Listed below is the dancing doll init method.

For Example:
public void init()
{
for(int I=0; I < images Doll.length; I++)
images Doll(I) = getlmage (getCodeBase(), “doll” + I + “.gif”);
}

5.2.5 Layout Managers

5.2.5.1 Introduction
a. Java AWT (Abstract Windowing Toolkit)
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
It generates events when user performs actions like mouse click, key press etc. AWT
communicates these actions to the program using events. When the user initiates an action, the
AWT generates an event and communicates it to event handlers. These event handlers can
respond to the events appropriately.
The whole of event handling in Java 1.0 AWT is done using two methods action() and
handle event that has occurred, the x and y co-ordinates at which this event occurred. To find out
the AWT component (like button, checkbox, radio button, textbox) in which the event is
generated, the instanceof operator is used. The handleEvent() method is called automatically
for an object and an Event object is created and passed on to it. This type of event handling had
various problems, which were addressed and solved in Java.1.1

Page 139
Internet and Java Programming

It examines the standard controls and layout managers defined by Java. It also discusses
menus and the menu bar. The chapter concludes with a discussion of two high-level components:
the dialog box and the file dialog box.

Controls are components that allow a user to interact with your application in various
ways-for examples; a commonly used control is the push button. A layout manager automatically
positions components within a container. Thus, the appearance of a window is determined by a
combination of the controls that it contains and the layout manager used to position them.

In addition to the controls, a frame window can also include a standard-style menu bar.
Each entry in a menu bar activates a drop-down menu of options from which the user can
choose. A menu bar is always positioned at the top of a window. Although different in
appearance, menu bars are handled in much the same way, as are the other controls.

While it is possible to manually position components within a window, doing so is quite


tedious. The layout manager automates this task.

Java-enabled development environment, it will probably have a layout tool that


automates some or all of these tasks. Nevertheless, it is important to know exactly what goes on
"under the hood" since even the best of these tools will usually require hand-tweaking to get a
professional look and feel. Let us start by reviewing the program from the last chapter that used
buttons to change the background color of a frame.

Let us quickly recall how we built this program:

1. We defined the look of each button by setting the label string in the constructor, the
example JButton yellowButton = new Jbutton (“yellow”)

2. We then added the individual buttons to a panel, for example, with:


add (yellowButton);

3. Then, we added the needed event handlers, for example:

yellowButton. addActionListener (listener);

Java has a very elegant concept to enable this dynamic layout: all components A layout
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
manager manages container. In our example, the flow layout manager, the default layout
manager for a panel, manages the buttons. The flow layout manager lines the components
horizontally until there is no more room and then starts a new row of components. When the user
resizes the container, the layout manager automatically reflows components to fill the available
space

Note: Normally, you just let the flow layout manager control the vertical and horizontal gaps
between the components. You can, however, force a specific horizontal or vertical gap by using
another version of the flow layout constructor.

Page 140
Internet and Java Programming

Java. Awt.container
Setlayout (LaycutManager m)
Sets the layout manager for this container.

Java. Awt. Flowlayout


Fllowlayout (int align)
Constructs a new FlowLayout with specified alignment.

FlowLayout (int align, int hgap, int vgap)


Constructs a new FlowLayout with the specified alignment and the specified 141orizontal
and vertical gaps between components.

Parameters Align
One of LEFT, CENTER, or
RIGHT. The horizontal gap to
hgap
use in pixels (negative values
force an overlap)
The vertical gap to use in pixels.
vgap
(negative values force an overlap)

Table 5.4: Flow Layout Parameters

5.2.5.2 The GridLayout Manager

The GridLayout class organizes all components in a container into a specific number of
rows and columns. All components are allocated the same amount of size in the display area. To
see the Crisis applet with a grid layout, load the file Crisis, java back into your word processor
and edit the in it () method. Delete the first three statements immediately following the public
void init () | statement and replace them with the following statements:

Container pane = getContentPane();


GridLayout crisisLayout = new GridLayout(2, 3);
pane.setLayout(crisisLayout);

Save and compile the new version of Crisis. java and load the Crisis.html Web page back

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
into applet viewer.

5.2.5.3 Border Layout

Java comes with several layout managers, and you can also make your own layout
managers. However, to enable us to give you more interesting examples right away, we need to
briefly describe another layout manager called the border layout manager. This is the default
layout manager of the content pane of ever Jframe. Unlike the flow layout manager, which
completely controls the position of each component, the border layout manager lets you choose
where you want to place each component. You can choose to place the component in the center,
north, south, east, or west of content pane.

Page 141
Internet and Java Programming

The last layout manager left to experiment with is the BorderLayout class. Return to the
Crisis.java file in your word processor, and replace the init () method with the following
statements:

Figure 5.1: Border Layout

public void init()


{
Container pane = getContentPane();
BorderLayout crisisLayout = new BorderLayout();
pane.setLayout(crisisLayout);
pane.add(panicButton, BorderLayout.NORTH);
pane.add(dontPanicButton, BorderLayout.SOUTH);
pane.add(blameButton, BorderLayout.EAST);
pane.add(mediaButton, BorderLayout.WEST);
pane.add(saveButton, BorderLayout.CENTER);
}
After you save the change and recompile the Crisis applet, the page you load with the
appletviewer should resemble. The BorderLayout manager arranges components into five areas:
four denoted by compass directions and one for the center area. When you add a component
under this layout, the add () method includes a second argument to specify where the component
should be placed.
Like the GridLayout class, BorderLayout devotes all available space to the
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
components.The component placed in the center is given all space that is not needed for the four
border components, so it usually is the largest.
When you place components unto an applet or some other kind of container, the way they
are organized onscreen is highly variable. The following things can affect the layout of buttons,
text fields, and other components:
 The size of the applet window
 The size of other components and containers
 The layout manager that is being used

Page 142
Internet and Java Programming

There are several layout managers you can use to affect how components are shown.
Default manager is the FlowLayout class, which is what has been used for the entire example
shown up to this point. Under FlowLayout, components are dropped onto an area in the same
way words are organized on a printed page-from left to right, and to the next line when there’s
no more space.

To set up an applet to work under FlowLayout, create a FlowLayout object and then call
the setLayout() method of the applet’s content pane. The argument to setLayout() should be the
layout manager to associate with the pane, which is shown in the following example:

Container pane = getcontentpane() ;


FlowLayout topLayout = new FlowLayout() ;
Pane. SetLayout (topLayout) ;

User can also set up a layout manager to work within a specific container, such as a
Jpanel object. You can do this by using the setLayout() method of that container object.

5.2.6 Menus

5.2.6.1 Using Menus

This menu bar displays a list of top level menu choices each and every choices associated
with drop-down menu. This concept is implemented in java by following classes.menu
Bar,menu, Menultem. In general, a menu bar contains one or more Menu objects. Each Menu
object contains a list of Menultem objects. Each Menultem object represents something that can
be selected by the user. Since Menu is a subclass of Menultem, a hierarchy of nested submenus
can be created. It is also possible to include checkable menu items. These are menu options of
type CheckboxMenuItem and will have a check mark next to them when they are selected.

To create a menu bar, first create an instance of MenuBar. This class only defines the
default constructor. Next, Create instances of Menu that will define the selections displayed on
the bar. Following are the constructors for Menu:

Syntax:

Menu(String optionName)
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Menu(String optionName, boolean removable)

Here, optionName specifies the name of the menu selection. If removable is true, the
pop-up menu can be removed and allowed to float free. Otherwise, it will remain attached to the
menu bar. (Removable menus are implementation dependent.) Individual menu items are of type
Menultem. It defines this constructor:

MenuItem(String itemName)

Here, itemName is the name shown in the menu.

Page 143
Internet and Java Programming

You can disable a menu item by calling disable(). You can enable the item by calling
enable(). You can determine an item's status by calling isEnabled(). These methods are shown
here:
void disable()
void enable()
boolean isEnabled()
isEnabled() returns true if the menu item on which it is called is enabled. Otherwise it
returns false
You can change the name of a menu item by calling setLabel( ). You can retrieve the
current name using getLabe(). These methods are as follows:
void setLabel(String newName)
String getLabel()
Here newName becomes the new name of the invoking menu item. getLabel( ) retun the
current name. can create a checkable menu item by using a subclass of Menultem called
CheckboxMenuItem. It has this general form:
CheckboxMenuItem(String itemName)
Here,itemName is the name shown in the menu. Checkable items operate as toggles.
Each time one is selected, its state changes. You can obtain the status of a checkable item by
calling getState(). Programmer can set it to a known state using setState(). These methods are
shown here:

boolean getState()
void setState(boolean checked)

If the item is checked, getState() returns true. Otherwise it returns false. To check an
item, pass true to setState(). To clear an item, pass false. Once user have created a menu item,
must add the item to a Menu object by using add(), which has the following general form:

Menultem add(MenuItem item)

Here, item is the item being added. Items are added to a menu in the order in which the
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
calls to add() take place. The item is returned. Once you have added all items to a Menu object,
you can add that object to the menu bar by using this version of add().where menu is the menu
being added. The menu is returned.

Menus only generate events when an item of type Menultem is selected. They do not
generate events when a menu bar is accessed to display a drop-down menu example. Each time a
menu item is selected, action() is called. The target field Event parameter contains a reference to
the item that generated the action. Its parameter contains a reference to the string that is the name
of the option. usually, either value may be used to identify the selection.

Page 144
Internet and Java Programming

5.2.6.2 Dialog Boxes

Dialog Boxes often use to hold a set of related controls. Dialog boxes are primarily used
to obtain user input. They are similar to frame windows, except that dialog boxes are always
child windows of a top-level window. Also, they don't have menu bars. In other respects, dialog
boxes function like frame windows. (You can add controls to them, for example, in the same
way that you add controls to a frame window.) Dialog boxes may be modal or modeless. When a
modal dialog box is active, all input is directed to it until it is closed. This means that you cannot
access other parts of your program until you have closed the dialog box. When a modeless
dialogue box is active, input focus can be directed to another window in your program. Thus
other parts of your program remain active and accessible. Dialog boxes are of type Dialog and
are constructed with one of the following constructors:

Dialog(Frame parentWindow, boolean mode)

Dialog(Frame parentWindow, String title, boolean mode)

Here, parentWindow is the owner of the dialog box. If mode is true, the dialog box is
modal. Otherwise, it is modeless. The title of the dialog box can be passed in title. Generally, you
will subclass Dialog, adding the functionality required by your application.

Following is a modified version of the preceding menu program that displays a modeless
dialog box when the new option is chosen. Notice that when the dialog box is closed, dispose() is
called. This method is defined by Window, and it frees all system resources associated with the
dialog box window.

5.2.6.3 FileDialog

Java provides a built-in dialog box that lets the user specify a file. To create a file dialog
box, instantiate an object of type FileDialog. This causes a file dialog box 1 displayed. Usually,
this is the standard file dialog box provided by the operating system. FileDialog provides these
two constructors:

FileDialog(Frame parent, String boxName)


FileDialog(Frame parent, String boxName, int how)
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Here, parent is the owner the dialog box, and boxName is the name displayed in the title
bar. If how is FileDialog.LOAD, then the box is selecting a file for reading. If is
FileDialog.SAVE, the box is selecting a file for writing.

FileDialog() provides methods that allow you to determine the name of the file and its
path as selected by the user. Here are two examples:

String getDirectory()
String getFile()

Page 145
Internet and Java Programming

public boolean handleEvent(Event evtObj)


{
if(evt0bj.id == Event.WINDOW_DESTROY)
{
System.exit(0) ;
return true;
}
return super.handleEvent(evtObj) ;

// Create frame window.


class FileDialogDemo
{

public static void main(String args[])


{

Frame f = new SampleFrame("File Dialog Demo");


f.show() ;
f.resizedOO, 100) ;
FileDialog fd = new FileDialog(f, "File Dialog"
fd.show() ;

}
}

These methods return the directory and the filename, respectively.

The following program activates the standard file dialog box.

/* Demonstrate File Dialog box.

This is an application, not an applet.


*/

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
import j ava.awt.* ;

// Create a subclass of Frame


class SampleFrame extends Frame
{
SampleFrame(String title)
{
super(title) ;
}
}

Page 146
Internet and Java Programming

5.2.6.4 Text Controls

a. TextField

Textfields are UI components that accept text input from the user. They are often
accompanied by a label control that provides guidance to the user on the content to be entered in
the TextField.

Textfields only have single line text and are ideal in situations where a relatively small
piece of information, such as name, age etc. is to be got from the user. For more than one line of
text, TextArea is better choice.

 TextField() constructs a new text field.

 setText(String t) sets the text that is represented by the corresponding text component to
be the specified text.

b. Text Area

TextAreas behave like the TextFields except that they have more functionality to handle
large amounts of text. These functionalities include:

 Text areas can contain multiple rows of text.

 Text areas have scrollbars that permit handling of large amounts of data.

 TextArea() constructs a new text area.

 Append(String str) appends the given text to the text area’s contents.

5.2.7 Images

5.2.7.1 Introduction

Images are off-screen representations of rectangular pixel patterns. There are three things
can do with images:
ANNAMALAI
ANNAMALAI UNIVERSITY
 create them
UNIVERSITY
 modify them

 draw them to the screen or to other image

There are two ways to create an image can create an empty one, or you can create one
that is initialized from a .gif or a .jpeg file to create an empty image ( ) method of the component
class and pass in the desired width and height. For example, the following line creates an images
called Iml that is 400 pixel high; it might appear in the int( ) method of an applet.

Page 147
Internet and Java Programming

Image Iml = createImage(400, 250);

An image can be created based on the information in a .gif or a .jpeg file. The Applet and
Toot kit classes both have a method called get image, which has two common forms:

getImage(URL f-HeURL)
getImage(URL dirURL, String path)

The first form takes a URL that references the desired image file second form takes a
URL that references a directory and the path of the desired image file, relative to that directory.
The code fragment below shows an applet's int( ) method; it loads an image from a file that
resides in the same server directory as the page that contains the applet:

public void int( )


{
Image Iml = getImage(getDocumentBase( ),
}

5.2.7.2 Displaying the Images

All text and images are displayed in the paint () method of the Pan applet. An offscreen
graphics object is used for all drawing methods, and, when everything has been drawn, the
offscreen area is copied to the applet window. Using double buffering produces much better
results than displaying each image and string in the window individually.

If a line of text is specified as a parameter, the applet will center it horizontally and
vertically onscreen. This is done using a class called FontMetrics, which reports on how large a
line of text will be if displayed in a specific font, size, and style. The following statements create
a Font object and set up a FontMetrics object that is linked to it

Font f = new Font(fontName, Font.BOLD, fontSize);

FontMetrics frn = getFontMetrics(f);

The Font object is used as an argument to the getFontMetrics() method. Once you create
the FontMetrics object, you can use two of its methods to help determine how to use the font and
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
center a line of text. These methods are stringWidth (), which indicates how wide the text will
be, and get Height (), which reveals how tall anything in the font will be. In the Pan applet you're
going to create, the following statements use these methods:

int xStart = (getSize().width - fm.stringWidth(text)) / 2;

int yStart = getSize().height/2 + fm.getHeight()/4;

offscreen.drawString(text, xStart, yStart);

Page 148
Internet and Java Programming

The getSize ().width and getSize ().height statements are the dimensions of the applet
window itself. By using these statements with the FontMetrics methods, the program can
determine the right location for the text.
The Pan applet with a line of text centered in the applet window. It's a little harder to
distinguish in black and white, but the text is drawn twice—once in black and again in white.
The text is drawn at a slightly different place the second time, as shown in the following
statement:
offscreen.drawString(text, xStart-2, yStart-2):

This statement creates a shadow effect that makes the text easier to see over the
background.

5.2.7.3 Drawing the Image


The Bounce applet has the same basic structure as the animate applet. It's a threaded
program with start (), stop (), and run () methods to control the operation of the thread. There's
also an update () and a paint () method to display information on screen.

The Image object called ball is loaded with the tennis.jpg image in the init () method.
Several variables are used in the applet to keep track of the ball's location and its current rate of
movement:

 xPosition - This variable is the x coordinate where the ball should be drawn. This
coordinate begins as 10.'""7

 xMove - This variable is the amount the ball should move along the x axis after
every screen update This amount starts out as 1, but it will change to -1 when the ball hits
the right edge of the applet window. It changes back and forth from -1 to 1 every time it
hits an edge, and lines 53-57 handle this change.

 Yposition - This variable is the y coordinate where the ball should be drawn. This
coordinate rs- initially set to -1, which is a signal to the paint () method that the yPosition
needs to be set up before the ball can be drawn for the first time. The yPosition value
varies from a point near the bottom of the applet window to the top edge.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
 Current - This floating-point number starts at 0 and increases by 0.1 each time the ball is
redrawn. When it reaches 3, it is set back to 0 again. The current variable is used with a
mathematical sine function to determine how high the ball bounces.

Sine waves are a good way to approximate the movements of a bouncing ball, and the
Math. sin() method enables a sine value to be used in conjunction with animation. The tennis ball
is traveling half a sine wave each time it goes from the ground to the top of the window and back

The movement rules that you establish for an animation applet will vary depending on
what user was trying to show. The Bounce applet uses the Math. sin() method to create the slow
arcs traveled by the ball.

Page 149
Internet and Java Programming

5.2.7.4 Drawing to a Hidden Screen


The paint() method uses a technique called double-buffering to make the animation
display more smoothly. Double buffering is drawing everything offscreen to a storage place
that's the same size as the program's display area and copying it to the display only when all
drawing is done. The advantage to using double buffering is that it reduces flickering and other
things that might be seen while the paint () method is drawing things onscreen.
All drawing in a Java 1.2 applet is done to a Graphics2D object that represents the applet
Window. An additional Graphics object represents the offscreen area user also must create an
Image object to hold everything that's being drawn to the hidden area. Lines 15-16 create an
Image object called workspace and a Graphics object called offscreen. These objects are set up in
the init () method. Line 19 uses the createlmage() method to set up workspace as an empty image
the size and width of the applet window. Line 20 associates the offscreen object with the
workspace image, using the getGraphics () method of the Image class.
The key to double buffering is to draw everything to the offscreen area in the paint ()
method. To do this use the offscreen object for all display methods instead of the screen2D
object. Each of these methods will update the workspace image with the thing;
that are being displayed.

When all drawing has been done and you know the offscreen area looks the way the
screen should look, draw that entire offscreen image to the applet window by using a statement
such as the one on line 36:

screen2D.drawlmage(workspace, 0, 0, this);

Because workspace is an Image object with the same dimensions as the applet window,
You can use (0,0) as its coordinates, and it will fill the display area.

When drawing only one image to the screen during each update, as user did in the
animate applet, there's no reason to use double buffering. However, if the animation involves
more than one thing to draw, you will get better results by drawing to an off-screen area and then
copying the whole thing to the screen at one time.
Simple images can be draw-using lines and shapes complex images such as photographs
are usually generated externally, for example, with a scanner or special image-manipulation
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
software it is also possible to produce an image, pixel by pixel, and store the result in an array.
This procedure is common for fractal images, for example.
Once image are stored in local files or on the net, can read them into a java application
and display them on graphics object. To read a graphics file in to a application, use a tool kit. A
tool kit object can read in GIF and JPEG files.
To get a Toolkit object, use the static getDefaultToolkit method of the toolkit class. Here
is the code to get a local image file from the current user’s directory.
String name = “blue-ball.gif”;
Image image= Toolkit.getDefaultToolkit ( ).get image (name);

Page 150
Internet and Java Programming

5.2.8 Animation in Java

5.2.8.1 Introduction

This Session starts with an introduction to Animation in Java and then goes on to explain
painting and repainting in Java Animation programs. The session also covers the causes of
Flickers in (he animation programs and how to reduce it. It then goes on to explain how to
reduce flickers by using the technique of double buffering.

This session gives a brief discussion on animation using images and also discusses how
sound can be implemented in programs. This session concludes with an explanation to create
animation for applets in the Java Language.

Animation in Java involves two steps:

 Constructing a frame of animation

 Ask Java program to paint that frame.

5.2.8.2 Painting and Repainting

The paint( ) method is called by Java whenever an applet needs to be painted - when the
applet is initially drawn, when the window containing it is moved, or when another window is
moved from over it. You can also, however, ask Java to repaint the applet at a time you choose.
So, to change the appearance of what is on the screen, you construct the image or "frame" you
want to paint, and then ask Java to paint this frame. If this is done repeatedly, and fast enough,
we get animation.

Where does all this take place? Not in the paint( ) method itself. All paint( ) does is put
dots on the screen paint( ), in other words, is responsible only for the current frame of animation
at a time. The real work of changing what paint( ) does, of modifying the frame for an animation,
actually occurs somewhere else in the definition of your applet.

The listing below uses basic applet animation to display the date and time and constantly
updates it every second, creating a very simple animated digital clock.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
/*DigitalClock applet*/

import Java.awt.Graphics;
import java.awt.Font;
import Java.util.Date;

public class DigitalClock extends Java.applet.Applet


{
Font theFont = new FontC'TimesRoman", Font.BOLD, 24);
Date theDate;

Page 151
Internet and Java Programming

public void start( )


{
while (true)
{
theDate = new Date();
repaint();
try {Thread.sleep(lOOO);}
catch (InterruptedException e) {}
}
}
public void paint(Graphics g)
{
g.setFont(theFont);
g.drawString(theDate.toString(), 10, 50);
}
}

Inside paint( ), all that happens is that the current font is set, and the date itself is printed
on the screen. Because paint( ) is called repeatedly with whatever value happens to be in the
Date, the string is updated every second to reflect the new date.
The sleep( ) method, which is a part of the Thread class, is what causes the applet to
pause. By specifying the sleep() method, the applet frames will be displayed one after another by
giving a pause between each frames. Using the method sleep(), enables you to control how fast
the animation takes place. The try and catch methods used m the program, enables you to control
exactly how fast the animation takes place.
However note that the Digital Clock applet listed above won't work. The applet isn't
running in a separate thread of control. The while( ) loop in the start() method is monopolizing
all resources in the system — including painting.
There are four modifications you need to make to create an applet that uses threads:
 Change the signature of your applet class to include the word implements Runnable.
 Include an instance variable to hold this applet's thread.
 Modify your start( ) method to do nothing but spawn a thread and start the running of

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
the animation.

 Create a run() method that contains the actual code that starts your applet running.

Now need to change the first line of your class definition to :

public class MyAppletClass extends java.applet.Applet implements Runnable


{
……
}

Page 152
Internet and Java Programming

The Runnable interface includes the behavior your applet needs to run a thread; in
particular it gives you a default definition for the run() method.

The second step is to add an instance variable to hold this applet's thread.

Third, add a start( ) method or modify the existing one so that it does nothing but create a new
thread and start it running.

public void start()


{
if (runner == null)
{
runner = new Thread(this);
runner.start( );
}

The actual processing would be part of the run() method.


public void run()
{
// what your applet actually does
}

Finally, should add a stop( ) method to suspend execution of the thread.

public void stop( )


{
if (runner != null)
{
runner.stop();
runner = null;
}
}

The stop( ) method here does two things: it stops the thread from executing and also sets
the thread's variable(runner) to null. Setting the variable to null makes the Thread object it
previously contained available for garbage collection so that the applet can be removed from
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
memory after a certain amount .of time. If the reader comes back to this page and this applet, the
start method creates a new thread and starts the applet once again.

The code for the final applet is listed below:

Import java.awt.Graphics;
import java.awt.Font;
import Java.util.Date;

Page 153
Internet and Java Programming

public class DigitalThread extends java.applet.Applet implements Runnable


{
Font theFont = new FontC'TimesRoman^Font.BOLD^);
Date theDate;
Thread runner;

public void start()


{
if (runner = null)
{
runner = new Thread(this);
runner.start();
}
}

public void stop()


{
If (runner != null)
{
runner.stop();
runner = null;
}

public void run( )


{
while(true)
{
theDate = new Date( );
repaint();

try { Thread.sleep(l000);}

catch (InterruptedException e) {}
}

public void paint(Graphics g)


ANNAMALAI
ANNAMALAI UNIVERSITY
{ UNIVERSITY
g.setFont(theFont);
g.drawString(theDate.toString( ),10,50);

}
}

The above animation applet would execute, but would produce a lot of flicker.

Page 154
Internet and Java Programming

5.2.8.3 Flicker and How to Avoid It

Flicker is caused by the way Java paints and repaints each frame of an applet. We have
seen that the repaint( ) method invokes paint( ). To put it in an other way, a call to paint( ) does
indeed occur in response to a repaint(). However, what actually happens is elaborated in the
following steps:

 The call to repaint() results in a call to the method update( ).

 The update( ) method clears the screen of any existing contents( in essence, fills it with
the current background color), and then calls paint( ).

 The paint() method then draws the contents of the current frame.

It is the call to update( ) that causes the flicker. Because the screen is cleared between
frames, the parts of the screen that don't change alternate rapidly between being painted and
being cleared.

There are two major ways to avoid flicker in your Java applets:

1. Override update( ) either not to clear the screen at all, or to clear only the parts of the
screen you've changed.

2. Override both update() and paint( ), and use double-buffering.

The first method can be implemented as:

public void update(Graphics g)


{
paint(g);
}

5.2.8.4 Reducing flicker using Double-buffering

With double-buffering, one can more or less reduce flicker completely. In this, you create
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
a second surface (offscreen, so to speak), do all your painting to that offscreen surface, and then
draw the whole surface at once onto the actual applet (and onto the screen) at the end—rather
than drawing to the applet's actual graphics surface. Because all the work actually goes on behind
the scenes, there's no opportunity for interim parts of the drawing process to appear accidentally
and disrupt the smoothness of the animation.
Double-buffering is not very efficient since it takes up more memory and space, so if you
can avoid it, make an effort to do so. In terms of nearly eliminating animation flicker, however,
double-buffering works exceptionally well.

Page 155
Internet and Java Programming

5.2.8.5 Animation using Images

Basic image handling in Java is easy. The Image class in java.awt provides abstract
methods to represent common image behavior, and special methods defined in Applet and
Graphics give you everything to load and display images.

a. Getting Images

To display an image in your applet, you first must load that image over the net into your
Java program. Images are stored as separate files from your Java class files, so you have to tell
Java where to find them.

The Applet class provides a method called getImage, which loads an image and
automatically creates an instance of the Image class for you. To use it, all you have to do is
import the java.awt.Image class, and then give getlmage the URL of the image you want to load.
There are two ways of doing the latter step:

 The getlmage() method with a single argument(an object of type URL) retrieves the
image at that URL.

 The getlmage() method with two arguments: the base URL and a string representing the
path or filename of the actual image(relative to the base).

 The Applet class also provides two methods that will help with the base URL argument
to getlmage:

 The getDocumentBase( ) method returns a URL object representing the directory of the
HTML file that contains this applet.

 The getCodeBase( ) method returns a string representing the directory in which this
applet is contained.

The use of the above two depends on whether your images are relative to your HTML
files or relative to your Java class files. Either of these methods is flexible than hard-coding a
URL for getImage().

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Image img = getlmage(new URL”http”/www.yahoo com/files/image.gif));

The above statement will get the image " image.gif from the site : www.yahoo.com /files.

Image img =getImage(getDocumentBase( )"image.gif”);

getDocumentBaseO returns the URL of the document where the applet is contained.

Image img =getImage(getCodeBase( ),"image.gif”);


getCodeBase() will return the URL of the applet's current location.

Page 156
Internet and Java Programming

5.2.8.6 Creating applets with Double-Buffering

To execute double-buffering, you need two things: an image to draw on and a graphics
context for that image. These two together mimic the effect of the applet's drawing surface: the
graphics context (an instance of Graphics) to provide the drawing methods, such as drawlmage
and drawString, and the Image to hold the dots that get drawn. There are four major steps to
adding double-buffering to your applet.

First, the offscreen image and graphics context need to be stored in instance variables so
that you can pass them to the paint() method. Declare the following instance variables in your
class definition:

Image offscreenImage;
Graphics offscreenGraphics;

Second, during the initialization of the applet, you'll create an Image and a Graphics
object and assign them to these variables. The createImage method gives you an instance of
Image, which you can then send the getGraphicsQ method in order to get a new graphics context
for that image:

offscreenlmage = createlmage(this.size( ).width,this.size( ).height);


ofTscreenGraphics = offscreeImage.getGraphics();

Now, whenever you have to draw to the screen, rather than drawing to paint's graphics,
draw to the offscreen graphics. For example, to draw an image called img at position 10,10 use
this line:

Off screenGraphics.drawImage(img,10,10,this);

Finally, at the end of your paint method, after all the drawing to the offscreen image is
done, add the following line to print the offscreen buffer to the real screen:

g.drawlmage(offcsreenlmage,0,0,this);

Of course, you most likely will want to override update so that it does not clear the screen

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
between paintings:

public void update(Graphics g)


{
paint(g);
}

Page 157
Internet and Java Programming

5.2.9 Swing Class Library

5.2.9.1 Introduction

Java classes that can expand on the Abstract Windowing Toolkit's ability to display and
control a graphical user interface. When java 1.0 was introduced, it contained a class library,
which sun called the Abstract Window Toolkit (AWT), for basic GUI programming. The way
the basic AWT library deals with user interface elements is to delegate their creation and
behavior to the native GUI toolkit on each target platform (Windows, Solaris and so on..) for
example, if you used the original AWT to put a text box on a Java window, an underlying "Peer"
text box actually handled the text input.

The peer-based approach worked well for simple applications, but it soon became
apparent that it was fiendishly difficult to write a high-quality portable graphics library that
depended on native user interface elements. User interface elements such as menus, scrollbars,
and text fields can have subtle differences in behavior on different platforms. It was hard,
therefore, to give users a consistent and predictable experience with this approach. More
depressingly, there were different bugs in the AWT user interface library on the different
platforms. Developers complained that they needed to test their applications on each platform, a
practice derisively called "write once, debug everywhere."

In 1996, Netscape created a GUI library they called the IFC (Internet Foundation Classes)
that used an entirely different approach. User interface elements, such as buttons, menus, and so
on, were painted onto blank windows.

5.2.9.2 Reasons to choose swing are overwhelming

 Swing has a much richer and more convenient set of user interface elements.

 Swing depends far less on the underlying platform; it is therefore less prone to
platform-specific bugs.

 Swing will give a consistent user experience across platforms.

User interaction with programs is by far the most important aspect of creating Java
applets and applications. If interface is bad, people will not want to use program. Come up with a
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
unique interface, however, and that could have the next "killer" app. But keep in mind that
creating those awesome interfaces requires starting with some foundation. It is that Java
foundation. Learning about all the different tools at your disposal will allow you to build cool
interfaces and keep your users happy.

Page 158
Internet and Java Programming

5.3) Revision Points


Applet
Applets are small applications that are accessed on an Internet server, transported over the
Internet, automatically installed and run as a part of the Web document.

Abstract Windowing Toolkit


The basic set of Java classes that can be used to display and control a graphical user interface,
which has been extended by the Swing windowing classes. Generally, it is called as AWT.

Event handler
It generates events when user performs actions like mouse click, key press etc. AWT
communicates these actions to the program using events. When the user initiates an action, the
AWT generates an event and communicates it to event handlers. These event handlers can
respond to the events appropriately.

Layout Managers
Java has a very elegant concept to enable this dynamic layout: all components A layout manager
manages container.

Swing
Swing is a GUI toolkit for Java. Swing is one part of the Java Foundation Classes (JFC). Swing
includes graphical user interface (GUI) widgets such as text boxes, buttons, split-panes, and
tables.

5.4) Intext Questions


1. Explain Applet and how it differs from Java applications?
2. Explain applet life cycle
3. Write any 5 AWT components and explain it
4. What is container?
5. Explain about windows?
6. What is layout manager? Explain any 2 with example

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
7. How to do animations using Java?
8. Write a notes about Graphics
9. Write a short notes about Swing
5.5) Summary
 An applet is nothing more (or less) than a Java class that inherits from the Java API's
Applet class and implements certain methods.
 An inlined element is an element that is drawn right onto the Web page, as opposed to
appearing in a separate window, with the page's text wrapping around it.

Page 159
Internet and Java Programming

 A Java applet is handled with HTML as a type of inline element.


 JApplet is a subclass of Applet, a class in the java.applet package.
 The paint () method should be a part of almost every applet written because you can't
display anything without it.
 The repaint ( ) method can be used inside any method of the applet's class, but avoid
calling it inside the paint ( ) method.
 The start () method will be handled when a program first begins.
 The stop() method is called when an applet stops execution.
 The destroy () method is used to restore the original state of the instance.
 Text is displayed in an applet window by using the drawString () method of the
Graphics2D class.
 JFrame is used to create pop-up windows.
 Java classes that can expand on the Abstract Windowing Toolkit's ability to display and
control a graphical user interface.

5.6) Terminal Exercises


1. Name any two methods to handled applet?

2. Most popular browsers in the world today are the Netscape Navigator and ______.

3. Define the term “Swing”?

4. Name any three components that provided by the AWT?

5. The two most common windows are ___________ and _____________.

6. The Panel class is a concrete subclass of Container (true/false).

7. Once you have added all items to a Menu object, you can add that object to the
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
menu bar by using this version of add( ). (Yes/NO).

8. Simple images can be draw using ________and __________.

9. Animation in Java involves two steps, What are they?

10. Any two reasons to choose swing is overwhelming?

Page 160
Internet and Java Programming

5.7) Supplementary Materials


1. “Java: The Complete Reference, J2SE TM” By Herbert Schildt
2. Head First Java By Sierra, Bates, Kathy Sierra, Bert Bates
5.8) Assignment

1. Develop a small applications using Applet and AWT

2. Discuss: AWT Vs Swing


Layout Managers and Event Handlers and its applications

5.9) Suggested Reading


1. http://jan.netcomp.monash.edu.au/java/xadvisor/intro/intro.html
2. http://www.oreilly.com/catalog/javawt/book/index.html
3. http://www.freeprogrammingresources.com/java-graphics-tutorial.html
4. http://www.java-swing-tutorial.com/
5. “Java Programming for the Absolute Beginner” By Joseph P. Russell
5.10) Learning Activities
An individual or a small group can improve the following concept:

1. Applet and Its development Environment


2. Graphics and Images
3. Swing

5.11) Keywords
Appletviewer - Appletviewer is a standalone program from Sun to run Java applets.

ANNAMALAI
ANNAMALAI UNIVERSITY
JDK UNIVERSITY
- Java Development Kid

HTML - Hypertext Markup Language

AWT - Abstract Windowing Toolkit

GUI - Graphical User Interface

Page 161

You might also like