UG - B.Sc. - Information Technology - 12933 - Internet and Java Programming PDF
UG - B.Sc. - Information Technology - 12933 - Internet and Java Programming PDF
(Accredited with ‘A+’ Grade by NAAC (with CGPA: 3.64) in the Third Cycle and Graded
as category - I University by MHRD-UGC)
(A State University Established by the Government of Tamilnadu)
i
Author:
Dr. P. Prabhu
Assistant Professor in Information Technology
Directorate of Distance Education
Alagappa University,
Karaikudi. 630 003.
All rights reserved. No part of this publication which is material protected by this copyright notice
may be reproduced or transmitted or utilized or stored in any form or by any means now known or
hereinafter invented, electronic, digital or mechanical, including photocopying, scanning, recording
or by any information storage or retrieval system, without prior written permission from the
Alagappa University, Karaikudi, Tamil Nadu.
Reviewer:
Dr. S. Santhosh Kumar
Assistant Professor
Department Of Computer Science
Alagappa University,
Karaikudi 630 003
ii
SYLLABI-BOOK MAPPING TABLE
Internet and Java Programming
BLOCK 1
INTRODUCTION
1 Basic Internet Concepts: Pages 1 - 16
Connecting to the Internet – Domain Name System –
E-mail
2 The World Wide Web Pages 17 - 22
Internet Search Engines – Web Browsers – Chatting
and conferencing on the Internet
3 Online Chatting Pages 23 - 28
Messaging – Usenet Newsgroup – Internet Relay chat
(IRC) – FTP – Telnet.
BLOCK 2
FUNDAMENTALS OF OBJECT-ORIENTED
PROGRAMMING
4 Basic concepts of Object Oriented Programming – Pages 29 – 37
Benefits – Applications
5 Java Evolution: Pages 38 – 45
Features – how java differs from C and C++ - java and
internet- java support system – java environment
6 Overview of Java Language Pages 46 – 70
Constants variables and data types- Operators and
Expressions - Decision Making and Branching -
Looping
BLOCK 3
CLASSES, OBJECTS AND METHODS
7 Class: Pages 71–85
Defining a class –fields –methods –creating objects –
accessing class members – constructors – methods
overloading –static members –nesting of methods –
Inheritance –overriding methods –final variables-
classes –methods
8 Arrays, Strings and Vectors : Pages 86 – 96
One dimensional Arrays –creating of array – Two
dimensional arrays- strings –vectors –Wrapper classes
– Enumerated Types - Interfaces: Multiple Inheritance
9 Packages and Interfaces: Pages 97 – 108
Defining interface –Extending interfaces –
Implementing Interfaces -Putting Classes Together
iii
BLOCK 4
MULTITHEREADING , EXCEPTION AND
APPLETS
10 Multithreaded Programming Pages 109 – 129
Creating Threads –Extending the thread class –
Stopping and Blocking a thread –Life cycle of a thread
–using thread methods –Thread Exceptions –Priority –
Synchronization –Implementing the ‘Runnable’
Interface
11 Managing Error and Exceptions: Pages 130 – 146
Types of errors –Exceptions –Syntax of Exception
Handling code – Multiple Catch statements –using
finally statement – Throwing our own Exceptions –
using exceptions for Debugging
iv
CONTENTS PAGE NUMBER
BLOCK I INTRODUCTION
1.1 Introduction
1.2 Objectives
1.3 Connecting to the Internet
1.4 Domain Name System (DNS)
1.5 E-mail
1.6 Check Your Progress
1.7 Answers to Check Your Progress Questions
1.8 Summary
1.9 Key Words
1.10 Self-Assessment Questions and Exercises
1.11 Further Readings
2.1 Introduction
2.2 Objectives
2.3 Internet Search Engines
2.4 Web Browsers
2.5 Chatting and conferencing on the Internet
2.5.1 Chatting
2.5.2 Conferencing
2.6 Check your Progress
2.7 Answers to Check Your Progress Questions
2.8 Summary
2.9 Key Words
2.10 Self-Assessment Questions and Exercises
2.11 Further Readings
3.1 Introduction
3.2 Objectives
3.3 Online Chatting and Messaging
3.4 Usenet Newsgroup
3.5 Internet Relay chat (IRC)
3.6 File Transfer Protocol (FTP)
3.7 Telnet
3.8 Check Your Progress Questions
3.9 Answers to Check Your Progress Questions
3.10 Summary
3.11 Key Words
3.12 Self-Assessment Questions and Exercises
3.13 Further Readings
v
BLOCK 2 : FUNDAMENTALS OF OBJECT-ORIENTED
PROGRAMMING
4.1 Introduction
4.2 Objectives
4.3 Basic concepts of OOP
4.4 Benefits
4.5 Applications
4.6 Check Your Progress Questions
4.7 Answers to Check Your Progress Questions
4.8 Summary
4.9 Key Words
4.10 Self-Assessment Questions and Exercises
4.11 Further Readings
5.1 Introduction
5.2 Objectives
5.3 Java Evolution
5.4 Features
5.5 How java differs from C and C++
5.6 Java and internet
5.7 Java support system
5.8 Java environment
5.9 Check Your Progress Questions
5.10 Answers to Check Your Progress Questions
5.11 Summary
5.12 Key Words
5.13 Self-Assessment Questions and Exercises
5.14 Further Readings
6.1 Introduction
6.2 Objectives
6.3 Overview of Java
6.4 Constants variables and data types
6.5 Operators and Expressions
6.6 Decision Making and Branching
6.7 Looping
6.8 Check Your Progress Questions
6.9 Answers to Check Your Progress Questions
6.10 Summary
6.11 Key Words
6.12 Self-Assessment Questions and Exercises
6.13 Further Readings
vi
BLOCK 3 : CLASSES, OBJECTS AND METHODS
71 - 85
UNIT - 7 CLASS
7.1 Introduction
7.2 Objectives
7.3 Defining a class and fields / methods
7.4 Creating objects – accessing class members
7.5 Constructors
7.6 Method overloading
7.7 Static members
7.8 Nesting of methods
7.9 Inheritance
7.10 overriding methods
7.11 Final variables-classes –methods
7.12 Check Your Progress Questions
7.13 Answers to Check Your Progress Questions
7.14 Summary
7.15 Key Words
7.16 Self-Assessment Questions and Exercises
7.17 Further Readings
8.1 Introduction
8.2 Objectives
8.3 One dimensional arrays
8.4 Creating of array
8.5 Two dimensional arrays
8.6 Strings
8.7 Vectors
8.8 Wrapper classes
8.9 Enumerated Types
8.10 Interfaces: Multiple Inheritances
8.11 Check Your Progress Questions
8.12 Answers to Check Your Progress Questions
8.13 Summary
8.14 Key Words
8.15 Self-Assessment Questions and Exercises
8.16 Further Readings
9.1 Introduction
9.2 Objectives
9.3 Packages:
9.3.1 Defining a package
9.3.2 Importing packages
9.4 Interfaces
9.4.1 Defining interface
vii
9.4.2 Extending interfaces
9.4.3 Implementing Interfaces
9.4.4 Putting Classes Together
9.5 Check Your Progress Questions
9.6 Answers to Check Your Progress Questions
9.7 Summary
9.8 Key Words
9.9 Self-Assessment Questions and Exercises
9.10 Further Readings
10.1 Introduction
10.2 Objectives
10.3 Creating Threads
10.4 Extending the thread class
10.5 Stopping and blocking a thread
10.6 Life cycle of a thread
10.7 Using thread methods
10.8 Thread Exceptions
10.9 Priority
10.10 Synchronization
10.11 Implementing the ‘Runnable’ Interface
10.12 Check Your Progress Questions
10.13 Answers to Check Your Progress Questions
10.14 Summary
10.15 Key Words
10.16 Self-Assessment Questions and Exercises
10.17 Further Readings
11.1 Introduction
11.2 Objectives
11.3 Types of errors
11.4 Exceptions
11.4.1 Syntax of Exception Handling code
11.4.2 Multiple Catch statements
11.4.3 Using finally statement
11.4.4 Throwing our own Exceptions
11.4.5 Using exceptions for Debugging
11.5 Graphics Programming:
11.5.1 The Graphics Class
11.5.2 Drawing Lines, Rectangle, Circles, Ellipses, Arcs and
Polygons
11.5.3 Line Graphs
11.5.4 Using Control Loops in Applets
11.5.5 Drawing Bar Charts.
11.6 Check Your Progress Questions
viii
11.7 Answers to Check Your Progress Questions
11.8 Summary
11.9 Key Words
11.10 Self-Assessment Questions and Exercises
11.11 Further Readings
12.1 Introduction
12.2 Objectives
12.3 How applets differ from Applications
12.4 Preparing to write applets
12.5 Building Applet Code
12.6 Applet life cycle
12.7 Creating an Executable Applet
12.8 Designing a Web Page
12.9 Running the Applet
12.10 Passing parameters to Applets
12.11Displaying Numerical values
12.12 Getting input from the user
12.13 Check Your Progress Questions
12.14 Answers to Check Your Progress Questions
12.15 Summary
12.16 Key Words
12.17 Self-Assessment Questions and Exercises
12.18 Further Readings
13.1 Introduction
13.2 Objectives
13.3 Stream & Stream classes
13.3.1 Byte stream classes
13.3.2 Character Stream
13.4 Check Your Progress Questions
13.5 Answers to Check Your Progress Questions
13.6 Summary
13.7 Key Words
13.8 Self-Assessment Questions and Exercises
13.9 Further Readings
14.1 Introduction
14.2 Objectives
14.3 Using stream
14.4 Using the file class
14.5Input / Output Exceptions
14.6 Creation of files
ix
14.7 Reading / writing characters
14.8 Reading / writing bytes
14.9 Random access files
14.10 Interactive input and output
14.11 Check Your Progress Questions
14.12 Answers to Check Your Progress Questions
14.13 Summary
14.14 Key Words
14.15 Self-Assessment Questions and Exercises
14.16 Further Readings
x
Basic Internet Concepts
NOTES
BLOCK – I INTRODUCTION [
T
y
p
UNIT 1 e
BASIC INTERNET CONCEPTS
t
h
Structure e
1.1 Introduction
s
1.2 Objectives
1.3 Connecting to the Internet i
1.4 Domain Name System (DNS) d
1.5 E-mail e
1.6 Check Your Progress b
1.7 Answers to Check Your Progress Questions a
1.8 Summary r
1.9 Key Words
1.10 Self-Assessment Questions and Exercises
c
1.11 Further Readings
o
n
1. 1 Introduction t
e
n
During the first two decades, computer systems were highly
t
centralized, usually within a single large room called computer centre.
The concept of the computer centre as room with a large computer to .
which users bring their work for processing is rapidly becoming
obsolete. A single computer serving all of the organizations A
computational needs is rapidly being replace in which a large number
of separate but interconnected computers do the job. The systems are s
called computer networks. i
d
Computer network is a set of interconnected autonomous computers to
e
communicate each other. Network usually fall into one of two groups:
Local Area Networks (LAN) and Wide Area Networks (WAN). Local b
area networks connect computers located near each other. Wide Area a
Network consists of computers in different cities, states or even r
countries. Personal Area Network (PAN) is a network which enables
communication between computer devices near a person. Virtual i
Private Network (VPN) is a network technology that is used to create a s
Self-Instructional Material
1 a
s
t
a
Basic Internet Concept
NOTES
safe and encrypted connection over a less secure network such as internet.
[Storage Area Network (SAN) is a block base storage. It is a technology by
Twhich high speed architecture connects with servers to their logical disk
yunits.
p
eInternet is a network of network connected to World Wide Web
(WWW).Internet gives people the opportunity to connect with anyone in
tthe world at any given time and allows business to be conducted more
efficiently and on a grander scale. In essence, the internet makes the world
h
much more efficient. Internet uses the standard Internet Protocol
e
(TCP/IP).Every computer in internet is identified by a unique IP address.IP
Address is a unique set of numbers (such as 110.22.31.124) which
sidentifies a computer location.
i
dThe first workable prototype of the Internet came in the late 1960s with the
ecreation of ARPANET, or the Advanced Research Projects Agency
bNetwork. ... ARPANET adopted TCP/IP on January 1, 1983, and from
a
there researchers began to assemble the “network of networks” that
became the modern Internet.Ten years of research brought Local Area
r
Ethernet Networks (LANs) and workstations were developed to get
connected to LAN.Computers connected to ARPANET used a standard or
crule to communicate with each other with NCP (National Control
oProtocol).Protocol is a network term used to indicate the standard used by
na network for communication.Rapid change in information technology
tsuppressed NCP and brought TCP/IP (Transmission Control
eProtocol/Internet Protocol) in to the world of networking
n
Need for Internet:
t
. Most of us use, the internet as a way to connect with other people, sharing
information, sharing of files, for entertainment, socializing, and many
Aother things that could be beneficial for us.The internet is necessary for the
following reasons;
s
i Communication – People use the Internet to communicate with one
danother using e-mail. Software has made it possible to stream voice and
video across the world with minimal delay, and email has become the
e
main means of communicating for many a modern person.
b
aEntertainment – Many people use the Internet to enjoy themselves and to
rengage in personal interests. In recent years, multiple player games and
virtual worlds have engaged the time and money of many. Plus, video and
i music are easy to find, stream and download.
s
Self-Instructional Material
a 2
s
t
a
n
Basic Internet Concepts
NOTES
Market – People use the Internet to research, find and buy services and
products or to target and sell to the ultimate consumer. In effect, the [
Internet has become THE best way to buy and sell merchandise, as T
online “stores” are open 24 hours a day, 7 days a week.
y
Ask for Help - Some people use the Internet to ask for help. People ask p
for help in the form of emotional support, medical advice, or even e
simply listening.
t
Education and Research - People use internet for education to learn h
and research purpose e
In this unit you will learn about the structure of DNS, Name Server A
concept and resolver, e-mail communication and world wide web..
s
1.2 Objectives i
d
e
After going through the unit you will be able to; b
a
Understand the fundamentals of computer networks r
Know about the Domain Name System
Discuss about e-mail communication system
i
Learn how to connect to the Internet
s
Self-Instructional Material
3 a
s
t
a
Basic Internet Concept
NOTES
[
1.3 Connecting to the Internet
T
y
pWhen connecting one or more computers for communication, it forms a
enetwork. We can also connect two or more networks and form an
internetwork or internet.
t
hAn Internet service provider (ISP) is an organization that provides services
e
for accessing, using, or participating in the Internet. Internet services
typically provided by ISPs include Internet access, Internet transit, domain
name registration, web hosting, Usenet service, and colocation. Internet
sservice providers (ISPs) offering broadband and narrow band internet
i services in India. They are namely Jio,Airtel,Vodaphone,Idea Cellular,
dBSNL,Tata Teleservices, ACT,MTNL and Hathway.
e
bThe type of Internet service you choose will largely depend on which
aInternet service providers (ISPs) serve your area, along with the types of
rservice they offer. Here are some common types of Internet service.
Dial-up:
c
oThis is generally the slowest type of Internet connection, and you should
nprobably avoid it unless it is the only service available in your area. Dial-
tup Internet uses your phone line, so unless you have multiple phone lines
eyou will not be able to use your landline and the Internet at the same time.
n
tLeased Connection
.
Leased connection is also known as direct Internet access or LevelThree
connection. It is the secure, dedicated and most expensive,level of Internet
Aconnection. With leased connection, your computeris dedicatedly and
directly connected to the Internet using highspeed transmission lines. It is
son-line twenty-four hours a day, sevendays a week. Leased Internet
i connections are limited to large corporations and universities who could
dafford the cost.
e
bDigital Subscriber Line (DSL):
a
Digital Subscriber Line (DSL) is the newest technology being usedfor
rInternet access. DSL connects your home or office to the Internetthrough
the same telephone wire that comes from the telephonepole on the street.
i Like ISDN, with DSL, user can make and receivetelephone calls while
sconnected simultaneously to the Internet.However, DSL service is limited
Self-Instructional Material
a 4
s
t
a
n
Basic Internet Concepts
NOTES
Cable: t
h
Cable service connects to the Internet via cable TV, although you do e
not necessarily need to have cable TV in order to get it. It uses a
broadband connection and can be faster than both dial-up and DSL
s
service; however, it is only available where cable TV is available.
i
Satellite: d
e
A satellite connection uses broadband but does not require cable or b
phone lines; it connects to the Internet through satellites orbiting the a
Earth. As a result, it can be used almost anywhere in the world, but the r
connection may be affected by weather patterns. Satellite connections
are also usually slower than DSL or cable. c
o
3G and 4G:
n
3G and 4G service is most commonly used with mobile phones, and it t
connects wirelessly through your ISP's network. However, these types e
of connections aren't always as fast as DSL or cable. They will also n
limit the amount of data you can use each month, which isn't the case t
with most broadband plans. .
Modem
A
Once you have your computer, you really don't need much additional
hardware to connect to the Internet. The primary piece of hardware you s
need is a modem.A modem transmits binary data by representing a 0 as i
decreased frequency signal and 1 as increased frequency signal. The d
computer uses a modem to translate binary data into analog signal for e
transmission over telephone line. The figure 1.1 shows the example b
model used to connect Internet. a
r
i
s
Self-Instructional Material
5 a
s
t
a
Basic Internet Concept
NOTES
[
T
y
p
e
Figure 1.1A Modem
tRouter
h
A router is a hardware device that allows you to connect several computers
e
and other devices to a single Internet connection, which is known as a
home network. Many routers are wireless, which allows you to create a
shome wireless network, commonly known as a Wi-Fi network.
i
d
e
b
a
r
c
o
Figure 1.2 Router
n
Web Browser
t
eA web browser, or simply "browser," is a Software / application used to
naccess and view websites. Common web browsers include Microsoft
tInternet Explorer, Google Chrome, Mozilla Firefox, and Apple Safari.
.
s
i
d
e
b
a
r
i
s 1.3 Most Popular Web Browsers
Self-Instructional Material
a 6
s
t
a
n
Basic Internet Concepts
NOTES
Search Engine: s
i
A search engine is a web-based tool that enables users to locate d
information on the World Wide Web. Generally, people use search
e
engines for one of three things: research, shopping, or
entertainment. Most people who are using a search engine are b
doing it for research purposes. They are generally looking for a
answers or at least to data with which to make a decision. Types of r
Search Engines include;
c
Crawler Based Search Engines. o
Directories Search Engines. n
Hybrid Search Engines. t
Meta Search Engines e
n
Popular examples of search engines are Google, Yahoo!, ask,altavista
t
and MSN Search.
.
s
i
d
e
b
a
r
1.4 Most Popular Search engines
i
s
Self-Instructional Material
7 a
s
t
a
Basic Internet Concept
NOTES
s
i
d
e
b
a
r
Self-Instructional Material
a 8
s
t
a
n
Basic Internet Concepts
NOTES
The level immediately below the root of the Internet DNS consists of
three top domains. The internet usually divides this group of domains [
into seven basic categories. The given table identifies the seven basic T
classifications of the organizational domains.
y
p
Domain Description
com Commercial organizations such as business e
edu Educational organizations such as universities
gov US government organizations etc t
Int International organizations h
mil US military organization e
net A network that doesn’t fit into one of the other
organizational domain categories s
org An organization that doesn’t fit into one of the other i
organizational domain categories d
e
b
Uniform Resource Locators (URL)
a
An URL identifies a resource, normally a file. It is the computer r
address of a resource, such as web document, a file or a program. An
example of url is https://www.alagappauniversity.ac.in/. When typing the c
URL into your browsers location field and hit enter, your browser will o
attempt to connect you to the resource at that URL address. After you connect
n
to a web server, your browser displays the web information set to it by the
server. t
e
n
1.5 Electronic Mail – E-mail t
.
s
t
a
Basic Internet Concept
NOTES
Self-Instructional Material
a 10
s
t
a
n
Basic Internet Concepts
NOTES
Each e-mail message has a sender and receiver, both of which have a
user interface into the Internet electronic mail system. [
T
E-mail Message Components
y
E-mail message comprises of different components: E-mail Header, p
Greeting, Text, and Signature. These components are described in the e
following figure 1.7
t
h
e
s
i
d
e
b
a
r
c
o
n
t
e
n
t
.
E-mail Header s
i
The first five lines of an E-mail message is called E-mail header. The d
header part comprises of following fields: e
b
From
a
Date r
To i
s
Self-Instructional Material
11 a
s
t
a
Basic Internet Concept
NOTES
Subject
[ CC
T
y BCC
p
eFrom
tThe From field indicates the sender’s address i.e. who sent the e-mail.
h
Date
e
The Date field indicates the date when the e-mail was sent.
s
i To
d
eThe To field indicates the recipient’s address i.e. to whom the e-mail is
bsent.
a
Subject
r
The Subject field indicates the purpose of e-mail. It should be precise and
cto the point.
o
nCC
t
eCC stands for Carbon copy. It includes those recipient addresses whom we
nwant to keep informed but not exactly the intended recipient.
t
BCC
.
BCC stands for Black Carbon Copy. It is used when we do not want one or
Amore of the recipients to know that someone else was copied on the
message.
s
i Greeting
d
Greeting is the opening of the actual message. Eg. Hi Sir or Hi Guys etc.
e
b
Text
a
rIt represents the actual content of the message.
i Signature
s
Self-Instructional Material
a 12
s
t
a
n
Basic Internet Concepts
NOTES
Reliable t
Convenience h
Speed e
Inexpensive
Printable
s
Global
i
Disadvantages d
e
Apart from several benefits of E-mail, there also exists some b
disadvantages as discussed below: a
r
Forgery
Overload c
Misdirection
o
Junk
No response n
t
The Internet e-mail system consists of an outgoing queue, a client e
process, a server process and mailboxes for incoming mail. A mail box n
can refer to user address or a container file that stores e-mail data. The t
user agent replaces the e-mail program and the message transfer agent .
replaces the client and server process. Most Internet e-mail
specifications refer to an e-mail program as a user agent. Likewise, it
A
message transfer agent is a client or server program that performs e-
mail related services such as sending and receiving mail for a host
computer. You interact with user agent program which in turn s
interacts with an email container on your behalf. At the same time, the i
MTA program acts as an agent on behalf of a host computer. The user d
agent shields your from interacting with a wide variety of user agents e
or other MTA’s. b
a
Conceptually, the user agent to an email system is separate from the r
message transfer agent. Although you can implement both the user
agent and message transfer agent in a single program. You should
isolate the design of each agent in separate modules. The agents perform i
s
Self-Instructional Material
13 a
s
t
a
Basic Internet Concept
NOTES
very different functions through they are closely related. On the Internet,
the message transfer agent represents the internet email. The MTA’s that
[establish TCP connections to communicate with other MTAs typically use
Tthe Simple Mail Transfer Protocol (SMTP)
y
pSimple Mail Transfer Protocol (SMTP)
e
The core of the internet’s e-mail system is the message transfer agent. The
tmessage transfer agent represents the e-mail system to a host computer.
Although internet e-mail users rarely work with a message transfer agent
h
MTAs play a crucial role in all e-mail transmissions.
e
SMTP is similar to FTP in many ways, including the same simplicity of
soperation. SMTP uses TCP port number 25. It uses spools or queues.
i When a message is sent to SMTP, it places it in a queue. It attempts to
dforward the message from the queue whenever it connects to remote
emachines.
b
a1.6 Check Your Progress
r
Self-Instructional Material
a 14
s
t
a
n
Basic Internet Concepts
NOTES
A
1. Describe the functions of e-mail.
2. Explain in detail about Domain Name system with examples.
3. How will you connect with internet? What are the components s
required to connect Internet? i
4. Explain in detail about some common types of Internet service. d
e
b
1.11 Further Readings
a
r
1. R. Krishnamoorthy and S. Prabhu, Internet and Java
Programming, New Age International Publishers, 2004 i
s
Self-Instructional Material
15 a
s
t
a
Basic Internet Concept
NOTES
c
o
n
t
e
n
t
.
s
i
d
e
b
a
r
i
s
Self-Instructional Material
a 16
s
t
a
n
The world wide web(WWW)
NOTES
UNIT – 2 [
T
THE WORLD WIDE WEB (WWW) y
p
e
Structure
2.1 Introduction t
2.2 Objectives h
2.3 Internet Search Engines e
2.4Web Browsers
2.5Chatting and conferencing on the Internet s
2.5.1 Chatting i
2.5.2 Conferencing
d
2.6 Check your Progress
e
2.7Answers to Check Your Progress Questions
2.8Summary b
2.9Key Words a
2.10Self-Assessment Questions and Exercises r
2.11Further Readings
c
2.1 Introduction o
n
t
The term World Wide Web (WWW, or W3 or Web) and internet are e
widely used word in the communication technology. World Wide Web is n
a collection millions of linked HTML(Hyper Text Markup Language) t
pages on the internet. We can view text, graphics, video, and hear audio .
when we use our browser to access web sites. The internet is a vehicle
that lets computers around the world communicates. WWW was
A
originally developed at CERN(Conseil European Pour la Recherche
Nucleaire), Geneva’s European Laboratory for Particle Physics, the high-
energy physics research centre in Switzerland. Today more than one s
million web servers exist in the world. No web has grown dramatically i
and has taken on a new appearance. The web is no longer limited to d
scientific information exchange by researchers. Business uses the web to e
advertise their products. b
a
To surf the web, we must have a computer with a modern and a telephone
r
connection. Also we need browser software such as Netscape navigator or
Internet Explorer or Google Chrome. A web browser is used to view the
web pages on the internet.WWW clients on theinternet can display pages i
from any of the nearly 10000 web servers. Each time we choose a link; s
WWW Connects to the appropriate server retrieves the next page and
returns control to the local client. WWW is thus an efficient method of a
finding and using the information widely dispersed throughout the world.
s
t
Self-Instructional Material
17 a
n
d
a
The World Wide Web(WWW)
NOTES
In Internet, Web operations are depending on a protocol called Hyper Text
Transfer Protocol (HTTP). Hyper Text Transfer Protocol (HTTP) is used
[ to transfer HTML files between web pages over the World Wide Web.
THTML is the mostly widely used language for developing web pages. All
yweb browsers follow internet standards for accessing web pages. World
pWide Web is composed of a set of HTML web pages.
e
2.2 Objectives
t
h
eAfter going through the unit you will be able to;
c
oSearch engine is a service that allows Internet users to search for content
nvia the World Wide Web (WWW). A user enters keywords or key phrases
t into a search engine and receives a list of Web content results in the form
e
of websites, images, videos or other online data. The list of content
returned via a search engine to a user is known as a search engine results
n
page (SERP).(Source ;Tecopedia)
t
. For example
A Google.
Bing.
s Yahoo.
i Ask.com.
d AOL.com.
e Baidu.
b Wolframalpha.
a DuckDuckGo.
r
NOTES
including Web pages, images, video and other files. As a client/server
model, the browser is the client run on a computer that contacts the Web [
server and requests information. There are varieties of web browsers T
available with different advantages and working on different platforms. y
The most popular web browsers are; p
e
Hot Java
Netscape Navigator t
Avant
h
Internet Explorer
e
Google Chrome
Mozilla fire box
s
Opera and
Safari. i
d
Internet Explorer was developed by Microsoft in 1994 and released in e
1995. Mozilla fire box browser was developed by Mozilla Corporation in b
2004. This is the second most popular browser after Internet Explorer. a
Safari is the web browser made by apple with compatibility with r
Microsoft Windows iPhone OS and Mac OS. Opera is a web browser
developed by Opera Software specially used for mobile applications.
c
Google Chrome is another web browser developed by Google in
o
September 2008 for Windows. Netscape navigator is also a web browser
developed by Netscape communications which supports almost all n
Operating systems. The following figure 2.1 shows the example internet t
explorer web e
n
browser. t
.
s
i
d
e
b
a
r
Figure 2.1 Example Web Browser – Internet Explorer
i
The most distinguish areas of web browsers are platform (Unix, s
Windows, Mac, Linux), protocols(FTP,SMTP,HTTP,IMAP), GUI
(Graphical User Interface), mobile compatibility and open source.
a
s
t
Self-Instructional Material
19 a
n
d
a
The World Wide Web(WWW)
NOTES
e-mail
t
website
h
e-commerce
e
social media
resource sharing
s Conferencing
i Chatting
d Online courses
e
b2.5.1 Chatting
a
rChatting is almost as good as speaking to the other person over the phone.
Online chatting is a online conversation between users or group of users.
There are many free chat sites on the web through which you can
c
communicate with one or many people from different locations. After you
o
log on to free chat site, go to the specific chat room where you have agreed
nto meet other person. For example:
t
e 1. Type the site address www.yahoo.com
n 2. Click on chat option
t 3. Click on sign up for yahoo chat to create a new account
. 4. If you already have an account with yahoo you can enter Yahoo Id
and Password and click on Sign In button.
5. Click on Start Chatting button.
A
2.5.2 Conferencing
s
i Conferencing comprises the technologies for transmission of audio/video
dsignals by users from different places for communication between users on
ethe network. Video conferencing is also called as video collaboration is a
btype of network groupware. Video conferencing systems during 1990’s are
aexpensive communication systems with network and software
requirements. Video conferencing using two protocols such as Session
r
Initialization Protocol (SIP) and H3.xxx.
i SIP is a protocol for creating, modifying and terminating sessions with one
sor more users. The architecture of SIP is similar to Hyper Text Markup
Protocol(HTTP). The client request services to the server for processing
athe tasks. The server receives the request and processes it and responds
s
Self-Instructional Material
t 20
a
n
d
The world wide web(WWW)
NOTES
back to the client. This protocol itself provides reliability, which is not
depending on TCP/IP. [
T
The SIP system has two components; user agents and network servers. A y
user agent is an end system acting on behalf the user. It has two parts p
namely client and server. There are three types of network servers namely e
proxy server, registration server and redirect server. A registration server
receives updates about the user location. A proxy servers receives the
t
message and forwards to next-hop server. A redirect server receives the
message, and determine the next-hop server to the client. h
e
H.3XX are ITU-T study group XVI umbrella recommendations for video
conferencing. These recommendations refer other recommendations that s
include multiplexing, control and signalling. i
d
2.6 Check your Progress e
b
a
1. What is web browser? Give examples r
2. List any two internet search engines.
c
2.7 Answers to Check Your Progress Questions o
n
t
1. A browser is a software application used to locate, retrieve and e
display content and languages such as XML or Extensible Markup n
Language, HTML or Hyper Text Markup Language. on the World t
Wide Web, including Web pages, images, video and other files.
.
Examples : Google chrome and Internet Explorer
s
2.8 Summary i
World Wide Web (WWW) is a collection of linked HTML(Hyper Text d
Markup Language) pages on the internet. Search engine is a service that e
allows Internet users to search for content via the World Wide Web b
(WWW). A browser is a software application used to locate, retrieve and a
display content and languages such as XML or Extensible Markup r
Language, HTML or Hyper Text Markup Language. on the World Wide
Web, including Web pages, images, video and other files. i
s
Conferencing comprises the technologies for transmission of audio/video
signals by users from different places for communication between users
on the network. Video conferencing is also called as video collaboration a
is a type of network groupware.
s
t
Self-Instructional Material
21 a
n
d
a
The World Wide Web(WWW)
NOTES
i
s
s
Self-Instructional Material
t 22
a
n
d
Online Chatting
NOTES
[
UNIT – 3 T
y
ONLINE CHATTING p
e
Structure
t
3.1 Introduction
3.2 Objectives h
3.3Online Chatting and Messaging e
3.4Usenet Newsgroup
3.5Internet Relay chat (IRC) s
3.6 File Transfer Protocol (FTP) i
3.7Telnet d
3.8 Check Your Progress Questions e
3.9Answers to Check Your Progress Questions
b
3.10Summary
3.11Key Words a
3.12Self Assessment Questions and Exercises r
3.13Further Readings
c
o
3.1 Introduction
n
t
Communication plays major role in internet applications. It provides e
sharing of information, messages between user and/or group of users. n
There are various applications such as online chatting, messenger and user t
networks groups provide opportunity to share information over the .
network.
A
3.2 Objectives
s
After going through the unit you will be able to;
i
Understand about online chatting d
Know about the message between network user e
Explain about the user network groups b
Discuss about file transfer protocol a
Learn about the use of Telnet r
s
Self-Instructional Material
23 t
a
n
d
a
Online Chatting
NOTES
[communicating or interacting with users over internet. It can be
Testablished by connecting one user with other users using chat software.
y
p
The chat software creates one or more rooms for users to communicate
with each other according to the user’s interest. To chat with users, one
e
who need internet relay chat or instant messenger application. Chat may
be delivered through verbal, audio, text and video.
t
h
e3.4 Usenet Newsgroup
sUsenet Newsgroup is storage with in the usenet system where the users
i from different geographical locations post their messages over internet.
dThe usenet files uploaded by the users are stored in the servers
edistributed over the various geographical locations and connected
bthrough the internet. The sending and receiving of files is performed by
athe Network News Transfer Protocol (NNTP) which allows connection
rto Usenet servers and data transfer over the internet. The communication
is established between server-server and client-server. Newsgroups are
divided into two ways; text and binary which depend on bandwidth.
c
o
n3.5 Internet Relay chat (IRC)
t
e
nInternet Relay Chat (IRC) is an application layer protocol which is used
tto communicate in the form of text. It was developed in August 1988, by
. Jarkko Oikarinel. IRC is used to enable the users to request to a server
using server side programming software and communicate with each
other online.
A
The IRC client software is used to connect to the IRC server. There are
ssome small IRC servers available for Internet Relay chat.The small IRC
i servers are namely OperaNet which has less number of users. The
dmedium IRC servers are freenode and Dalnet which may have 40,000
eusers.The big IRC servers may consist of over 100,000 users; for
bexample, EFNet and UnderNet. The example IRC is shown in figure 3.1
a
r
i
s
Self-Instructional Material s
t 24
a
n
d
a
Online Chatting
NOTES
[
T
y
p
e
t
h
e
s
i
d
e
b
a
r
File transfer protocol, usually called FTP, is a utility for managing files s
across machines without having to establish a remote session with Telnet. i
FTP enables to transfer files back and forth, manage directions, and access
d
electronic mail. FTP is not designed to enable access to another machine to
e
execute programs, but it is the best utility for file transfer.
b
FTP uses two TCP channels. TCP port 20 is the data channel, and port 21 a
is the command channel. FTP is different from most other TCP/IP r
application programs in that it does uses two channels, enabling
simultaneous transfer of FTP commands and data. i
s
FTP transmission Modes
a
The transmission modes specify how FTP transmits the file across the TCP
data connection. FTP defines three transmission modes;
s
Self-Instructional Material
25 t
a
n
d
a
Online Chatting
NOTES
[
T Block mode
y Compressed mode and
p Stream mode
e
3.7 Telnet
t
h
eThe Telnet (Telecommunication network) program is intended to
provide a remote login or virtual terminal capability across a network. In
s
other words, a user on machine A should be able to log into machine B
anywhere on the network, and as far as user is concerned, it appears that
i
the user is seated in front of the machine B. The telnet service is
dprovided through TCPs port number 3. The term Telnet is used to refer
eto both the program and the protocol that provide these services.
b
aWhen two machines communicate using Telnet, Tenet itself can
rdetermine and set the communications and terminal parameters for the
session during connection phase.
c
The Telnet protocol includes the capability not to support a service that
o
one end of the connection cannot handle. When a connection has been
nestablished by Telnet, both ends have agreed upon a method for the two
tmachines to exchange information, taking the load off the server CPU
efor a sizable amount of this work. The figure 3.2 shows the Microsoft
ntelnet client window.
t
.
s
i
d
e
b
Figure 3.2 Microsoft Telnet Client Window
a
rTelnet involves a process on the server that accepts incoming request for
a Telnet Session. On UNIX systems, this process is called tented. On
i Windows NT and other PC based operating systems, a Telnet Server
sprogram is usually involved. The client runs a program, usually called
telnet that attempts the connection to the server.
a
Self-Instructional Material s
t 26
a
n
d
a
Online Chatting
NOTES
[
3.8 Check Your Progress Questions T
y
p
1 What do you meant by File Transfer Protocol?
e
2. List various types of FTP transmission modes.
3. Write short note on: Telnet
t
h
3.9 Answers to Check Your Progress Questions e
s
1. File transfer protocol, usually called FTP, is a utility for managing files i
across machines without having to establish a remote session with d
Telnet. FTP enables to transfer files back and forth, manage directions, e
and access electronic mail.
b
2. Block mode, Compressed mode and Stream mode a
r
3. The telnet (Telecommunication network) program is intended to
provide a remote login or virtual terminal capability across a network. c
In other words, a user on machine A should be able to log into machine o
B anywhere on the network, and as far as user is concerned, it appears n
that the user is seated in front of the machine B. t
e
n
3.10 Summary
t
.
Usenet Newsgroup is storage with in the usenet system where the users
from different geographical locations post their messages over internet. A
Internet Relay Chat (IRC) is an application layer protocol which is used to
communicate in the form of text. File transfer protocol, usually called FTP, s
is a utility for managing files across machines without having to establish a i
remote session with Telnet. d
e
3.11 Key Words b
a
r
Chatting is to talk in a way with one person with other or group of
persons over the telecommunication especially internet. i
s
The telnet (Telecommunication network) program is intended to
provide a remote login or virtual terminal capability across a
network. a
s
Self-Instructional Material
27 t
a
n
d
a
Online Chatting
NOTES
[
3.12Self-Assessment Questions and Exercises
T
y
p 1. Name any two chat servers.
e 2. Write short note on Messaging and chatting
3. Briefly explain about Telnet communication
t
h3.13 Further Readings
e
s
1. R. Krishnamoorthy and S. Prabhu, Internet and Java
Programming, New Age International Publishers, 2004
i
2. Programming with Java, 4e, E. Balagurusamy, Tata McGraw-
d Hill, 2010.
e 3. Deitel, Deitel and Nieto, Internet and World Wide Web – How to
b program, Pearson Education, 2000.
a 4. Naughton and H.Schildt, Java 2 - The complete reference, Tata
r McGraw-Hill, Fourth edition, 2006.
5. Elliotte Rusty Harold, Java Network Programming, O’Reilly
c Publishers, 2000.
6. B.Mohamal Ibrahim , Java : J2SE – A Practical Approach,
o
Firewall media, 2006.
n 7. Cay S. Horstmann, Gary Cornell, Core Java, Volume I and II, 5th
t Edition, Pearson Education, 2003.
e 8. Topley, J2ME in A Nutshell, O’Reilly Publishers, 2002.
n 9. Hunt, Guide to J2EE Enterprise Java, Springer Publications,
t 2004.
. 10. Ed Roman, Enterprise Java Beans, Wiley Publishers, 1998.
s
i
d
e
b
a
r
i
s
Self-Instructional Material s
t 28
a
n
d
a
Basic Concepts Of Object
Oriented Programming
NOTES
BLOCK 2 [
T
FUNDAMENTALS OF OBJECT y
ORIENTED PROGRAMMING p
e
t
h
UNIT – 4 e
4.1 Introduction A
s
Computer programs consists of two elements namely code and
i
data. A program can be organized around its code and data. There
are two paradigms that reveal how a program is constructed. They d
are procedure oriented and Object oriented programming. e
Procedure oriented programming basically consists of writing a list b
of instructions for a computer to follow and organizing these a
instructions into functions. Little emphasis is given to data. More r
emphasis is on doing procedure. Larger programs are divided into
functions. These functions share global data. Data move openly i
around the system from function to function. It uses top down s
approach in program design. The procedural languages
BASIC,COBOL, FORTRAN and C adopt this approach. Object
a
Self-Instructional Material
29 s
t
a
n
d
Basic Concepts Of Object
Oriented Programming
NOTES
[ Oriented Programming is a new paradigm with various features such as
T structured programming, reliability and data security. There are many
y object oriented programming languages such as C++ and Java.
p
e
4.2 Objectives
t
h After going through the unit you will be able to;
e
Know the fundamentals of Object Oriented Programming (OOP)
s Understand the basic concepts of Object Oriented Programming
i Discuss about the applications of Java
d Know the advantages of Java Programming.
e
b
a 4.3Basic concepts / Principles of OOP
r
Self-Instructional Material
s 30
t
a
n
d
a
Basic Concepts Of Object
Oriented Programming
NOTES
within class and it describes a set of objects with common
behavior. The class definition describes all the properties, [
behavior, and identity of objects present within that class. T
y
Object p
e
An Object is an Instance of a Class. Objects are created by
generating an instance of a class or in other words instantiating a
t
class. There can be more than one object for a particular class.
Objects are the basic unit of object orientation with behaviour, h
identity. Figure 1.1 shows the representation of class and objects. e
s
i
d
e
b
a
r
c
o
Figure 1.1 Class and its objects
n
Data Abstraction t
e
Data abstraction defines the essential components (data members / n
attributes / properties such as size, price supplier and methods / t
membership function prototypes such as calculate()) excluding the .
implementation of it. It defines only what is to be implemented but
excluding how. In object oriented programming class defines the A
abstraction of data. The data members are sometimes called as
attributes or properties. Methods of a class are also called as
membership function or data members. s
i
Data Encapsulation d
e
Combining data and its function into a single unit is called Data b
Encapsulation. Data encapsulation, sometimes referred to as data a
hiding, is the mechanism whereby the implementation details of a r
class are kept hidden from the user. This idea of hiding the details
away from the user and providing a restricted, clearly defined
interface is the underlying theme behind the concept of an abstract i
data type. s
a
Self-Instructional Material
31 s
t
a
n
d
Basic Concepts Of Object
Oriented Programming
NOTES
[ Inheritance
T
y Inheritance is the process by which child object can get the properties of
p
parent object. In object-oriented programming, inheritance is a way to
form new classes (instances of which are called objects) using classes
e
that have already been defined. The new classes, known as derived
classes, take over (or inherit) attribute and behavior of the pre-existing
t classes, which are referred to as base classes (or ancestor classes). It is
h intended to help reuse existing code with little or no
e modification.Figure 1.2 shows the process of inheritance.
s
i
Animal
d
e
b Domestic Wild
a
r
i
s
Self-Instructional Material
s 32
t
a
n
d
a
Basic Concepts Of Object
Oriented Programming
NOTES
[
Polymorphism
T
y
p
e
Compile Time Runtime
t
h
e
Function Operator
s
Virtual Function
Overloading Overloading
i
d
Figure 1.3 Two types of Polymorphism e
b
Overloading occurs when several methods have same names with a
different method signature. Overloading is determined at the r
compile time.Overriding occurs when a class method has the same
name and signature as a method in parent class.
c
A single function name area can be used to handle different o
number and different type of arguments like area(a) for square n
,area(b,h) for triangle and area(rad) for circle. When you override t
methods, java determines the proper methods to call at the e
program’s run time, not at the compile time. Figure 1.4 shows the n
function overloading of area() method. t
.
A
Shape
Area() s
i
d
e
Circle Square Square b
Area(rad) Area(r) Area(b,h)
a
r
i
s
Figure 1.4 Function Overloading
a
Self-Instructional Material
33 s
t
a
n
d
Basic Concepts Of Object
Oriented Programming
NOTES
[ Message Passing
T
y Message Passing is another object oriented programming concept in
p
which one object can communicate with other objects. Objects can
communicate each other through message passing.
e
For example, Consumer and Producer relationship can be established
t using message passing mechanism. In this example consumer and
h producer are considered as two objects.
e
s 4.4Benefits
i
d
The Object oriented programming paradigm came into existence to
e
resolve the disadvantages of structured programming language
b
paradigms. The benefits of object oriented Programming includes;
a
r Reusability:Reusability of code can be achieved through
inheritance. By deriving a new class from the existing parent class
c reusability can be achieved.
o
n Secure and Robust: The principles of data hiding help to write
t a code to secure the data in various applications.
e
n
Message Passing:These systems used to communicate between
one object with other objects.
t
.
Flexibility:Through polymorphism flexibility in code can be
A achieved using overloading and virtual function.
i
s
Self-Instructional Material
s 34
t
a
n
d
a
Basic Concepts Of Object
Oriented Programming
NOTES
4.5Applications [
T
y
Object oriented programming has featured many applications from p
1960’s. Some of the applications of Object oriented Programming e
for software developments are;
t
Client Server systems : Object Oriented Programming is h
used to develop client side (HTML, Javascript) and server
e
side (Servlets) programming.
NOTES
[ 4.7 Answers to Check Your Progress Questions
T
y
p 1. Mixing of data and its function into a single unit is called Data
e Encapsulation.
2. Run-time polymorphism and Compile time polymorphism
3. Class,Objects, Data Abstraction, overloading, inheritance, data
t
hiding, polymorphism and message passing.
h
e
4.8 Summary
s
i
Java is an object oriented programming. The basic concepts of object
d oriented Programming include class, objects, data abstraction,
e overloading, inheritance, data hiding, polymorphism and message
b passing. There are various benefits such as reusability, secure and
a robust. Object oriented programming is used to develop various
r applications such as real-time, embedded and cloud/distributed systems.
NOTES
4. Naughton and H.Schildt, Java 2 - The complete reference,
Tata McGraw-Hill, Fourth edition, 2006. [
5. Elliotte Rusty Harold, Java Network Programming, T
O’Reilly Publishers, 2000. y
6. B.Mohamal Ibrahim , Java : J2SE – A Practical Approach, p
Firewall media, 2006. e
7. Cay S. Horstmann, Gary Cornell, Core Java, Volume I and
II, 5th Edition, Pearson Education, 2003.
t
8. Topley, J2ME in A Nutshell, O’Reilly Publishers, 2002.
9. Hunt, Guide to J2EE Enterprise Java, Springer h
Publications, 2004. e
10. Ed Roman, Enterprise Java Beans, Wiley Publishers, 1998.
s
i
d
e
b
a
r
c
o
n
t
e
n
t
.
s
i
d
e
b
a
r
i
s
a
Self-Instructional Material
37 s
t
a
n
d
Java Evolution
NOTES
[
T
y UNIT 5
p
e JAVA EVOLUTION
t
Structure
h
e5.1Introduction
5.2 Objectives
s5.3Java Evolution
i 5.4Features
d5.5How java differs from C and C++
e5.6Java and internet
b5.7Java support system
5.8Java environment
a
5.9 Check Your Progress Questions
r5.10 Answers to Check Your Progress Questions
5.11 Summary
c5.12 Key Words
o5.13 Self-Assessment Questions and Exercises
n5.14 Further Readings
t
e5.1 Introduction
n
t
. Java is a programming language derived from Oak language. It has
many features such as robust, secure and platform independent. It differs
Afrom C and C++ in many ways. It also supports for internet
programming. It has special environment to work with console and
internet. This unit discuss about the evolution of java and its features.
s
i
d5.2 Objectives
e
b
aAfter going through the unit you will be able to;
r
Understand Java Evolution
List out the Features of Java
i
Know How java differs from C and C++
s
Learn about Java and internet
Identify Java support system
a Discuss about Java environment
Self-Instructional Material s
t 38
a
n
d
a
Java Evolution
NOTES
[
5.3Java Evolution T
y
p
The Java programming Language evolved from a language named e
Oak. Oak was developed in the early nineties at Sun Microsystems
as a platform-independent language aimed at allowing
entertainment appliances such as video game consoles and VCRs t
to communicate. Oak was first slated to appear in television set- h
top boxes designed to provide video-on-demand services. As e
Oak’s developers began to recognize this trend, their focus shifted
to the Internet and WebRunner, an Oak-enabled browser, was s
born. Oak’s name was changed to Java and WebRunner became i
the HotJava web browser. d
e
b
5.4 Features of Java
a
r
Java has many features, where it follows object oriented
programming and platform independence, the features are, c
o
1. Java is Interpreted: - Strictly speaking java is interpreted n
although in reality java is both interpreted and compiled. A t
programmer first compiles java source code into byte code e
using java compiler. These byte codes are binary and
n
architecturally neutral(platform independent)
2. Java is platform independent and portable: - Java t
programs can be executed easily from one type of .
computer to another.
3. Java is Object Oriented: - Java is a true object oriented A
language. Almost everything in java is an object. Java
comes with an extensive set of classes arranged in s
packages that we can use in our programs by Inheritance. i
4. Java is robust and secure: - It provides many safeguards d
to ensure reliable code. Java incorporates the concept of
e
exception handling which captures serious errors and
eliminate the errors. b
5. Java is distributed: - Java is designed as a distributed a
language for creating applications on network. Java r
application can open and access remote objects on Internet
as in a local system. i
6. Java is familiar, simple and small: - Java does not use s
pointers, pre processors header files, goto statement etc. It
also eliminates operator overloading and multiple
a
inheritance.
Self-Instructional Material
39 s
t
a
n
d
a
Java Evolution
NOTES
[ 7. Java offers high performance:-Java architecture is designed to
T reduce overheads during run time. The multi threading enhances
y the execution speed of java program.
p
8. Java is dynamic and extensible: - Java is capable of
dynamically linking in new class methods and objects. Java
e
programs supports functions written in other languages such as C
and C++. Native methods are linked dynamically at run time.
t
h5.5 How java differs from C and C++
e
NOTES
The Java language is a high level one that at a glance looks very [
similar to C and C++ but offers many unique features of its own. T
y
Java bytecode p
e
A compiler, such s Sun's javac, transforms the Java language
source code to bytecode that runs in the JVM.
t
Java Virtual Machine (JVM) h
e
A program, such as Sun's java, that runs on a given platform and
takes the byte code programs as input and interprets them just as if s
it were a physical processor executing machine code. JVM is the i
heart of java which is a virtual computer that resides in the d
memory only. The JVM enables java programs to be executed on e
various types of platforms. The JVM is the very reason that java is
b
portable. JVM provides a layer of abstraction between the
compiled java program and the underline hardware platform and a
the OS. r
c
5.8 Java environment o
n
t
A compiler converts the java program into an intermediate e
language representation called BYTECODE which is platform n
independent. A java file will have the extension .java. For example
t
Hello.java. When this file is compiled we get a file called
Hello.class. .
class Hello1 s
{ i
public static void main(String args[]) d
{
e
system.out.println(“Hello java world”);
b
}
} a
r
The steps for compiling and running java program are as follows;
i
C:\java> javac Hello1.java s
C:\java> java Hello1
Hello java world. a
Self-Instructional Material
41 s
t
a
n
d
a
Java Evolution
NOTES
[The following figure 5.1 shows the architecture of java execution
Tenvironment.
y
p
e
t
h
e
s
i
d
e
b
a
r
c
o
n
t
Figure 5.1 shows the java execution architecture
e
nThe concept of “Write Once, run anywhere” is possible in java. The
tjava program can be compiled on any platform having a java compiler.
. The resulting byte-codes can be then run on any operating system on
any machine like windows, Unix etc.. The above diagram illustrate how
Adoes it work.
Self-Instructional Material s
t 42
a
n
d
a
Java Evolution
NOTES
tab at the top named "Advanced." Then, click on "Environment
Variables." In the bottom window that shows system variables, [
select "Path" and then click on "Edit..." Add C:\j2sdk1.5.0_04\bin T
as the first item in the list. Note that all items are separated by a y
semicolon, with no spaces around the semicolon. You should end p
up with a path variable that looks something like e
C:\j2sdk1.5.0_04\bin;C:\WINNT\system32;C:\WINNT;C:\WINN
T\system32\Wbem
t
For Windows 98 or ME, open the file AUTOEXEC.BAT in h
Notepad. You should find a line in this file that begins SET e
PATH=...Modify this line to add C:\j2sdk1.5.0_04\bin;
immediately after the equals sign. s
i
4. Modify or create a system variable called "CLASSPATH," as d
follows. In the lower "System Variables" pane choose "New..." e
and type in Variable Name "CLASSPATH" and value (note that it
b
begins with dot semicolon) .;C:\j2sdk1.5.0_04\lib
a
r
5. To test Java to see if everything is installed properly, open a
command window (a DOS window) and type the command
"javac" The result should be information about the Usage of javac c
and its options. If you get a result that "'javac' is not recognized as o
an internal or external command, operable program or batch file" n
then there is a problem and Java will not work correctly. t
e
Note: n
t
The name of the file and the name of the class must be same. The .
names are also case sensitive. It is a common practice to use a
capital letter at the beginning of the name for a class. A
i
s
Self-Instructional Material
43 s
t
a
n
d
a
Java Evolution
NOTES
[
5.10 Answers to Check Your Progress Questions
T
y
p 1. Java programs can be executed easily from one type of computer
e to another.
2. Java is capable of dynamically linking in new class methods and
t objects. Java programs supports functions written in other
h languages such as C and C++. Native methods are linked
e dynamically at run time.
3. A compiler converts the java program into an intermediate
language representation called BYTECODE which is platform
s independent.
i
d
e5.11 Summary
b
a
The Java programming Language evolved from a language named
rOak.Java has many features, where it follows object oriented
programming and platform independence
c
o
5.12 Key Words
n
t
e Platform Independent -Java programs can be executed easily
n from one type of computer to another.
t
. Bytecode - A compiler converts the java program into an
intermediate language representation called bytecode which is
A platform independent.
i
5.14 Further Readings
s
NOTES
2. Programming with Java, 4e, E. Balagurusamy, Tata
McGraw-Hill, 2010. [
3. Deitel, Deitel and Nieto, Internet and World Wide Web – T
How to program, Pearson Education, 2000. y
4. Naughton and H.Schildt, Java 2 - The complete reference, p
Tata McGraw-Hill, Fourth edition, 2006. e
5. Elliotte Rusty Harold, Java Network Programming,
O’Reilly Publishers, 2000.
t
6. B.Mohamal Ibrahim , Java : J2SE – A Practical Approach,
Firewall media, 2006. h
7. Cay S. Horstmann, Gary Cornell, Core Java, Volume I and e
II, 5th Edition, Pearson Education, 2003.
8. Topley, J2ME in A Nutshell, O’Reilly Publishers, 2002. s
9. Hunt, Guide to J2EE Enterprise Java, Springer i
Publications, 2004. d
10. Ed Roman, Enterprise Java Beans, Wiley Publishers, 1998. e
b
a
r
c
o
n
t
e
n
t
.
s
i
d
e
b
a
r
i
s
Self-Instructional Material
45 s
t
a
n
d
a
Overview of Java language
NOTES
[ UNIT 6
T
y
OVERVIEW OF JAVA LANGUAGE
p
e
Structure
t 6.1 Introduction
h6.2 Objectives
e6.3 Overview of Java
6.4Constants variables and data types
s 6.5Operators and Expressions
i 6.6Decision Making and Branching
6.7Looping
d
6.8 Check Your Progress Questions
e6.9 Answers to Check Your Progress Questions
b6.10 Summary
a6.11 Key Words
r 6.12 Self-Assessment Questions and Exercises
6.13 Further Readings
c
o6.1 Introduction
n
t
eThe Java programming Language evolved from a language named
nOak. Oak was developed in the early nineties at Sun Microsystems
t as a platform-independent language aimed at allowing entertainment
.
appliances such as video game consoles and VCRs to communicate.
A6.2 Objectives
s
i After going through the unit you will be able to;
d
1. To understand the fundamentals of java programming.
e 2. To learn about Constants, variables and various data types.
b 3. To know about Operators and expressions in java
a 4. To discuss about various branching and Looping structure for
r decision making.
i
s
a
Self-Instructional Material
s 46
t
a
n
d
Overview Of Java Language
NOTES
s
t
a
Overview of Java language
NOTES
6.4 Constants, Variables and data types
[
T
y Constants
p
eConstants are identifiers with values that can't be changed. The value
is assigned to a constant when it is declared.
t
Integer Constants - 0 to n
h
Floating point Constants - 3.14
e
Boolean Constants - 0, 1, true, false
Character Constants - characters, alphanumeric, escape
s sequences
i String Constants - “HELLO WORLD”
d
eVariables
b
aVariables are places in the computer's memory where you store the
r data for a program. Each variable is given a unique name which you
refer to it with.
c Declaring variables
o
nYou can declare a variable either inside the class curly brackets or
t inside the main method's curly brackets. You declare a variable by
efirst saying which type it must be and then saying what its name is.
nA variable name can only include any letter of the alphabet, numbers
t and underscores. Spaces are not allowed in variable names. You
usually start a variable name with a lower case letter and every first
.
letter of words that make up the name must be upper case. for
Example,
A
public class VariablesExample{
s public static void main(String[] args)
i {
d int var1;
e }
b}
a
If you want to declare more than one variable of the same type you
r must separate the names with a comma.
NOTES
int var1,var2;
}
} [
T
Scope of variables y
p
Variables can be defined within any block. A block defines a scope.
Each time you start a new block you are creating a new scope. A e
scope ultimately determines what objects visible to other parts of
the program. t
h
Three types of variables in java:- e
1. Instance variables s
2. class (or) static variables
i
3. local variables
d
1.Instance variables:- e
b
Instance and class variables are declared inside a class. They are a
created when the objects are instantiated and therefore they are r
associated with close objects.
c
2. Class (or) static variables:- o
n
Class variables are global to a class and belong to an entire set of
objects that the class creates. Only one location is created for each t
class variable. If an object changes value of a static data member e
then the changed value is available for all other objects of that n
class. t
.
3. Local variables:-
A
Variables declared and used inside methods are called local
variables because they are not available for use outside the method
definition Local variables can also be declared inside program s
blocks. When the program control leaves a block all the variables in i
the block will cease to exist. d
e
Data Types b
a
There are 8 primitive data types. The 8 primitive data types are r
numeric types. The names of the eight primitive data types are
byte,short,int,long,float,double,char and boolean.
i
s
Self-Instructional Material
49 a
s
t
a
Overview of Java language
NOTES
Type Values Size Default
[ Byte signed integers 8 bits 0
T
Short signed integers 16 bits 0
Int signed integers 32 bits 0
y
Long signed integers 64 bits 0l
p
Float IEEE 754 floating 32 bits 0.0f
e point
Double IEEE 754 floating 64 bits 0.0d
t point
h Char Unicode character 16 bits \u0000
eBoolean true,false 1 bit used in 32 bit false
integer
s
i Example
d
public class main1
e
{
b public static void main(String[] args)
a {
r int days = 468;
System.out.println("Days Passed: "+days);
c }
o }
n
t 6.5 Operators and Expressions
e
n
t There are eight types of operators in java. They are Assignment
. operators, Arithmetic operators, Increment / Decrement operators,
Relational operators, Conditional operators, Bitwise operators
,Boolean operators, and Special operators.
A
Assignment Operators
s
i The basic assignment operator = is used to assign a value to a
dvariable or initialize a variable. The following assignment operations
ecan be performed in java.
b
a
r
i
s
a
Self-Instructional Material
s 50
t
a
n
d
Overview Of Java Language
Assignment Operators
x operation= y NOTES
is equivalent to
x = x operation y
Assignment operator. t
x = y; h
y is evaluated and x set to this value. e
The value of x is then returned.
= s
i
Arithmetic operation and then assignment,
d
e.g.
+=, -=, *=, /=, %= x += y; e
is equivalent to b
x = x + y; a
Bitwise operation and then assignment, e.g. r
x &= y;
&=, |=, ^= c
is equivalent to
x = x & y; o
n
Shift operations and then assignment, e.g. t
<<=, >>=, >>>= x <<= n; e
is equivalent to n
x = x << n; t
.
Arithmetic Operators A
i
s
Self-Instructional Material
51 a
s
t
a
Overview of Java language
NOTES
Arithmetic Operators
x[ and y are numeric or char types. If mixed floating-point and integer
types,
T then floating-point arithmetic used and a floating-point value
returned. If mixed integer types, the wider type is returned. If double and
y
float mixed, double is returned.
p
ex+y Addition
x-y Subtraction
tx * y Multiplication
h
x/y Division.
e
Modulo - remainder of x/y returned.
x%y
s
i -x Unary minus
d Negation of x value
e
bExample to add two numbers:
/* program to add two numbers */
a
class addnum{
r
public static void main(String args[]){
c int a =10;
o int b = 20;
n int sum;
t sum = a+b;
e System.out.println(“sum=”sum);
}
n
}
t
Compiling and Executing the above program is :
. C:\java>javac addnum.java
C:\java>java addnum
A sum = 30
i
s
a
Self-Instructional Material
s 52
t
a
n
d
Overview Of Java Language
NOTES
i
s
Self-Instructional Material
53 a
s
t
a
Overview of Java language
NOTES
[
Relational Operators
T
The following Boolean operations can be performed in java.
y Relational Operators
px and y are numeric or char types only except for "==" and "!="
eoperators, which can also compare references. If mixed types, then
the narrower type converted to wider type. Returned value is boolean
t true or false.
h x<y Is x less than y ?
e x <= y Is x less than or equal to y ?
x>y Is x greater than y ?
s x >= y Is x greater than or equal to y ?
i x == y Is x equal to y ?
x != y Is x not equal to y ?
d
e
The example below prints larges of two numbers
b
a /* program to find the largest of two numbers */
r class largest
{
c public static void main(String args[])
o {
n int x1=10;
int x2=20;
t
e if(x1>x2)
n System.out.println(“x1 is larger than x2”);
t Else System.out.println(“x2 is larger than x1”);
. }}
NOTES
Bitwise Operators
[
A bitwise operator allows you to perform bit manipulation on data. T
The following Bitwise operations can be performed in java. y
p
Bitwise Operators
e
x and y are integers. If mixed integer types, such as int and long,
the result will be of the wider type
~x Compliment Flip each bit, ones to zeros, zeros t
to ones h
X&y AND AND each bit a with corresponding e
bit in b
X|y OR OR each bit in a with s
corresponding bit in b i
X^y XOR XOR each bit in x with d
corresponding bit in y
e
X << y Shift left Shift x to the left by y bits. High
order bits lost.Zero bits fill in right b
bits. a
X >> y Shift Right - Shift x to the right by y bits. Low r
Signed order bits lost.
Same bit value as sign (0 for c
positive numbers, 1 for negative) o
fills in the left bits. n
X >>> y Shift Right - Shift x to the right by y bits. Low t
Unsigned order bits lost.
e
Zeros fill in left bits regardless of
sign. n
t
The following example shows subtraction using one’s complement .
operation.
A
class sub
{ s
public static void main(String args[]) i
{
d
int x1=25;
int x2=20; e
int temp,result; b
a
//To find one’s complement r
temp =~x2;
i
//To find two’s complement s
Self-Instructional Material
55 a
s
t
a
Overview of Java language
NOTES
[
temp=temp+1;
result = x1+temp;
T
System.out.println(“x1-x2=”+result);
y Sytem.out.println(“x1=x2=”+result);
p }
e }
t Boolean Operators
h
eThe following Boolean operations can be performed in java.
Boolean Operators
s
x and y are boolean types. x and y can be expressions that result in a
i boolean value . Result is a boolean true or false value.
d X && y (short If both x and y are true, result is true.
e circuit) If either x or y are false, the result is
b Conditional false
a AND If x is false, y is not evaluated.
r X&y Boolean If both x and y are true, the result is
AND true.
If either x or y are false, the result is
c
false
o
Both x and y are evaluated before the
n test.
t X || y (short If either x or y are true, the result is
e circuit) true.
n Conditional If x is true, y is not evaluated.
t OR
. X|y Boolean If either x or y are true, the result is
OR true.
Both x & y are evaluated before the
A
test.
!x Boolean If x is true, the result is false.
s NOT If x is false, the result is true.
i X^y Boolean If x is true and y is false, the result is
d XOR true.
e If x is false and y is true, the result is
b true.
a Otherwise, the result is false.
r Both x and y are evaluated before the
test.
i
Class and Object Operators
s
The following class and object operations can be performed in java.
a
Self-Instructional Material
s 56
t
a
n
d
Overview Of Java Language
NOTES
Operator Precedence c
o
When more than one operator is used in an expression, java has n
established operator precedence to determine the order in which the
t
operators are evaluated. For example, consider the following
e
example, Cal = 10 + 3 * 2 – 12 / 4.In this expression
multiplication and division operation have higher priority than n
addition and multiplication. Hence they are performed first. After t
that the right hand side becomes 10 + 6 – 3 .
s
i
d
e
b
a
r
i
s
Self-Instructional Material
57 a
s
t
a
Overview of Java language
NOTES
[
Operator Associatively
T
The following operators have Right to Left associatively. All other
y operators (see precedence table above) are evaluated left to right.
p
= ?:
e *= new
/= (type cast)
t %= ++x
h += --x
e -= +x
<<= -x
s >>= ~
>>>= !
i
&=
d ^=
e |=
b
a
r Operator Precedence
i
s
a
Self-Instructional Material
s 58
t
a
n
d
Overview Of Java Language
NOTES
For example, it may be required to find the area of the triangle for t
many values of the sides. To perform these tasks, the control h
statements come in handy.
e
Conditional Control (Branching ) Statements
s
The conditional control statement can be broadly classified as i
follows: d
e
i) Conditional Execution b
ii) Selection a
iii) Transfer statements r
iv) Looping
if (condition) { A
statements;
} s
i
General format 2 : d
e
if (condition) {
b
statements;
a
}
else { r
statements;
} i
s
Self-Instructional Material
59 a
s
t
a
Overview of Java language
NOTES
Example:
[
class IfElseDemo {
T
public static void main(String[] args) {
y int testscore = 76;
p char grade;
e if (testscore >= 90) {
grade = 'A';
t } else if (testscore >= 80) {
h grade = 'B';
e } else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
s grade = 'D';
i } else {
d grade = 'F';
e }
b System.out.println("Grade = " + grade);
a }
r }
Nested if statement
A
The conditional if-else statement can be used one within the other
s and these statements are said to be nested. The general form is as
i follows :
d
e if (condition 1){
b if(condition 2)
{
a
Statements
r
}
else
i {
s Statements
}
a }
Self-Instructional Material
s 60
t
a
n
d
Overview Of Java Language
NOTES
else{
if(condition 3)
{ [
Statements T
} y
else{
p
Statements
} e
}
t
Example h
e
if (length < 10)
{ s
System.out.println("Small");
i
}
d
else {
if (length < 20) e
{ b
System.out.println("Medium"); a
} r
else
{ c
System.out.println("Large"); o
}
n
}
t
e
Selection ( Switch statement) n
t
Selection statement allows the user to select a particular group of .
statements from several groups. The switch statement is used for
this purpose. A
s
t
a
Overview of Java language
NOTES
.
[
.
.
T
default:
y code default;
p }
e
The expression to the switch must be of a type byte, short, char, or
t int. Then there is a code block following the switch statement that
hcomprises of multiple case statements and an optional default
estatement.
NOTES
Transfer Statements [
T
Sometimes we use Jumping Statements in Java. Using for, while y
and do-while loops is not always the right idea to use because they
p
are cumbersome to read. Using jumping statements like break and
continue it is easier to jump out of loops to control other areas of e
program flow.
t
break statement h
e
break statement is used to terminate the loop once the condition is
satisfied.. s
i
Syntax: break;
d
Example: e
class BreakDemo b
{ a
public static void main(String[] args) r
{
for (int i = 0; i < 5; i++) { c
System.out.println(i); o
if (i==3) {
n
break ;
} t
} e
} n
} t
.
Output :
BreakDemo A
0
1
2 s
3 i
d
continue statement e
b
Continue statement is just similar to the break statement in the way a
that a break statement is used to pass program control immediately r
after the end of a loop and the continue statement is used to force
program control back to the top of a loop. The continue statement
i
skips the current iteration of a for, while, or do-while loop. Lets see
s
Self-Instructional Material
63 a
s
t
a
Overview of Java language
NOTES
the same example of break statement but here we will use continue
[
instead of break.
T
Syntax : continue;
y
pExample:
e class continueState
{
t public static void main(String[] args)
h {
e for (int i = 0; i < 5; i++) {
System.out.println(i);
if (i==3) {
s continue ; } }} }
i Output :
d 0
e 1
b 2
a 3
r 4
return statements:
c
oIt is a special branching statement that transfers the control to the
ncaller of the method. This statement is used to return a value to the
t caller method and terminates execution of method. This has two
eforms: one that returns a value and the other that cannot return. The
nreturned value type must match the return type of method.
t
. Syntax:
return;
A
return values;
s
i
dExample:
e
b public static void demo()
{
a
System.out.println(“welcome”+welcome());
r
}
static String welcome()
i {
s return “java world”;
}
a
Self-Instructional Material
s 64
t
a
n
d
Overview Of Java Language
NOTES
[
6.7 Looping Statements
T
y
There may be situations in a problem where a single statement or p
group of statements may have to be executed repeatedly, until a e
particular condition is satisfied. The following various looping
statements are available in Java. t
h
i) while statement
e
ii) do – while statement
iii) for statement
s
i
i) while statement d
e
The ‘while’ statement continually executes a block of statements b
when a particular condition is true. Its syntax can be expressed as: a
r
while (conditional expression) {
statement(s)
} c
o
The while statement evaluates expression, which must return a n
boolean value. If the expression evaluates to true, the while t
statement executes the statement(s) in the while block. The while e
statement continues testing the expression and executing its block n
until the expression evaluates to false. t
.
Example : Using the while statement to print the values from 1
through 5 can be accomplished as in the following program:
A
/* To illustrate while statement
class WhileDemocode s
{ i
public static void main(String[] args) d
{ e
int count = 1;
b
while (count < 6) {
a
System.out.println("Count is: " + count);
count++; r
}
} i
} s
Self-Instructional Material
65 a
s
t
a
Overview of Java language
NOTES
[
The output of this program is:
T
Count is : 1
y Count is : 2
p Count is : 3
e Count is : 4
Count is : 5
t
hii) do - while statement
e
The Java programming language also provides a do-while statement,
which can be expressed as follows:
s
i do {
d statement(s)
e } while (conditional expression);
b
aThe difference between do-while and while is that do-while
r evaluates its expression at the bottom of the loop instead of the top.
Therefore, the statements within the do block are always executed at
least once, as shown in the following Program:
c
oExample
n
t class DoWhileDemo
e{
n public static void main(String[] args)
t{
. int count = 1;
do {
System.out.println("Count is: " + count);
A count++;
} while (count <= 6);
s }
i}
dThe output of this program is:
e
b Count is : 1
Count is : 2
a
Count is : 3
r
Count is : 4
Count is : 5
i
s
a
Self-Instructional Material
s 66
t
a
n
d
Overview Of Java Language
NOTES
The for loop is the most versatile loop provided in java language. It [
accepts an initial condition and continues to loop until the condition T
is specified in the loop is met. In for loop, the initial value, y
increment value and the condition are specified in single statement.
p
This reduces ambiguity and increases the readability of the
program. e
s
t
a
Overview of Java language
NOTES
Nested Loops
[
The placing of one loop inside the body of another loop is called
T
nesting. When you "nest" two loops, the outer loop takes control of
y the number of complete repetitions of the inner loop. While all types
pof loops may be nested, the most commonly nested loops are for
eloops.The following are the rules to be followed while implementing
the nested for – loops
t
h i) Each for the loops should have a unique index
e variable and should not coincide with the other index
variables
ii) The loops should not overlap each other.
s iii) The loops should be completely embedded with each
i other.
d
e For example :
b
a System.out.println(“num2 "+” “+ " num1”);
r for(num2 = 0; num2 <= 3; num2++)
{
for(num1 = 0; num1 <= 2; num1++)
c
{
o System.out.println(num2 + " " + num1);
n }
t }
e
nOutput
t
. num2 num1
0 0
0 1
A 0 2
1 0
s 1 1
i 1 2
d 2 0
e 2 1
b 2 2
3 0
a
3 1
r
3 2
i
s
a
Self-Instructional Material
s 68
t
a
n
d
Overview Of Java Language
NOTES
c
Java was started by JAMES GOSLING team at SUN o
MICROSYSTEMS INC. in 1991. The main purpose of java is n
embedded systems like electronic devices like microwave oven, t
remote control system. Java was emerging to play a role in the e
administration of Internet.
n
t
There are eight types of operators in java. They are Assignment
operators, Arithmetic operators, Increment / Decrement operators, .
Relational operators, Conditional operators, Bitwise operators
,Boolean operators, and Special operators. A
Decision making and branching are needed for the user to execute a s
set of statements repeatedly for a specific number of times or till a i
particular condition is satisfied. d
e
6.11 Key Words b
a
r
Constants are identifiers with values that can't be changed.
The value is assigned to a constant when it is declared. i
s
Self-Instructional Material
69 a
s
t
a
Overview of Java language
NOTES
Variables are places in the computer's memory where you
[ store the data for a program. Each variable is given a unique
name which you refer to it with.
T
y
p6.12 Self-Assessment Questions and Exercises
e
t
1. Differentiate between continue and break statements
2. Differentiate between while and for looping statements
h
3. Briefly explain about nested loops and nested if structure.
e
i
s
a
Self-Instructional Material
s 70
t
a
n
d
Class, objects and methods
NOTES
BLOCK 3 [
T
CLASSES, OBJECTS AND METHODS y
p
e
UNIT 7CLASS
t
Structure h
e
7.1 Introduction
7.2 Objectives s
7.3Defining a class and fields / methods i
7.4Creating objects – accessing class members d
7.5 Constructors e
7.6Method overloading
b
7.7Static members
7.8 Nesting of methods a
7.9Inheritance r
7.10overriding methods
7.11 Final variables-classes –methods c
7.12 Check Your Progress Questions o
7.13 Answers to Check Your Progress Questions n
7.14 Summary t
7.15 Key Words
e
7.16 Self-Assessment Questions and Exercises
7.17 Further Readings n
t
.
7.1 Introduction
A
In object oriented programming class, object and methods play vital role.
s
Class defines the structure of an object. Class consist of data member are
membership functions. You can have any number of objects for a i
particular class. Class members can be accessed use class member access d
operator. e
b
a
7.2 Objectives r
i
After going through the unit you will be able to;
s
To understand about class, objects, fields and methods
To know about the inheritance and its types. a
Self-Instructional
s Material
71
t
a
n
d
Classes, Objects and mmethods
NOTES
To discuss about constructors
To learn about method overloading and method overriding
[
To understand the nesting of methods and final
T
y
p7.3Defining a class, fields and methods
e
A class is a collection of data and methods that operate on that data. A class
t
is a template of an object. Class is a keyword.
h
eDefining Class and fields
NOTES
{ return 2 * 3.14159 * r; }
public double area()
[
{ return 3.14159 * r*r; }
} T
y
Defining Methods p
e
Methods can be defined inside a class. The methods contains the
following parts, t
h
• return type
e
• Name of the method
• A list of arguments
• Body of the method s
i
General format: d
e
access returntype methodname1(arguments list); b
a
Where access is access specifier like public,private,default and
r
protected.
Example c
o
void display() n
{ t
System.out.println(“message”); e
} n
t
7.4Creating objects and accessing class members .
A
An Object is an Instance of a Class. Objects are created by generating an
instance of a class or in other words instantiating a class. There can be s
more than one object for a particular class.
i
d
Example :
e
Circle c; b
c = new Circle(); a
r
or
i
Circle c = new Circle(); s
Circle c1 = new Circle();
a
Self-Instructional
s Material
73
t
a
n
d
Classes, Objects and mmethods
NOTES
Now you have created an instance of our Circle class In this new is the java
Operator that creates the object.
[
TAccessing Object Data
y
pNow that we've created an object, you can use its data fields.
eCircle c = new Circle();
c.x = 2.0; // Initialize our circle to have center (2, 2) and radius 1.0.
tc.y = 2.0;
c.r = 1.0;
h
Using Object Methods
eThis is where things get interesting! To access the methods of an object, you
use the same syntax as accessing the data of an object:
sCircle c = new Circle();
i double a;
dc.r = 2.5;
ea = c.area();
bTake a look at that last line. We did not say:
a = area(c);
a
We said:
r
a = c.area();
c
o7.5Constructors
n
t
eConstructor is a special function used to initialize the objects.Every class has
nat least one its own constructor. Constructor creates an instance for the class.
tConstructor initiates (initialize) something related to the class's methods.
.
Constructor is the method which name is same to the class.
Constructors are invoked automatically when an object is created.
A
Constructor methods do not have any return type.
Typically they are used to set initial values to instance variables.
s
i
dExample
e class another
b {
a int x,y;
r another(){ }
int area()
i {
s int ar = x*y;
return(ar); }
}
a public class Construct{
Self-Instructional Material
s
74
t
a
n
d
Class, objects and methods
NOTES
public static void main(String[] args){
another b = new another();
[
b.x = 2;
b.y = 3; T
System.out.println("Area of rectangle : " + b.area()); y
System.out.println("Value of y in another class : " + b.y); p
} e
}
t
Parameterized Constructors: h
e
Similar to the methods Constructors also can have parameters. for
example
s
class another{ i
int x,y; d
another(int a, int b) e
{ b
x = a; y = b; } a
int area(){ r
int ar = x*y; return(ar); }
}
public class Construct c
{ o
public static void main(String[] args) { n
another a = new another(1,1); t
System.out.println("Area of rectangle : " + a.area()); e
System.out.println("Value of x in another class : " + a.x); n
}} t
.
Constructor Overloading
You can have more then one constructor for a particular class. But the A
number or type of arguments has to be different.In this example you will
see that how to implement the constructor feature in a class. This program s
is using two classes. First class is another and second is the main class i
which name is Construct. In the Construct class two objects (a and b) are d
created by using the overloaded another Constructor by passing different e
arguments and calculated. The area of the different rectangles is b
calculated by passing different values to the constructor.
a
Example r
class another i
s
Self-Instructional
s Material
75
t
a
n
d
Classes, Objects and mmethods
NOTES
{
int x,y;
[ another(int a, int b)
T
y {
p x = a;
e
y = b;
}
another()
t
h {
e }
int area()
s {
i int ar = x*y;
d return(ar);
e }
b }
a public class Construct
r {
public static void main(String[] args)
c {
o another b = new another();
n b.x = 2;
t b.y = 3;
e System.out.println("Area of rectangle : " + b.area());
System.out.println("Value of y in another class : " + b.y);
n
another a = new another(1,1);
t System.out.println("Area of rectangle : " + a.area());
. System.out.println("Value of x in another class : " + a.x);
}
A }
s
A Constructor which doesn’t take any arguments is called as default
i constructor. Default constructors are automatically provided by java.
d
e
b7.6Methods overloading
a
r
You can have same name for more than one method. The number of
arguments and / or they type of arguments are to be different for creating
i two or more methods with the same name. The return types of the methods
scan be different as long as the parameter is different
Self-Instructional Material
s
76
t
a
n
d
Class, objects and methods
NOTES
The following example below shows overloading of a method call as add.
The first add() takes integers as arguments and returns the sum of a
[
floating point number. The second add() takes floating point numbers as
parameters and returns the sum as a floating point number. The third T
add() method takes string as arguments, and converts them to integer and y
then returns sum as flowing point number. p
e
// Program to illustrate Overloading
t
class overloadingmethod h
{
e
static float add(int x , int y)
{
return x+y; s
} i
static float add(float t1,float t2) d
{ e
return t1+t2; b
} a
static float add(String s1,String s2)
r
{
float sum;
sum=Integer.parseInt(s1)+Integer.parseInt(s2); c
return sum; o
} n
public static void main(String args[]) t
{ e
int x = 100; int y=200; n
float m =15.5f; t
float n = 10.5f;
.
String s1="125";
String s2="145";
System.out.println(add(x,y)); A
System.out.println(add(m,n));
System.out.println(add(s1,s2)); s
} i
} d
e
Output:
b
a
300.0
26.0 r
270.0
i
s
Self-Instructional
s Material
77
t
a
n
d
Classes, Objects and mmethods
NOTES
7.7Static Methods and Members
[
T
yA static method can be accessed without creating an instance of the class. If
pyou try to use a non-static method and variable defined in this class then the
compiler will say that non-static variable or method cannot be referenced
e
from a static context.
t
hNote :
e
Static method can call only other static methods and static variables defined
sin the class.
i
dThe this keyword can't be used in a static methods.
e
b
Example
a
r public class staticmethodex
{
c int i;
o static int j;
n public static void staticMethod()
t{
e
System.out.println("you can access a static method this way");
}
n
public void nonStaticMethod()
t{
. i=100;
j=1000;
A System.out.println("non static method—cannot be called");
}
s public static void main(String[] args)
i{
//i=10;
d
j=100;
e //non static methods cannot be called without instance
b //nonStaticMethod();
a staticMethod();// called without instance
r }
}
i
s
Self-Instructional Material
s
78
t
a
n
d
Class, objects and methods
NOTES
7.8Nesting of methods
[
T
A method which embeds another method is called nesting of method. For y
example. p
e
void outer_method1()
{
int a,b; t
h
void innermethod_display() e
{
System.out.println(“nested method”) s
} i
}
d
e
b
7.9Inheritance
a
r
Inheritance is the mechanism through which you can derive
classes/subclasses from other classes. This means that an object of a c
subclass can be used wherever an object of the superclass can be used. o
n
The derived class is called as child class or the subclass or you can say t
the extended class and the class from which you are deriving the subclass
e
are called the base class or the parent class. To derive a class in java the
keyword extends is used.. The subclass inherits members of the n
superclass and hence promotes code reuse. The subclass itself can add its t
own new behavior and properties. .
Example:
a
Self-Instructional
s Material
79
t
a
n
d
Classes, Objects and mmethods
NOTES
class superclass{
void addnum(int x, int y)
[ {
T int sum;
y Sum = x+y;
p System.out.pritnln(“sum of numbers =”+sum);
e }
void display(){
t System.out.pritnln(“this is super class display ”);
}
h
}
e
class subclass extends superclass
s {
i public static void main(String args[])
d {
e subclass s1 = new subclass();
b s1.display();
s1.adnum(10,20);
a
}
r
}
cMultilevel Inheritance
o
nIt is the enhancement of the concept of inheritance. When a subclass is
tderived from a derived class then this mechanism is known as the multilevel
einheritance. The derived class is called the subclass or child class for its
nparent class and this parent class works as the child class for it's just above (
parent ) class. Multilevel inheritance can go up to any number of levels. for
t
Example,
.
A class A {
int x;
s int y;
i int get(int p, int q){
d x=p;
y=q;
e
return(0);
b
}
a void Show()
r {
System.out.println(x);
i }
s }
a class B extends A
Self-Instructional Material
s
80
t
a
n
d
Class, objects and methods
NOTES
{ // level one
void Showb(){
[
System.out.println("B");
} T
} y
p
class C extends B e
{ // level two
void display(){ t
System.out.println("C"); h
}
e
public static void main(String args[])
{ s
A a = new A(); i
a.get(5,6); d
a.Show(); e
} b
} a
r
Multiple Inheritances
The mechanism of inheriting the features of more than one base class into c
a single subclass is known as multiple inheritances. Java does not support o
multiple inheritances directly but the multiple inheritances can be n
achieved by using the interface. t
e
In Java Multiple Inheritance can be achieved through use of Interfaces by n
implementing more than one interface in a class. t
.
7.10Method Overriding
A
When a subclass contains a method with the same name and signature as s
in the super class then it is called as method overriding. i
d
Example
e
class superclass{ b
void addnum(int x, int y){ a
int sum; r
sum = x+y;
System.out.println("sum of numbers ="+sum); i
} s
void display(){
System.out.println("super class method is hidden by
subclass"); a
Self-Instructional
s Material
81
t
a
n
d
Classes, Objects and mmethods
NOTES
}
}
[
T class subclass extends superclass{
y void display(){
p //hides super class display method
e System.out.println("sub class method is called");
}
t public static void main(String args[]){
subclass s1 = new subclass();
h
s1.display();
e s1.addnum(10,20);
}
s }
i
dIn this example display() method is defined in both superclass and subclass
ewith same name and type signatures. When display() method is called with
bsubclass object, it hides superclass method and calls subclass method.
a
r
Dynamic Method Dispatch
NOTES
obj.fun1(2); // line 4 (prints "int in subclass")
}
[
}
T
y
p
7.11final Variables,classes and methods e
t
A final variable cannot change its value ( to define identifier as
constant) h
A final class cannot be subclassed (to prevent inheritance) e
A final method cannot be overridden by any subclasses (to
prevent overriding) s
i
Variables are declared as final when their value does not change. d
e
public final PI=3.14; b
a
A final class cannot be sub classed by another class. For example
java.lang.String is final. All methods in a final class are automatically r
final.
c
public final class A {} o
n
then that means that A cannot be further extended or subclassed. t
e
class B extends A {} // will not work n
t
A final method cannot be overridden by subclasses. This is used to
prevent unexpected behavior from a subclass altering a method that may .
be crucial to the function or consistency of the class.
A
publicclass A {
publicfinal void myFinalMethod() { } s
} i
Class B extends A{ d
void myFinalMethod() { } // will not work
e
} b
a
Abstract Classes r
Sometimes you will want to create a super class that only defines the
generalized form that will be shared by all of its sub classes leaving it to i
each sub class to fill in the details. Java Abstract classes are used to s
declare common characteristics of subclasses. Abstract classes are used to
provide a template or design for concrete subclasses down the inheritance
a
Self-Instructional
s Material
83
t
a
n
d
Classes, Objects and mmethods
NOTES
tree. Such objects would be used as abstract because an abstract class is not
fully defined. Abstract classes are declared with the abstract keyword.
[
T An abstract class cannot be instantiated with new operator.
y It can only be used as a superclass for other classes that extend the
p abstract class.
e You cannot declare abstract constructors.
You cannot declare abstract static members.
t
hAny sub class of an abstract class must either implement all of the abstract
emethods in the super class, or be itself declared as abstract.For Example,
NOTES
7.14 Summary [
T
y
Inheritance is the mechanism through which you can derive p
classes/subclasses from other classes. This means that an object of a e
subclass can be used wherever an object of the superclass can be used.
7.15 Key Words t
h
class is a collection of data and methods that operate on that data. e
A
1. R. Krishnamoorthy and S. Prabhu, Internet and Java
Programming, New Age International Publishers, 2004 s
2. Programming with Java, 4e, E. Balagurusamy, Tata McGraw-Hill, i
2010.
d
3. Deitel, Deitel and Nieto, Internet and World Wide Web – How to
program, Pearson Education, 2000. e
4. Naughton and H.Schildt, Java 2 - The complete reference, Tata b
McGraw-Hill, Fourth edition, 2006. a
5. Elliotte Rusty Harold, Java Network Programming, O’Reilly r
Publishers, 2000.
6. B.Mohamal Ibrahim , Java : J2SE – A Practical Approach, i
Firewall media, 2006. s
Self-Instructional
s Material
85
t
a
n
d
Classes, Objects and mmethods
NOTES
7. Cay S. Horstmann, Gary Cornell, Core Java, Volume I and II, 5th
Edition, Pearson Education, 2003.
[ 8. Topley, J2ME in A Nutshell, O’Reilly Publishers, 2002.
T 9. Hunt, Guide to J2EE Enterprise Java, Springer Publications, 2004.
y 10. Ed Roman, Enterprise Java Beans, Wiley Publishers, 1998.
p
e
t
h
e
s
i
d
e
b
a
r
c
o
n
t
e
n
t
.
s
i
d
e
b
a
r
i
s
Self-Instructional Material
s
86
t
a
n
d
Arrays, Strings and Vectors
NOTES
UNIT 8 [
T
ARRAYS, STRINGS AND VECTORS y
p
e
Structure
8.1 Introduction t
8.2 Objectives h
8.3One dimensional arrays e
8.4 Creating of array
8.5Two dimensional arrays s
8.6 Strings i
8.7Vectors
d
8.8Wrapper classes
e
8.9Enumerated Types
8.10Interfaces: Multiple Inheritances b
8.11 Check Your Progress Questions a
8.12 Answers to Check Your Progress Questions r
8.13 Summary
8.14 Key Words c
8.15 Self-Assessment Questions and Exercises o
8.16 Further Readings n
t
8.1 Introduction e
n
t
Variables are used to store one value at a time. When you want to store .
multiple values of same type in a single identifier array is used. Strings
are special form of arrays which contains sequence of characters.
A
Vectors differ considerably from arrays. Arrays are of only one type of
values and the number of elements cannot be changed. Vectors instead s
can hold a mix of class objects (they are, of course, all subclasses of i
Object.) d
e
8.2 Objectives b
a
r
After going through the unit you will be able to;
Know about fundamentals of arrays, strings and vectors
i
Understand about creating and using one dimensional and
multidimensional arrays. s
Perform various string manipulation functions
Know about various wrapper classes a
Self-Instructional
s Material
87 t
a
n
d
Arrays, Strings and Vectors
NOTES
Discuss about creating and using vectors
[
Learn about multiple inheritances
T
y8.1 One dimensional Arrays
p
e
The java array enables the user to store the values of the same type in
contiguous memory allocations. Arrays are always a fixed length
t
abstracted data structure which cannot be altered when required. Arrays
h
can hold data of similar type.
e
To use an array we require the following to be done.
s
i Declare a variable to be used as the array name
d Create an array object and assign to the variable
e
b8.2 Creating One Dimensional Array
a
r
Array variable has a type and a valid Java identifier i.e. the array's type and
cthe array's name. By type we mean the type of elements contained in
oan array. To represent the variable as an Array, we use [] notation. These
ntwo brackets are used to hold the array of a variable.for Example,
t
Examples
e
n int[] array_name; //declares an array of integers
t String[] names;
. int[][] matrix; //this is an array of arrays
The "new" operator is used for the allocation of memory to the array
a
object. The correct way to use the "new" operator is
s
Self-Instructional Material
t
88
a
n
d
a
Arrays, Strings and Vectors
NOTES
String names[];
names = new String[10]; [
T
Here, the new operator is followed by the type of variable and the number
of elements to be allocated. In this example [] operator has been used to y
place the number of elements to be allocated. For Example p
e
public class Sum{
public static void main(String[] args){ t
int[] x = new int [101]; h
for (int i = 0; i<x.length; i++ ) x[i] = i; e
int sum = 0;
for(int i = 0; i<x.length; i++)
s
sum += x[i];
System.out.println(sum); i
} d
} e
b
In this example, a variable 'x' is declared which has a type array of int, a
that is, int[]. The variable x is initialized to reference a newly created r
array object. The expression 'int[] = new int[50]' specifies that the array
should have 50 components. To know the length of the Array, we use
c
field length, as shown.
o
Output for the given program: n
t
C:\java>java Sum e
n
5050 t
.
Instead of assigning memory to the array you can assign values to it
instead. This is called initializing the array because it is giving the array
initial values. A
Self-Instructional
s Material
89 t
a
n
d
Arrays, Strings and Vectors
NOTES
public class Array{
public static void main(String[] args) {
[
int[] a = new int[5];
T a[0] = 10;
y a[1] = 20;
p a[2] = 30;
e a[3] = 40;
a[4] = 50; }}
t
hA much more useful way of using an array is in a loop. Here is an example
of how to use a loop to set all the values of an array to 0 which you will
e
see is much easier than setting all the values to 0 separately.
s public class Array{
i public static void main(String[] args) {
d int[] a = new int[5];
e for (int i = 0; i < 5; i++) a[i] = 0;
b }
a }
r
Sorting an array
cSometimes you will want to sort the elements of an array so that they go
ofrom the lowest value to the highest value or the other way around. Here is
nan example.
t
e public class Array{
n public static void main(String[] args) {
t int[] a = {3, 5, 1, 2, 4};
int i, j, temp;
.
for (i = 4; i >= 0; i--)
for (j = 0; j < i; j++)
A if (a[j] > a[j + 1])
{
s temp = a[j];
i a[j] = a[j + 1];
d a[j + 1] = temp;
e }
b }
}
a
r
Character Arrays:
NOTES
/**
* Converts a String to a character array [
*/
T
public void convertStringToCharArray() {
String str = "Abcdefg"; y
char[] cArray = str.toCharArray(); p
for (char c=0;c<=cArray.length-1;c++) e
System.out.println(cArray[c]);
} t
public static void main(String[] args) { h
new Main1().convertStringToCharArray(); e
}
}
s
i
d
8.3 Two dimensional arrays e
b
a
Two-dimensional arrays are defined as "an array of arrays" which
contains two or more indexes. Since an array type is a first-class Java r
type, we can have an array of integers, an array of Strings, or an array of
Objects. For example, an array of ints will have the type int[]. Similarly c
we can have int[][], which represents an "array of arrays of ints". Such an o
array is said to be a two-dimensional array. n
t
The command e
n
int[][] A = new int[3][4]
t
Declares a variable, A, of type int[][], and it initializes that variable to .
refer to a newly created object.for Example,
A
public class Array{
public static void main(String[] args) { s
int[][] a = new int[3][3]; i
a[0][0] = 1; d
}
e
}
b
Multidimensional arrays a
r
To store data in more dimensions a multi-dimensional array is used. The
Java programming language does not really support multi-dimensional i
arrays. It does, however, support an array of arrays. In Java, a two- s
dimensional array 'x' is an array of one-dimensional array. For instance :-
a
Self-Instructional
s Material
91 t
a
n
d
Arrays, Strings and Vectors
NOTES
int[][] x = new int[3][5];
[
T
y
p8.4 Strings
e
Every string is actually an object of type string. Even string constants are actually
tstring objects.A simple String can be created using a string literal enclosed inside
hdouble quotes as shown;
e
String str1 = “My name is babu”;
sSince a string literal is a reference, it can be manipulated like any other String
i reference. The reference value of a string literal can be assigned to another String
dreference.
e
If two or more Strings have the same set of characters in the same sequence then
b
they share the same reference in memory. Below illustrates this phenomenon.
a
r String str1 = “My name is babu”;
String str2 = “My name is babu”;
c String str3 = “My name ”+ “is babu”; //Compile time expression
String name = "babu";
o String str4 = “My name is” + name;
n String str5 = new String(“My name is babu”);
t
eIn the above code all the String references str1, str2 and str3 denote the same
String object, initialized with the character string: “My name is babu”. But the
n
Strings str4 and str5 denote new String objects.
t
.
8.5Vectors
A
Vectors differ considerably from arrays. Arrays are of only one type and
sthe number of elements cannot be changed. Vectors instead can hold a mix
i of class objects (they are, of course, all subclasses of Object.) The size of a
dvector may increase and / or decreasedepending on the program. Vector is
esynchronized. Constructors for Vector class,
b
aVector(int, int) Constructs an empty vector with the specified storage
rcapacity and the specified capacity Increment.
Vector(int) Constructs an empty vector with the specified storage
capacity.
i
Vector() Constructs an empty vector.
s
List of few methods from Vector class,
a
addElement(Object) Adds the specified object as the last element of the
s
Self-Instructional Material
t
92
a
n
d
a
Arrays, Strings and Vectors
NOTES
vector.
capacity() Returns the current capacity of the vector. [
contains(Object) Returns true if the specified object is a value of the
T
collection.
elementAt(int) Returns the element at the specified index. y
firstElement() Returns the first element of the sequence. p
indexOf(Object) Searches for the specified object, starting from the e
first position and returns an index to it.
lastElement() Returns the last element of the sequence. t
removeAllElements() Removes all elements of the vector. h
removeElementAt(int) Deletes the element at the specified index. e
size() Returns the number of elements in the vector.
toString() Converts the vector to a string.
s
Example : i
d
Vector list = new Vector (); e
list.addElement (" a new string object"); b
list.addElement (" another new string object"); a
list.addElement (new Date ()); r
list.addElement (new Date ());
list.removeElementAt (3);
c
o
Example program : n
t
import java.util.*; e
public class VectorDemo n
{ t
public static void main(String[] args) .
{
Vector vector = new Vector();
A
int primitiveType = 10;
Integer wrapperType = new Integer(20);
String str = "sunil kumar"; s
vector.add(wrapperType); i
vector.add(str); d
vector.add(2, new Integer(30)); e
System.out.println("the elements of vector: " + vector); b
System.out.println("The size of vector are: " + vector.size()); a
System.out.println("The elements at position 2 is: " +
r
vector.elementAt(2));
System.out.println("The first element of vector is: " +
vector.firstElement()); i
System.out.println("The last element of vector is: " + s
vector.lastElement());
vector.removeElementAt(2); a
Enumeration e=vector.elements();
Self-Instructional
s Material
93 t
a
n
d
Arrays, Strings and Vectors
NOTES
System.out.println("The elements of vector: " + vector);
while(e.hasMoreElements()){
[
System.out.println("The elements are: " + e.nextElement());
T } }}
y
pOutput :
e
the elements of vector: [20, sunil kumar, 30]
tThe size of vector are: 3
hThe elements at position 2 is: 30
The first element of vector is: 20
e
The last element of vector is: 30
The elements of vector: [20, sunil kumar]
sThe elements are: 20
i The elements are: sunil kumar
d
e
8.6 Wrapper classes
b
a
r A primitive wrapper class in the Java programming language is one
of eight classes provided in the java.lang package to provide object
cmethods for the eight primitive types. All of the primitive wrapper classes
oin Java are immutable.The primitive wrapper classes and their
ncorresponding primitive types are:
t
Primitive Wrapper
e
type class
n
byte Byte
t short Short
. long Long
float Float
A double Double
char Char
s Boolean Boolean
i
d
For example , Integer class has parseInt() method to parse integer from
e string data type.
b
a Class cmdLine {
r public static void main(String args[])
{
int u, sum = 0;
i
for(i=0;i<args.lenth;i++)
s sum += Integer.parseInt(args[i]);
System.out.println(“sum of numbers =”+sum);
a }
s
Self-Instructional Material
t
94
a
n
d
a
Arrays, Strings and Vectors
NOTES
The output is :
[
C:\java>javac cmdLine.java
T
C:\java>java cmdLine 10 20 30 y
Sum of numbers = 60 p
e
HIGH A
s
8.8 Interfaces: Multiple Inheritances
i
d
The mechanism of inheriting the features of more than one base class into e
a single subclass is known as multiple inheritances. b
a
Java does not support multiple inheritances directly but the multiple r
inheritances can be achieved by using the interface.
i
In Java Multiple Inheritance can be achieved through use of s
Interfaces by implementing more than one interface in a class.
a
8.11 Check Your Progress Questions
Self-Instructional
s Material
95 t
a
n
d
Arrays, Strings and Vectors
NOTES
[
1. Define Array.
T2. Differentiate between array and vector.
y
p
e8.12 Answers to Check Your Progress Questions
t
h1. An Array is an ordered list of elements stored in a single variable with
evariable indexes. The values of the array are of same type.
2. Vectors differ considerably from arrays. Arrays are of only one type and
s
the number of elements cannot be changed. Vectors instead can hold a mix
i of class objects (they are, of course, all subclasses of Object.)
d
e
b8.13 Summary
a
rThe java array enables the user to store the values of the same type in
contiguous memory allocations. Arrays are always a fixed length
cabstracted data structure which cannot be altered when required. Two-
odimensional arrays are defined as "an array of arrays" which contains two
nindexes.
t
eVectors differ considerably from arrays. Arrays are of only one type and
the number of elements cannot be changed. Vectors instead can hold a mix
n
of class objects (they are, of course, all subclasses of Object.)
t
. A primitive wrapper class in the Java programming language is one of
eight classes provided in the java.lang package to provide object methods
Afor the eight primitive types.
s
i
8.14 Key Words
d
eString is actually an object of type string. Even string constants are actually
bstring objects.
a
Array is an ordered list of elements of same type.
r
Vectors can hold a mix of class objects (they are, of course, all subclasses
i of Object.)
s
a
8.15 Self-Assessment Questions and Exercises
s
Self-Instructional Material
t
96
a
n
d
a
Arrays, Strings and Vectors
NOTES
s
i
d
e
b
a
r
i
s
Self-Instructional
s Material
97 t
a
n
d
Packages and Interfaces
NOTES
[ UNIT 9
T
y
PACKAGES AND INTERFACES
p
eStructure
t9.1 Introduction
h9.2 Objectives
e9.3Packages:
9.3.1 Defining a package
9.3.2 Importing packages
s
9.4 Interfaces
i 9.4.1 Defining interface
d 9.4.2 Extending interfaces
e 9.4.3 Implementing Interfaces
b 9.4.4 Putting Classes Together
a9.5 Check Your Progress Questions
r9.6 Answers to Check Your Progress Questions
9.7 Summary
9.8 Key Words
c
9.9 Self-Assessment Questions and Exercises
o
9.10 Further Readings
n
t
e9.1 Introduction
n
t
Java classes and interfaces are wrapped into packages. There are some
. predefined packages such as java.applet, java.awt(abstract windowing
tool kit) and java.io (input and output). The users can also define their
Aown packages with set of its methods and data members. Packages
provide opportunity in combing classes belong particular project or work.
sPackages can also further divided into sub packages.An interface is a
i skeleton of a class showing the methods the class with have when
dsomeone implements. Using the keyword interface you can fully abstract
a class interface from its implementation.
e
b
a
9.2 Objectives
r
After going through the unit you will be able to;
i
s Learn about creating and importing packages
Know about different type of access modifiers
a Understand defining, extending and implementing interfaces
Set the class path to access packages.
s
Self-Instructional Material
t 98
a
n
d
a
Packages and Interfaces
NOTES
[
9.3 Packages
T
y
Packages are a collection of classes and interfaces of similar nature. p
Packages are containers for classes that are used to keep the class e
namespace compartmentalized. For example java.io package contains
classes and interfaces for various kinds of input and output.java programs t
automatically import all classes in the java.lang package. h
e
9.3.1 Defining a package
s
i
To create packages simply include the package keyword as the first
d
command in a java source file. Any classes declared within that file will
e
belong to specified package. The package statement defines a
namespace in which classes are stored. b
a
Note: - r
If you omit the package statement class names are put into default a c
package which has no name. o
n
General format:-
t
package pkgname;
Example:- e
package mypackage; n
t
Java uses file system directories to store packages. .
Example::- A
package pk1[.pk2[.pk3]];
a
Self-Instructional Material
99 s
t
a
n
Packages and Interfaces
NOTES
Example:
[
T package java.awt.image;
y
pThe following Example explains creating and importing package called
eMyPack.
s /* Now, the Balance class, its constructor, and its show() method
i are public. This means that they can be used by non-subclass code
d outsidetheir package.
e */
b
public class Balance
a
{
r
String name;
double bal;
c
o public Balance(String n, double b)
n {
t name=n;
e bal=b;
n }
t
public void show()
. {
if(bal<0)
A System.out.println("------>");
System.out.println(name + ": $" +bal);
s }
i}
d
Now compile that Balance.java file.
e
b
C:\jdk1.3\bin\MyPack>javac Balance.java
a
rWhen you run this file
i C:\jdk1.3\bin>java MyPack.Balance
s
Exception in thread “main” java.lang.NoSuchMethodErro : main will
a
occur.Because there is no main() method inside Balance class. It can be
access by importing the Balance.class from another java file.
s
Self-Instructional Material
t 100
a
n
d
a
Packages and Interfaces
NOTES
import MyPack.*;
c
class TestBalance{
public static void main(String args[]){ o
n
/*Because Balance is public, you may use Balance t
class and call its constructor */ e
n
Balance test = new Balance ("kumar", 99.88); t
.
test.show(); // You may also call show()
}
} A
Note that to execute TestBalance class you must one level up in the a
Self-Instructional Material
101 s
t
a
n
Packages and Interfaces
NOTES
Balance.class or you can set the classpath.
[Setting Class path:
T
yCLASSPATH variable play a significant role in locating classes. If
pclasspath is not set, java will look for the classes in the current directory
eand the default directory that is generally c:\jdk\lib. If the classpath is
specified then java will look only in those directories specified by the
tvariable CLASSPATH. Remember to include current directory and the
default directory also when you are setting classpath.
h
e
Access Modifiers :Access modifiers are used to specify the visibility and
accessibility of a class, member variables and methods. Java provides
ssome access modifiers like: public, private etc.. These can also be used
i with the member variables and methods to specify their accessibility.
d
e public keyword specifies that the public class, the public fields and
b the public methods can be accessed from anywhere.
a
r private:This keyword provides the accessibility only within class
i.e. private fields and methods can be accessed only within the
same class.
c
o protected:This modifier makes a member of the class available to
n all classes in the same package and all sub classes of the class.
t
e
n
default :When you don't
twrite any access modifier
. then default is considered. No
Private Protected Public
It allows the class, fields modifier
Aand methods accessible
within the package only.
sSame class Yes Yes Yes Yes
i Same package subclass No Yes Yes Yes
dSame package non No Yes Yes Yes
e
subclass
Different package
b No No Yes Yes
subclass
a
Different package non
rsubclass No No No Yes
i
9.4 Interfaces
s
NOTES
c
9.4.1 Defining an Interface
o
n
The General form of an interface : t
access interface iname{ e
returntype methodname1(parameter list); n
returntype methodname2(parameter list); t
type final variablenam1 = value; .
type final variablenam2 = value;
//..
A
returntype methodnameN(parameter list);
type final variablenamN = value;
} s
i
Where, access is either public or not used. d
e
Variables can be declared inside of interface declarations but they are b
implicitly final and static, they cannot be changed by the implementing a
class and must be initialized by constant value. All methods and variables
r
are implicitly public if the interface itself is declared as public.
Example i
s
interface ifacename
{ a
Self-Instructional Material
103 s
t
a
n
Packages and Interfaces
NOTES
void display(int param1);
}
[
T
y9.4.2 Extending Interfaces
p
eOne interface can inherit another by used of the keyword extends. The
general format is the same as for inheriting classes. When a class
timplements an interface that inherits another interface, it must provide
himplementations for all methods defined within the interface inheritance
ehierarchy.
sExample:
i
interface parent{
d void method1();
e void method2();
b }
a
r interface child extends parent
{
c void method3();
}
o
n
// this class must implement all of parent and child methods
t
e class Myclass implements child
n {
t public void method1(){
. System.out.println(“implementation of method1”);
}
A public void method2(){
System.out.println(“implementation of method2”);
}
s public void method3(){
i System.out.println(“implementation of method3”);
d }
e }
b
a class Iface
r {
public static void main(String args[])
{
i
Myclass ob= new Myclass();
s ob.method1();
ob.method2();
a ob.method3();
}
s
Self-Instructional Material
t 104
a
n
d
a
Packages and Interfaces
NOTES
}
} [
T
9.4.3 Implementing Interfaces y
p
e
To implement an interface, include the implements keyword in a class
definition and then create the methods defined by the interface. Once an t
interface has been defined, one or more classes can implement that h
interface.
e
The General Format of a class that implement an interface
s
access class classname[extends superclass] [implements interface i
[,interface…]] d
{ e
// class body b
} a
r
Where, access is either public or not used. If a class implements more
than one interface, the interfaces are separated by comma.
c
Example 1: o
n
class myclass implements ifacename t
{ e
// Implement ifacename interface n
public void display (int p) t
{
.
System.out.println(“display is called with “+p);
}
} A
s
Example 2: i
d
class myclass implements ifacename e
{ b
// Implement ifacename interface
a
public void display (int p) r
{
System.out.println(“display is called with “+p); i
} s
void nonIfacemeth() a
Self-Instructional Material
105 s
t
a
n
Packages and Interfaces
NOTES
{
System.out.println(“Class can define its own methodstoo..”)
[}
T
y
pAccessing implementations through interface references
e
You can declare variable as object references that use an interface rather
tthan a class type. Any instance of any class that implements the declared
interface can be stored in such a variable.
h
eThe following example calls the display() method, via an interface
reference variable.
s
i class ireftest
d{
e public static void main(String args[])
b {
ifacename c = new myclass();
a
c.display(100);
r
}
}
c
oVariable in Interfaces
n
tVariables can be declared inside interface but they are final. You can use
einterfaces to import shared constants into multiple classes.
n
Example ;
t
. interface constants
{
A final int OK =1;
final int NOTOK=2;
s final int CANCEL=3;
i }
d
e9.4.4 Putting Classes Together
b
a
rFirst, an interface can only contain abstract methods and/or static final
variables (constants). Classes, on the other hand, can implement methods
and contain variables that are not constants.
i
sSecond, an interface cannot implement any methods. A class that
implements an interface must implement all methods defined in that
ainterface. An interface has the ability to extend from other interfaces, and
(unlike classes) can extend from multiple interfaces. Furthermore, an
s
Self-Instructional Material
t 106
a
n
d
a
Packages and Interfaces
NOTES
c
9.7 Summary o
n
t
Packages are a collection of classes and interfaces of similar nature.
Packages are containers for classes that are used to keep the class e
namespace compartmentalized. Access modifiers are used to specify the n
visibility and accessibility of a class, member variables and methods. Java t
provides some access modifiers like: public, private etc. Interfaces are .
designed to support dynamic method resolution at run time.
A
9.8 Key Words
s
Access Modifiers : Access modifiers are used to specify the visibility and i
accessibility of a class, member variables and methods. Java provides d
some access modifiers like: public, private etc. e
b
public keyword specifies that the public class, the public fields and the
a
public methods can be accessed from anywhere.
r
private: This keyword provides the accessibility only within class i.e.
private fields and methods can be accessed only within the same class. i
s
protected: This modifier makes a member of the class available to all
classes in the same package and all sub classes of the class. a
Self-Instructional Material
107 s
t
a
n
Packages and Interfaces
NOTES
default : When you don't write any access modifier then default is
[considered. It allows the class, fields and methods accessible within the
Tpackage only.
y
pInterfaces are designed to support dynamic method resolution at run
etime.
s
Self-Instructional Material
t 108
a
n
d
a
Multithreaded programming
NOTES
BLOCK 4 [
T
MULTITHREADING, EXCEPTION y
AND APPLETS p
e
UNIT 10 t
h
MULTITHREADED PROGRAMMING e
Structure s
i
10.1 Introduction d
10.2 Objectives e
10.3Creating Threads b
10.4Extending the thread class a
10.5Stopping and Blocking a thread r
10.6Life cycle of a thread
10.7Using thread methods
10.8Thread Exceptions c
10.9Priority o
10.10Synchronization n
10.11Implementing the ‘Runnable’ Interface t
10.12 Check Your Progress Questions e
10.13 Answers to Check Your Progress Questions n
10.14 Summary t
10.15 Key Words
.
10.16Self-Assessment Questions and Exercises
10.17 Further Readings
A
10.1 Introduction s
i
d
A thread is a lightweight process which exists within a program and
executed to perform a special task. Several threads of execution may be e
associated with a single process. Each thread has its own local variables, b
program counter and lifetime. a
r
In single threaded runtime environment, operations are executes
sequentially i.e. next operation can execute only when the previous one is i
complete. Thus a process that has only one thread is referred to as a single- s
threaded process, while a process with multiple threads is referred to as a
multi-threaded process.
a
Self-Instructional Material
109 s
t
a
n
Multithreaded Programming
NOTES
10.2 Objectives
[
T
yAfter going through the unit you will be able to;
p
e Create Threads
Extending the thread class
t Stopping and Blocking a thread
h Understand Life cycle of a thread
e Use thread methods
Know about Thread Exceptions
s Learn about thread Priority
i Discuss about Synchronization
d Learn how to Implement the ‘Runnable’ Interface
e
b10.3 Creating a Thread
a
r
To create a new thread, your program will either extend Thread or
implement the Runnable interface.
c
o
The Main Thread
n
tThe main() method is the first executable method runs in a one thread
ewhen java programs starts. The main thread creates some other threads
ncalled child threads. Often main() must be the last thread to finish
texecution because it performs various shutdown actions. If no other
. threads are created by the main thread, then program terminates when the
main() method complete its execution. Main thread can be controlled
through a Thread object. To do so, you must obtain a reference to it by
A
calling the method currentThread( ), which is a public static member of
Thread.
s
i Its general form is shown here:
d
e static Thread currentThread( )
b
aThis method returns a reference to the thread in which it is called. Once
you have areference to the main thread, you can control it just like any
r
other thread. for Example,
NOTES
NOTES
group. And all thread groups (except the root thread group) belongs to
[exactly one parent thread group.
T
y
Steps for creating Thread by Extending Thread class
p
e 1. Extend the java.lang.Thread Class.
2. Override the run( ) method in the subclass from the Thread class to
t define the code executed by the thread.
h 3. Create an instance of this subclass. This subclass may call a Thread
e class constructor by subclass constructor.
4. Invoke the start( ) method on the instance of the class to make the
s thread eligible for running.
i
Example To create new thread by extending Thread class
d
e class MyThread1 extends Thread
b {
a String s=null;
r MyThread1(String s1){
s=s1;
c start();
o
}
public void run(){
n
System.out.println(s);
t }}
e public class RunThread{
n public static void main(String args[]){
t MyThread1 m1=new MyThread1("Thread started....");
. }
}
A
10.5 Stopping and Blocking a thread
s
i
dThe Thread class has a method suspend( ) to temporarily halt the thread
eand resume( ) that re-starts it at the point it was halted. A program used
b
suspend( ) and resume( ), which are methods defined by Thread, to pause
and restart the execution of a thread. They have the form shown below:
a
r final void suspend( )
final void resume( )
i
sThe Thread class also defines a method called stop( ) that stops a thread.
Its signature is shown here:
a
final void stop( )
s
Self-Instructional Material
t
a 112
n
d
a
Multithreaded programming
NOTES
s
i
d
e
b
a
r
c
o
n
t
Figure 10.1 Life cycle of a thread
e
n
1. New t
.
When you create a new instance of a thread class and before calling
the start() method, the thread state is called new. A
2. Runnable s
i
The thread is in runnable state when the invocation of start()
d
method.
e
3. Non-runnable(blocked) b
a
When the thread is still alive but not under running state the thread r
is called blocked or non-runnable state.
i
4. Terminated s
a
Self-Instructional Material
113 s
t
a
n
Multithreaded Programming
NOTES
When the run method is existed the thread goes to terminate or
[ dead state.
T
y10.7 Using thread methods
p
e
The Thread class defines several methods that help manage threads. The
tones that will be used in this chapter are shown here:
h
e
Method Meaning
getName() Obtain a thread’s name.
getPriority() Obtain a thread’s priority.
s
isAlive() Determine if a thread is still running.
i join() Wait for a thread to terminate.
d run () Entry point for the thread.
e sleep () Suspend a thread for a period of
b time.
a start () Start a thread by calling its run
r method
c
o10.8 Thread Exception
n
t
In Java all uncaught exceptions are handled by code outside of the run()
e
method before the thread terminates. The following example shows how to
nhandle exception in thread.
t
. class MyThreadDemo extends Thread
{
A public void run(){
System.out.println("Throwing in " +"MyThread");
s throw new RuntimeException();
}
i
}
d
public class MainDemo
e{
b public static void main(String[] args)
a{
r MyThreadDemo t = new MyThreadDemo();
t.start();
i try {
s
Thread.sleep(1000);
} catch (Exception x) {
System.out.println("Exception - Caught it" + x);
a }
System.out.println("Exiting main");
s
Self-Instructional Material
t
a 114
n
d
a
Multithreaded programming
NOTES
}
}
[
T
y
10.9Thread Priorities
p
e
In Java, thread scheduler can use the thread priorities in the form of
integer value to each of its thread to determine the execution schedule of t
threads . The thread scheduler provides the CPU time to thread of highest h
priority. Priorities are integer values from 1 (lowest priority given by the e
constant Thread.MIN_PRIORITY) to 10 (highest priority given by the
constant Thread.MAX_PRIORITY). The default priority is 5 s
Thread.NORM_PRIORITY). If two threads of the same priority are
i
waiting for the CPU, the scheduler chooses one of them to run in a round-
robin fashion. d
e
When a Java thread is created, it inherits its priority from the thread that b
created it. At any given time, when multiple threads are ready to be a
executed, the runtime system chooses the runnable thread with the highest r
priority for execution.
c
In Java runtime system, preemptive scheduling algorithm is applied. If at
o
the execution time a thread with a higher priority and all other threads are
n
runnable then the runtime system chooses the new higher priority thread
for execution. On the other hand, if two threads of the same priority are t
waiting to be executed by the CPU then the round-robin algorithm is e
applied in which the scheduler chooses one of them to run according to n
their round of time-slice. t
.
Thread Scheduler
A
In the implementation of threading scheduler usually applies one of the
two following strategies:
s
Preemptive scheduling – If the new thread has a higher priority i
then current running thread leaves the runnable state and higher d
priority thread enter to the runnable state. e
b
Time-Sliced (Round-Robin) Scheduling – A running thread is a
allowed to be execute for the fixed time, after completion the time, r
current thread indicates to the another thread to enter it in the
runnable state.
i
To set a thread’s priority, use the setPriority( ) method, which is a s
member of Thread.
a
Self-Instructional Material
115 s
t
a
n
Multithreaded Programming
NOTES
General format is ,
[
T final void setPriority(int level)
y
Here, level specifies the new priority setting for the calling thread. The
p
value of level must be within the range MIN_PRIORITY and
eMAX_PRIORITY. These priorities are defined as final variables within
Thread.
t
hYou can obtain the current priority setting by calling the getPriority( )
emethod of Thread.
NOTES
NOTES
public void increment( ) {
[ count++;
T }
y
public void decrement( ) {
count--;
p
}
e public int value() {
return count;
t }
h
eWhen the two threads are executed to access these methods (one for
increment( ),another for decrement( )) then both will share the variable
s"count". in that case, you can't be sure that what value will be returned of
variable "count".
i
d
To avoid this problem, Java uses monitor also known as “semaphore” to
eprevent data from being corrupted by multiple threads by a keyword
bsynchronized to synchronize them and intercommunicate to each other. It
ais basically a mechanism which allows two or more threads to share all the
ravailable resources in a sequential manner. Java's synchronized is used to
ensure that only one thread is in a critical region. critical region is a lock
carea where only one thread is run (or lock) at a time. Once the thread is in
o
its critical section, no other thread can enter to that critical region. In that
case, another thread will has to wait until the current thread leaves its
n
critical section.
t
eWhen two or more threads need access to a shared resource, they need
nsome way to ensure that the resource will be used by only one thread at a
ttime. The process by which this is achieved is called synchronization.
.
You can synchronize your code in either of two ways. Both involve the use
Aof thesynchronized keyword, and both are examined here.
1. Synchronized Methods
s
i 2. Synchronized Blocks (Statements)
d
e
bUsing Synchronized Methods
a
rAny method is specified with the keyword synchronized is only executed
by one thread at a time. If any thread wants to execute the synchronized
method, firstly it has to an object’s monitor, just call a method that has
i
been modified with the synchronized keyword. While a thread is inside a
ssynchronized method, all other threads that try to call it on the same
instance have to wait. To exit the monitor and relinquish control of the
aobject to the next waiting thread.
NOTES
class DisplayMessage {
void display(String msg) {
[
System.out.print("[" + msg);
try { T
Thread.sleep(1000); y
} catch(InterruptedException e) p
{ e
System.out.println("Interrupted"); }
System.out.print("]"); } t
} h
class Caller implements Runnable {
e
String msg;
DisplayMessage target;
Thread t; s
public Caller(DisplayMessage targ, String s) { i
target = targ; msg = s; d
t = new Thread(this); t.start(); e
} b
public void run() { a
target.display(msg); } r
}
class Sync {
public static void main(String args[]) { c
DisplayMessage target = new DisplayMessage(); o
Caller ob1 = new Caller(target, "This"); n
Caller ob2 = new Caller(target, "is not"); t
Caller ob3 = new Caller(target, "Synchronized"); e
try { n
ob1.t.join(); t
ob2.t.join();
.
ob3.t.join();
} catch(InterruptedException e) {
System.out.println("Interrupted"); A
}}}
s
Output i
d
[This[is not[Synchronized]]] e
b
To fix the preceding program, you must serialize access to display( ). That
a
is, you must restrict its access to only one thread at a time. To do this, you
simply need to precede display( )’s definition with the keyword r
synchronized, as shown here:
i
class Display Message{ s
synchronized void display(String msg) {
... a
Self-Instructional Material
119 s
t
a
n
Multithreaded Programming
NOTES
This prevents other threads from entering display( ) while another thread is
[using it.
T
y
/* This is Synchronized
class DisplayMessage
p
{
e synchronized void display(String msg)
{
t System.out.print("[" + msg);
h try {
e Thread.sleep(1000);
} catch(InterruptedException e) {
s System.out.println("Interrupted"); }
System.out.print("]"); }
i
}
d class Caller implements Runnable
e {
b String msg;
a DisplayMessage target;
r Thread t;
public Caller(DisplayMessage targ, String s) {
c target = targ;
msg = s;
o
t = new Thread(this);
n
t.start();
t }
e public void run() {
n target.display(msg); }
t }
. class Sync {
public static void main(String args[])
A {
DisplayMessage target = new DisplayMessage();
Caller ob1 = new Caller(target, "This");
s Caller ob2 = new Caller(target, "is");
i Caller ob3 = new Caller(target, "Synchronized");
d try {
e ob1.t.join();
b ob2.t.join();
a ob3.t.join();
r } catch(InterruptedException e)
{ System.out.println("Interrupted");
}}}
i
sAfter synchronized has been added to display(), the output of the program
is as follows:
a
[This][is][Synchronized]
s
Self-Instructional Material
t
a 120
n
d
a
Multithreaded programming
NOTES
NOTES
{
[ target = targ;
T msg = s;
y
t = new Thread(this);
t.start();
p
}
e // synchronize calls to call()
public void run()
t {
h synchronized(target) { // synchronized block
e target.display(msg);
}
s }
}
i
class SynchBlockDemo
d {
e public static void main(String args[])
b {
a Displaymessage target = new Displaymessage();
r Caller ob1 = new Caller(target, "This");
Caller ob2 = new Caller(target, "is");
c Caller ob3 = new Caller(target, "Synchronized");
Caller ob4 = new Caller(target, ”Example”);
o
// wait for threads to end
n
try {
t ob1.t.join();
e ob2.t.join();
n ob3.t.join();
t ob4.t.join();
.
} catch(InterruptedException e)
A {
System.out.println("Interrupted");
}
s }
i }
d
eThe synchronized statement is used inside Caller’s run( ) method.
b
aThe output of the program is as follows:
r
[This][is][Synchronized][Example]
i
Messaging
s
After you divide your program into separate threads, you need to define how they
awill communicate with each other. When programming with most other
languages, you must depend on the operating system to establish communication
between threads. This, of course, adds overhead.
s
Self-Instructional Material
t
a 122
n
d
a
Multithreaded programming
NOTES
By contrast, Java provides a clean, low-cost way for two or more threads to talk to
each other, via calls to predefined methods that all objects have. Java’s messaging [
system allows a thread to enter a synchronized method on an object, and then wait T
there until some other thread explicitly notifies it to come out. y
p
e
Inter-Thread Communication
NOTES
notify();
[ }
}
T
y
p
e class Producer extends Thread {
Shared s;
Producer(Shared s) {
t this.s=s;
h this.start();
e }
public void run() {
int i=0;
s
s.put(++i);
i }
d }
e
b class Consumer extends Thread
{
a Shared s;
r Consumer(Shared s)
{
c this.s=s;
this.start();
o
}
n public void run() {
t s.get();
e }
n }
t public class InterThreadComm
. {
public static void main(String[] args)
A {
Shared s=new Shared();
new Producer(s);
s new Consumer(s);
i }}
d
eOutput:
bProduce : 1
aConsumes :1
r
In this program, two threads "Producer" and "Consumer" share the
i synchronized methods of the class "Shared". At time of program execution, the
"put( )" method is invoked through the "Producer" class which increments the
svariable "num" by 1. After producing 1 by the producer, the method "get( )" is
invoked by through the "Consumer" class which retrieves the produced number
aand returns it to the output. Thus the Consumer can't retrieve the number without
producing of it.
s
Self-Instructional Material
t
a 124
n
d
a
Multithreaded programming
NOTES
wait() method
[
the wait() method causes a thread to release the lock it is holding on an
object; allowing another thread to run T
the wait() method is defined in the Object class y
wait() can only be invoked from within synchronized code p
it should always be wrapped in a try block as it throws IOExceptions e
there are actually three wait() methods
1. wait()
2. wait(long timeout) t
3. wait(long timeout, int nanos) h
the timeout is measured in milliseconds e
nanos is measured in nanoseconds
wait() can only invoked by the thread that own's the lock on the object
when wait() is called, the thread becomes disabled for scheduling and s
lies dormant until one of four things occur: i
d
1. another thread invokes the notify() method for this object and e
the scheduler arbitrarily chooses to run the thread
b
2. another thread invokes the notifyAll() method for this object
3. another thread interrupts this thread a
4. the specified wait() time elapses r
when one of the above occurs, the thread becomes re-available to the
Thread scheduler and competes for a lock on the object c
once it regains the lock on the object, everything resumes as if no
suspension had occurred o
if the thread was interrupted by another thread, an n
InterruptedException is thrown BUT not until after the thread regains t
it's lock on the object e
n
notify() and notifyAll() Methods
t
the notify() and notifyAll() methods are defined in the Object class .
they can only be used within synchronized code
notify() wakes up a single thread which is waiting on the object's lock A
if there is more than one thread waiting, the choice is arbitrary i.e. there
is no way to specify which waiting thread should be re-awakened
s
notifyAll() wakes up ALL waiting threads; the scheduler decides which
one will run i
if there are no waiting threads, the notify’s are forgotten d
only notifications that occur after a thread has moved to wait state will e
effect it; earlier notifies are irrelevant b
a
r
Deadlock
i
A situation where a thread is waiting for an object lock that holds by second s
thread, and this second thread is waiting for an object lock that holds by first
thread, this situation is known as Deadlock.
a
Self-Instructional Material
125 s
t
a
n
Multithreaded Programming
NOTES
Suspending, Resuming, and Stopping Threads
[
TThe Thread class has a method suspend( ) to temporarily halt the thread and
resume( ) that re-starts it at the point it was halted. A program used suspend( )
yand resume( ), which are methods defined by Thread, to pause and restart the
pexecution of a thread. They have the form shown below:
e
final void suspend( )
final void resume( )
t
hThe Thread class also defines a method called stop( ) that stops a thread. Its
esignature is shown here:
i After you create a class that implements Runnable, you will instantiate an
object oftype Thread from within that class. Thread defines several
s
constructors. The one that you will use is shown here:
a Thread(Runnable threadOb, String threadName)
s
Self-Instructional Material
t
a 126
n
d
a
Multithreaded programming
NOTES
NOTES
s10.14 Summary
i
d
eA thread is a lightweight process which exists within a program and
bexecuted to perform a special task. It has four states namely new, runnable,
not-runnable and terminated. Threads can be implemented by extending
a
thread class and implementing runnable interface. Thread has various
r
priorities such as normal, maximum and minimum.
s
10.16 Self-Assessment Questions and Exercises
i
d
e 1) What is multitasking?
b 2) Define thread.
a 3) Write short note on main() thread.
r 4) Explain the ways to create a new thread. Explain.
5) What is multithreading?
6) What are the merits of multithreading?
i 7) Write a java program to illustrate multithreading.
s 8) Write short note on isAlive() and join() methods.
9) What are Thread Priorities? Explain how to assign priorities to threads.
10) Write shot note on thread scheduler.
a
11) Briefly explain how synchronization is achieved in java.
12) Write short note on Messaging.
s
Self-Instructional Material
t
a 128
n
d
a
Multithreaded programming
NOTES
s
i
d
e
b
a
r
i
s
a
Self-Instructional Material
129 s
t
a
n
Managing error, exceptions
and graphics programming
NOTES
[ UNIT 11
T
y MANAGING ERROR, EXCEPTIONS
p AND
e
GRAPHICS PROGRAMMING
t
h
Structure
e 11.1 Introduction
11.2 Objectives
s 11.3 Types of errors
i 11.4 Exceptions
d 11.4.1Syntax of Exception Handling code
e 11.4.2Multiple Catch statements
b 11.4.3Using finally statement
11.4.4Throwing our own Exceptions
a
11.4.5Using exceptions for Debugging
r
11.5Graphics Programming
11.5.1The Graphics Class
c 11.5.2Drawing Lines,Rectangle,Circles,Ellipses,Arcs and
o Polygons
n 11.5.3 Line Graphs
t 11.5.4Using Control Loops in Applets
e 11.5.5Drawing Bar Charts.
n
11.6Check Your Progress Questions
11.7Answers to Check Your Progress Questions
t
11.8Summary
. 11.9Key Words
11.10Self-Assessment Questions and Exercises
A 11.11Further Readings
s
11.1 Introduction
i
d
e Writing an error-free code is a concern of programmers. The presence of
b errors leads to undesirable results. To avoid unwanted termination of
a program execution, exception handling is required to identify and handle
r errors. This unit will discuss about various types of errors and the ways to
handle exceptions.
i 11.2 Objectives
s
Self-Instructional Material
s
t 130
a
n
d
Managing error, exceptions and
graphics programming
NOTES
1. It helps to separate the error handling code from the regular source A
code.
2. It prevents the program from automatically terminating. s
3. The run time system searches backwards through the call stack, i
beginning with the method in which the error occurred, until it finds a d
method that contains an appropriate exception handler. e
b
A Java exception is an object. Exceptions can be generated by the Java
run-time system, or they can be manually generated by your code. They are a
instances of classes that inherit from the class called Throwable. r
i
s
a
Self-Instructional Material
131 s
t
a
n
Managing error, exceptions
and graphics programming
NOTES
Exception Types
[
All exception types are subclasses of the built-in class Throwable. Thus,
T
Throw ableis at the top of the exception class hierarchy. Throwable are
y
two subclasses.
p
e Object
|
t Throwable
h |
e ----------------------------
| |
Error Exception
s
|
i RuntimeException
d |
e ------------------------
b | | | | | |
a
r
One is headed by Exception. This class is used for exceptional conditions
that user programs should catch. This is also the class that you will
c
subclass to create your own custom exception types. There is an important
o subclass of Exception, called RuntimeException. Exceptions of this type
n are automatically defined for the programs that you write and include
t things such as division by zero and invalid array indexing.
e
n The other is Error, which defines exceptions that are not expected to be
t caught under normal circumstances by your program. Exceptions of type
. Error are used by the Java run-time system to indicate errors having to do
with the run-time environment, itself. This unit will dealing with
exceptions of type Exception.
A
RuntimeExceptions are those exceptions that occur with in the java
s runtime system. This includes arithmetic exceptions(such as when dividing
i by zero).Runtime exceptions can occur anywhere in a program and in a
d typical program can be very numerous.
e
b Java exception handling is managed via five keywords: They are try,
a catch, throw, throws, and finally.
r
Program statements that you want to monitor for exceptions are
contained within a try block. If an exception occurs within the try
i block, it is thrown. Your code can catch this exception (using
s catch) and handle it in some rational manner.
Self-Instructional Material
s
t 132
a
n
d
Managing error, exceptions and
graphics programming
NOTES
try
s
{
// block of code to monitor for errors i
} d
catch (ExceptionType1 exOb) { e
// exception handler for ExceptionType1 b
} a
catch (ExceptionType2 exOb) { r
// exception handler for ExceptionType2
}
c
// ...
o
finally
{ n
// block of code to be executed before try block ends t
} e
n
Here, ExceptionType is the type of exception that has occurred. t
.
Using try and catch
A
To guard against and handle a run-time error, simply enclose the code that
youwant to monitor inside a try block. Immediately following the try
block, includes a catch clause that specifies the exception type that you s
wish to catch. i
d
Syntax : e
try{ b
……… a
………
r
}
catch(<exceptionclass1> <obj1>){
……… i
……… s
}
a
Self-Instructional Material
133 s
t
a
n
Managing error, exceptions
and graphics programming
NOTES
For Example,
[
class Excep {
T
public static void main(String args[]) {
y
int d, a;
p try { // monitor a block of code.
e d = 0;
a = 42 / d;
t System.out.println("This will not be printed.");
h }catch (ArithmeticException e) { // catch divide-by-zero
e error
System.out.println("Division by zero.");
}
s
System.out.println("After catch statement.");
i }
d }
e
b
a Output :
r
Division by zero.
After catch statement.
c
o Notice that the call to println( ) inside the try block is never executed.
n Once an exception is thrown, program control transfers out of the try block
t into the catch block. Once the catch statement has executed, program
e control continues with the next line in the program following the entire
n try/catch mechanism.
t
. 11.4.2 Multiple Catch statements
A
There may be situations where more than one exception could be raised by
s a single piece of code. To handle this type of situation, you can specify two
i or more catch clauses, each catching a different type of exception.
d
Syntax
e
try{
b ………
a ………
r }
catch(<exceptionclass_1> <obj1>)
i {
s //statements to handle the exception
}
catch(<exceptionclass_2> <obj2>)
a
Self-Instructional Material
s
t 134
a
n
d
Managing error, exceptions and
graphics programming
NOTES
{
//statements to handle the exception [
} T
catch(<exceptionclass_N> <objN>) y
{
p
//statements to handle the exception
} e
t
For Example, h
e
public class Multi_Catch
{ s
public static void main (String args[]) i
{
d
int array[]={20,10,30};
int num1=15,num2=0; e
int res=0; b
try a
{ r
res = num1/num2;
System.out.println("The result is" +res); c
for(int ct =2;ct >=0; ct--) o
System.out.println("The value of array are" +array[ct]);
n
}catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error…. Array is out of Bounds"); t
}catch (ArithmeticException e) { e
System.out.println ("Can't be divided by Zero"); n
} t
} .
}
A
Output
s
Can't be divided by Zero
i
d
11.4.3 Using finally statement e
b
a
Other than exception handling the finally clause helps you in avoiding any
cleanup code accidentally bypassed by a return etc. For example, if a r
method opens a file upon entry and closes it upon exit, then you will not
want the code that closes the file to be bypassed by the exception-handling i
mechanism. It is always a good practice to use finally clause after the try s
and catch block because the finally block always executes even if an
unexpected exception occurs i.e. whether or not an exception thrown. The a
Self-Instructional Material
135 s
t
a
n
Managing error, exceptions
and graphics programming
NOTES
finally block executes if and only if the try block exits. The statements
[ within the finally block gets executed by the runtime system without taking
care of what happens within the try block.
T
y
Note: The finally block will execute whether or not an exception is
p
thrown.
e The finally clause is optional.
Each try statement requires at least one catch or a finally clause.
t
h Finally block can be useful for closing file handles and freeing up any
e other resources that might have been allocated at the beginning of a
method with the intent of disposing of them before returning.
s
Syntax:
i
d
try{
e ………
b ………
a }
r catch(<exceptionclass1> <obj1>){
………
c ………
o }
finally{
n
………
t ………
e }
n
t The following example, whether the exception is occurred or not always
. the finally statement is executed and its closes the file.
A import java.io.*;
class Test{
public static void main(String args[])throws IOException {
s
FileInputStream fis=null;
i try{
d fis = new FileInputStream (new File (args[0]));
e }
b catch (FileNotFoundException e){
a System.out.println("File not found!");
r }
finally{
fis.close();}
i
}
s }
Self-Instructional Material
s
t 136
a
n
d
Managing error, exceptions and
graphics programming
NOTES
Output: i
s
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo a
Self-Instructional Material
137 s
t
a
n
Managing error, exceptions
and graphics programming
NOTES
[ Using ‘throws’
T
‘throws’ clause is used when a method is capable of causing an exception
y
that it does not handle, it must specify this behavior so that callers of the
p method can guard themselves against that exception. This is the general
e form of a method declaration that includes a throws clause:
inside throwOne
A
caught java.lang.IllegalAccessException: demo
NOTES
Your code can simply throw the custom exception when something s
goes wrong. i
You can wrap an exception that provides extra information by
d
adding your own message.
e
Example b
a
import java.io.*; r
import java.util.*;
class MyException extends Exception{ c
private String nm=""; o
public String getMessage(String s){
n
nm=s;
t
return ("you are not permitted to enter inside "+nm);
} e
} n
public class ExcepDemo { t
public static void main(String args[])throws MyException,IOException .
{
String temp=""; A
try
{
s
String str="kumar";
System.out.println("Enter your name"); i
BufferedReader br=new BufferedReader(new d
InputStreamReader(System.in)); e
temp=br.readLine(); b
if(!temp.equals(str)) a
throw new MyException(); r
else
System.out.println("Welcome to Java world kumar");
i
}
catch(MyException e) s
{
System.err.println(e.getMessage(temp)); a
Self-Instructional Material
139 s
t
a
n
Managing error, exceptions
and graphics programming
NOTES
}
[ catch(Exception e)
{
T
System.err.println(e); }
y
}
p }
e
Output :
t
h Enter your name
e senthil
you are not permitted to enter inside senthil
s
In this example you have created own exception class as MyException
i that throws an exception and a function with argument as getMessage that
d shows an exception message, if the user tries to enter the another name
e which doesn't match with a particular predefined name. After
b throwing exception the control will be transferred in the catch block to
a handle the exception, where the function is invoked to display the message
r included in that function.
NOTES
For example;
c
o
import java.awt.*;
import java.applet.*; n
public class drawShapes extends Applet t
{ e
n
// this is for drawPolygon t
int xs[] = {40,49,60,70,57,40,35}; .
int ys[] = {260,310,315,280,260,270,265};
A
// this is for fillPolygon
int xss[] = {400,150,180,200,170,150,140};
int yss[] = {260,310,315,280,260,270,265}; s
i
public void paint(Graphics g) d
{ e
g.drawString("Some of the drawing objects", 40,20); b
g.drawLine(40,30,200,30); a
g.drawRect(40,60,70,40);
r
g.fillRect(140,60,70,40);
g.fillRoundRect(240,60,70,40,10,20);
g.fillRoundRect(40,120,70,40,10,20); i
g.drawOval(240,120,70,40); s
g.fillOval(40,180,70,40);
g.drawArc(140,180,70,40,0,180); a
Self-Instructional Material
141 s
t
a
n
Managing error, exceptions
and graphics programming
NOTES
g.fillArc(240,180,70,40,0,-180);
[ g.drawPolygon(xs,ys,7);
g.fillPolygon(xss,yss,7);
T
}
y
}
p
e
Output
t
h
e
s
i
d
e
b
a
r
c
o
n
t
e
11.5.3 Line Graphs
n
t
. Line graph is a graphic which has a series of points connected based on
origin and (x,y) coordinates.One axis of the chart plots categories and the
A other axis represents the value scale. It is used to visualize the value with
time or other variables. Java.awt. packages provides methods to support
s drawing line graphs.
i
d 11.5.4 Using Control Loops in Applets
e
b
a Control loops such as for,while and do-while are statements which are used
r to control the statements in applets. For example the following program
illustrate the use of for loop to display welcome applet four times.
i
import java.awt.*;
s
import java.applet.*;
/* <applet code="TestApplet" width=200 height=60>
a </applet> */
Self-Instructional Material
s
t 142
a
n
d
Managing error, exceptions and
graphics programming
NOTES
t
11.5.5 Drawing Bar Charts. h
e
A bar chart represents quantitative information. The chart consists of
horizontal bars of equal width with lengths proportional to the values they s
represent, something that aids in instant comparison of data. One axis of i
the chart plots categories and the other axis represents the value scale. For d
example. e
b
import java.applet.*; a
import java.awt.*; r
/*
<applet code="Bargraph.class" width =500 height =400> c
<param name="time1" value ="2"> o
<param name="time2" value ="3"> n
<param name="time3" value ="4"> t
<param name="time4" value ="5"> e
<param name="time5" value ="6"> n
<param name="temperature1" value ="35"> t
<param name="temperature2" value ="36">
.
<param name="temperature3" value ="40">
<param name="temperature4" value ="39">
<param name="temperature5" value ="38"> A
</applet>
/* s
i
public class Bargraph extends Applet d
{ e
int n; b
String ttime[];
a
int value[];
r
ttime[0] = getParameter("time1");
ttime[1] = getParameter("time2"); i
ttime[2] = getParameter("time3"); s
ttime[3] = getParameter("time4");
ttime[4] = getParameter("time5"); a
Self-Instructional Material
143 s
t
a
n
Managing error, exceptions
and graphics programming
NOTES
[ value[0]= Integer.parseInt(getParameer("temperature1"));
value[1]= Integer.parseInt(getParameer("temperature2"));
T
value[2]= Integer.parseInt(getParameer("temperature3"));
y
value[3]= Integer.parseInt(getParameer("temperature4"));
p value[4]= Integer.parseInt(getParameer("temperature5"));
e}
s
i 1) What is an Exception?
d 2) List predefined exceptions.
e
b
a 11.7 Answers to Check Your Progress Questions
r
1. An exception is an event, which occurs during the execution of a
i program that disrupts the normal flow of the program's instructions.
s
2. Arithmetic Exception, IndexOutofBoundsException and
a IllegalAccessException
Self-Instructional Material
s
t 144
a
n
d
Managing error, exceptions and
graphics programming
NOTES
11.8 Summary [
T
Errors are generally classified into compile time error and run-time errors. y
An exception is an event, which occurs during the execution of a program p
that disrupts the normal flow of the program's instructions. e
When an error occurs within a method, the method creates an object and t
hands it off to the runtime system. h
e
11.9 Key Words
s
i
Throws – This is used when a method is capable of causing an d
exception that it does not handle, it must specify this behavior so e
that callers of the method can guard themselves against that
b
exception.
a
finally - This block can be useful for closing file handles and r
freeing up any other resources that might have been allocated at the
beginning of a method with the intent of disposing of them before c
returning. o
n
t
11.10 Self-Assessment Questions and Exercises
e
n
1) What are the advantages of handling exception? t
2) What are the types of exceptions? .
3) Write a simple program to illustrate exception handling in java using try
and catch.
4) What is the use of finally clause? Give examples A
5) Write short note on uncaught exceptions
6) Briefly explain about nested try statements. s
7) What is the use of throw keyword? Explain with suitable example. i
8) What is the use of throws keyword? Explain with suitable example.
d
9) Distinguish between throw and throws keyword.
e
b
11.11 Further Readings a
r
NOTES
3. Deitel, Deitel and Nieto, Internet and World Wide Web – How to
[ program, Pearson Education, 2000.
4. Naughton and H.Schildt, Java 2 - The complete reference, Tata
T
McGraw-Hill, Fourth edition, 2006.
y
5. Elliotte Rusty Harold, Java Network Programming, O’Reilly
p Publishers, 2000.
e 6. B.Mohamal Ibrahim , Java : J2SE – A Practical Approach, Firewall
media, 2006.
t 7. Cay S. Horstmann, Gary Cornell, Core Java, Volume I and II, 5th
h Edition, Pearson Education, 2003.
e 8. Topley, J2ME in A Nutshell, O’Reilly Publishers, 2002.
9. Hunt, Guide to J2EE Enterprise Java, Springer Publications, 2004.
10. Ed Roman, Enterprise Java Beans, Wiley Publishers, 1998
s
i
d
e
b
a
r
c
o
n
t
e
n
t
.
s
i
d
e
b
a
r
i
s
Self-Instructional Material
s
t 146
a
n
d
Applet Programming
NOTES
[
UNIT 12 T
APPLET PROGRAMMING y
p
e
Structure
t
12.1 Introduction
h
12.2 Objectives
12.3How applets differ from Applications e
12.4Preparing to write applets
12.5 Building Applet Code s
12.6Applet life cycle i
12.7 Creating an Executable Applet d
12.8Designing a Web Page e
12.9Running the Applet b
12.10 Passing parameters to Applets
a
12.11Displaying Numerical values
12.12 Getting input from the user r
12.13 Check Your Progress Questions
12.14 Answers to Check Your Progress Questions c
12.15 Summary o
12.16 Key Words n
12.17 Self-Assessment Questions and Exercises t
12.18 Further Readings e
n
12.1 Introduction t
.
NOTES
Know the life cycle of an applet
[ Design a web page to invoke applets
T
Learn the ways of executing applets
y 12.3 How applets differ from Applications
p
e
Two types of Programs you can do with java. They are application
t programs and Applet programs. All of the preceding examples in this book
have been Java applications... Another type of program is the applet.
h
Applets are applications that are accessed on an Internet server. An applet
e is a java program that can be embedded in a web page. Applets are run on
any browser that supports java.
s
i Java Applets has certain limitations,
d
e They cannot load or run any program stores on the user’s system.
b They cannot read or write files on the user’s system
a
r 12.4 Preparing to write applets
c
o An applet displays information on the screen by using paint () method.
n This method is from java.awt.Component class. This method takes an
t instance of the Graphics class. Graphics class provides various methods to
display information.
e
n
t NOTE
. 1. All applets are subclasses of the Applet class in the
java.applet.package.
A 2. All applets must be declared public.
3. Applets do not begin execution at main ( ).
s 4. Applets do not have main() method
5. User I/O is not accomplished with Java’s stream I/O classes.
i
Instead, Applets use the interface provided by the AWT.
d
e
b
a
r
12.5 Building an Applet code
NOTES
After you enter the source code for TestApplet, compile in the same way A
thatyou have been compiling programs. However, running TestApplet
involves adifferent process.
s
i
12.6 Applet Life Cycle d
e
b
In java, java.applet.Applet class has four methods defines the lifecycle of
a
the servlets, They are,
r
public void init();
public void start(); i
public void stop(); s
public void destroy();
a
Self-Instructional Material
149
s
t
a
n
Applet Programming
NOTES
The init() method is called exactly once in an applet's life, when the applet
is first loaded. It's normally used to read PARAM tags, start downloading
[
any other images or media files you need, and set up the user interface.
T
y The start() method is called at least once in an applet's life, when the
p applet is started or restarted. A start() method is often used to start any
e threads the applet will need while it runs.
t The stop() method is called at least once in an applet's life, when the
h browser leaves the page in which the applet is embedded. The applet's
e
start() method will be called if at some later point the browser returns to
the page containing the applet. In some cases the stop() method may be
called multiple times in an applet's life.. Your applet should use the stop()
s method to pause any running threads.
i
d The destroy() method is called exactly once in an applet's life, just before
e the browser unloads the applet. This method is generally used to perform
b any final clean up. For example, an applet that stores state on the server
a might send some data back to the server before it's terminated.
r
12.7 Creating executable Applet
c
o
n To create an executable applet, compile the applet .java extension file
t using javac.exe file. For ex: javac myapplet.java. The result of compilation
e generates myapplet.class file.
n
t 12.8 Designing a Web Page HTML file
.
In fact, there are two ways in which you can run an applet:
A
■ Executing the applet within a Java-compatible Web browser using
HTML file.
s
■ Using an applet viewer, such as the standard SDK tool, appletviewer.
i
d Using web browser to view Applet
e
b Applet Tag
a
r In order to view the applet in a Web browser, you need to write a short
HTML text file. This code contains the APPLET tag. For example,
i
TestApplet :
s
<html>
a <applet code="TestApplet" width=200 height=60>
Self-Instructional Material
s
150
t
a
n
d
Applet Programming
NOTES
</applet>
</html> [
T
The width and height statements specify the dimensions of the display y
area usedby the applet. After you create this file, you can execute your
p
browser and then load this file, which causes TestApplet to be executed.
e
To execute TestApplet with an applet viewer, you may also execute the s
HTMLFor example, if the preceding HTML file is called RunApp.html, i
then the following command line will run TestApplet: d
e
C:\>appletviewer RunApp.html b
a
However, a more convenient method exists that you can use to speed up r
testing.
c
Note :
o
You can also include a comment at the head of your Java source code file n
that contains theAPPLET tag. If you use this method, the TestApplet t
source file looks like this: e
n
import java.awt.*; t
import java.applet.*; .
/* <applet code="TestApplet" width=200 height=60>
</applet> */ A
public class TestApplet extends Applet
{ s
public void paint(Graphics g) i
{ d
g.drawString("Welcome to Applet", 20, 20); e
b
}
a
}
r
Now, Execute the applet viewer, specifying the name of your applet’s
source file. Theapplet viewer will encounter the APPLET tag within the i
comment and executeyour applet. s
a
Self-Instructional Material
151
s
t
a
n
Applet Programming
NOTES
Output :
[
T
y
p
e
t
h
e
s
i
d
e
12.10Passing Parameters to Applets
b
a
r Parameters are passed to applets in <PARAM> tags between the opening
and closing APPLET tags. Inside the applet, you read the values passed
c through the PARAM tags with the getParameter() method of the
o java.applet.Applet class. For example
n
t import java.applet.*;
import java.awt.*;
e
public class ParameterEx extends Applet {
n
private String strDefault = "Myfirst Java Applet.";
t public void paint(Graphics g) {
. String str = this.getParameter("Message");
if (str == null) str = strDefault;
A g.drawString(str, 50, 25); }
}
s
i HTML CODE :
d
<HTML>
e <TITLE>Passing Parameter in Java Applet</TITLE>
b <BODY>
a This is the My applet:<P>
r <APPLET code="ParameterEx.class" width="500" height="200">
<PARAM name="message" value="Passing parameter example.">
i </APPLET>
s </BODY>
</HTML>
a
Self-Instructional Material
s
152
t
a
n
d
Applet Programming
NOTES
NOTES
}
public void paint(Graphics g)
[
{
T int a=0,b=0,c=0;
y String str1,str2,str;
p g.drawString("Enter the number in each box",10,50);
e try
{
t str1=t1.getText();
h a=Integer.parseInt(str1);
str2=t2.getText();
e
b=Integer.parseInt(str2);
}
s catch(Exception e){ }
i c=a+b;
d str=String.valueOf(c);
e g.drawString(“a =”,10,15);
b g.drawString(a,20,75);
a g.drawString(“b =”,30,15);
r
g.drawString(b,40,75);
g.drawString("Sum is",50,15);
g.drawString(str,100,75);
c }
o}
n
t HTML CODE TO RUN APPLET
e
n <HTML>
t <HEAD>
<TITLE>Getting Input from the User</TITLE>
.
</HEAD>
<BODY>
A <APPLET Code="GettingInputfromtheUserEx.class" Width=400
Height=300>
s </APPLET>
i </BODY>
d </HTML>
e
b 12.13 Check Your Progress Questions
a
r
1 What is an applet?
i 2 What does the <applet> tag specify?
s
Self-Instructional Material
s
154
t
a
n
d
Applet Programming
NOTES
i
s
a
Self-Instructional Material
155
s
t
a
n
Applet Programming
NOTES
12.17 Self-Assessment Questions and Exercises
[
T
y 1) Define Applet.
p 2) What are the limitations of Applet?
3) Write a simple program to illustrate Applet program.
e 4) How to define and invoke applets? Explain.
5) Discuss the life cycle of an Applet.
t 6) Briefly explain how parameters are passed to applet.
h
e 12.18Further Readings
s 1. R. Krishnamoorthy and S. Prabhu, Internet and Java Programming,
i New Age International Publishers, 2004
d 2. Programming with Java, 4e, E. Balagurusamy, Tata McGraw-Hill,
e 2010.
b 3. Deitel, Deitel and Nieto, Internet and World Wide Web – How to
program, Pearson Education, 2000.
a
4. Naughton and H.Schildt, Java 2 - The complete reference, Tata
r McGraw-Hill, Fourth edition, 2006.
5. Elliotte Rusty Harold, Java Network Programming, O’Reilly
c Publishers, 2000.
o 6. B.Mohamal Ibrahim , Java : J2SE – A Practical Approach, Firewall
n media, 2006.
t 7. Cay S. Horstmann, Gary Cornell, Core Java, Volume I and II, 5th
e Edition, Pearson Education, 2003.
8. Topley, J2ME in A Nutshell, O’Reilly Publishers, 2002.
n
9. Hunt, Guide to J2EE Enterprise Java, Springer Publications, 2004.
t
10. Ed Roman, Enterprise Java Beans, Wiley Publishers, 1998
.
s
i
d
e
b
a
r
i
s
Self-Instructional Material
s
156
t
a
n
d
Introduction to Input / Output
NOTES
BLOCK 5 [
T
MANAGING INPUT/OUTPUT FILES y
IN JAVA p
e
UNIT 13 t
h
INTRODUCTION TO INPUT / OUTPUT e
s
Structure
i
13.1 Introduction d
13.2 Objectives e
13.3Stream & Stream classes b
13.3.1Byte stream classes a
13.3.2Character Stream r
13.4Check Your Progress Questions
13.5Answers to Check Your Progress Questions c
13.6Summary
o
13.7Key Words
n
13.8Self-Assessment Questions and Exercises
13.9 Further Readings t
e
n
13.1 Introduction t
.
The Java Input/Output (I/O) is a part of java.io package. The java.io
package contains a relatively large number of classes that support input A
and output operations. Java does provide strong, flexible support for I/O as
it relates to files and networks. s
i
The classes in the java.io package are primarily abstract classes and d
stream-oriented that define methods and subclasses which allow bytes to e
be read from and written to files or other input and output sources. All data
b
in java is written and read using streams.
a
r
13.2 Objectives
i
s
After going through the unit you will be able to;
s
Self-Instructional Material
157 t
a
n
d
Introduction to Input / Output
NOTES
Learn about various stream classes
[
Write program using Byte stream classes
Able to understand about character stream classes
T
y
p
13.3Stream &Stream classes
e
tStream
h
eJava programs perform I/O through streams. A stream is an abstraction that
either produces or consumes information. A stream is a path traveled by
sdata in a program A stream is linked to a physical device by the Java I/O
system. An input stream can abstract many different kinds of input: from a
i
disk file, a keyboard, or a network socket. Likewise, an output stream may
drefer to the console, a disk file, or a network connection. Java implements
estreams within class hierarchies defined in the java.io package.
b
aStream Classes
r
Java defines two types of streams:
c
o Byte streams
Character streams.
n
t
Stream
e classes
n
t
Character
. Byte Stream
stream
Classes
classes
A
Input Output
Reader Writer
s stream stream
Classes Classes
classes classes
i
d 13.1 Classification of stream classes
e
bByte streams provide a convenient means for handling input and output of
abytes. Byte streams are used, for example, when reading or writing binary
rdata.Character streams provide a convenient means for handling input and
output of characters.
i
These streams are declared in the java.lang.System class and they are all
sbyte streams. For example, using some of its methods, you can obtain the
current time and the settings of various properties associated with the
asystem. Systems also contain three predefined stream variables in, out,
and err. These fields are declared as public and static within System.
s
Self-Instructional Material
t 158
a
n
d
a
Introduction to Input / Output
This means that they can be used by any other part of your program and NOTES
without reference to a specific System object. [
T
System.out refers to the standard output stream. By default, this is y
the console.
p
System.in refers to standard input, which is the keyboard by
e
default.
System.err refers to the standard error stream, which also is the
console by default. t
h
Note: System.in is an object of type InputStream. e
System.out and System.err are objects of type PrintStream.
s
i
For example Accepting input through keyboard Using standard Streams :
d
e
import java.io.*;
class stdin{ b
Public static void main(String args[]){ a
byte name = new byte[10]; r
System.out.println(“What is your name?”);
try{ c
System.in.read(name); o
System.out.write(“Hello “+name); n
}catch(IOException e){
t
System.out.println(“Error”);} }
} e
n
t
.
13.3.1 Byte stream classes
A
To use the stream classes, you must import java.io.Byte streams are
defined by using two class hierarchies. At the top are two abstract classes: s
InputStream and OutputStream. Each of these abstract classes has i
several concrete subclasses. d
e
The abstract classes InputStream and OutputStream define several key b
methods that the other stream classes implement. Two of the most a
important are read( ) and write( ), which, respectively, read and write
r
bytes of data.
Input Steam i
s
The InputStream class is used for reading the data such as a byte and
array of bytes from an input source. An input source can be a file, a string, a
or memory that may contain the data
s
Self-Instructional Material
159 t
a
n
d
Introduction to Input / Output
NOTES
An input stream is automatically opened when you create it. You cans
[
explicitly close a stream with the close( ) method, or let it be closed
Timplicitly when the object is found as a garbage.
y
pOutputStream
e
The OutputStream class is a sibling to InputStream that is used for
twriting byte and array of bytes to an output source. Similar to input
hsources, an output source can be anything such as a file, a string, or
memory containing the data.
e
You can explicitly close an output stream with the close( ) method, or let it
sbe closed implicitly when the object is garbage collected. The following
i listings of classes are provided by the java.io package for byte stream
dclasses shown in the table 13.1:
e
b Table 13.1 Byte stream classes
aClass Description
r BufferedInputStream contains methods to read bytes from the buffer
(memory area)
ByteArrayInputStream contains methods to read bytes from a byte
c
array
oDataInputStream contains methods to read Java primitive data
n types
tFileInputStream contains methods to read bytes from a file
eFilterInputStream contains methods to read bytes from other input
n streams which it uses as its basic source of data
tObjectInputStream contains methods to read objects
. PipedInputStream contains methods to read from a piped output
stream. A piped input stream must be connected
to a piped output stream
A
SequenceInputStream contains methods to concatenate multiple input
streams and then read from the combined
s stream
i
d
e13.3.2 Character Stream classes
b
a
Reader and Writer are the abstract super classes for character stream sin
rjava.io package. The abstract classes Reader and Writer define several
key methods that the other stream classes implement. Two of the most
i important methods are read( ) and write( ), which read and write
scharacters of data, respectively. The following listings of classes are
provided by the java.io package for character stream classes shown in the
atable 13.2:
s
Self-Instructional Material
t 160
a
n
d
a
Introduction to Input / Output
// Example PrintWriter i
s
import java.io.*;
s
Self-Instructional Material
161 t
a
n
d
Introduction to Input / Output
NOTES
{
public static void main(String args[])
[
{
T PrintWriter pw = new PrintWriter(System.out, true);
y pw.println("Hello Java world");
p int i = 1000;
e pw.println(i);
double d = 45.0;
t pw.println(d);
h }
}
e
Output:
s Hello Java world
i 1000
d 45.0
e
bCharacter Streams for Files
a
Character streams are used to work with any text using files The
r
FileReader and FileWriter classes are used for the text manipulation.
cFileReader class
o
nThe FileReader class creates a Reader that you can use to read the
tcontents of a file. Its two most commonly used constructors are shown
ehere:
n
t FileReader(String filePath)
FileReader(File fileObj)
.
Either can throw a FileNotFoundException. Here, filePath is the full path
Aname of a file, and fileObj is a File object that describes the file.
sThe following example shows how to read lines from a file and print these
i to the standard output stream. It reads its own source file, which must be in
dthe current directory.
e
b
// Example FileReader.
a
r import java.io.*;
i class FileReaderDemoPro
s {
public static void main(String args[]) throws Exception
a {
FileReader fr = new FileReader("HELLO.java");
BufferedReader br = new BufferedReader(fr);
s
Self-Instructional Material
t 162
a
n
d
a
Introduction to Input / Output
FileWriter class t
h
FileWriter creates a Writer that you can use to write to a file. Its most e
commonly used constructors are shown here:
s
FileWriter(String filePath)
i
FileWriter(String filePath, boolean append)
d
FileWriter(File fileObj)
e
They can throw an IOException or a SecurityException. Here, filePath is b
the full path name of a file, and fileObj is a File object that describes the a
file. If append is true, then output is appended to the end of the file. r
s
Self-Instructional Material
163 t
a
n
d
Introduction to Input / Output
NOTES
13.4 Check Your Progress Questions
[
T
y 1. What are the types of character classes?
p 2. Name the two class hierarchies of byte streams.
e
13.5 Answers to Check Your Progress Questions
t
h
e 1. Reader and Writer are the abstract super classes for character
stream sin java.io package.
s 2. Byte streams are defined by using two class hierarchies. At the top
i are two abstract classes: InputStream and OutputStream.
d
e13.6 Summary
b
a
rA stream is a path traveled by data in a program A stream is linked to a
physical device by the Java I/O system.Java defines two types of streams
cnamely Byte streams and Character streams.
o
n13.7 Key Words
t
e
n Stream A stream is an abstraction that either produces or consumes
t information.
. System.out refers to the standard output stream. By default, this is
the console.
A System.in refers to standard input, which is the keyboard by
default.
System.err refers to the standard error stream, which also is the
s
console by default.
i
d
e13.8 Self-Assessment Questions and Exercises
b
a
r 1) What are streams?
2) What are predefined streams supported in java?
3) What are character streams? Explain about various character stream
i
classes.
s 4) What are Byte streams? Explain about byte stream classes with
examples.
a
s
Self-Instructional Material
t 164
a
n
d
a
Introduction to Input / Output
NOTES
[
13.9 Further Readings
T
y
1. R. Krishnamoorthy and S. Prabhu, Internet and Java Programming, p
New Age International Publishers, 2004 e
2. Programming with Java, 4e, E. Balagurusamy, Tata McGraw-Hill,
2010. t
3. Deitel, Deitel and Nieto, Internet and World Wide Web – How to h
program, Pearson Education, 2000. e
4. Naughton and H.Schildt, Java 2 - The complete reference, Tata
McGraw-Hill, Fourth edition, 2006.
s
5. Elliotte Rusty Harold, Java Network Programming, O’Reilly
Publishers, 2000. i
6. B.Mohamal Ibrahim , Java : J2SE – A Practical Approach, Firewall d
media, 2006. e
7. Cay S. Horstmann, Gary Cornell, Core Java, Volume I and II, 5th b
Edition, Pearson Education, 2003. a
8. Topley, J2ME in A Nutshell, O’Reilly Publishers, 2002. r
9. Hunt, Guide to J2EE Enterprise Java, Springer Publications, 2004.
10. Ed Roman, Enterprise Java Beans, Wiley Publishers, 1998.
c
o
n
t
e
n
t
.
s
i
d
e
b
a
r
i
s
s
Self-Instructional Material
165 t
a
n
d
Input / Output classes
NOTES
[ UNIT 14
T
y
INPUT / OUTPUT (I/O) CLASSES
p
e Structure
14.1 Introduction
t 14.2 Objectives
h 14.3Using stream
e 14.4 Using the file class
14.5Input / Output Exceptions
s
14.6 Creation of files
14.7Reading / writing characters
i
14.8Reading / writing bytes
d 14.9Random access files
e 14.10 Interactive input and output
b 14.11Check Your Progress Questions
a 14.12Answers to Check Your Progress Questions
r 14.13Summary
14.14Key Words
c 14.15Self-Assessment Questions and Exercises
14.16Further Readings
o
n
t 14.1 Introduction
e
n
t Most of the real-life applications require a large amount of input and
. output data, which is difficult to manage using the commonly used console
Input/Output (I/O) devices like keyboard and screen. Java supports input
and output of data through the classes included in the java.io package. This
A unit will take you through the various aspects of input/output handling in
Java.
s
i
d
14.2 Objectives
e
b
After going through the unit you will be able to;
a
r Know using stream &the file class
Learn about various Input / output Exceptions
i Understand how to create files
s Write programs for Reading / writing characters
Write programs for Reading writing bytes
a Understand about Random access files
Learn about Interactive input and output
s
Self-Instructional Material
t
166
a
n
d
a
Input / Output Classes
NOTES
[
14.3 Using Stream T
y
A stream is an abstraction that either produces or consumes information. p
The following listings of classes are provided by the java.io package e
tabulated in Table 13.3
t
Table 13.3 java.io.package classes h
Class Description e
BufferedInputStream It used for creating an internal
buffer array. It supports the
s
mark and reset methods.
i
BufferedOutputStream This class used for writes byte to
output stream. It implements a d
buffered output stream. e
BufferedReader This class provides read text b
from character input stream and a
buffering characters. It also r
reads characters, arrays and
lines. c
BufferedWriter This class provides write text
o
from character output stream
n
and buffering characters. It also
writes characters, arrays and t
lines. e
ByteArrayInputStream It contains the internal buffer n
and read data from the stream. t
ByteArrayOutputStream This class used for data is .
written into byte array. This is to
implement in output stream A
class.
CharArrayReader It used for char input stream and
s
implements a character buffer.
CharArrayWriter This class also implements a i
character buffer and it uses a d
writer. e
DataInputStream This class reads the primitive b
data types from the input stream a
in a machine format. r
DataOutputStream This class writes the primitive
data types from the output i
stream in machine format.
s
File This class shows a file and
directory pathnames.
FileDescriptor This class uses for create a a
FileInputStream and
s
Self-Instructional Material
167 t
a
n
d
Input / Output classes
NOTES
FileOutputStream.
FileInputStream It contains the input byte from a
[
file and implements an input
T stream.
y FileOutputStream It uses for writing data to a file
p and also implements an output
e stream.
FilePermission It provides the permission to
t access a file or directory.
h FileReader This class used for reading
e characters file.
FileWriter This class used for writing
characters files.
s
FilterInputStream This class overrides all methods
i of InputStream and contains
d some other input stream.
e FilterOutputStream This class overrides all methods
b of OutputStream and contains
a some other output stream.
r FilterReader It reads the data from the filtered
character stream.
c FilterWriter It writes data from the filtered
character stream.
o
InputStream This class represents an input
n
stream of bytes.
t It reads bytes and decodes them
InputStreamReader
e into characters.
n LineNumberReader This class has a line numbers
t ObjectInputStream This class used for recover the
. object to serialize previously.
ObjectInputStream.GetField This class access to president
A fields read form input stream.
ObjectOutputStream This class used for write the
s
primitive data types and also
writes the object to read by the
i
ObjectInputStream.
d ObjectOutputStream.GetField This class access to president
e fields write in to ObjectOutput.
b ObjectStreamClass Serialization's descriptor for
a classes.
r ObjectStreamField This class describes the
serializable field.
i OutputStream This class represents an output
s stream of bytes.
OutputStreamWriter It writes bytes and decodes them
into characters.
a
PipedInputStream In this class the data bytes are
written into piped output stream.
s
Self-Instructional Material
t
168
a
n
d
a
Input / Output Classes
NOTES
The File class allows you to obtain and manipulate the information about a
a
file such as permissions, size, time and so on. Unlike the other classes of
java.io package, this class does not operate on the streams; it deals directly
s
Self-Instructional Material
169 t
a
n
d
Input / Output classes
NOTES
with the files and file system. That is, it does not specify how the data is
retrieved from or sent to the files. Using this class, you can also make new
[
directories, rename as well as delete the files.
T
y A object can be created using any one of the following constructors;
p
e File(File parent, String child) : Creates a new File instance from a
parent abstract pathname and a child pathname string.
t
h File(String pathname) : Creates a new File instance by converting the
e given pathname string into an abstract pathname.
s
Self-Instructional Material
t
170
a
n
d
a
Input / Output Classes
NOTES
Output
[
File name :file.txt T
Path: file.txt y
Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\file.txt p
Parent:null
e
Exists :true
Is writeable:true
Is readabletrue t
Is a directory:false h
File Size in bytes 20 e
s
14.5 Input / Output Exceptions
i
d
I/O exception occurs when an IO operation has failed for some reason. It is e
also a checked exception which means that your program has to handle b
it.IOException has many sub classes that are specific in nature. That a
means, when your application searching to read a file, if the file is not r
found that there is a FileNotFoundException to be thrown.
FileNotFoundException is a subclass of IOException.For
c
example;(FileNotFoundException)
o
import java.io.File; n
import java.io.FileInputStream; t
import java.io.FileNotFoundException; e
import java.io.IOException; n
/** t
* File Not Found Exception example .
* @author Krishna
*
A
*/
public class JavaFileExample
{ s
public static void main(String[] args) i
{ d
File file = new File("D:/JavaTest.txt"); e
FileInputStream fileInputStream = null; b
try a
{
r
fileInputStream = new FileInputStream(file);
while (fileInputStream.read()!=-1){
System.out.println(fileInputStream.read()); i
} s
}catch (FileNotFoundException e){
e.printStackTrace(); a
}catch (IOException e){
s
Self-Instructional Material
171 t
a
n
d
Input / Output classes
NOTES
e.printStackTrace();
}finally{
[
try{
T fileInputStream.close();
y }catch (IOException e)
p{
e e.printStackTrace();
}
t }
h }
}
e
The above program would throw an exception if the file “JavaText.txt” is
s not in the mentioned path. You will get the following exception.
i
d The java.io.Exceptions provides for system input and output through data
e streams, serialization and the file system.
b
a Data Streams
r
Data streams perform binary I/O operation on primitive data type values
(boolean, char, byte, short, int, long, etc.) as well as on String values. If
c you need to work with data that is not represented as bytes or characters
o then you can use Data Streams. These streams filter an existing byte stream
n so that each primitive data types can be read from or written to the stream
t directly. The two data streams are DataInputStream and
e DataOutputStream.
n
t The methods to read and write data inputs are,
.
Read Write
readBoolean() writeBoolean()
A readByte() writeByte()
readDouble() writeDouble()
s ReadFloat() writeFloat()
i ReadLong() writeLong()
d ReadShort() writeShort()
e readInt() writeInt()
b
a These input methods returns the primitive data type indicated by the name
r of the method.
DataInputStream
i
s A data input stream is created with the constructor of DataInputStream
class. The constructor of DataInputStream is written as:
a
DataInputStream(java.io.InputStream in);
s
Self-Instructional Material
t
172
a
n
d
a
Input / Output Classes
NOTES
The read( ) method is used to read the data according to its types. For [
example, the readInt( ) method reads the int type of value while the T
readFloat() method reads the fraction value. The readLine( ) Methods y
reads the string per line from a file. for Example, p
e
import java.io.*;
public class DataIstr{
pubic static void main(String args[]){ t
try{ h
FileInputStream file = new FileInputStream("e.dat") e
DataInputStream data = new DataInputStream(file);
try{ s
while{true){ i
int in = data.readInt(); d
System.out.print(in+" ");
e
}
}catch(EOFException eof){data.close();} b
}catch(IOException e){ a
System.out.println("Error "e.toString()); } r
}}
c
DataOutputStream o
n
It writes only Java primitive data types and doesn't write the object values.
t
A data output stream is created with the constructor of
DataOutputStream class. The constructor of DataOutputStream is written e
as: n
t
DataOutputStream(java.io.OutputSrream out); .
The write( ) method is used to write the data according to its types. For A
example, the writeInt( ) method writes the int type of value while the
writeFloat() method writes the fraction value. The writeUTF( ) method s
writes the string per line to a file. for example,
i
import java.io.*; d
public class DataOstr{ e
pubic static void main(String args[]){ b
try{ a
FileInputStream file = new FileInputStream("e.dat") r
DataInputStream data = new DataInputStream(file);
for(int i =0 ; i<50;i++) i
data.writeInt(i*2);
s
data.close();
}catch(IOException e)
{ a
System.out.println("Error "+.toString()); }
s
Self-Instructional Material
173 t
a
n
d
Input / Output classes
NOTES
}
}
[
T 14.6 Creation of files
y
p
e Java provides a number of classes and methods that allow you to read and
write (create) files. In Java, all files are byte-oriented, and Java provides
methods to read and write bytes from and to a file. However, Java allows
t you to wrap a byte-oriented file stream within a character-based object.
h
e File Output Stream
NOTES
}
} [
} T
y
The following program uses write( ) method to write text to text file . p
e
/* Write a text to text file.
import java.io.*; t
public class WriteFile h
{ e
public static void main(String[] args) throws IOException
{ s
File f=new File("writefile.txt"); i
FileOutputStream fop=new FileOutputStream(f); d
if(f.exists())
e
{
String str="This data is written through the program"; b
fop.write(str.getBytes()); a
fop.flush(); r
fop.close();
System.out.println("The data has been written"); c
} o
else n
System.out.println("This file is not exist");
t
}
} e
n
t
File Input Streams .
The method returns an integer contain the next byte in the stream. If the i
method returns -1 it identifies that the end of the file stream has been
s
reached. It can throw an IOException. When you are done with a file, you
should close it by calling close( ).
a
s
Self-Instructional Material
175 t
a
n
d
Input / Output classes
NOTES
void close( ) throws IOException
[
The following program uses read( ) to input and display the contents of a
T file.
y
p import java.io.*;
e public class ReadBytesDemo{
public static void main(String args[]){
t try{
h FileInputStream file = new FileInputStream("Hello.class");
boolean eof= false;
e
int c=0;
while(!eof){
s int inp = file.read();
i System.out.println(input+" ");
d if(inp == -1) eof = true;
e else c++;
b }
a file.close();
System.out.println("\n Output Bytes read :" "+c);
r
}catch(IOException e){
System.out.println("Error -- "+e.toString());
c }
o }
n }
t
e /* Read a text file. */
n
t
import java.io.*;
.
public class ReadFile{
public static void main(String[] args) throws IOException{
A File f;
f=new File("myfile.txt");
s
i if(!f.exists()&& f.length()<0)
d System.out.println("The specified file is not exist");
e
else{
b
FileInputStream finp=new FileInputStream(f);
a byte b;
r do{
b=(byte)finp.read();
i System.out.print((char)b);
s }
while(b!=-1);
a finp.close();
}
s
Self-Instructional Material
t
176
a
n
d
a
Input / Output Classes
NOTES
}
} [
T
Output: y
p
My Text file contents are displayed here.
e
H i
E s
L
L a
O
s
Self-Instructional Material
177 t
a
n
d
Input / Output classes
NOTES
Reading Strings
[
T To read a string from the keyboard, use the version of readLine( ) that is a
y member ofthe BufferedReader class. Its general form is shown here:
p
e String readLine( ) throws IOException
s
Self-Instructional Material
t
178
a
n
d
a
Input / Output Classes
NOTES
This class contains a buffer(array) or bytes that store the next few bytes s
that will be read from the stream. i
d
Example :
e
import java.io.FileInputStream; b
import java.io.InputStream; a
public class InputStreamDemo { r
public static void main(String[] args) throws Exception {
InputStream is = null; c
byte[] buffer = new byte[5]; o
char c; n
try {
t
// new input stream created
is = new FileInputStream("C://testread.txt"); e
n
System.out.println("Characters printed:"); t
.
// read stream data into buffer
is.read(buffer); A
NOTES
if(is!=null)
is.close();
[
}
T }
y }
p
e
Writing bytes
t
h All classes that write bytes extend java.io.OutputStream. The important
classes are:
e
FileOutputStream
s
i The methods in this class write bytes of data to a file. Note that this writes
d raw bytes and not characters.
e
b ObjectOutputStream
a
It writes primitive java types and objects to an ouputstream. The data could
r
be written to a file or to a socket. Data written using this method can be
read back using the ObjectInputStream
c
o PipedOutputStream
n
t A piped output stream connects to aPipedInputStream to read bytes. Data
e may be written by one thread and read by another.
n
t
BufferedOutputStream
.
It buffers data from an input stream and writes the buffered data. It is an
efficient method of writing data since the operating systems may write an
A array of bytes in a single operation and invoking write operation for each
byte may be inefficient
s
i PrintStream
d
e It wraps an InputStream and adds functionality to print various
representations of data values. It never throws IOException and there is an
b
option for automatic flushing
a
r ByteArrayOutputStream-This class writes bytes at an array of bytes.
i
s
14.9Using RandomAccessFile class
NOTES
is a cursor implied to the array called file pointer, by moving the cursor we
do the read write operations. The constructors for the RandomAccessFile [
class are; T
y
RandomAccessFile(File file, String mode) p
e
Creates a random access file stream to read from, and optionally to write
to, the file specified by the File argument.
t
RandomAccessFile(String name, String mode) h
e
Creates a random access file stream to read from, and optionally to write
to, a file with the specified name. s
i
Java provides java.io.RandomAccessFile class that enables you to perform d
random access file input and output operations as opposed to sequential
e
file I/O offered by ByteStream and CharacterStream classes.
b
When a data file is opened for random read and write access, an internal a
file pointer is set at the beginning of the file. When you read or write data r
to the file, the file pointer moves forward to the next data item. For
example, when reading an in t value using readlnt() , 4 bytes are read from c
the file and the file pointer moves 4 bytes ahead from the previous file o
pointer position. n
t
Similarly, when reading a double value using readDouble () , 8 byte are
read from the file pointer and the file pointer moves 8 bytes ahead from the e
previous file pointer position. n
t
import java.io.*; .
class RandomFileExample A
{
public static void main(String[] args)
s
{
i
try
{ d
RandomAccessFile file = new RandomAccessFile("std.dat","rw"); e
file.setLength(0); b
for(int i=0;i<50;i++) a
file.writeInt(i); r
System.out.println("Length of File After Writing Data is :
"+file.length()); i
file.seek(0);
s
System.out.println("First Number is : "+file.readInt());
file.seek(1*4);
System.out.println("Second Number is : "+file.readInt()); a
file.writeInt(101);
s
Self-Instructional Material
181 t
a
n
d
Input / Output classes
NOTES
file.seek(file.length());
file.writeInt(50);
[
System.out.println("Current Length of File is : "+file.length());
T}
y catch(Exception e)
p {
e e.printStackTrace();
}
t }
h }
e
Output
s
i
d
e
b
a
r
NOTES
NOTES
NOTES
***** s
i
d
e
b
a
r
c
o
n
t
e
n
t
.
s
i
d
e
b
a
r
i
s
s
Self-Instructional Material
185 t
a
n
d
MODEL QUESTION PAPER
DISTANCE EDUCATION
13. (a) Summarize the use of Wrapper classes and its methods.
Or
(b) Write a java program to illustrate method overriding.
186
Part – C (3 x 10 = 30 Marks)
Answer any three questions.
********
187