Sie sind auf Seite 1von 476

INTERNET APPLICATIONS

AND JAVA
BCA - 501
This SIM has been prepared exclusively under the guidance of Punjab Technical
University (PTU) and reviewed by experts and approved by the concerned
statutory Board of Studies (BOS). It conforms to the syllabi and contents as
approved by the BOS of PTU.
Author: Rohit Khurana
Copyright ITL Education Solutions Ltd, 2011
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 Publisher.
Information contained in this book has been published by VIKAS

Publishing House Pvt. Ltd. and has


been obtained by its Authors from sources believed to be reliable and are correct to the best of their
knowledge. However, the Publisher and its Authors shall in no event be liable for any errors, omissions
or damages arising out of use of this information and specifically disclaim any implied warranties or
merchantability or fitness for any particular use.
Vikas

is the registered trademark of Vikas

Publishing House Pvt. Ltd.


VIKAS

PUBLISHING HOUSE PVT LTD


E-28, Sector-8, Noida - 201301 (UP)
Phone: 0120-4078900 Fax: 0120-4078999
Regd. Office: 576, Masjid Road, Jangpura, New Delhi 110 014
Website: www.vikaspublishing.com Email: helpline@vikaspublishing.com
Reviewer
Sonia Sharma
CAREER OPPORTUNITIES
Java is used in all areas associated with the Internet, Web
development and Web technologies. Java programmers will
find job opportunities in all areas related to e-commerce, portals,
content management, databases, data warehousing and custom
applications development.
Those wishing to take up software programming jobs
would be expected to work on adding new functionality to
existing systems. Java programming skills would be required
to prepare user and technical support manuals for different
applications.
Java programmers can use their skills to work on various
aspects of video game programming. Experienced video game
programmers can go on to become project managers in charge
of making sure that all the different programming components
are working smoothly together. Being a vast field, the
opportunities are many, depending on the field that the student
wants to specialize in. Coupled with a degree in management,
Java programmers can climb the corporate ladder very fast
Section I
Introduction: Internet Architecture Board, Understanding
the Internet.
Concept: Working, Surfing and Security on the Internet.
Internet protocols Internet Addressing, Internet Routing
Protocols Internet Message Protocol, Internet Group
Management protocols, Internet mail protocol.
Internet applications: E-mail, multi cost backbone, net news.
Web: World Wide Web advantages of web, web terminology,
web access using web browser, locating information on the
web.
Section II
Introduction to Java: Applets, application & JDK, different
b/w Java & C++, working with Java objects: Encapsulation,
inheritance & polymorphism, constructors. Garbage
collection & finalisers, data types, modifies & expressions,
array & flow control statements.
Section III
Exception handling threads, Event handling, Network
programming & Java virtual machines, Java & databases.
PTU DEP SYLLABI-BOOK MAPPING TABLE
Internet Applications and Java
Syllabi Mapping in Book
Unit 1: Internet
(Pages 316);
Unit 2: Web: World Wide Web
(Pages 1727);
Unit 3: Java and the Internet
(Pages 2938)
Unit 4: Programming Elements of Java
(Pages 3957)
Unit 5: Control Statements
(Pages 5976);
Unit 6: Java Classes and Objects
(Pages 7794);
Unit 7: Arrays and Vectors
(Pages 95108);
Unit 8: Inheritance and Polymorphism
(Pages 109131)
Unit 3: Java and the Internet
(Pages 2937);
Unit 9: Exception Handling Threads
(Pages 133166);
Unit 10: Exception Handling
(Pages 167184);
Unit 11: Event Handling
(Pages 185198);
Unit 12: Network Programming
(Pages 199212)
Unit 13: Java and Database
(Pages 213228)
CONTENTS
INTRODUCTION 1
UNIT 1 INTERNET 316
1.0 Introduction
1.1 Unit Objectives
1.2 Understanding the Basics of the Internet
1.2.1 Evolution of the Internet
1.2.2 Internet Architecture Board
1.2.3 Accessing the Internet
1.2.4 Working of the Internet
1.2.5 Surfing on the Internet
1.3 Security on the Internet
1.4 Internet Protocols
1.5 Internet Addressing
1.6 Internet Routing Protocols
1.7 Internet Message Protocol (Internet Control Message Protocol)
1.8 Internet Group Management Protocols
1.9 Internet Mail Protocols
1.10 Internet Applications
1.11 Summary
1.12 Key Terms
1.13 Answers to Check Your Progress
1.14 Questions and Exercises
UNIT 2 WEB: WORLD WIDE WEB 1727
2.0 Introduction
2.1 Unit Objectives
2.2 The Web: Advantages and Terminology
2.2.1 Web Terminology
2.3 Web Access Using Web Browser
2.4 Locating Information on the Web
2.5 Summary
2.6 Key Terms
2.7 Answers to Check Your Progress
2.8 Questions and Exercises
UNIT 3 JAVA AND THE INTERNET 2938
3.0 Introduction
3.1 Unit Objectives
3.2 Basic Features of Java Programming Language
3.3 Difference between Java and C++
3.4 Java Applications and Applets
3.5 Java Compiler
3.6 Java Virtual Machine Concepts
3.7 Java Development Kit (JDK)
3.8 A First Look at Java Program
3.9 Running Java Applications
3.10 Command Line Arguments
3.11 Summary
3.12 Key Terms
3.13 Answers to Check Your Progress
3.14 Questions and Exercises
UNIT 4 PROGRAMMING ELEMENTS OF JAVA 3957
4.0 Introduction
4.1 Unit Objectives
4.2 Character Set
4.3 Tokens
4.3.1 Keywords
4.3.2 Identifiers
4.3.3 Constants
4.3.4 Operators
4.3.5 Punctuators
4.4 Structure of a Java Program
4.5 Data Types
4.5.1 Primitives Data types
4.5.2 Non-Primitive Data types
4.6 Variables
4.7 Type Casting
4.8 Operators and Operations
4.8.1 Arithmetic Operators
4.8.2 Increment and Decrement Operators
4.8.3 Relational Operators
4.8.4 Logical Operators
4.8.5 Conditional Operator
4.8.6 Assignment Operators
4.8.7 Other Operators
4.8.8 Operators Precedence and Associativity
4.9 Summary
4.10 Key Terms
4.11 Answers to Check Your Progress
4.12 Questions and Exercises
UNIT 5 CONTROL STATEMENTS 5976
5.0 Introduction
5.1 Unit Objectives
5.2 Selection Statements
5.3 Iteration Statements
5.3.1 The for Loop
5.3.2 The while Loop
5.3.3 The do-while Loop
5.4 Jump Statements
5.5 Labelled Loops
5.6 Summary
5.7 Key Terms
5.8 Answers to Check Your Progress
5.9 Questions and Exercises
UNIT 6 JAVA CLASSES AND OBJECTS 7794
6.0 Introduction
6.1 Unit Objectives
6.2 Encapsulation
6.3 Defining a Class
6.3.1 Defining Methods
6.4 Creating Objects
6.5 Accessing Members of a Class
6.6 Argument Passing
6.6.1 Call-by-Value
6.6.2 Call-by-Reference
6.7 Constructors
6.7.1 Parameterized Constructors
6.8 Method Overloading
6.9 Static Members
6.10 this Keyword
6.11 Garbage Collection
6.11.1 The finalize() Method
6.12 Summary
6.13 Key Terms
6.14 Answers to Check Your Progress
6.15 Questions and Exercises
UNIT 7 ARRAYS AND VECTORS 95108
7.0 Introduction
7.1 Unit Objectives
7.2 Arrays
7.2.1 Single-Dimensional Arrays
7.2.2 Multi-Dimensional Arrays
7.3 Vectors
7.4 Wrapper Classes
7.5 Summary
7.6 Key Terms
7.7 Answers to Check Your Progress
7.8 Questions and Exercises
UNIT 8 INHERITANCE AND POLYMORPHISM 109131
8.0 Introduction
8.1 Unit Objectives
8.2 Inheritance Basics
8.2.1 Defining a Subclass
8.3 Types of Inheritance
8.3.1 Single Inheritance
8.3.2 Hierarchical Inheritance
8.3.3 Multilevel Inheritance
8.3.4 Multiple Inheritance
8.4 Access Modifiers
8.5 Subclass Constructor
8.6 Method Overriding
8.7 Polymorphism
8.8 Using final Keyword
8.8.1 Final Variables
8.8.2 Final Methods
8.8.3 Final Classes
8.9 Abstract Methods and Classes
8.10 Summary
8.11 Key Terms
8.12 Answers to Check Your Progress
8.13 Questions and Exercises
UNIT 9 EXCEPTION HANDLING THREADS 133166
9.0 Introduction
9.1 Unit Objectives
9.2 Concept of Threads
9.2.1 Main Thread
9.2.2 Creating Threads
9.2.3 Extending Threads
9.2.4 Implementing Runnable Interface
9.3 Life Cycle of a Thread
9.4 Thread Methods
9.4.1 Using Yield(), Sleep() and Stop() Method
9.4.2 Using isalive() and join() Method
9.5 Threads Priority
9.6 Synchronization of Threads
9.6.1 Synchronizing Methods
9.6.2 Synchronizing Statements
9.6.3 Deadlock
9.7 Inter-Thread Communication
9.8 Suspending, Resuming and Stopping Threads
9.9 Summary
9.10 Key Terms
9.11 Answers to Check Your Progress
9.12 Questions and Exercises
UNIT 10 EXCEPTION HANDLING 167184
10.0 Introduction
10.1 Unit Objectives
10.2 Exceptions
10.2.1 Keywords Used in Exception Handling
10.2.2 Types of Exceptions
10.3 Using try and catch Blocks
10.3.1 Multiple catch Blocks
10.3.2 Nested try Blocks
10.4 Using finally Block
10.5 Using throw Block
10.6 Using throws Keyword
10.7 Creating Your Own Exceptions
10.8 Summary
10.9 Key Terms
10.10 Answers to Check Your Progress
10.11 Questions and Exercises
UNIT 11 EVENT HANDLING 185198
11.0 Introduction
11.1 Unit Objectives
11.2 Events
11.3 Event Handling Model
11.3.1 Java 1.0 Event Model
11.3.2 Delegation Event Model
11.4 Event Handling: Classes, Sources and Listner Interfaces
11.4.1 Event Classes
11.4.2 Event Sources
11.4.3 Event Listener Interfaces
11.5 Summary
11.6 Key Terms
11.7 Answers to Check Your Progress
11.8 Questions and Exercises
UNIT 12 NETWORK PROGRAMMING 199212
12.0 Introduction
12.1 Unit Objectives
12.2 Networking Fundamentals
12.2.1 TCP/IP Protocols
12.2.2 Internet Addressing
12.2.3 Ports
12.2.4 Sockets
12.3 The Networking Classes and Interfaces
12.4 The InetAddress Class
12.5 TCP/IP Socket Programming
12.5.1 Creating a TCP Server
12.5.2 Creating a TCP Client
12.6 UDP Socket Programming
12.6.1 Creating a UDP Server Program
12.6.2 Creating a UDP Client Program
12.7 Summary
12.8 Key Terms
12.9 Answers to Check Your Progress
12.10 Questions and Exercises
UNIT 13 JAVA AND DATABASE 213228
13.0 Introduction
13.1 Unit Objectives
13.2 Architecture of JDBC
13.3 JDBCODBC Bridge
13.4 The java.sql Package
13.4.1 The DriverManager Class
13.4.2 The Connection Interface
13.4.3 The Statement Interface
13.4.4 The ResultSet Interface
13.4.5 The PreparedStatement Interface
13.4.6 The ResultSetMetaData Interface
13.4.7 The SQLException Class
13.5 Summary
13.6 Key Terms
13.7 Answers to Check Your Progress
13.8 Questions and Exercises
Self-Instructional
Material 1
Introduction
NOTES
INTRODUCTION
Java is a programming language that has been developed by Sun Microsystems and is
one of the most popular programming languages in use. It is widely used in various ways
ranging from application software to Web applications. It is a general-purpose, class-
based and object-oriented language that is specifically designed to have the least number
of implementation dependencies possible. All these features led to the process of using
it as the language for the Internet. It also supports various Internet protocols and Web
services and is used for all applications of the Internet.
This book, Internet Applications and Java, is divided into thirteen units. The
first unit deals with the basics of the Internet, including its evolution and various
applications. The next unit provides an introduction to the World Wide Web. The
relationship between Java and the Internet has been analysed in the third unit. The
fourth unit deals with the programming elements of Java, while the control statements in
Java have been shown in the fifth unit. The following unit highlights Java classes and
objects. The seventh unit deals with arrays and vectors. The eighth unit deals with
inheritance and polymorphism. The next unit discusses the exception handling threads.
The tenth unit explains exception handling, while the eleventh unit deals with event
handling. Network programming has been discussed in the twelfth unit. Accessing a
database in Java has been dealt with in the last unit.
The book follows the self-instructional mode wherein each unit begins with an
Introduction to the topic. The Unit Objectives are then outlined before going on to the
presentation of the detailed content in a simple and structured format. Check Your
Progress questions are provided at regular intervals to test the student's understanding
of the subject. A Summary, a list of Key Terms and a set of Questions and Exercises are
provided at the end of each unit for recapitulation.
Self-Instructional
Material 3
Internet
NOTES
UNIT 1 INTERNET
Structure
1.0 Introduction
1.1 Unit Objectives
1.2 Understanding the Basics of the Internet
1.2.1 Evolution of the Internet
1.2.2 Internet Architecture Board
1.2.3 Accessing the Internet
1.2.4 Working of the Internet
1.2.5 Surfing on the Internet
1.3 Security on the Internet
1.4 Internet Protocols
1.5 Internet Addressing
1.6 Internet Routing Protocols
1.7 Internet Message Protocol (Internet Control Message Protocol)
1.8 Internet Group Management Protocols
1.9 Internet Mail Protocols
1.10 Internet Applications
1.11 Summary
1.12 Key Terms
1.13 Answers to Check Your Progress
1.14 Questions and Exercises
1.0 INTRODUCTION
The word Internet is derived from two words: Interconnection and Network. The
Internet is basically a network of networks that facilitates data transmission and exchange,
across the million of domestic, academic, business and government networks. It is a
global, publicly accessible network that enables sharing of files and other resources
using protocols through the transmission media. With the two hundred computers in
1980, the Internet has now evolved to millions of computers linked worldwide.
The Internet has grown from a small network to todays biggest network of
computers. Due to this colossal growth, the Internet has become the biggest domain of
information. Nowadays, an Internet user has access to a wide variety of services, such
as electronic mail, file transfer, vast information resources, interest group membership,
interactive collaboration, multimedia displays, real-time broadcasting, shopping
opportunities, and much more.
1.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Understand the basics of the Internet
Discuss the working of Internet
Describe the various protocols that are used for communication between different
devices
Self-Instructional
4 Material
Internet
NOTES
Understand the Internet addressing
Explain Internet routing protocols, Internet message control protocols, Internet
group management protocols and Internet mail protocols
Explain few applications of Internet
1.2 UNDERSTANDING THE BASICS OF THE
INTERNET
The Internet refers to a global system of interconnected computer networks that use the
standard Internet Protocol Suite (TCP/IP) for serving millions of users worldwide. It is
a network of networks comprising millions of private, public, academic, business and
government networks.
This section deals with the basic aspects of the Internet, such as how it evolved,
how it is accessed, how it works, and so on.
1.2.1 Evolution of the Internet
The foundation of the Internet was laid in 1969 by the Department of Defense (DOD)
of the United States of America. The DOD wanted to create a computer network that
could continue to function in the event of a disaster, such as a nuclear war. Even if a part
of the network was damaged or destroyed, the rest of the system would continue to
work. That network was known as Advanced Research Projects Agency Network
(ARPANET), which linked US scientific and academic researchers. It was the forerunner
of todays Internet.
Later in 1980, another agency, the National Science Foundation (NSF) created a
new network of computers based on ARPANET, called NSFNET, which turned out to
be more efficient and capable. Initially, NSFNET was designed to link five super
computers situated at the major universities of NSF and allowed only academic research.
Over the time, this network expanded to include sites for business, universities,
government, etc. and finally becoming a network consisting of millions of computers,
now known as the Internet.
1.2.2 Internet Architecture Board
When ARPANET was developed, the DOD established a committee known as Internet
Activities Board (IAB) to monitor and control the development of Internet. This board
was later renamed to Internet Architecture Board. This committee was responsible for
deciding the standards required and how these standards should be implemented to
control the working of Internet. Some of the other responsibilities of IAB include:
It monitors the structure of protocols used by the Internet.
It monitors the procedures used to create the Internet standards.
It acts as a representative of the interests of the Internet Society.
The members of IAB regularly met and discussed the outcomes of the research
and reported to the DOD and NSF. In 1989, the IAB committee was divided into two
groups, namely, Internet Research Task Force (IRTF) and Internet Engineering Task
Force (IETF). The idea underlying the reorganization is to make IRTF focus on long
term research and IETF to handle short term engineering issues. The main purpose of
IRTF is to create research groups that focus on Internet protocols, applications,
Self-Instructional
Material 5
Internet
NOTES
architecture, and technology, whereas, IETF is a large open community of network
designers, operators, vendors and researchers that focuses on solving technical problems
on the Internet.
1.2.3 Accessing the Internet
As you know, the Internet is a vast collection of different networks that allows the
computers to exchange information with each other. It is a huge cooperative community
that is not under the control of anyone. However, there are several organizations that
propose standards and the guidelines for its proper usage. As a result, anyone having
Internet access can communicate directly with anyone on the Internet, post information,
use distant applications and services or buy and sell products. For accessing the Internet,
you need to buy an Internet connection from an authorized Internet Service Provider
(ISP). An ISP is an organization that provides access to the Internet. It charges a monthly
fee and subscribes you as a user to connect to the Internet. Once you get subscribed,
you can log on to the Internet and browse the Web any time as per your convenience.
There are thousands of ISPs established all over India. Some of the common ISPs
include Mahanagar Telephone Nigam Limited (MTNL), Videsh Sanchar Nigam Limited
(VSNL), Satyam Online, etc.
ISP provides a variety of Internet connections varying in the speed of accessing
the Internet. Following are the types of Internet connections provided by ISPs.
Dial-up access
Integrated services digital network (ISDN)
Cable
Digital subscriber line (DSL)
Leased line
1.2.4 Working of the Internet
Most of the computers are not directly connected to the Internet, instead they are part of
small networks which in turn are connected to Internet backbone through gateways.
Internet backbone act as interconnecting structure used to connect one or more networks
and gateway is a device used to connect dissimilar networks.
Now, let us see how messages are transferred from one system to another on the
Internet. The message sent by the source computer is divided into small parts known as
packets. Each packet is assigned a sequence number 1, 2, 3, so on. All these packets
are then sent to the destination computer with the help of routers. At the destination
computer, the packets may be received in random order, thus the packets are rearranged
according to their sequence number and reassembled together to form the original
message. If any of the packets is lost or corrupted, it is resent from the source computer.
1.2.5 Surfing on the Internet
Internet contains a huge wealth of information which can help us in many ways. There
are different websites on the Internet which are hosted by various companies,
organizations, educational institutions, newspapers, magazines, individuals, etc. With the
help of the web browser, one can easily visit these websites and gather competitive
information, conduct market research, and stay in touch with the current happenings.
The process of locating information on the Internet is called Internet surfing or Internet
browsing. Details of locating information on the Internet are discussed in Unit 2.
Self-Instructional
6 Material
Internet
NOTES
1.3 SECURITY ON THE INTERNET
Internet, being a vital source of data and information, plays an important role in the
growth of organizations, business, etc. However, at the same time, it has been a cause of
many security risks. This is because computer systems on the Internet are vulnerable to
various kinds of threats. Some of the common security threats that are faced today are
as follows:
Password cracking: Password cracking is a way for illegally accessing someones
computer without his or her permission to do so.
E-mail spoofing: Sometimes, a user can receive e-mail that appears to have
been sent by one person but was actually sent by some other person and it results
to spoofing. The aim of spoofing is to make the user divulge the confidential
information.
Virus intrusion: Viruses are short programs which are attached to other programs
with the intent to corrupt executable codes. Viruses are exposed when we receive
e-mails, send documents over the network and even when we install software or
copy files from another hard disk. They are of various types, such as file infecting
virus, boot sector virus, polymorphic virus, multipartite virus, stealth virus, etc.
They can affect the system in many ways like slowing down the system, formatting
the hard disk, corrupting the data, etc.
Hackers: Hackers are the people who focus on finding some weak points in the
security mechanism of websites and other computer systems in order to gain
unauthorized access. The activities of hackers are not limited to only gaining the
unauthorized access of systems, but also include theft of confidential information
and damage the information systems. They can also introduce viruses in the
network which can enter database or other applications and crash the whole
server.
There are various ways through which Internet security can be provided. Some of them
are as follows:
Authentication: It is the process of determining whether the user is allowed to
access the computer. Identification is usually done on the basis of username and
password and it can also be done on the basis of fingerprints, voice recognition,
signature, etc.
Authorization: It is the process of specifying whether the user is granted
permission to use certain resources. The computer resource is thus protected
from unauthorized users. The resources comprise data, programs, files, application,
devices, etc. Usually the permission is granted by the system administrators.
Cryptography: It is the process of encrypting or modifying the messages to hide
its meaning from the unauthorized users who try to intercept it. With the help of
this technique, the sensitive data which is sent across the Internet can be protected.
Firewall: A firewall is a part of a computer system or network which is placed
between an internal network and Internet. It is configured with a set of rules to
determine which network traffic should be allowed to pass and which one should
be blocked, that is, it blocks the unauthorized access. It is implemented in either
software or hardware or, a combination of both.
Check Your Progress
1. The Department of
Defense of USA
laid the foundation
of Internet in the
year 1969. That
network was
known as_______.
2. What was the
purpose of
establishing the
Internet
Architecture
Board?
3. _________ is a
device used to
connect dissimilar
networks.
4. Define Internet
surfing.
Self-Instructional
Material 7
Internet
NOTES
Cyber laws: Cyber laws are enforced to control the cyber crime. The laws
address the legal issues related to the communication technology.
Digital signature: In order to prevent spoofing, the original sender of the e-mail
must put the electronic signature in the message. This electronic signature is also
known as digital signature. Electronic signature ensures that the original messages
are not changed during the transmission process and the messages are also from
the person which is in the sender list.
1.4 INTERNET PROTOCOLS
A protocol is referred to as the formal set of rules and conventions that govern how
different computer devices communicate with each other. Some of the protocols used
for communication between different devices are discussed here.
TCP/IP
The TCP/IP is a layered set of protocols that handles the way data is transmitted across
the Internet. The TCP/IP has two major components, namely, Transmission Control
Protocol (TCP) and Internet Protocol (IP).
The TCP is a reliable and connection-oriented protocol that allows the data that
originates from source machine, to be delivered without error to the destination. It
fragments the incoming data into discrete messages called packets. TCP at
receiving the data, sends an acknowledgement that guarantees that the data is
received and then reassembles the packets into original form.
IP is an unreliable and connectionless protocol. It does not require a connection to
be established to transmit the data and does not guarantee the delivery of data to
its destination. IP is primarily responsible for delivering the packets to the destination.
HyperText Transfer Protocol (HTTP)
HTTP is a protocol that facilitates accessing hypertext documents. It is designed
specifically for the WWW at CERN. It is based on the client/server principle that allows
the client to make a connection with the server and then place a request. The server
services that request and sends an appropriate reply to the client. The HTTP is used as
a protocol for communication between the user agent and gateways to other IP protocols
like SMTP, FTP, etc.
File Transfer Protocol (FTP)
FTP is a set of rules that enables a user to transfer files from one system to another. It
allows the user to get access to the files stored in the directory of a remote computer
that is connected to the Internet. Using FTP, one can upload and download files from the
remote computer (known as FTP Server), if he has access permission on the remote
machine.
Some FTP servers allow users to use a method called anonymous FTP, which
allows users to access files without any specific permission to access. One can download
FTP files using either web browser or a special software known as FTP client program
such as Cube or Fetch.
Self-Instructional
8 Material
Internet
NOTES
Network News Transfer Protocol (NNTP)
NNTP is a protocol which is used by computer clients and servers to manage the news
posted on newsgroup. It is used to transfer news messages over the Internet. NNTP is
a replacement of original Usenet protocol. A copy of news messages posted by the
users can be collected from the newsgroups by NNTP server, which can later be read
by other users. These users can send their own messages to the same group. NNTP has
been created for the efficient transmission of Netnews articles over a full duplex 8-bit-
wide data stream communication channel.
1.5 INTERNET ADDRESSING
Every machine on the Internet is identified by a numerical address known as IP address.
It is a 32 bit number which is assigned to each computer connected to the Internet. An
IP address comprises four sections that are separated by periods (.). Each section consists
of a number which ranges from 0 to 255. An example of a typical IP address is:
216.27.61.137. Note that, no two computers can share the same IP address. As IP
addresses are in the form of numerical strings, they are hard to remember. Thus, there
exists a domain name that corresponds to an IP address. Domain names are human-
readable addresses and are much easier to remember. A domain name consists of two
or more parts separated by periods (.). Some of the examples of domain name are
www.yahoo.com, www.nasa.org, etc. The domain name represents the name of the
web server where the desired web page or other resources resides. The last part of the
domain name is the top-level name which represents the type of organization or country
to which the server belongs. Three-letter abbreviations are used for organizations and
two-letter abbreviations are used for countries. Some of the abbreviations which are
reserved for various organizations are listed in Table 1.1.
Table 1.1 Reserved Abbreviations for Organizations
Domain Name Organization Type
.com Commercial / profit organizations
.edu Educational institutions
.net Networking organizations
.gov Government agencies
.org Non-profit organizations
.mil United states military
Some of the abbreviations which are reserved for various countries are listed in
Table 1.2.
Table 1.2 Reserved Abbreviations for Organizations
Domain Name Country Name
.in India
.uk United Kingdom
.au Australia
.nz New Zealand
.dk Denmark
.jp Japan
Check Your Progress
5. Which of the
following method
should be used to
prevent E-mail
spoofing?
(a) Cryptography
(b) Cyber laws
(c) Firewalls
(d) Digital
signature
6. Differentiate
between
authentication and
authorization.
7. TCP is an
unreliable and
connectionless
protocol of TCP/
IP. (True or False)
8. Which of the
following protocol
facilitates accessing
hypertext
documents?
(a) TCP/IP
(b) FTP
(c) HTTP
(d) NNTP
9. The mapping
between the
domain name and
its associated IP
address is
performed by an
Internet service
known as ______.
Self-Instructional
Material 9
Internet
NOTES
The mapping between the domain name and its associated IP address is performed
by an Internet service known as domain name system (DNS). It allows users to work
with domain names; however, Internet operates in IP address.
1.6 INTERNET ROUTING PROTOCOLS
Internet routers are specialized computers that interconnect several different networks.
A computer on the Internet communicates with other computer by forwarding packets
containing other computers IP address to the closest Internet router. The router maintains
the information required for routing purposes in the routing table. The routing table can
be either static or dynamic. If the routing table is updated with change in the topology of
any network the routing table is said to be dynamic otherwise static. Today dynamic
tables are needed by the Internet. For handling dynamic routing tables, routing protocols
have been developed. A routing protocol is a set of rules and procedures which specifies
how routers share information with each other for routing purposes.
As the Internet is so vast, the updation of routing tables cannot be handled by one
routing protocol, thus, the Internet is divided into a number of independent networks
known as autonomous systems. An autonomous system (AS) is a group of networks
and routers which is controlled by a single administration. On the basis of routing inside
an autonomous system or between autonomous systems, routing protocols are divided
into types:
Interior Gateway Protocol (IGP)
Exterior Gateway Protocol (EGP)
Interior Gateway Protocol (IGP)
The Interior gateway protocol is a routing protocol which is used for routing purpose
within an AS. The two of the commonly used IGP protocols are Routing Information
Protocol (RIP) and Open Shortest Path First (OSPF).
RIP: It is based on an algorithm known as distance vector algorithm. It uses
hop count as its metric (cost) which represents the number of networks passed to
reach the destination. This protocol treats all the networks equally, that is, the cost
of passing through any of the networks is same; the hop value for passing each
network is 1. In this protocol, while crossing several networks, if the hop value for
a particular network reaches 16, then that network is said to be unreachable.
Hence, this protocol is not suitable for very large networks.
OSPF: It supports large networks and has become the main interior gateway
protocol. It divides an autonomous system into areas, which is a set of routers,
hosts and networks comprised in an AS. All the areas inside an AS are connected
to a special area called backbone. Routers within an area are called internal
routers and those located at area borders are known as area border routers.
Area border routers summarize routing information of an area and exchange it
with neighbouring areas. This protocol allows assigning a metric to each route
and the metric or cost is based on the type of services on a particular route like
minimum delay, maximum throughput, etc. This protocol maintains several routing
tables based on the different types of services. These routing tables can be used
for selecting optimal route for sending the packets.
Self-Instructional
10 Material
Internet
NOTES
Exterior Gateway Protocol
The exterior gateway protocol is a routing protocol which is used for routing purpose
across one or more autonomous systems. One of the most common EGP protocols is
Border Gateway Protocol (BGP).
BGP is based on an algorithm known as path vector routing. In this algorithm,
the routing table maintains the information containing details of the path used to reach a
destination along with addresses of destination network and the next router. Every BGP
router evaluates the different paths used for reaching a destination and provides rating
to them. It then shares this information with other routers. The other routers, if required
can update their own routing tables and propagate this information to other neighbouring
routers. However, the route which is optimal for one router may not be optimal for other
router; therefore router has to decide whether to update its routing table.
1.7 INTERNET MESSAGE PROTOCOL (INTERNET
CONTROL MESSAGE PROTOCOL)
The Internet Control Message Protocol (ICMP) is a network layer protocol which was
designed to overcome the limitations of IP. The limitations included lack of error reporting
messages and lack of procedures for handling host and management queries. An ICMP
packet is encapsulated inside an IP packet and is responsible for error free transmission
of IP packets over the network. Some of the important ICMP messages are as follows:
Destination unreachable: This message is used when the router or subnet is
not able to reach the destination.
Time exceeded: This message is used when the counter associated with the
packet hits zero and the packet is dropped. It indicates looping of packets due to
congestion or setting very low timer values.
Source quench: This message is sent to the host which sends too many packets
leading to congestion in the network.
Redirect: This message is used by the router to tell the source host about wrong
routing of a packet.
Echo: This message is used to check whether a destination host is reachable and
alive.
Echo reply: This message is generated by the destination host in response to the
Echo message received.
Timestamp request: This message is used to determine the round trip time
needed for an IP packet to travel between two machines.
Timestamp reply: This message is generated in response to Timestamp Request
message. It is similar to Timestamp Request message except that it also contains
the arrival time of Timestamp Request message and departure time of the reply.
1.8 INTERNET GROUP MANAGEMENT PROTOCOLS
The Internet Group Management Protocol (IGMP) protocol is designed to support
multicasting. Multicasting is a process in which a message is sent to a large number of
hosts belonging to a group. To implement multicasting, a host must acquire a class D
address (each class D address identifies a group of hosts). Whenever a message is sent
Check Your Progress
10. The two of the
commonly used
IGP protocols are
____________ and
___________.
11. BGP is based on
an algorithm
known as
______________.
12. _____________
message is sent to
the host which
sends too many
packets leading to
congestion in the
network.
Self-Instructional
Material 11
Internet
NOTES
to the address by a process, it is sent to all the members of the group associated with that
address. The host can join or leave the group as required by the process. Each host
maintains the list of groups to which its processes currently belongs to.
Each multicast router sends the queries regularly to determine the hosts running
the processes belonging to any of the groups. Each host in turn sends a response message
for each group currently running one or more processes. The messages sent by the
router and hosts are called IGMP query packet and IGMP response packet,
respectively. Both these packets use a simple and fixed format with control information.
It consists of several fields which are as follows:
Ver: It specifies the version of the IGMP protocol.
Message type: It specifies the type of message which can be a query message
or a response message.
Maximum response time: It specifies the maximum amount of time in which a
query must be answered.
Checksum: It specifies the checksum, calculated for the message.
Group address: It contains the class D IP address of the group.
1.9 INTERNET MAIL PROTOCOLS
An Internet mail protocol is a protocol which is used by mail clients to exchange information
with the mail servers. The three main protocols which are commonly used are Simple
Mail Transfer Protocol (SMTP), Post Office Protocol Version 3 (POP3) and Internet
Message Access Protocol Version 4 (IMAP4).
Simple Mail Transfer Protocol (SMTP)
SMTP is used for sending a mail from one machine to another over the Internet. It is a
push protocol, that is, it sends the message from source machine to destination machine
whether the destination machine wants it or not.
When a source machine wants to send a message, it establishes a TCP connection
with the destination machine. Once the TCP connection is established, the sending machine
(that acts as client) waits for the destination machine (that acts as server) to be ready.
The server initiates by sending a text message containing its id to tell the client, it is
ready. In case the server is not ready, the connection is released by the client and is tried
again.
If the server is ready for receiving mail, the client tells it the sender and the
recipient of the message. If that recipient exists, the server allows the client to send the
message. Once the message is received by the server, it sends the acknowledgement to
the client.
Post Office Protocol Version 3 (POP3)
POP3 is a standardized protocol that allows a user to access the mail box on the mail
server. POP3 begins when the user runs the mail reader. The mail reader establishes the
TCP connection with the server. Once the connection is established, POP3 passes through
three stages which are as follows:
Authorization: It deals with the login of the user. After the successful login, user
can access his mail box.
Self-Instructional
12 Material
Internet
NOTES
Transaction: During this state, user can retrieve and download messages on the
local system.
Update: In this phase, all the messages are deleted on the server side and TCP
connection is broken.
Internet Message Access Protocol Version 4 (IMAP4)
Like POP3, IMAP4 is a protocol that allows to access the mail box. However, unlike
POP3, in which generally all the stored messages are downloaded and mail box is cleared
off, in IMAP4, all the messages remain stored on the server for indefinite period. This
protocol assumes that all the messages are not transferred to the local system.
1.10 INTERNET APPLICATIONS
Internet user has access to a wide variety of services such as electronic mail, file transfer,
vast information resources, interest group membership, interactive collaboration,
multimedia displays, real-time broadcasting, shopping opportunities, and much more.
Some of the Internet applications are described in this section.
E-mail
E-mail or electronic mail is the most commonly used Internet service. It refers to the
facility of sending and receiving messages electronically over a network of computers.
Sending and receiving e-mails requires a user to have an e-mail address (sometimes
called an e-mail account or an e-mail ID) in any of the websites that provides e-mail
service. A number of websites, such as www.yahoo.com, www.gmail.com,
www.rediffmail.com and www.hotmail.com, provide the facility to create free e-mail
account. Note that since, multiple users can access the Internet at the same time; the e-
mail address must be unique for each Internet user.
An e-mail address is divided into two parts, namely, username and the mail server
name. The two parts are separated by the symbol @. The structure of an e-mail address
is as follows:
username@mailservername.com
For example, itl.esl@gmail.com is an e-mail address where,
itl.esl = the username
gmail = the name of the mail server
.com = a commercial website
Though e-mail is a very popular service of the Internet because of its numerous
advantages, it has few disadvantages also. The advantages and disadvantages of e-mail
are as follows:
Advantages
The advantages of e-mail are as follows:
It is very fast medium of communication. The messages can be sent in no time
irrespective of the distance.
It is a very economic medium of communication. You are only charged the cost of
being online whether you are sending it overseas or down the road.
Self-Instructional
Material 13
Internet
NOTES
Any form of data such as text, graphics, sound, or video can be sent through
e-mails.
It is secure medium of communication, that is, no one can access anybodys
e-mail account without knowing the password.
Disadvantages
The disadvantages of e-mail are as follows:
A slight error in the e-mail address of the recipient is enough to prevent the
delivery of the message and even when you do everything right, there is always a
chance of failure in one of the links between you and your recipient.
Sometimes viruses can enter into your system through the attachments received
in e-mails.
Multicast Backbone
Mbone (Multicast Backbone) is a kind of virtual network running over the top of Internet.
Mbone finds its application in conducting audio and video conference among users located
geographically apart. Today, many researchers use Mbone to develop protocols and
applications for group communication. Earlier, it was almost impossible to transmit audio
or video files over the Internet. However, today with Mbone, the audio or video conference
can be conducted without any difficulty in spite of limited bandwidth available and variable
packet delivery delays on the Internet. Moreover, Mbone also compresses the data and
provides privacy by using encryption techniques.
Usenet (Net News)
On the Internet, one can also share news, views, ideas and information on any topic like
politics, science, computers, etc. This can be accomplished using a newsgroup service.
A newsgroup, also known as a Usenet, is an online discussion group on the Internet
who share a common interest. Many websites, like www.NewsOne.net, www.google.com,
www.Usenet-Replayer.com, etc., provide the facility of newsgroups.
People interested in a specific topic write articles and post them to the bulletin
board of the newsgroup server (a machine that posts the message for everyone to read)
so that others can read, reply and comment on them. You can read and post newsgroup
articles using newsreader software such as Microsoft Outlook Express News or Netscape
News or using a web browser like Internet Explorer.
1.11 SUMMARY
In this unit, you have learned that:
The Internet is basically a network of networks that facilitates data transmission
and exchange, across the million of domestic, academic, business and government
networks.
When ARPANET was developed, the DOD established a committee known as
Internet Activities Board (IAB) to monitor and control the development of Internet.
In 1989, the IAB committee was divided into two groups, namely, Internet Research
Task Force (IRTF) and Internet Engineering Task Force (IETF). The idea
underlying the reorganization is to make IRTF focus on long term research and
IETF to handle short term engineering issues.
Check Your Progress
13. Which of these
protocols is
designed to
support
multicasting?
(a) SMTP
(b) IGMP
(c) ICMP
(d) none of these
14. In which of these
Internet mail
protocols do all the
messages remain
stored on the
server for
indefinite period?
(a) SMTP
(b) POP3
(c) IMAP4
(d) none of these
15. Which of these is
used in conducting
audio and video
conference among
users located
geographically
apart?
(a) Mbone
(b) E-mail
(c) Usenet
(d) all of these
Self-Instructional
14 Material
Internet
NOTES
An ISP is an organization that provides access to the Internet. It charges a monthly
fee and subscribes you as a user to connect to the Internet.
Internet backbone acts as interconnecting structure used to connect one or more
networks and gateway is a device used to connect dissimilar networks.
The process of locating information on the Internet is called Internet surfing or
Internet browsing.
Some of the ways through which Internet security can be provided are
authentication, authorization, cryptography, firewall, cyber laws, digital signature,
etc.
The TCP/IP is a layered set of protocols that handles the way data is transmitted
across the Internet.
The File Transfer Protocol is a set of rules that enables a user to transfer files
from one system to another.
Network News Transfer Protocol is a protocol, which is used by computer clients
and servers to manage the news posted on newsgroup.
Every machine on the Internet is identified by a numerical address known as IP
address. There exists a domain name that corresponds to an IP address. The
mapping between the domain name and its associated IP address is performed by
an Internet service known as domain name system (DNS).
A routing protocol is a set of rules and procedures which specifies how routers
share information with each other for routing purposes.
An autonomous system (AS) is a group of networks and routers which is controlled
by a single administration. Interior gateway protocol is a routing protocol which is
used for routing purpose within an AS. Exterior gateway protocol is a routing
protocol which is used for routing purpose across one or more autonomous systems.
An ICMP packet is encapsulated inside an IP packet and is responsible for error
free transmission of IP packets over the network.
Internet Group Management Protocol (IGMP) protocol is designed to support
multicasting. Multicasting is a process in which a message is sent to a large
number of hosts belonging to a group.
Simple Mail Transfer Protocol (SMTP) is used for sending a mail from one machine
to another over the Internet.
Post Office Protocol Version 3 (POP3) is a standardized protocol that allows a
user to access the mail box on the mail server.
IMAP4 is a protocol that allows accessing the mail box. In IMAP4, all the messages
remain stored on the server for indefinite period.
E-mail or electronic mail is the most commonly used Internet service which refers
to the facility of sending and receiving messages electronically over a network of
computers.
Mbone (Multicast Backbone) is a kind of virtual network running over the top of
Internet. Mbone finds its application in conducting audio and video conference
among users located geographically apart.
A newsgroup, also known as a Usenet, is an online discussion group on the Internet
who share a common interest.
Self-Instructional
Material 15
Internet
NOTES
1.12 KEY TERMS
Internet Service Provider (ISP): It is an organization that provides access to
the Internet.
Internet surfing or Internet browsing: It is the process of locating information
on the Internet.
Authentication: It is the process of determining whether the user is allowed to
access the computer.
Authorization: It is the process of specifying whether the user is granted
permission to use certain resources.
Cryptography: It is the process of encrypting or modifying the messages to hide
its meaning from the unauthorized users who try to intercept it.
Firewall: A firewall is a part of a computer system or network which is placed
between an internal network and Internet.
Protocol: It is referred to as the formal set of rules and conventions that govern
how different computer devices communicate with each other.
TCP/IP: It is a layered set of protocols that handles the way data is transmitted
across the Internet.
Hypertext transfer protocol (HTTP): It is a protocol that facilitates accessing
hypertext documents.
File Transfer Protocol (FTP): It is a set of rules that enables a user to transfer
files from one system to another.
Network News Transfer Protocol (NNTP): It is a protocol, that is used by
computer clients and servers to manage the news posted on newsgroup.
Routing protocol: It is a set of rules and procedures which specifies how routers
share information with each other for routing purposes.
Autonomous System (AS): It is a group of networks and routers which is
controlled by a single administration.
Multicasting: It is a process in which a message is sent to a large number of
hosts belonging to a group.
Internet mail protocol: It is a protocol which is used by mail clients to exchange
information with the mail servers.
1.13 ANSWERS TO CHECK YOUR PROGRESS
1. ARPANET
2. The Internet Architecture Board was established to monitor and control the
development of Internet. It was responsible for deciding the standards required
and how these standards should be implemented to control the working of Internet.
3. Gateway
4. The process of locating information on the Internet is called Internet surfing or
Internet browsing.
5. (d)
Self-Instructional
16 Material
Internet
NOTES
6. Authentication is the process of determining whether the user is allowed to access
the computer, whereas authorization is the process of specifying whether the
user is granted permission to use certain resources.
7. False
8. (c)
9. Domain name system (DNS)
10. Routing Information Protocol (RIP), Open Shortest Path First (OSPF)
11. Path vector routing
12. Source quench
13. (b)
14. (c)
15. (a)
1.14 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What are the types of Internet connections provided by ISPs?
2. How does the Internet work?
3. What do you understand by Internet addressing?
4. What is the role IGMP protocol?
5. What are the various Internet routing protocols?
Long-Answer Questions
1. What are the common Internet security threats faced today? Also describe some
of the ways through which Internet security can be provided.
2. Discuss some Internet protocols used for communication between different
devices.
3. Explain various ICMP messages.
4. Describe the various Internet mail protocols.
5. Write short notes on the following Internet applications:
(a) E-mail
(b) Multicast Backbone
(c) Usenet
Self-Instructional
Material 17
Web: World Wide Web
NOTES
UNIT 2 WEB: WORLD WIDE WEB
Structure
2.0 Introduction
2.1 Unit Objectives
2.2 The Web: Advantages and Terminology
2.2.1 Web Terminology
2.3 Web Access Using Web Browser
2.4 Locating Information on the Web
2.5 Summary
2.6 Key Terms
2.7 Answers to Check Your Progress
2.8 Questions and Exercises
2.0 INTRODUCTION
The concept of the Web emerged at CERN (the European Council for Nuclear Research)
Geneva, Switzerland, in the year 1989. Since then, WWW is the most popularly used
Internet sub network. The CERN team developed the protocol based on hypertext that
makes it possible to connect content on the Web with hyperlinks. Earlier, the Internet
was largely a text-based system. However, the WWW permitted access to information
using a Graphical User Interface (GUI) and the use of hypertext links to access
information across the network without being a computer expert and without knowing
the exact physical location.
2.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Understand World Wide Web and its advantages
Define some Web-related terms and technologies
Understand how to access Web using a Web browser
Explain how to locate information on the Web
2.2 THE WEB: ADVANTAGES AND TERMINOLOGY
The World Wide Web (WWW) or W3 or simply the Web is a collection of linked documents
or pages, stored on millions of computers and distributed across the Internet. Some of
the advantages of WWW that led to its popularity are as follows:
It provides information in multimedia form, that is, in more than one medium such
as text, graphics, video and audio.
It provides a simple and consistent way of accessing the information available on
the Internet by using hypertext. The hypertext is a system in which the documents
contain links to other pages on the Internet. These links are called hyperlinks.
Note: The term World Wide Web is not a synonym of the Internet; it is one of the
services provided by the Internet.
Self-Instructional
18 Material
Web: World Wide Web
NOTES
2.2.1 Web Terminology
Some of the terms and technologies related to the Web are discussed in this section.
Web Page
A Web page is a document on the WWW that can include text, images, audio, video, etc.
A Web page is of two types, namely, static Web page and dynamic Web page. A static
Web page sends the same information to every end-user, whereas a dynamic Web page
customises the information according to the end-user.
Website
A collection of related Web pages stored on a Web server is known as a Website. A
Website is owned and maintained by a person, group, company or an organisation. Each
Website is accessed by its address known as URL (Uniform Resource Locator). All
the Websites on the Internet constitute the World Wide Web.
Home Page
A home page (also called index page) refers to the Web page that identifies the Website
and contains the hyperlinks to other Web pages in a Website. A Website may have
hundreds of pages or may consist of one page only.
Web Portal
A Website that acts as a gateway to a broad range of other sites on the Internet is
known as Web portal or simply a portal. In other words, a portal has a catalogue of
other Websites. It may also offer various other resources and services like a search
engine, e-mail, chatting, on-line shopping, horoscopes, latest news, etc. The first Web
portal was America Online (AOL). Some of the popular Web portals used today are
yahoo.com, rediff.com and indiatimes.com.
Web Browser
A Web browser is a software application that enables to view and navigate information
on the Web. A Web browser uses the HTTP protocol to request Web pages from the
Web. A Web browser may be text or graphical browser. For example, Lynx is the text-
based Web browser whereas Netscape Navigator and Internet Explorer are commonly
used graphical Web browsers.
Web Server
The Web pages on the Internet are stored on the computers that are connected to the
Internet. These computers are known as Web servers. Any computer that has a server
software installed on it and is connected to the Internet can act as a Web server. The
Web browsers and the Web servers are linked together using the client/server architecture.
The Client/Server Architecture
The client/server architecture is a network architecture in which each computer on the
network is either a client or a server. Servers are the computers that provide services to
other computers attached to them. The services may include file transfer, printing files,
sharing data, sending information, etc. On the other hand, clients are PCs or workstations
that request for different types of services provided by the server. In terms of the
Internet, Web browsers are the clients that request for the Web pages residing on the
Self-Instructional
Material 19
Web: World Wide Web
NOTES
Web server and the Web server fulfills their requests by sending the Web pages. Web
servers provide services to Web browser using the HTTP protocol.
2.3 WEB ACCESS USING WEB BROWSER
A Web browser is a software application that is used to view and browse information on
the Web. With the help of a Web browser, one can easily visit various Websites and
gather competitive information, conduct market research, and stay in touch with the
current happenings.
Internet Explorer is the most widely used Web browser developed by Microsoft.
Let us take an example to illustrate how Web can be accessed using Internet Explorer.
Open and Navigate a Website
Open Internet Explorer by double clicking the Internet Explorer shortcut icon placed on
the desktop. After opening the Internet Explorer, enter the address of the Website, that
is, URL in the address bar and press Enter to open the Website. The home page of the
Website is displayed. You can move around the home page using various methods, which
are as follows:
Using the vertical or horizontal scroll bars to move around a document.
Pressing the Up and Down arrow keys to move up or down one line.
Pressing the Page Up key to move up one window length and Page Down to
move down one window length.
Pressing Ctrl+Home and Ctrl+End to go to the beginning of the document and
the end of the document, respectively.
The home page displays various hyperlinks which link to other Web pages or to the other
parts of the same Web page. To open a hyperlink, just click any of the hyperlinks to open
the linked document. Alternatively, right-click on the hyperlink and select the Open
option from the shortcut menu to open the Web page in the same window or select the
Open in New Window to open the Web page in a new window (see Figure 2.1).
Figure 2.1 Home Page of a Website
Check Your Progress
1. WWW is a simple
way of accessing
information
available on the
Internet by using
_________.
2. Which of these is a
software
application that
helps to view and
navigate
information on the
Web?
(a) Web page
(b) Web portal
(c) Web browser
(d) Web server
3. What is the client/
server architecture?
Self-Instructional
20 Material
Web: World Wide Web
NOTES
After browsing through several pages in a window, you can move backward and forward
by clicking the Back and Forward button on the Standard toolbar.
Save Text and Images
Internet Explorer helps not only to find the required information from the Internet but it
also allows saving the retrieved information on the local system for future reference. To
save part of the text from a Web page, select the text that has to be saved. Right-click
the selected text and then click Copy option from the shortcut menu that appears. Now
you can paste the selected text in any of the word processor such as Notepad, Wordpad,
MS Word, etc., and save it for future reference, as shown in Figure 2.2.
Figure 2.2 Saving the Text
Similarly, images can also be saved from a Web page. To save the image, right-
click the image and then click the Save Picture As option from the shortcut menu. This
displays the Save Picture dialog box. Select the location for the image from the Save in
drop-down list box and enter a name for the image in the File name box. Click Save to
save the image at the desired location, as shown in Figure 2.3.
Figure 2.3 Saving the Image
Self-Instructional
Material 21
Web: World Wide Web
NOTES
If you want to save the entire Web page, click the File menu and the click Save
As option to displays the Save Web Page dialog box. Select the location for the Web
page from the Save in drop-down list box and enter a name for the Web page in the File
name box. Click Save to save the Web page, as shown in Figure 2.4.
Figure 2.4 Saving a Web Page
Add to Favorites
Internet Explorer provides a feature called Favorites. This feature maintains a list
called the Favorites list, of all the Web pages that you visited and want to visit again. To
add a Web page to the Favorites list, follow these steps.
1. Open the Web page that you want to add to your favorites. Click Add to Favorites
option on the Favorites menu. The Add Favorite dialog box appears (see Figure
2.5).
2. Enter a different name for the Web page, if required, in the Name box.
3. Select the Make available offline check box to view the page even when you
are not connected to the Internet and click OK.
Figure 2.5 Add Favorite Dialog Box
Self-Instructional
22 Material
Web: World Wide Web
NOTES
After the Website is added to the favorites list, you can view it by clicking on the
desired link on the Favorites menu.
2.4 LOCATING INFORMATION ON THE WEB
Locating information on the Web is one of the most popular services provided on the
Internet. You can find information on various topics, such as science, travel, politics,
education, health, etc., on the Internet. In addition, the Internet can be used to find
people and retrieve information about them.
A search engine is software that enables you to search information on the Internet.
It displays the results of a search based on the criteria entered by the user. That is, the
user provides a keyword or a phrase that helps the search engine to start the search. For
example, to find information about the various generations of the computer, enter the
phrase generations of computer and the search engine will display a list of Web pages
containing the desired information.
A search engine mainlys uses three tools for searching, namely, a spider or a
crawler, an indexer and a search algorithm. A crawler searches the Internet for new
terms and stores the searched terms in a database. An indexer then indexes all the
terms in the database to make the searching process fast. A search algorithm is simply
a method by which the search engine performs a search based on the keywords entered
by the user. Google, Yahoo and Altavista are some popular search engines.
To find information using a search engine, follow these steps.
1. Start Internet Explorer.
2. Open the home page of any search engine. For example, open www.google.com.
Figure 2.6 Google Home Page
Self-Instructional
Material 23
Web: World Wide Web
NOTES
3. Enter the search keyword, for example, Internet in the search text box (see
Figure 2.6).
or
Click Advanced Search if you want to perform advanced search. A page with
various Advanced Search options appears (see Figure 2.7). Select the required
options from the page to set your Advanced Search.
Figure 2.7 Advanced Search Page
4. Click the Advanced Search button when you finish setting the options. A Web
page with a list of hyperlinks appears (see Figure 2.8).
Figure 2.8 List of Hyperlinks
Self-Instructional
24 Material
Web: World Wide Web
NOTES
5. Choose any hyperlink and click it to open the Web page in the same window.
or
Right-click the hyperlink and click Open in New Window from the shortcut
menu to open the Web page in a new window.
6. Keep clicking the hyperlinks on the main search page till you find the required
information.
The Internet also helps you in finding the information about your friends, relatives
and other people online. You can find and get any persons e-mail address, telephone
number, mailing address or any other information through the Internet (if available on the
Internet). To find information about a person, initially you have to provide some basic
information about that person like the first and the last name, city, state or country name,
etc. The Internet retrieves and displays a list of people from where you can search the
required information.
Some of the Websites that provide the facility of finding people online are
www.people.yahoo.com, www.batchmates.com and www.orkut.com. To find any of
your friends or relatives using the Internet, follow these steps.
1. Open the Website for people search. For example, open www.people.yahoo.com.
2. To make a phone and address search, enter the First name, last name, City/Town
and State in the respective text boxes and then click the corresponding Search
button (see Figure 2.9). A Web page with phone numbers and address information
appears.
Figure 2.9 Finding People
3. To search for the e-mail address, enter the First Name and Last Name in the
respective text boxes and then click the corresponding Search button (see Figure
2.9). A Web page with the e-mail information appears (see Figure 2.10).
Self-Instructional
Material 25
Web: World Wide Web
NOTES
Figure 2.10 Finding E-mail Address
4. Enter the required information in the respective text boxes and click Search. A
Web page with the e-mail information appears.
2.5 SUMMARY
In this unit, you have learned that:
The concept of the Web began at CERN (the European Center for Nuclear
Research) Geneva, Switzerland, in the year 1989. Since then, WWW is the most
popularly used Internet sub network.
The hypertext is a system in which the documents contain links to other pages on
the Internet. These links are called hyperlinks.
The World Wide Web (WWW) or W3 or simply the Web is a collection of linked
documents or pages, stored on millions of computers and distributed across the
Internet.
A collection of related Web pages stored on a Web server is known as a Website.
A Website that acts as a gateway to a broad range of other sites on the Internet
is known as Web portal
A Web browser is a software application that enables to view and navigate
information on the Web. A Web browser may be text or graphical browser.
The Web pages on the Internet are stored on the computers that are connected to
the Internet. These computers are known as Web servers.
The client/server architecture is a network architecture in which each computer
on the network is either a client or a server. Web servers provide services to Web
browser using the HTTP protocol.
Check Your Progress
4. Which of these
searches new terms
on Internet and
stores the searched
terms in a
database?
(a) Crawler
(b) Indexer
(c) Search
algorithm
(d) None of these
5. Define search
engine.
6. What shortcut
keys can be used
to go to the
beginning of the
document and the
end of the
document,
respectively?
7. Which feature of
Internet Explorer is
used to organize
the frequently
visited Websites?
Self-Instructional
26 Material
Web: World Wide Web
NOTES
Locating information on the Web is one of the most popular services provided on
the Internet.
A search engine is software that enables you to search information on the Internet.
It displays the results of a search based on the criteria entered by the user. A
search engine mainly uses three tools for searching, namely, a spider or a crawler,
an indexer and a search algorithm.
2.6 KEY TERMS
World Wide Web (WWW) or W3: It is a collection of linked documents or
pages, stored on millions of computers and distributed across the Internet.
Web page: It is a document on the WWW that can include text, images, audio,
video, etc.
Website: It is a collection of related Web pages stored on a Web server.
Home page (index page): It refers to the Web page that identifies the Website
and contains the hyperlinks to other Web pages in a Website.
Web portal (or simply a portal): It refers to a Website that acts as a gateway
to a broad range of other sites on the Internet.
Web browser: It is a software application that enables to view and navigate
information on the Web.
Client/server architecture: It is a network architecture in which each computer
on the network is either a client or a server.
Servers: They are the computers that provide services to other computers
attached to them.
2.7 ANSWERS TO CHECK YOUR PROGRESS
1. Hypertext
2. (c)
3. The client/server architecture is a network architecture in which each computer
on the network is either a client or a server. Servers are the computers that
provide services to other computers attached to them. On the other hand, clients
are PCs or workstations that request for different types of services provided by
the server.
4. (a)
5. A search engine is software that enables to search information on the Internet. It
displays the results of a search based on the criteria entered by the user.
6. To go to the beginning of the document, the Ctrl + Home key is pressed, while to
go to the end of the document, the Ctrl + End key is pressed.
7. Internet Explorer provides a feature called Favorites, which maintains a list called
the Favorites list of all the Web pages that the visited and wants to visit again.
Self-Instructional
Material 27
Web: World Wide Web
NOTES
2.8 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What is the reason for the popularity of WWW?
2. What is the difference between a static Web page and a dynamic Web page?
3. What do you understand by Web portal?
4. Differentiate between a Web browser and a Web server.
5. What are the main tools used by a search engine?
6. What type of information can be located on the Web?
Long-Answer Questions
1. Discuss the various methods that can be used to move around the home page.
2. Write short notes on:
(i) Web page
(ii) Website
(iii) Web browser
(iv) Client/server architecture
3. Describe the various steps to be taken to find information using a search engine.
4. Explain the various steps you would take to find any of your friends or relatives
using the Internet.
Self-Instructional
Material 29
Java and the Internet
NOTES
UNIT 3 JAVA AND THE INTERNET
Structure
3.0 Introduction
3.1 Unit Objectives
3.2 Basic Features of Java Programming Language
3.3 Difference between Java and C++
3.4 Java Applications and Applets
3.5 Java Compiler
3.6 Java Virtual Machine Concepts
3.7 Java Development Kit (JDK)
3.8 A First Look at Java Program
3.9 Running Java Applications
3.10 Command Line Arguments
3.11 Summary
3.12 Key Terms
3.13 Answers to Check Your Progress
3.14 Questions and Exercises
3.0 INTRODUCTION
Java, initially named as Oak, was developed by the team headed by James Gosling at
Sun Microsystems, USA in 1991. The first and foremost reason behind the development
of Java was the need for a platform-independent and portable software to be embedded
in the consumers electronic devices like remote controls, microwave ovens, etc. The
second reason that led to the growth of Java is the Internet and World Wide Web as
these media need portable and platform-independent programs. Gosling and other team
members developed Web applets using the new language that could run on all types of
computers. During 1993, first Web browser, namely HotJava was developed to locate
and run applet programs. This development made Java language popular for the Internet.
By the year 1996, Java became a general-purpose, object-oriented programming language
which was used for Internet programming. Soon, Java became popular and many Web
browsers, such as Internet Explorer, Netscape Navigator etc., incorporated the ability to
run Java applets. In this unit, you will learn about the various features of Java which
have made it a popular language for various Internet applications.
3.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Describe Java programming language and explain its features
Differentiate between Java and C++
Explain Java applications and applets
Understand the role of Java compiler
Explain the features of Java Virtual Machine
Identify the various tools in the Java Development Kit
Self-Instructional
30 Material
Java and the Internet
NOTES
Understand the simple Java program
Run Java application
Explain command line arguments
3.2 BASIC FEATURES OF JAVA PROGRAMMING
LANGUAGE
Java is a third generation programming language which implements most of the concepts
of OOPs. Java has become a popular language for Internet applications because of
various features which are as follows.
Simple: Java inherits the syntax of C/C++ and many of the OOPs features of
C++ thus one who has understood the concepts of object-oriented language can
learn Java with least effort. Moreover Java omits the complex and unreliable
code of C and C++ like operator overloading, pointers, preprocessor header files.
Java provides small and convenient ways to accomplish a given task.
Interpreted: Unlike other languages Java uses two-stage system as it uses both
compiler and interpreter for its program execution. First, the compiler converts
the program code to bytecode which in turn is converted to machine code on any
machine using the interpreter. The machine code so generated can be executed
irrespective of the system on which it is being executed.
Architecture-neutral (platform-independent): This feature makes Java
language very special. Java programs can run on any platform that is they can
run on different CPUs and on different operating system architectures. The
bytecode produced by Java compiler can be run on any machine which has Java
runtime environment.
Object-Oriented language: Java is an object-oriented language as everything
in Java is an object. The objects and classes contain the program code and data.
The Java object model is easily extensible and classes can be used anywhere in
the program in the form of packages.
Robust: Java is a robust language because of mainly two reasons. Firstly, it is a
strictly typed language that checks the code at the compile time. Secondly, Java
does memory management in an effective way. In C++, the programmer has to
manually deallocate the dynamic memory used by the objects. Java automatically
deallocates free memory that is no longer referenced by the objects (with the
help of garbage collector).
Distributed: Since Java is platform independent, it is suitable for developing
applications for the networks. Java can handle TCP/IP protocols and hence
applications developed in Java can access remote objects on Internet like any
object on a local system.
Multithreaded: Java supports multithreaded programming which allows us to
write a program that can perform more than one task simultaneously. User need
not wait for one program to finish one task before starting next task. For example,
user can listen to an audio clip while downloading the applet. This feature helps to
improve the performance of graphical applications.
Self-Instructional
Material 31
Java and the Internet
NOTES
High Performance: As stated earlier, the Java program is converted to bytecode
which is then converted to machine code using interpreter. Since bytecode is
highly optimized, it enables the JVM to execute programs at much faster rate.
Dynamic: It is dynamic in nature that is Java programs can link to new class
libraries, objects, methods, etc., at the run-time. Java language also provides the
facility to include the functions of other languages like C and C++. They are
referred to as native methods. These methods are also linked dynamically at
run-time.
3.3 DIFFERENCE BETWEEN JAVA AND C++
Both C++ and Java are object-oriented languages but they are very different from each
other. Some of the features of C++ language were deliberately removed and some new
features were added to make Java more flexible and reliable language. Some of the
differences between Java and C++ are as follows:
Java does not support multiple inheritance of classes directly.
The concept of multithreading is supported by Java.
The destructor function in Java is replaced by finalize method.
The keyword typedef is not supported by Java.
Java does not support pointers instead it uses implicit object references.
The virtual keyword is not supported in Java.
Java does not support the concept of global variables.
Java supports exception handling in different way than C++. It provides finally
clause for cleanup.
The non-primitive data types are allocated memory by using the new operator.
Java adds many features that are necessary for object-oriented programming.
3.4 JAVA APPLICATIONS AND APPLETS
In recent years, Java has become popular language for the programs that are required to
run on different systems. Java enables us to create three types of applications. First,
Java can be used to create a normal Java application. A Java application is quite
similar to any program written in C or C++ which gets the user input, performs calculations
and displays the result.
Second, Java can be used to create Web-based applications called applets. It
has completely changed the Internet programming. Applets are tiny programs that are
designed in such a way that they can be transmitted over the Internet. They can be
downloaded on demand and executed automatically by Java compatible Web browser.
They are used to handle user input, data supplied by the server and simple functions that
executes locally on the client machine.
Applet is dynamic, self-executing program and is intelligent enough that can change
it with the user inputs. The dynamic programs when downloaded and executed can
cause serious harms to the computer as it may contain viruses like Trojan horse and
Check Your Progress
1. Java was
developed at Sun
Microsystems in
1991 by the team
headed by______
2. First Web browser
HotJava was
developed in year
1993.
(True or False)
3. Java used both
_______ and
_________ for its
program execution.
4. Bytecode is
platform
independent.
(True or False)
5. Native methods
can be linked
dynamically
at_____.
Self-Instructional
32 Material
Java and the Internet
NOTES
malicious programs. These harmful programs may search the contents on local file
system of the client computer and may gather private information like credit card numbers,
passwords, etc. Earlier viruses were scanned before executing the downloaded program,
but Java has resolved the issue by confining the Java programs to Java execution
environment only.
3.5 JAVA COMPILER
In most of the programming languages, the program is converted to machine code either
by using compiler or interpreter. The machine code so generated is machine dependent
that is it may not run on the machine other than the one on which it is generated. Unlike
in case of other programming languages, the Java compiler does not convert source
code to machine code rather it converts source code to a special intermediate code
known as bytecode. The bytecode so generated is in the form of class files that can be
interpreted. The command used for compilation in Java is javac which converts the
corresponding Java file into class file. The bytecode is machine independent that is it can
be run on any machine with the help of Java virtual machine (JVM), which is discussed
in the next section.
Source Code Bytecode
Compiler
.java file .class file
Figure 3.1 Compilation of a Java Program
3.6 JAVA VIRTUAL MACHINE CONCEPTS
As discussed earlier, Java uses both compiler and interpreter. Source code written in
Java is compiled to generate bytecode and then this bytecode is interpreted to machine
instructions for specific machine. The bytecode generated by the compiler is not machine
specific. It is generated for the virtual machine that exists only inside the computer
memory known as Java Virtual Machine (JVM). This virtual machine is designed in
such a way that it can be implemented on the top of any existing processor and itself
acts as virtual processor chip. It hides the underlying operating system details from Java
applications. The process of converting source code to machine code is shown in
Figure 3.2.



Source Code Bytecode
Compiler Interpreter
Machine Code
JVM
Figure 3.2 Conversion of Source Code to Machine Code
JVM obtains the bytecode stream from the .class file in the form of series of
instruction. Each instruction consists of a one-byte opcode (a valid and understandable
command which tells the JVM what to do) and zero or more operands, which are
required to complete the opcode.
Self-Instructional
Material 33
Java and the Internet
NOTES
Some of the main components of JVM are stack, registers, garbage-collection heap and
method area.
Stack: JVM stacks are similar to the stacks used in C or other conventional
languages. It consists of frames that hold the state of Java method invocation. It
holds the local variables, parameters, its return value and the intermediate results.
JVM stack can not be manipulated directly and only pushing and popping of
frames can take place. When a method is invoked, the JVM pushes a new frame
into the stack and after the completion of execution of the method the frame is
popped and discarded by the virtual machine. The size of the JVM stack can be
fixed or may dynamically increase and decrease according to the requirement.
Registers: JVM uses different types of registers to control the stacks. Some of
the important JVM registers are:
o Optop: It points to the top of operand stack.
o Frame: It points to the current execution environment.
o Vars: It points to the local variables.
o Program counter: It keeps record of the next instruction in a program to
be executed.
Garbage-collection heap: Heap is a free memory space used for allocations to
the variables like arrays, class instances, etc., at runtime. Whenever memory is
allocated with the help of new operator, that memory space is allocated from the
heap. Heap provides an automatic storage management system known as garbage-
collection heap. Whenever there are objects which are no longer referenced,
then the runtime environment automatically reclaims the memory occupied by the
objects. Size of the heap may be fixed or may increase or decrease according to
the requirement.
Method area: Method area is a storage area for the compiled code. Although
the method area is a part of heap, there is no specific area where it exists. This
feature makes JVM more portable and secure. Size of the method area may be
fixed or may increase or decrease according to the requirement. Method area is
used to store:
o Runtime constant pool
o Field information
o Method information
o Code for methods and constructors
o Special methods that are used in class and instance initialization.
o Interface type initialization
The primitive data types that can be handled by the JVM are byte(8 bits), char(16
bits), short(16 bits), int(32 bits), float(32 bits), long(64 bits), double(64 bits).
3.7 JAVA DEVELOPMENT KIT (JDK)
JDK consists of various tools that are used to develop and execute Java programs. The
tools included in JDK are listed in Table 3.1.
Self-Instructional
34 Material
Java and the Internet
NOTES
Table 3.1 Tools in Java Development Kit
Tool Function
javac Java compiler that converts source code to Java bytecode
java Java interpreter that interprets class files generated by java compiler
and converts it to machine code
javadoc Document generator which automatically generates documentation
form source code
javah Generates C headers and a stub generator used for writing native
methods
javap The class file disassembler which enables to convert bytecode files to
a program description
jdb Java debugger which helps in tracking errors in the program
appletviewer Used for running and debugging Java applets without a web browser

3.8 A FIRST LOOK AT JAVA PROGRAM
Let us start learning Java with a simple Java program that prints a string on the screen.
Example 3.1: A simple Java program
class Sample
{
public static void main (String args[])
{
System.out.println(Welcome to Java Programming);
System.out.println(Its easy and simple.);
}
}
Though this program is the simplest one, it includes the basic features that every
Java program has. Let us now look at the features one by one.
Class Definition
The first statement class Sample declares a class where class is a keyword and
Sample is the identifier that indicates the name of the class. The opening and closing
curly braces { } enclose the definition of a class.
The Main Statement
The statement public static void main (String args[]) indicates the
main method. This method is the point where the execution of Java program begins.
Since, it is the startup point of any Java program, it is the most essential part of any Java
program.
This statement has keywords, namely, public, static and void. The descriptions
of these keywords are as follows.
public: It is an access specifier which specifies that the main method is
accessible to all other classes.
static: The main method is declared static which specifies that this method
belongs to the entire class. Interpreter use this method before the creation of
objects.
Check Your Progress
6. _________method
replaces destructor
function in Java.
7. Global variables
are supported in
Java. (True or
False)
8. Applets are tiny
programs that can
be downloaded
from the internet
and can be run on
Java compatible
Web browser.
(True or False)
9. _________command
converts the source
code to
intermediate
bytecode.
10. Name some of the
important JVM
registers.
11. What is the role of
garbage-collection
heap?
12. JDK is a set of
various tools used
to develop and
execute java
programs.
(True or False)
Self-Instructional
Material 35
Java and the Internet
NOTES
void: The void keyword specifies that the main method does not return a
value. The pair of parentheses contains the declaration of the parameters of the
methods. In the above statement, the String args[ ] declares a parameter
args, that contains an array of objects of the class type String.
The Output Statement
The statements System.out.println(Welcome to Java
Programming.);
and System.out.println(Its easy and simple.); are used to
display information on the standard output device, that is the println() is a method
of the out object, which is the static member of class System. These statements will
display the following strings on the monitor.
Welcome to Java Programming.
Its easy and simple.
The statements will be printed in separate lines as the method println()
appends a newline character at the end of the string. However, if we use print()
method instead of println() newline character is not appended at the end of the
string. Note that like C++, every statement in Java must end with a semicolon.
3.9 RUNNING JAVA APPLICATIONS
A program can be created using any text editor. Nowadays, there are several text
editors available for writing programs like Notepad, Jcreator, etc. After creating the file,
save the file with the name <filename>.Java. The name of the file must be same
as that of the class name containing the main() method.
Once the file is created, it can be compiled to generate the bytecode using Java compiler
javac as given here.
javac Sample.java
If the source code is error free then the compiler creates a file containing the
bytecode and the file will be named as <filename>.class. In our example, the
name of file will be Sample.class.
Even though after compilation, the source code is converted into its equivalent
bytecode, it cannot be executed. To execute this bytecode, it needs to be converted to
machine code using the interpreter. The command for converting bytecode to machine
code and run it is as follows:
java Sample
After giving this command, the interpreter searches for the main() method in
the source code and starts executing the instructions written in this method and displays
the corresponding output.
3.10 COMMAND LINE ARGUMENTS
Like C++, Java enables to pass arguments to the main() method also. These arguments
are passed by typing them after the program name on the command line. Hence, these
arguments are known as command line arguments. They help in providing data to the
program.
Self-Instructional
36 Material
Java and the Internet
NOTES
As stated earlier, the argument named as args of String type is passed to the
main method. It is this argument which will receive any data passed to the program
through command line.
Example 3.2: A program to demonstrate the use of command line arguments
class CommandLineArg
{
public static void main(String args[])
{
System.out.println(The arguments entered are: );
int a;
for (a=0;a<args.length;a++)
{
System.out.print(args[ + a + ]: );
System.out.println(args[a]);
}
int b=args.length; // returns the number of
arguments
System.out.println(The number of arguments is:
+b);
}
}
The command entered on the command prompt is as follows:
java CommandLineArg Hello! How are you?
The output of the program is as follows:
The arguments entered are:
args[0]: Hello!
args[1]: How
args[2]: are
args[3]: you?
The number of arguments is: 4
3.11 SUMMARY
In this unit, you have learned that:
Java, initially, named Oak was developed by the team headed by James Gosling
at Sun Microsystems of USA in 1991.
Java inherits the syntax of C/C++ and many of the OOPs features of C++. Thus,
one who is familiar with the concepts of object-oriented language can learn Java
with least effort.
Java uses two-stage system as it uses both compiler and interpreter for its program
execution.
Applets are tiny programs that are designed in such a way that they can be
transmitted over the Internet.
Check Your Progress
13. The statement
class sample
declares a class
with name
sample. (True or
False)
14. ________ access
specifier states
that main()
method is
accessible to all
other classes.
15. String args[]
declares a
parameter args
which contains an
array of objects.
(True or False)
16. ___________
statement is used
to display
information on the
standard output
device.
17. What are command
line arguments?
Self-Instructional
Material 37
Java and the Internet
NOTES
Java compiler does not convert source code to machine code rather it converts
source code to a special intermediate code known as bytecode.
The command used for compilation in Java is javac which converts the
corresponding Java file into class file.
Bytecode is generated for the virtual machine that exists only inside the computer
memory known as Java Virtual Machine (JVM).
JDK consists of various tools that are used to develop and execute Java programs.
Some of the tools included in JDK are javac, java, javadoc, javap, etc.
The access specifier public specifies that the main method is accessible to
all other classes.
The void keyword specifies that the main method does not return a value.
3.12 KEY TERMS
Bytecode: It is one of the codes which gets converted to machine code by the
compiler for its program execution.
Native Method: It refers to the facility provided by the Java language to include
the functions of other languages like C and C++.
Architecture-neutral: It is one of the features of Java which helps Java programs
to run on any platform.
Java Compiler: It helps to convert the source code to a special intermediate
code.
Command line arguments: These are arguments which are passed by Java to
the main( ) method.
Java Virtual Machine: It refers to the virtual machine that exists only inside the
computer memory.
3.13 ANSWERS TO CHECK YOUR PROGRESS
1. James Gosling
2. True
3. Compiler, interpreter
4. True
5. run-time
6. finalize
7. False
8. True
9. javac
10. Some of the important JVM registers are:
Optop
Frame
Vars
Program counter
Self-Instructional
38 Material
Java and the Internet
NOTES
11. Heap provides an automatic storage management system known as garbage-
collection heap. Whenever there are objects which are no longer referenced,
then the runtime environment automatically reclaims the memory occupied by the
objects.
12. True
13. True
14. public
15. True
16. System.out.println()
17. Java enables to pass arguments to the main() method also. Command line
arguments are passed by typing them after the program name on the command
line. Hence, these arguments are known as command line arguments.
3.14 QUESTIONS AND EXERCISES
Short-Answer Questions
1. Why is Java called an object-oriented language?
2. What are applets?
3. What is the benefit of multithreaded programming?
4. What is the function of javap?
Long-Answer Questions
1. Explain all the tools of Java Development Kit along with their functions.
2. Mention some of the differences between Java and C++.
3. Explain the steps involved in running Java applications.
4. Explain all the basic features of Java in detail.
Self-Instructional
Material 39
Programming
Elements of Java
NOTES
UNIT 4 PROGRAMMING ELEMENTS
OF JAVA
Structure
4.0 Introduction
4.1 Unit Objectives
4.2 Character Set
4.3 Tokens
4.3.1 Keywords
4.3.2 Identifiers
4.3.3 Constants
4.3.4 Operators
4.3.5 Punctuators
4.4 Structure of a Java Program
4.5 Data Types
4.5.1 Primitives Data types
4.5.2 Non-Primitive Data types
4.6 Variables
4.7 Type Casting
4.8 Operators and Operations
4.8.1 Arithmetic Operators
4.8.2 Increment and Decrement Operators
4.8.3 Relational Operators
4.8.4 Logical Operators
4.8.5 Conditional Operator
4.8.6 Assignment Operators
4.8.7 Other Operators
4.8.8 Operators Precedence and Associativity
4.9 Summary
4.10 Key Terms
4.11 Answers to Check Your Progress
4.12 Questions and Exercises
4.0 INTRODUCTION
In any programming language, writing even an elementary program requires the knowledge
and clear understanding of various data types, variables, constants and operators provided
by that language. All these constitute the most basic elements of a language which are
combined to form an instruction and a set of these instructions constitute a program. In
this unit, you will learn about these basic programming elements of Java.
4.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Discuss the character set and different tokens supported by Java
Describe the structure of a Java program
Discuss various primitive and non-primitive data types supported by Java
Self-Instructional
40 Material
Programming
Elements of Java
NOTES
Explain how to declare, initialize and assign values to a variable
Describe type casting
Explain the different types of operators and the operations that can be performed
4.2 CHARACTER SET
A character set can be defined as a set of characters that either individually or in
combination, represent information. Unlike other programming languages like C and
C++, Java uses a standard known as unicode to define characters. Unicode is a 16 bit
character code set which defines all of the characters available in all human languages
like English, Hindi, French, German, Chinese, Japanese, etc. This makes Java a worldwide
programming language. However, the characters of many languages can be represented
using the standard 8 bit character set (ASCII characters) which include letters, digits
and punctuation marks.
4.3 TOKENS
A token is defined as the smallest unit of a program. When a program is compiled, the
compiler scans the source code and parses it into tokens to find the syntax errors. Java
tokens are broadly classified into keywords, identifiers, constants, operators and
punctuators.
4.3.1 Keywords
Keywords are the predefined words that have special significance in any language.
Every keyword is reserved for a specific purpose and hence cannot be used as user-
defined names (identifiers). There are various keywords in Java, which are listed in
Table 4.1.
Table 4.1 Java Keywords
Keywords
abstract const final interface short transient
assert continue finally long static try
boolean default for native strictfp void
break do goto new super volatile
byte double if package switch while
case else instanceof private synchronized
catch enum implements protected this
char extends import public throw
class float int return throws

Notes: The keywords const and goto are reserved words but they are not used.
4.3.2 Identifiers
Identifiers are the names given to uniquely identify various programming elements like
variables, arrays, methods, classes, objects, packages, interface and so on. While
defining identifiers in Java, programmers must follow the rules listed below.
Self-Instructional
Material 41
Programming
Elements of Java
NOTES
An identifier must be unique in a program.
Alphabets, digits, underscore and dollar sign characters can be used in an identifier.
An identifier must not start with a digit.
An identifier in upper case is different from that in lower case.
An identifier must not contain other characters such as *, ; and white space
characters (tabs, space and newline).
Some valid and invalid identifiers in Java are listed here.
Pol78_ddm //valid
hh$gl //valid
_78hhvt4 //valid
902gt1 //invalid as it starts with a digit
Tyy;ui8 //invalid as it contains the ; character
for //invalid as it is a Java keyword
Fg026 neo //invalid as it contains spaces
4.3.3 Constants
Constants, also known as literals, are the values that a program cannot alter during its
execution. For example, 391, Byron, 51.072 and p are all constants. Based on
the type of value (data), Java constants are broadly classified into four categories, namely,
numeric constants, character constants, string constants and boolean constants.
Numeric Constants
Numeric constants refer to the numbers consisting of a sequence of digits (with or
without decimal point) that can be either positive or negative. By default, numeric constants
are positive. Numeric constants can be further classified as integer constants and
floating-point constants which are listed in Table 4.2.
Table 4.2 Types of Numeric Constants
Type Description Example
Integer Constants Integer constants refer to integer-valued
numbers. Integer constants can be represented
by three different number systems namely,
decimal (base 10), octal (base 8) and
hexadecimal numbers (base 16). The octal
constants are preceded by a 0 (zero) and
hexadecimal constants are preceded by a 0x or
0X.
54, -646, 01612,
0x38A
Floating Point Constants Floating-point constants refer to the real
numbers, that is, the numbers with a decimal
point. Floating-point constants are also written
in the floating-point notation in which the
constant is divided into a mantissa and an
exponent. Floating point constants default to
double precision, so we should append an F or
f to the constant in order to specify a float
constant.
64.23f, -74.32f,
537E-9f, 15e-3f

Note: Use of special characters like comma ,, semicolon ;and question mark ?
are not permitted in numeric constants.
Self-Instructional
42 Material
Programming
Elements of Java
NOTES
Character Constants
Character constants refer to a single character enclosed in single quotes (). The
examples of character constants are f, M, 8, &, etc. All character constants are
internally stored as integer value.
Character constants can represent either the printable characters or the non-
printable characters. The examples of printable character constants are a, 5, #,
;, etc. However, there are a few character constants that cannot be included in a
program directly through a keyboard such as backspace, new line and so on. These
character constants are known as non-printable constants and are included in a program
using the escape sequences. An escape sequence refers to a character preceded by
the backslash character (\). Some of the escape sequences used in Java are listed in
Table 4.3.
Table 4.3 Escape Sequences
Escape Sequences Character Constants
\b Backspace
\f Form feed
\n Newline (Linefeed)
\r Carriage return
\t Tab
\ Single quote
\ Double quote
\\ Backslash
String Constants
String constants refer to a sequence of any number of characters enclosed in the
double quotes (). The characters can be alphabets, digits, special characters and blank
spaces. The examples of string constants are hello java, 2009, !...?, 6+9,
Y, etc.
Boolean Constants
Boolean constants can represent only two values, true and false. In Java, there is
no numerical representation for these values, that is, true is not equal to 1 and false
is not equal to 0.
4.3.4 Operators
Operators are the symbols which perform operations (such as addition, subtraction,
multiplication etc.) on various data items to produce a result. These data items on which
operators act are known as operands. For example, in a*b, a and b are operands and
* is an operator.
4.3.5 Punctuators
Punctuators, also known as separators, are the symbols that define the structure of a
program by dividing and arranging a set of codes. The various punctuators defined are
braces { }, brackets [ ], colon :, comma ,, period ., semicolon ; and parentheses
( ).
Check Your Progress
1. In Java,_______ is
a 16 bit character
set which defines
characters found in
all human
languages.
2. Why do we need to
append an f or F
to a floating point
constant?
3. A keyword can be
used as an
identifier.
(True or False)
4. Briefly state the
rules for defining
an identifier in
Java.
5. _____is the
starting point of a
Java program.
6. Which of the
following is an
invalid identifier?
(a) pq_hr
(b) void
(c) na60f
(d) t$ggl
Self-Instructional
Material 43
Programming
Elements of Java
NOTES
4.4 STRUCTURE OF A JAVA PROGRAM
The Java program structure is divided into various sections, namely, documentation
section, package statement, import statements, interface statements, class definitions
and main method class (see Figure 4.1).

Documentation Section

Package Statement

Import Statements

Interface Statements

Class Definitions

Main Method Class
Figure 4.1 Java Program Structure
These sections are discussed as follows:
Documentation Section: Comments are vital elements of a program that are
used to increase its readability and describe its functionality. They may also include
information like program name and the author of the program, etc.
Package Statement: It is the first statement in Java program that tells the compiler
that all the classes defined in the file belong to this package. For example, consider
this statement.
package employee;
Here, employee is the name of the package. It is not necessary that our classes
are part of package, so this statement is optional.
Import Statements: It allows us to access a class which belongs to some other
package. For example, consider this statement.
import employee.EName;
Here, employee is the name of the package and EName is the class which we
want to access. There can be a number of import statements in a program.
Interface Statements: An interface is way for implementing multiple inheritance
in Java. It is just like a class but contains only method declarations.
Class Definitions: Class is the most important element of a program. A program
may consist of any number of class definitions.
Main Method Class: It is an essential part of a Java program as it contains the
main method which is the starting point of a program. Inside the main method
class, the objects of several classes can be created, accessed and manipulated.
Once all the instructions in the main method are executed, the control is transferred
out of the class thus terminating the entire program.
Self-Instructional
44 Material
Programming
Elements of Java
NOTES
4.5 DATA TYPES
A data type determines the type and the operations that can be performed on the data.
Java provides various data types and each data type is represented differently within the
computers memory. The type of data selected by a programmer depends on the particular
application. The various data types provided by Java are categorized into primitive data
types and non-primitive data types. (see Figure 4.2).

Data Types
Primitive
Data types
Non-primitive
Data types
Classes Arrays Interface
Integer
Floating-point Character Boolean
Figure 4.2 Data Types
4.5.1 Primitives Data Types
Primitive data types also known as built-in data types are the fundamental data types
provided by a programming language. In Java, primitive data types include integer,
floating point, character and boolean.
Integer Type
The integer data type is used to store integers like 4, 42, 5233, -32, -745. Java
supports four types of integers namely, byte, short, int and long. The default
value of these integer types is 0. There is no concept of unsigned integer in Java. The
various integer data types with their size and range are listed in Table 4.4.
Table 4.4 Size and Range of Integer Types
Type Size(bytes) Range
byte One -128 to 127
short Two -32,768 to 32,767
int Four -2,147,483,648 to 2,147,483,647
long Eight -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Note: It is recommended to use smaller data types whenever possible. This is
because larger the data type we choose, more time the program will take for
execution.
Floating Point Type
A floating point data type is used to store real numbers such as 3.28, 64.755765, -
8.01, -24.53. Java supports two floating point data types, namely, float and
double.
Self-Instructional
Material 45
Programming
Elements of Java
NOTES
float: The float type represents a single-precision number. Single precision
occupies lesser space than double precision but becomes inaccurate when the
values are large. For example, it can be used to represent value of marks of the
students. The default value of float data type is 0.0f.
double: The double type specifies a double-precision number. It is the best
choice when we need to store large-valued numbers. For example, it can be used
when we want to use mathematical functions like sin(), cos(), sqrt().
The default value of double data type is 0.0d.
The various floating point data types with their size and range are listed in
Table 4.5.
Table 4.5 Size and Range of Floating Point Types
Type Size(bytes) Range
float Four 3.4e-038 to 3.4e+038
double Eight 1.7e-308 to 1.7e+308
Character Type
The character data type is used to store single character enclosed in single quotes. It is
represented by using char keyword. It occupies 16 bits of memory. The range of the
character data type is 0 to 65,536. The default value of char data type is null
character.
Boolean Type
The boolean data type can hold only boolean values, that is, either true or false. The
keyword boolean is used to denote the boolean data type. The default value of
boolean data type is false.
4.5.2 Non-Primitive Data types
Non-primitive data types (user-defined data types) also known as reference types are
derived from the primitive data types. In Java, these include classes, interface and
arrays.
Note: The non- primitive data types classes and arrays are discussed in detail in
the later chapters.
4.6 VARIABLES
A variable is an identifier that represents a memory location that is used to store data
value. Data stored at a particular location can be accessed using the variable name. The
value of a variable can be changed anytime during the program execution. The variable
name we choose must be meaningful so as to understand what it represents in the
program.
Declaring Variables
Variables must be declared in a program before they are used. The declaration of a
variable informs the compiler, the specific data type to which a variable is associated
and allocates sufficient memory for it.
Self-Instructional
46 Material
Programming
Elements of Java
NOTES
The syntax for declaring a variable is
data_type variable_name;
For example, a variable a of type int can be declared using this statement.
int a;
At the time of the variable declaration, more than one variable of the same data type can
be declared in a single statement. For example, consider this statement.
int x, y, z;
Initializing Variables
Declaration of variables allocates memory for variables but it does not store any data at
the time of declaration. To store data in the variables, they need to be initialized. For
example, consider these statements.
int i;
i=10;
Here, a variable i of the integer type is declared and the value 10 is assigned to it. We
can combine both the statements into a single statement as follows
int i=10;
Besides initializing the variable with the constant values, variables can also be
initialized at run-time using expressions. Initialization of variables at run-time is known
as dynamic initialization.
Example 4.1: A program to demonstrate initialization of variable
public class dynamic_initializaton
{
public static void main(String[] args)
{
int x=40,y=40,z=10; //initialization with constant
values
int result=(x*y)+z; //dynamic initialization
System.out.println(The value of z is:+result);
}
}
The output of the program is
The value of z is:1610
Receiving input through keyboard
Variables can also be given values interactively through the keyboard using the
readLine() method.
Example 4.2: A program to demonstrate reading data from the keyboard
//importing package for using DataInputStream class
import java.io.*;
public class ReadingData
{
public static void main(String[] args)
{
Self-Instructional
Material 47
Programming
Elements of Java
NOTES
DataInputStream in=new DataInputStream(System.in);
int num1=0;
float num2=0;
try
{
System.out.println(Enter integer value);
num1=Integer.parseInt(in.readLine());
System.out.println(Enter float value);
num2=Float.valueOf(in.readLine()).floatValue();
}
catch(Exception e)
{
}
System.out.println(The integer value is +num1);
System.out.println(The float value is +num2);
}
}
The output of the program is
Enter integer value
4
Enter float value
6.7
The integer value is 4
The float value is 6.7
The method readLine() of class DataInputStream is used to read string
from the keyboard which is then converted to the corresponding data type, int and
float. To handle the error which may occur while reading data from the keyboard, we
have provided try and catch statements. Error handling will be discussed in detail in
Unit 10.
4.7 TYPE CASTING
While programming we might come across some situations where a value of one data
type needs to be stored into a variable of another data type. If both the data types are
compatible and the data type of the target variable is large enough to store the value of
the source variable, Java automatically converts the source type into target type. This is
known as automatic type conversion. For example, the value of int data type can
be assigned to a variable of long data type since long is larger than int. This type
of conversion in which data of smaller type is assigned to a larger type is called widening
conversion.
However, if the target type is smaller than the source type, conversion cannot be
performed automatically. For example, the value of int data type cannot be assigned to
a variable of byte type. For such conversion, Java provides a mechanism known as
type casting. Type casting refers to the type conversion that is performed explicitly.
Self-Instructional
48 Material
Programming
Elements of Java
NOTES
The syntax for type casting is
data_type variable1 = (data_type) variable2;
where,
data_type is the data type
variable1 is the target variable
variable2 is the source variable
For example, consider these statements.
int x = 20;
byte y = (byte) x;
In these statements, type casting is performed to convert int data type to byte
data type.
Following points should be kept in mind while type casting.
All the integer data types can be cast to any other data type except boolean.
Casting into smaller data type may lead to loss of data.
Casting a floating point value to an integer type may result in truncation of the
fractional part.
Example 4.3: A program to demonstrate type casting
class ExampleTypecast
{
public static void main(String[] args)
{
byte b = 20;
short s = 26;
int i = 123456789;
float f = 3.98f;
System.out.println(The existing variables and their
values are:);
System.out.println(b=+b);
System.out.println(s=+s);
System.out.println(i=+i);
System.out.println(f=+f);
System.out.println(The existing variables and their
values after conversion are:);
System.out.println( );
// type conversion
int i1=(int)b; // conversion from byte to int
short s1=(short)b; // conversion from byte to short
Self-Instructional
Material 49
Programming
Elements of Java
NOTES
short s2=(short)i; // conversion from int to short
int i2 =(int)f; // conversion from float to int
System.out.println((int)b: +i1);
System.out.println((short)b: +s1);
System.out.println((short)i: +s2);
System.out.println((int)f: +i2);
}
}
The output of the program is
The existing variables and their values are:
b=20
s=26
i=123456789
f=3.98
The existing variables and their values after conversion
are:
(int)b: 20
(short)b: 20
(short)i: -13035
(int)f: 3
4.8 OPERATORS AND OPERATIONS
As stated earlier, operators are the symbols which perform operations on various data
items known as operands. For example, in a + b, a and b are operands and + is an
operator. Note that to perform an operation, operators and operands are combined together
forming an expression. For example, to perform an addition operation on operands a
and b, the addition (+) operator is combined with the operands a and b forming an
expression.
Depending on the function performed, the Java operators can be classified into
various categories. These include arithmetic operators, increment and decrement
operators, relational operators, logical operators, conditional operator, assignment
operators, bitwise operators and special operators.
4.8.1 Arithmetic Operators
Arithmetic operators perform the basic arithmetic operations on operands. They can
work on any built-in data type of Java except on boolean type.
Java provides various arithmetic operators that are, +(addition or unary plus), -
(subtraction or unary minus), *(multiplication), /(division) and %(modulus). For example,
some of the expressions which involve arithmetic operators are x + y, x y, x * y,
x / y and x % y. When the unary minus operator is used with a single operand, the
operand is multiplied by -1.
Check Your Progress
7. The default value
of a boolean data
type is_______.
8. What are the four
types of integer in
Java?
9. Define variable.
10. Initializing a
variable at run-time
is called dynamic
initialization.
(True or False)
11. The process of
explicitly
converting one data
type to another
data type is
called______.
Self-Instructional
50 Material
Programming
Elements of Java
NOTES
Expressions formed by using arithmetic operators can be of these types:
Integer expression: The arithmetic expression where both the operands are
integers is called an integer expression.
Real expression: The arithmetic expression where both the operands are real is
called real expression.
Mixed mode expression: The expression is mixed mode if one operand is real
and the other is integer. In this case, the integer operand is converted to real and
the result is also of type real.
Note: Unlike C and C++, the modulus operator can be applied to the floating
point data type also in Java.
4.8.2 Increment and Decrement Operators
Java provides two special unary arithmetic operators, namely the increment operator
(represented by ++) and the decrement operator (represented by ). The operator ++
increases the value of operand by 1 and the operator decreases the value of operand
by 1.
The increment and decrement operators can be used in two forms which are as follows:
Prefix form: In this form, the increment or the decrement operator precedes its
operand. The prefix increment operator is represented as ++operand and the
prefix decrement operator is represented as operand. The prefix increment
or the prefix decrement operator increments or decrements the value of an operand
respectively before its value is used in an expression.
To understand prefix operators, consider this example.
Example 4.4: Evaluate these statements
x=10;
y=++x;
z=x;
In this example, the statement y=++x first increments the value of x by 1 and
then assigns the incremented value to y. Similarly, the decrement operator is used
to decrement the value of x by 1 and then assign the decremented value to z.
Thus, the value of y and z are 11 and 10 respectively.
Postfix form: In this form, the increment or the decrement operator succeeds its
operand. The postfix increment operator is represented as operand++, and the
postfix decrement operator is represented as operand. The postfix increment
or the decrement operator increments or decrements the value of an operand,
respectively after using it in the expression.
To understand postfix operators, consider this example.
Example 4.5: Evaluate these statements
x=10;
y=x++;
z=x;
Self-Instructional
Material 51
Programming
Elements of Java
NOTES
In this example, the statement y=x++ first assigns the value of x to y and then
increments the value of x by 1. Similarly, the statement z=x assigns the value of x to
z and then decrements the value of x by 1. Thus, the value of y and z are 10 and 11,
respectively.
4.8.3 Relational Operators
Relational operators are used for comparing two values or expressions. The various
relational operators provided by Java are less than <, less than or equal to <=, greater
than >, greater than or equal to >=, equal to == and not equal to != operator.
They return values of boolean type, that is, either true or false. For example, consider
two variables a and b having values 20 and 30 respectively. In this case, the expression
a<b returns true whereas the expression a>b returns false.
The operators == and != are also known as equality operators as they are
used for checking the equality of operands.
Note: All relational operators can work on integer, floating-point and character
data types.
4.8.4 Logical Operators
Logical operators combine expressions and then return true or false. The various
logical operators provided by Java are listed here.
AND (&&) operator: It returns true only if all the expressions evaluate to
true, otherwise it returns false.
OR (||) operator: It returns true if any one or all the expressions evaluate to
true and returns false only if all the expressions evaluate to false.
Negation (!) operator: It returns true if the expression on which it is operating
is false and vice versa.
For example, consider two expressions Exp1 and Exp2. Table 4.6 shows the
result after the logical operators are applied on these expressions.
Table 4.6 Truth Table
Exp1 Exp2 Exp1 && Exp2 Exp1 || Exp2 !Exp1
true true true true false
true false false true false
false true false true true
false false false false true
4.8.5 Conditional Operator
The conditional operator selects a value based on specified condition. Note that the
conditional operator is a ternary operator, that is, this operator involves three operands.
The syntax of the conditional operator is
expression1 ? expression2: expression3
If expression1 is true, then expression2 is evaluated, otherwise
expression3 is evaluated.
Self-Instructional
52 Material
Programming
Elements of Java
NOTES
To understand the working of conditional operator, consider this example.
Example 4.6: Evaluate this statement
(x==5) ? 8 : 9;
In this example, if the value of x is equal to 5, then the expression returns 8,
otherwise the expression returns 9.
4.8.6 Assignment Operators
Assignment operator assigns the value of an expression to a variable. Assignment
operators are of two types, namely, the simple assignment operator and compound
assignment operators.
Simple Assignment Operator
The simple assignment operator assigns the value on its right hand side to the variable on
its left hand side. Note that the left hand side of an assignment expression should be a
variable. It cannot be a constant or an expression. However, the right hand side of an
assignment expression can be a variable, constant or an expression.
To understand the simple assignment operator, consider this example.
Example 4.7: Evaluate this statement
x=8;
In this example, the value 8 is assigned to the variable x.
With the help of the assignment operator, several variables can be assigned a
common value. This is accomplished by using multiple assignments in a single statement.
For example, in the statement x=y=z=5, the value 5 is assigned to the three variable x,
y and z.
Compound Assignment Operators
Java provides compound assignment operators (also known as Java shorthands) which
is in the following form.
v op=exp;
Here, v is a variable, op is the binary operator and exp is an expression. This
form is equivalent to the statement v=v op(exp);
where we need to access v only once.
For example, the expression x=x+6 can be written as x+=6. In this expression,
x is incremented by 6 and then the result is assigned to x. The various compound
assignment operators used in Java are +=, -=, *=, /= and %=.
4.8.7 Other Operators
In addition to the operators discussed, Java supports some other operators which include
bitwise operators and special operators.
Bitwise operators
The bitwise operators are used to manipulate the data values at bit level. This operator
can be applied to all the primitive data types such as long, int, short, char and
Self-Instructional
Material 53
Programming
Elements of Java
NOTES
byte. Various bitwise operators are bitwise AND (&), bitwise OR (!), bitwise exclusive
OR (^), ones complement (~), shift left (<<), shift right (>>), shift right with zero
fill (>>>).
Special Operators
Java provides two special operators namely, instanceof and dot operator (.).
instanceof Operator: The instanceof operator is an operator which is used to
check whether the object belongs to a particular class or not. For example, consider this
statement.
novel instanceof book
This statement returns true if the object novel belongs to the class book,
otherwise, false.
Dot Operator: The instance variables and the methods of a class are accessed through
objects with the help of dot operator. Dot operator links the name of the object with the
name of the variable or method which needs to be accessed. For example, consider
these statements.
obj.name; // accessing instance variable of the class
obj.marks(); // accessing method of the class
Note: The instance variables and the methods are explained in Chapter 06.
4.8.8 Operators Precedence and Associativity
An expression consisting of more than one operator leads to a confusion as to which
operator is to be evaluated first. For example, consider this expression.
a + b * c - d
In this expression, the compiler needs to know which operator is evaluated first. For this,
it is important to determine the precedence and associativity of operators.
Precedence: The order or priority in which various operators in an expression
are evaluated is known as precedence. Every operator in Java has a precedence
associated with it. The operators with a higher precedence are evaluated before
the operators with a lower precedence. For example, multiplication is performed
before addition as the multiplication operator has higher precedence than the
addition operator.
Associativity: The order or priority in which operators of the same precedence
are evaluated is known as associativity. For example, the addition and subtraction
operators have the same precedence. However, addition or subtraction may be
performed on the expression depending upon the order of their occurrence.
The associativity of an operator can be either from left to right or from right to
left. The operators with left to right associativity are evaluated from the left hand side
while the operators with right to left associativity are evaluated from the right hand side.
The precedence and the associativity of Java operators are listed in Table 4.7.
Note that the precedence of operators decreases from top to bottom, that is, the priority
is highest at the top.
Self-Instructional
54 Material
Programming
Elements of Java
NOTES
Table 4.7 Precedence and Associativity of Java Operators
Operators Description Associativity
.
()
[]

Direct member selector
Function Call
Array subscript

Left to right
Left to right
Left to right
-
++
--
!
~
(type)

Unary minus
Increment
Decrement
Logical negation
Ones complement
Casting

Right to left
Right to left
Right to left
Right to left
Right to left
Right to left
*
/
%
Multiplication
Division
Modulus
Left to right
Left to right
Left to right

+
-
Addition
Subtraction
Left to right
Left to right

<<
>>
>>>
Left shift
Right shift
Right shift with zero fill
Left to right
Left to right
Left to right

<
<=
>
>=
instanceof
Less than
Less than or equal to
Greater than
Greater than or equal to
Type comparison
Left to right
Left to right
Left to right
Left to right
Left to right

= =
=!
Equal to
Not equal to
Left to right
Left to right
& Bitwise AND Left to right
^ Bitwise XOR Left to right
| Bitwise OR Left to right
&& Logical AND Left to right
|| Logical OR Left to right
?: Conditional operator Right to left
=
Op=
Assignment Operator
Shorthand assignment
Right to left


Note: The operators in the same row have same precedence.
4.9 SUMMARY
In this unit, you have learned that:
A character set can be defined as a set of characters that either individually or in
combination, represents information. Unlike C and C++, Java uses a standard
known as Unicode to define characters.
Unicode is a 16 bit character code set which defines all of the characters available
in all human languages.
Check Your Progress
12. Which of the
following is an
invalid arithmetic
expression?
(a) 14+20/5
(b) (10/5)*
3+6%2
(c) 64+/8.5
(d) (2+3)*9/3
13. Given a=10, b=2
and c=7, give the
result of the
following logical
expressions.
(a) a>b&&a<c
(b) a>b&&b<c
(c) a>c||b==c
(d) a/b==c|
|a==c
14. Which of these is
an example of
compound
assignment
operator?
(a) a=5
(b) a=b=c=8
(c) a=b+c
(d) a+=b/c
15. ________operator
is used to check
whether an object
belongs to a
specified class.
Self-Instructional
Material 55
Programming
Elements of Java
NOTES
A token is defined as the smallest unit of a program. Java tokens are broadly
classified into keywords, identifiers, constants, operators and punctuators.
Keywords are the predefined words that have special significance in any language.
Every keyword is reserved for a specific purpose and hence cannot be used as
user-defined names (identifiers).
Identifiers are the names given to uniquely identify various programming elements
like variables, arrays, methods, classes, objects, packages, interface and so on.
Constants, also known as literals, are the values that a program cannot alter
during its execution. Java constants are broadly classified into four categories,
namely, numeric constants, character constants, string constants and boolean
constants.
Punctuators, also known as separators, are the symbols that define the structure
of a program by dividing and arranging a set of codes.
The Java program structure is divided into various sections, namely, documentation
section, package statement, import statements, interface statements, class
definitions and main method class.
A data type determines the type and the operations that can be performed on the
data. The various data types provided by Java are categorized into primitive data
types and non-primitive data types.
Primitive data types also known as built-in data types are the fundamental data
types provided by a programming language. In Java, primitive data types include
integer, floating point, character and boolean.
Java supports four types of integer namely, byte, short, int and long. It
supports two floating point data types namely, float and double.
A variable is an identifier that represents a memory location that is used to store
data value. The value of a variable can be changed anytime during the program
execution.
Type casting is the process of explicitly converting one data type to another data
type.
Operators are symbols which represent various operations (such as addition,
subtraction, multiplication, etc.) performed on variables or constants.
Java operators can be classified into various categories. These include arithmetic
operators, increment and decrement operators, relational operators, logical
operators, conditional operators, assignment operators, bitwise operators and
special operators.
4.10 KEY TERMS
Character set: It is a set of characters that either individually or in combination
represent information.
Unicode: It is a 16-bit character code set which defines all of the characters
available in all human languages like English, Hindi, French, German, etc.
Token: It is defined as the smallest unit of a program.
Keyword: It is the predefined word that has special significance in any language.
Self-Instructional
56 Material
Programming
Elements of Java
NOTES
Identifier: It is the name given to uniquely identify various programming elements
like variables, arrays, methods, classes, objects, packages, interface, and so on.
Constants: It is a value that a program cannot alter during its execution.
Operators: They are symbols which perform operations such as addition,
subtraction etc. on various data items to produce a result.
Punctuators: They are symbols that define the structure of a program by dividing
and arranging a set of codes.
Reference type: They are non-primitive data types which are derived from
primitive data types.
Variables: It is an identifier that represents a memory location that is used to
store data value.
Type casting: It refers to the type conversion that is performed explicitly.
Widening conversion: It is a type of conversion in which data of smaller type is
assigned to a larger type.
instanceof operator: It is an operator which is used to check whether the
object belongs to a particular class or not.
Precedence: It is an order or priority in which various operators in an expression
are evaluated.
4.11 ANSWERS TO CHECK YOUR PROGRESS
1. unicode
2. If we do not append f or F to a floating point constant, it defaults to double
precision.
3. False
4. Rules for defining an identifier are:
(i) An identifier must not start with a digit.
(ii) An identifier can contain alphabets, digits, underscore and dollar sign
characters.
(iii) Characters such as *, ; and white spaces cannot be used in an identifier.
(iv) An identifier in uppercase is different from that in lowercase.
5. main()
6. (b)
7. false
8. The four types of integer in Java are int, byte, short and long.
9. A variable is an identifier which represents memory location that is used to store
data value. Data stored at a particular location can be accessed using a variable
name.
10. True
11. type casting
12. (c)
Self-Instructional
Material 57
Programming
Elements of Java
NOTES
13. (a) False (b) True
(c) True (d) False
14. (d)
15. instanceof
4.12 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What are keywords?
2. What are punctuators?
3. What are the different types of Java tokens?
4. What are Boolean constants?
5. What are relational operators?
Long-Answer Questions
1. Describe a Java program structure.
2. What are the various primitive data types in Java? Explain them in detail.
3. What are the different ways of initializing a variable? Explain with example.
4. What is type casting? State a program to demonstrate type casting?
5. Differentiate between the following:
(a) Simple assignment operator and compound assignment operator
(b) instanceof and dot operators
Self-Instructional
Material 59
Control Statements
NOTES
UNIT 5 CONTROL STATEMENTS
Structure
5.0 Introduction
5.1 Unit Objectives
5.2 Selection Statements
5.3 Iteration Statements
5.3.1 The for Loop
5.3.2 The while Loop
5.3.3 The do-while Loop
5.4 Jump Statements
5.5 Labelled Loops
5.6 Summary
5.7 Key Terms
5.8 Answers to Check Your Progress
5.9 Questions and Exercises
5.0 INTRODUCTION
A statement is an instruction given to the computer to perform a specific action. In Java,
a statement can either be a single statement or a compound statement. A single statement
specifies a single action and is always terminated by a semicolon ;. A compound
statement, also known as a block, is a set of statements that are always enclosed within
curly braces {}.
By default, the statements are executed in the same order in which they appear in
the program and each statement is executed only once. However, the serial execution of
statements makes a program inflexible and unsuitable for most of the practical applications.
To make a program more flexible, control statements are used to alter the flow of
control of the program. In Java, the control statements are broadly classified into three
categories, namely, conditional statements, iteration statements and jump statements.
All these control statements are commonly used with the logical tests or test conditions
to alter the flow of control conditionally or unconditionally.
In this unit, you will learn about the various types of control statements.
5.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Understand the different types of control statements in Java
Explain the various types of conditional statements
Discuss the different types of iteration statements
Understand the different types of jump statements
Understand the basic concept of labels
Self-Instructional
60 Material
Control Statements
NOTES
5.2 SELECTION STATEMENTS
Conditional statements, also known as selection statements, are used to make decisions
based on a given condition. If the condition evaluates to true, a set of statements is
executed, otherwise another set of statements is executed.
The if Statement
The if statement selects and executes the statement(s) based on a given condition.
The syntax of the if statement is
For a single statement
if(condition)
statement1;
nextstatement;
For a set of statements
if(condition)
{
statement1;
statement2;
}
nextstatement;
Here, if the condition evaluates to true, then a given set of statement(s) is
executed. However, if the condition evaluates to false, then the given set of statements
is skipped and the program control passes to the statement following the if statement
(Figure 5.1).

Is
condition
true?
nextstatement

statement1
No
Yes
Figure 5.1 Flow of Control in if Statement
The if-else Statement
The if-else statement causes one of the two possible statement(s) to execute
depending upon the result of condition.
Self-Instructional
Material 61
Control Statements
NOTES
The syntax of the if-else statements is
if(condition) //if part
{
statement1;
}
else //else part
statement2;
nextstatement;
Here, the if-else statement comprises two parts, namely, if and else. If
the condition is true, the statements within if part is executed. However, if the condition
is false, the statements within else part is executed (Figure 5.2).
Is
condition
true?
nextstatement
statement1
No Yes
statement2
Figure 5.2 Flow of Control in if-else Statement
Example 5.1: A program to demonstrate the use of if-else statement
class ConditionalStatement
{
public static void main (String args[])
{
int i=5;
if (i > 0)
System.out.println(i is a positive number);
else
System.out.println(i is a negative number);
}
}
Self-Instructional
62 Material
Control Statements
NOTES
The output of the program is
i is a positive number
Nested if-else Statement
A nested if-else statement contains one or more if-else statements. In other
words, if-else statement within another if-else statement is called nested if-
else statement. The if-else statement can be nested in three different ways
which are discussed here.
The if-else statement is nested within the if part.
The syntax is
if(condition1)
{
statement1;
if(condition2)
statement2;
else
statement3;
}
else
statement4;
nextstatement;
The if-else statement is nested within the else part.
The syntax is
if (condition1)
statement1;
else
{
statement2;
if (condition2)
statement3;
else
statement4;
}
nextstatement;
The if-else statement is nested within both the if and the else parts.
The syntax is
if(condition1)
{
statement1;
if(condition2)
statement2;
else
statement3;
}
Self-Instructional
Material 63
Control Statements
NOTES
else
{
statement4;
if(condition3)
statement5;
else
statement6;
}
nextstatement;
The if-else-if Ladder
The if-else-if ladder, also known as the if-else-if staircase, has an if-
else statement within the outermost else statement. The inner else statement can
further have other if-else statements.
The syntax of the if-else-if ladders is
if (condition1)
statement1;
else
if (condition2)
statement2;
else
if (condition3)
statement3;
else
statement4;
Third
if-else
nextstatement;
Second
if-else
First
if-else
Example 5.2: A program to demonstrate if-else-if statement
import java.io.*;
public class Grade
{
public static void main(String[] args)
{
int marks=0;
DataInputStream cin=new DataInputStream(System.in);
try
{
System.out.print(Enter the marks: );
//reading integer from keyboard
marks=Integer.parseInt(cin.readLine());
if(marks>90)
System.out.println(Grade is A);
else
if(marks>75)
Self-Instructional
64 Material
Control Statements
NOTES
System.out.println(Grade is B);
else
if(marks>60)
System.out.println(Grade is C);
else
System.out.println(Grade is D);
}
catch(Exception e)
{}
}
}
The output of the program is
Enter the marks: 78
Grade is B
Conditional Operator as an Alternative
The conditional operator ? : selects one of the two values or expressions based on a
given condition. Due to this decision-making nature of the conditional operator, it is
sometimes used as an alternative to if-else statements. Note that the conditional
operator selects one of the two values or expressions and not the statements as in the
case of an if-else statement. In addition, it cannot select more than one value at a
time, whereas if-else statement can select and execute more than one statement at
a time. For example, consider this statement.
max=(x>y ? x : y)
This statement assigns maximum of x and y to max.
The switch Statement
The switch statement selects a set of statements from the available sets of statements.
The switch statement evaluates the value of an expression and compares it with the
list of integer, character, short or byte constants. It should be noted that the case constants
must be compatible with the expression type. When a match is found, all the statements
associated with that constant are executed (Figure 5.3).
The syntax of the switch statement is
switch(expression)
{
case <constant1>: statement1;
[break;]
case <constant2>: statement2;
[break;]
case <constant3>: statement3;
[break;]
[default: statement4;]
}
nextstatement;
Self-Instructional
Material 65
Control Statements
NOTES
Is
constant1=
expression?
expression
statement1
Is
constant2=
expression?
Is
constant3=
expression?
statement2
statement3
nextstatement
No
No
Yes
Yes
Yes
No
Figure 5.3 Flow of Control in switch Statement
The Java keywords case and default provide the list of alternatives. Note
that it is not necessary for every case label to specify a unique set of statements. The
same set of statements can be shared by multiple case labels.
The keyword default specifies the set of statements to be executed in case
no match is found. Note that there can be multiple case labels but there can be only
one default label. However, default is an optional statement.
The break statements in the switch block are optional. However, it is used in
the switch block to prevent a fall through. Fall through is a situation that causes the
execution of the remaining cases even after a match has been found. In order to prevent
this, break statements are used at the end of statements specified by each case and
default. This causes the control to immediately break out of the switch block and
execute the next statement.
Similar to if and if-else statements, switch statements can also be nested
within one another. A nested switch statement contains one or more switch statements
within its case label or default label (if any).
Note: Switch statement cannot be used for testing floating-point values or string values.
Example 5.3: A program to demonstrate the use of switch statement
class SwitchStatement
{
public static void main(String args[])
{
Self-Instructional
66 Material
Control Statements
NOTES
int x=2;
switch(x)
{
case 1: System.out.println(Day is Monday);
break;
case 2: System.out.println(Day is Tuesday);
break;
case 3: System.out.println(Day is Wednesday);
break;
case 4: System.out.println(Day is Thursday);
break;
case 5: System.out.println(Day is Friday);
break;
case 6: System.out.println(Day is Saturday);
break;
case 7: System.out.println(Day is Sunday);
break;
default: System.out.println(Invalid option!);
}
}
}
The output of the program is
Day is Tuesday
In this example, since the value of x is 2 therefore the message Day is Tuesday is
displayed. In case the value of x is 8, the output Invalid option! is displayed.
5.3 ITERATION STATEMENTS
The statements that cause a set of statements to be executed repeatedly either for a
specific number of times or until some condition is satisfied are known as iteration
statements. That is, as long as the condition evaluates to true, the set of statement(s)
is executed. The various iteration statements used in Java are for loop, while loop and
do-while loop.
5.3.1 The for Loop
The for loop (Figure 5.4) is one of the most widely used loops in Java. The for loop
is a deterministic loop, that is, the number of times the body of the loop is executed is
known in advance.
The syntax of the for loop is
for(initialize; condition; update)
{
//body of the for loop
}
Check Your Progress
1. Conditional
statements are also
known as
____________
statements.
2. The set of
statements in the
else part of the if-
else statement are
executed when the
condition evaluates
to
_____________.
3. The
____________
operator can be
used as an
alternative to if-
else statement.
4. A switch block can
have more than one
default label. (True
or False)
5. The
____________
statement is used
to immediately exit
from the switch
block.
6. Which of the
following is an
invalid switch
expression?
(a) int
choice=4;
(b) char
choice=x;
switch(choice)
switch(choice)
(c) String
choice=Monday;
(d) short
choice=5;
switch(choice)
switch(choice)
Self-Instructional
Material 67
Control Statements
NOTES
initialize
Is
condition
true?
statement
update
nextstatement
No
Yes
Figure 5.4 Flow of Control in for Loop
The initialize expression in for loop can initialize one or more control variables.
A for loop can also update more than one variable in its update expression. Note that
initialize, condition and update are optional expressions and are always
specified in parentheses. All the three expressions are separated by semicolons. We can
also create an infinite loop by excluding all the three expressions as follows:
for( ; ; )
{
.
.
}
Example 5.4: A program to display a count down using for loop
class UpdateStatement
{
public static void main(String args[])
{
for (int i=10;i>=1;i)
{
System.out.print( +i);
}
System.out.println();
System.out.print(This is an example of for loop);
}
}
Self-Instructional
68 Material
Control Statements
NOTES
The output of the program is
10 9 8 7 6 5 4 3 2 1
This is an example of for loop
for loop using comma operator
for loop allows multiple variables to control the loop using comma operator. That is,
two or more variables can be used in the initialize and the update part of the
loop. For example, consider this statement.
for (i=1,j=50;i<10;i++,j)
This statement initializes two variables, namely i and j and updates them. Note
that for loop cannot have more than one condition separated by comma.
5.3.2 The while Loop
The while loop (Figure 5.5) is used to perform looping operations when the number of
iterations is not known in advance. That is, unlike for loop, the while loop is non-
deterministic in nature.
The syntax of the while loop is
while(condition)
{
// body of the while loop
}
initialize
Is
condition
true?
statement
update
nextstatement
No
Yes
Figure 5.5 Flow of Control in while Loop
The following points should be noted about the while loop:
Unlike for loops where explicit initialize and update expressions are
specified, while loops do not specify any explicit initialize and update
expressions. This implies that the control variable must be declared and initialized
before the while loop and needs to be updated within the body of the while
loop.
Self-Instructional
Material 69
Control Statements
NOTES
The while loop executes as long as condition evaluates to true. If
condition evaluates to false, then the body of while loop does not execute.
Example 5.5: A program to determine the sum of first n consecutive positive integers
import java.io.*;
public class Sum
{
public static void main(String[] args)
{
int n;
int sum=0;
DataInputStream cin=new DataInputStream (System.in);
try
{
System.out.print(Enter n: );
//reading input from the user
n=Integer.parseInt(cin.readLine());
//loop to calculate the sum
while(n>0)
{
sum=sum+n;
n=n-1;
}
System.out.print(The sum is + sum);
}
catch(Exception e)
{}
}
}
The output of the program is
Enter n: 7
The sum is 28
5.3.3 The do-while Loop
As discussed earlier, in a while loop, the condition is evaluated at the beginning of the
loop and if the condition evaluates to false, the body of the loop is not executed even
once. However, if the body of the loop is to be executed at least once, no matter whether
the initial state of the condition is true or false, the do-while loop is used. This
loop places the condition to be evaluated at the end of the loop (Figure 5.6).
The syntax of the do-while loop is
do
{
//body of do-while loop
}
while(condition);
Self-Instructional
70 Material
Control Statements
NOTES
Is
condition
true?
statement
Yes
nextstatement
No
Figure 5.6 Flow of Control in do-while Loop
Example 5.6: A program to calculate the sum of an Arithmetic Progression (AP)
class APSeries
{
public static void main(String args[])
{
int first_term=1;
int number_of_terms=5;
int term=0;
int i=1;
int common_difference=2;
int sum=0;
System.out.print(The terms are: );
do
{
term =first_term+(i-1)*common_difference;
sum+=term;
System.out.print( +term);
++i;
}
while(i<=number_of_terms);
System.out.println();
System.out.println(The sum of A.P is: +sum);
}
}
The output of the program is
The terms are: 1 3 5 7 9
The sum of A.P is: 25
Self-Instructional
Material 71
Control Statements
NOTES
Nested Loops
Nested loops are the loops present within the body of another loop. All the three loops
(for, while and do-while) can be nested.
Example 5.7: A program to demonstrate the nested for loop
class NestedLoop
{
public static void main(String args[])
{
int a,b;
for(a=0;a<5;a++) //outer loop
{
for(b=a;b<5;b++) //inner loop
{
System.out.print(*);
}
System.out.println();
}
}
}
The output of the program is
*****
****
***
**
*
5.4 JUMP STATEMENTS
Jump statements are used to alter the flow of control unconditionally. That is, jump
statements transfer the program control unconditionally. The jump statements defined in
Java are break, continue and return.
The break Statement
The break statement is extensively used in loops and switch statements. It immediately
terminates the loop or the switch statement, bypassing the remaining statements. The
control then passes to the statement that immediately follows the loop or the switch
statement. A break statement can be used in any of the three Java loops. In case of
nested loops, the break will exit the only the single loop, that is, the loop in which it is
placed.
The continue Statement
The continue statement is used to continue the loop with its next iteration. In other
words, it skips any remaining statements in the current iteration and immediately passes
the control to the next iteration. It does not terminate the loop (as in the case of break
statements) rather it only terminates the current iteration of the loop. Like a break
statement, a continue statement can be used in any of the three loops.
Check Your Progress
7. The control
statement that
executes a set of
statements
repeatedly based
on a condition is
known as an
____________
statement.
8. Declaration or
initialization of
more than one
variable is allowed
in a for loop. (True
or False)
9. What is the
difference between
while and do-
while loop?
10. Placing a loop
within the body of
another loop is
known as
____________ of
loops.
Self-Instructional
72 Material
Control Statements
NOTES
The return Statement
The return statement is used to transfer the control out of the method explicitly. It
transfers the control back to the caller and terminates the method in which it is present.
When the return statement is encountered in the main() method, it transfers the
control back to the Java run-time system and terminates the program execution.
Example 5.8: A program to add the factors of a number using break and continue
statements
class Jump
{
public static void main(String args[])
{
int factor=0, number=10, sum=0;
System.out.println(Number= +number);
while(true)
{
factor++;
if(factor>number)
break;
if(number%factor!=0)
continue;
sum=sum+factor;
}
System.out.println(Sum of factors= +sum);
if(sum>0)
return;
System.out.println(This statement is not executed);
}
}
The output of the program is
Number=10
Sum of factors=18
5.5 LABELLED LOOPS
As discussed earlier, break and continue statements allow the programmer to
break out of the loop. However, they do not allow you to simply jump to another part of
the program or out of the nested loop or switch statement. Java allows to jump from
one block of statement to another with the help of labels. A label is an identifier which
must follow the rules for naming identifiers in Java. It can be placed before the block of
statements or loop followed by a colon (:). For example, consider this statement.
LabelName: for( ; ; )
{
.
.
}
Self-Instructional
Material 73
Control Statements
NOTES
The break statement passes the control out of the innermost loop or the innermost
switch statement and the continue statement continues with the next iteration of
the innermost loop only. However, with the help of labels, break statement can be used
to cause the control to jump out of the outer loop or switch statement. For example,
consider these statements.
outerloop: for(i=0;i<5;i++)
{
innerloop: for(j=1;j<5;j++)
{
System.out.println(*);
if(i=j)
break outerloop;
.
.
}
}
In this case, the break statement placed inside the innerloop will force the
control to jump out of both the inner and outer loops. Similarly, with the help of labels,
continue statement can be used to continue with the next iteration of the outer loop.
Example 5.9: A program to demonstrate the use of continue statement in a labelled
loop
class LabelExample
{
public static void main(String args[])
{
outerloop: for(int i=0;i<3;i++)
{
for(int j=0;j<5;j++)
{
if(j>i)
continue outerloop;
System.out.println( i +i+ j +j);
}
}
System.out.println(Loop Ends);
}
}
The output of the program is
i 0 j 0
i 1 j 0
i 1 j 1
i 2 j 0
i 2 j 1
i 2 j 2
Loop Ends
Check Your Progress
11. The _________
statements are
used to transfer the
control from one
part of the
program to
another.
12. The
______________
statement when
encountered
terminates the
current iteration of
the loop.
13. What is the use of
return
statement?
14. ________ are the
names given to a
block of code
which allow you to
jump from one
loop to another
loop within a
nested loop.
Self-Instructional
74 Material
Control Statements
NOTES
In this program, if we substitute continue statement with the break statement, the
following output will be generated.
i 0 j 0
Loop Ends
5.6 SUMMARY
In this unit, you have learned that:
A statement is an instruction given to the computer to perform a specific action.
A statement can either be a single statement or a compound statement.
A single statement specifies a single action and is always terminated by a semicolon
;. A compound statement, also known as a block, is a set of statements that are
always enclosed within curly braces {}.
Control statements are used to alter the flow of control of the program. In Java,
the control statements are broadly classified into three categories, namely,
conditional statements, iteration statements and jump statements.
Conditional statements, also known as selection statements, are used to make
decisions based on a given condition.
The conditional operator ? : selects one of the two values or expressions
based on a given condition.
The switch statement selects a set of statements from the available sets of
statements.
The statements that cause a set of statements to be executed repeatedly either
for a specific number of times or until some condition is satisfied are known as
iteration statements.
The for loop is one of the most widely used loops in Java. The for loop is a
deterministic loop, that is, the number of times the body of the loop is executed is
known in advance.
The while loop is used to perform looping operations when the number of
iterations is not known in advance. In a while loop, the condition is evaluated at
the beginning of the loop and if the condition evaluates to false, the body of the
loop is not executed even once.
The do-while loop is used if the body of the loop is to be executed at least
once, no matter whether the initial state of the condition is true or false.
Nested loops are the loops present within the body of another loop.
Jump statements are used to alter the flow of control unconditionally. That is,
jump statements transfer the program control unconditionally. The jump statements
defined in Java are break, continue and return.
Labels are used to jump from one block of statement to another.
Self-Instructional
Material 75
Control Statements
NOTES
5.7 KEY TERMS
Selection statements: Also known as conditional statements, they are used to
make decisions based on a given condition.
Default: This is a keyword that specifies the set of statements to be executed
in case no match is found.
Iteration statements: They are the statements that cause a set of statements
to be executed repeatedly either for a specific number of times or until some
condition is satisfied.
for loop: It is a deterministic loop, that is, the number of times the body of the
loop is executed, is known in advance.
while loop: This is an is used to perform looping operations when the number
of iterations is not known in advance.
Jump statements: These are statements which are used to alter the flow of
control unconditionally.
5.8 ANSWERS TO CHECK YOUR PROGRESS
1. Selection
2. false
3. Conditional
4. False
5. break
6. (c)
7. Iteration
8. True
9. In a while loop, the condition is evaluated at the beginning of the loop and if the
condition evaluates to false, the body of the loop is not executed even once.
The do-while loop is used if the body of the loop is to be executed at least
once, no matter whether the initial state of the condition is true or false.
10. Nesting
11. jump
12. continue
13. The return statement is used to transfer the control out of the method explicitly.
It transfers the control back to the caller and terminates the method in which it is
present.
14. Labels
Self-Instructional
76 Material
Control Statements
NOTES
5.9 QUESTIONS AND EXERCISES
Short-Answer Questions
1. Write a program to find and print the multiples of 9 between 100 and 200 using
for loop.
2. State the difference between the executions of while and do-while loop.
3. Write a program to demonstrate the use of switch statement.
4. What is a return statement?
5. Write a short note on labelled loops.
Long-Answer Questions
1. What are control statements? Explain the different types of control statements
with examples?
2. Consider the following code segment
if(x%2>=0)
{
if(x%2==0)
System.out.println(x is an even number);
if(x%2>0)
System.out.println(x is an odd number);
}
Rewrite the code using:
(a) if-else statement (b) conditional operator
3. Explain the use of break and default in switch statements.
4. Write a program to print the following output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
5. Write a program to check whether the number is palindrome or not. (Hint:
Palindrome numbers are those which read the same from left to right and from
right to left.)
6. Write a program to calculate the sum of this series.
1+x+x
2
+x
3
++x
n
Self-Instructional
Material 77
Java Classes and Objects
NOTES
UNIT 6 JAVA CLASSES AND OBJECTS
Structure
6.0 Introduction
6.1 Unit Objectives
6.2 Encapsulation
6.3 Defining a Class
6.3.1 Defining Methods
6.4 Creating Objects
6.5 Accessing Members of a Class
6.6 Argument Passing
6.6.1 Call-by-Value
6.6.2 Call-by-Reference
6.7 Constructors
6.7.1 Parameterized Constructors
6.8 Method Overloading
6.9 Static Members
6.10 this Keyword
6.11 Garbage Collection
6.11.1 The finalize() Method
6.12 Summary
6.13 Key Terms
6.14 Answers to Check Your Progress
6.15 Questions and Exercises
6.0 INTRODUCTION
The key objective of object-oriented programming is to represent the various real-world
objects as program elements. In Java, this objective is accomplished with the help of
class that binds data and the methods to manipulate that data together under a single
entity.
All the OOP concepts, such as data abstraction, encapsulation, inheritance and
polymorphism, are implemented with the help of classes. A class serves as a template
that provides a layout common to all of its instances known as objects. In other words,
a class is only a logical abstraction that specifies what data and methods its objects will
have, whereas the objects are the physical entities through which those data and methods
can be used in a program. Thus, objects are considered as the building blocks of object-
oriented programming. This unit discusses the concept of classes and objects in detail.
6.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Explain classes and objects that form the basis of object-oriented programming
Create and use non parameterized and parameterized methods
Understand the significance of dot operator
Learn how to pass arguments to a method by value or by reference
Self-Instructional
78 Material
Java Classes and Objects
NOTES
Explain the purpose of constructor and its types
Understand the concept of method overloading
Explain the use of static members in a class
Understand the significance of this keyword and finalize method
6.2 ENCAPSULATION
Encapsulation is the technique of binding or keeping the data and functions (that operate
on them) together in a single unit called a class. Encapsulation is the way to implement
data abstraction. A well-encapsulated object acts as a black box for other parts of the
program. That is, it provides services to the external functions or other objects that
interact with it. However, these external functions or the objects do not need to know its
internal details.
6.3 DEFINING A CLASS
A class is a user-defined data type that can be used to create instances of its type called
objects. Like any other user-defined data type, it also needs to be declared and defined
in the program. A class definition specifies a new data type that can be treated as a built-
in data type.
The syntax for defining a class is
class class_name
{
//variables declaration
//methods declaration
}
The variables declared in the class are known as instance variables. The variables
and methods declared within the curly braces are collectively known as members of
the class.
A class can also be empty. That is, the class definition given below is also valid.
class class_name
{
}
Here, since the body of the class is empty, it does not contain any variables and
methods so it cannot perform any useful action. However, this class can be successfully
compiled and we can also create objects using it.
Note: In Java, there is no semicolon after closing brace in class definition.
Example 6.1: A simple class definition without any method
class Cuboid
{
int length;
int width; //variables declaration
Self-Instructional
Material 79
Java Classes and Objects
NOTES
int height;
}
In this example, a class named Cuboid with three instance variables of type
int, namely, length, width and height is created.
6.3.1 Defining Methods
As discussed earlier, a class consists of instance variables and methods. A class which
consists of only variables (and without methods which manipulate them) cannot perform
any useful operation. Therefore, to access the instance variables of a class and manipulate
them, we must add methods in the class.
The syntax for defining a method is
return_type method_name(parameter_list)
{
body of the method
}
where,
return_type is the type of data that is returned by the method
method_name specifies the name of the method. This can be any name other than
the keywords in Java
parameter_list consists of a series of pairs of data type and identifiers separated
by commas
Note: The parameter_list can be empty and if a method does not return any
value, its return type must be void.
For example, consider the following method definition.
int volume()
{
body of the method
}
Here, the method volume() does not accept any parameter and returns a
value of type int.
Example 6.2: A class definition with method
class Cuboid
{
int length;
int width; //variables declaration
int height;
int volume() //method definition
{
return(length*width*height);
}
}
Note: Methods must be declared immediately after the declaration of the instance
variables inside the body of the class.
Self-Instructional
80 Material
Java Classes and Objects
NOTES
6.4 CREATING OBJECTS
Once a class is defined, it can be used to create variables of its type known as objects.
The relationship between an object and a class is same as that of any variable and its
data type. To create an object, we need to first declare it.
The syntax for declaring an object is
class_name object_name;
where,
class_name is the name of the class
object_name is the name of the object of class_name type
For example, the statement to declare an object of Cuboid type is
Cuboid cobj;
This statement declares a variable cobj as a reference to an object of Cuboid
type. After the execution of this statement, cobj contains the null value, which
indicates that it does not point to an actual object. Once the object is declared, we need
to create it by allocating the required memory space to it. In Java, this is done with the
help of the new operator.
The syntax for creating an object is
object_name=new class_name;
For example, the statement to create an object of Cuboid type is
cobj=new Cuboid();
This statement creates an actual object by dynamically allocating memory space
to it and returns a reference to cobj.
The above two statements can be combined into one statement as shown below.
Cuboid cobj=new Cuboid ();
Note: Since an object is an instance of a class, the process of creating an object of
a class is known as instantiation.
6.5 ACCESSING MEMBERS OF A CLASS
Each object of a class has its own set of variables. These variables should be assigned
values before using them in the program. The instance variables and methods added in
the program cannot be accessed directly outside the class using their names. To access
the variables and methods outside the class, dot (.) operator is used as follows:
object_name.variable_name
object_name.method_name(parameter_list)
where,
object_name is the name of the object
variable_name is the name of the instance variable that is to be accessed
method_name is the name of the method which is to be called
parameter_list is the series of pairs of data types and their respective identifiers
Check Your Progress
1. A _________ has
the same relation
to an _________
that a basic data
type has to a
variable of that
type.
2. Which of these
operator is used
for creating an
object and
allocating memory
space to it?
(a) dot operator
(b) new operator
(c) instanceof
operator
(d) none of these
Self-Instructional
Material 81
Java Classes and Objects
NOTES
For example, the instance variable length of Cuboid class can be accessed as
follows:
cobj.length;
Similarly, the method volume()of Cuboid class can be accessed as follows:
cobj.volume();
Example 6.3: A program to demonstrate the accessing of members of a class
class Cuboid
{
int length;
int width;
int height;
int volume() //method definition
{
return(length*width*height);
}
}
class ClassDemo
{
public static void main(String args[])
{
Cuboid cobj=new Cuboid(); //object creation
cobj.length=60;
cobj.width=20; //accessing variables
cobj.height=40;
int vol=cobj.volume(); //calling method
System.out.println(The volume of the cuboid is:
+vol);
}
}
The output of the program is
The volume of the cuboid is: 48000
In this example, the instance variables length, width and height of the
object cobj are assigned values outside the class using the dot operator. Alternatively,
the instance variables can be assigned values by using a parameterized method.
Example 6.4: A program to demonstrate the use of parameterized method
class Cuboid
{
int length;
int width;
int height;
void initialize(int l, int w, int h) //parameterized
method
{
Self-Instructional
82 Material
Java Classes and Objects
NOTES
length=l;
width=w;
height=h;
}
int volume()
{
return(length*width*height);
}
}
class ParameterizedMethod
{
public static void main(String args[])
{
Cuboid c1=new Cuboid(); //creating object
Cuboid c2=new Cuboid();
c1.initialize(12,10,8); //calling initialize
method
int vol1=c1.volume(); //calling volume method
c2.initialize(13,11,9);
int vol2=c2.volume();
System.out.println(The volume of the Cuboid is:
+vol1);
System.out.println(The volume of the Cuboid is:
+vol2);
}
}
The output of the program is
The Volume of the Cuboid is: 960
The Volume of the Cuboid is: 1287
Here, the initialize() method accepts three parameters (arguments) namely, l,
w and h and assigns them to the instance variables, namely, length, width and
height, respectively of the appropriate object.
6.6 ARGUMENT PASSING
The argument(s) that appear in the method call statement are known as actual arguments
and those which appear in the method definition are known as formal arguments. The
number of actual arguments, their order and type in the method call must match with
that of the formal arguments. There are two ways by which an argument can be passed
to the methodcall by value and call by reference.
6.6.1 Call-by-Value
In call-by-value method, the values of the actual arguments are copied into the formal
arguments. Putting in simple words, the method creates a copy of argument values and
then works with these copied values. As a result any changes made to this set of copied
Self-Instructional
Material 83
Java Classes and Objects
NOTES
values in the called method do not affect the values of the actual arguments in the calling
method. In Java, when arguments of primitive type are passed to a method, they are
passed by value.
Example 6.5: A program to demonstrate the call-by-value mechanism
class FirstCall
{
void vol(int i, int j, int k)
{
i+=5;
j+=5;
k+=5;
}
}
class CallByValue
{
public static void main(String args[])
{
FirstCall fc =new FirstCall();
int l=10;
int w=20;
int h=15;
System.out.println(Length, Width, Height before
call is : +l+ +w+ +h);
fc.vol(l, w, h) //passing values as arguments
System.out.println(Length, Breadth, Height
after call is : +l+ +w+ +h);
}
}
The output of the program is
Length, Breadth, Height before call is :10 20 15
Length, Breadth, Height after call is :10 20 15
In this program, the values of l, w and h remain same before and after the call.
This is because when the method vol() is invoked l, w and h are passed by value and
their values gets copied into formal arguments i, j and k. Hence, the method
vol()works with i, j and k and not with l, w and h. As a result, the values of l, w
and h remain unaltered.
6.6.2 Call-by-Reference
In call-by-reference method, arguments reference is passed as method parameter. Unlike
call-by-value method, call-by-reference does not create a copy of the actual argument
and the called method works with the original values. This implies that any changes
made to the variable in the method body are reflected in the calling method. In Java,
when an object of a class is passed to a method as an argument it is passed by reference.
Self-Instructional
84 Material
Java Classes and Objects
NOTES
Example 6.6: A program to demonstrate the call-by-reference mechanism
class SecondCall
{
int length, breadth, height; //variables declaration
void vol(SecondCall s) //method definition
{
s.length+=5;
s.breadth+=5;
s.height+=5;
}
}
class CallByRefernce
{
public static void main(String args[])
{
SecondCall sc=new SecondCall();
sc.length=10;
sc.breadth=20;
sc.height=30;
System.out.println(The values of Length, Breadth and
Height before method call: +sc.length +
+sc.breadth + +sc.height);
sc.vol(sc); //passing object as method argument
System.out.println(The values of Length, Breadth and
Height after method call: +sc.length + +sc.breadth
+ +sc.height);
}
}
The output of the program is
The values of Length, Breadth and Height before method call:
10 20 30
The values of Length, Breadth and Height after method call:
15 25 35
In this program, the values of length, breadth and height of object sc
changes after invoking the method. Because here when the method vol() is called,
the object of a class is passed as parameter. As a result changes made to the length,
breadth and height of this passed object in the vol() method are reflected in the
original values.
6.7 CONSTRUCTORS
A constructor is a special method which is used to initialize objects at the time of their
creation. The name of the constructor is same as the name of the class in which it
resides. Unlike other methods in Java, a constructor does not have any return type (not
even void). This is because the implicit return type of constructor is the instance of the
class to which it belongs.
Check Your Progress
3. Which of these
entities is the
correct syntax for
accessing the
members of a
class?
(a)
class_member.
class_object
(b)
class_object.
class_name
(c) class_name.
class_member
(d)
class_object.
class_member
4. The____________
method allows the
programmer to
pass different
values to the
instance variables
of different
objects.
5. There are two
ways by which an
argument can be
passed to the
method, ________
and______________.
Self-Instructional
Material 85
Java Classes and Objects
NOTES
The syntax to define a constructor is
class class_name
{
//Variable declaration
class_name(parameter_list) //constructor definition
{
//body of the constructor
}
}
It should be noted that if you do not explicitly define any constructor, then the
Java compiler automatically provides a default constructor that initializes all the instance
variables to 0.
Example 6.7: A program to demonstrate the concept of a constructor
class Cuboid
{
int length;
int width;
int height;
Cuboid() //constructor definition without parameters
{
length=20;
width=10;
height=15;
}
int volume()
{
return (length*width*height);
}
}
class Constructor
{
public static void main(String args[])
{
Cuboid c1=new Cuboid();
Cuboid c2=new Cuboid();
int a=c1.volume();
int b=c2.volume();
System.out.println(The volume of first cuboid is +a);
System.out.println(The volume of second cuboid is +b);
}
}
The output of the program is
The volume of first cuboid is 3000
The volume of second cuboid is 3000
Self-Instructional
86 Material
Java Classes and Objects
NOTES
In this example, the constructor initializes both the objects c1 and c2 of Cuboid
type with the same values, as a result the volume of both the cuboids is same. Clearly, a
non-parameterized constructor provides same values to all the objects of a class.
6.7.1 Parameterized Constructors
When different objects of a class need to be initialized with different values, a
parameterized constructor can be defined. A parameterized constructor is a constructor
that accepts one or more parameters at the time of creation of objects and initializes the
instance variables of the objects with these parameters. It makes the program more
flexible, because using it we can assign different values to the instance variables of the
objects of a class.
Example 6.8: A program to demonstrate the concept of a parameterized constructor
class Cuboid
{
int length;
int width;
int height;
Cuboid(int l, int w, int h) //parameterized Constructor
{
length=l;
width=w;
height=h;
}
int volume() //method definition
{
return (length*width*height);
}
}
class ParameterizedConstructor
{
public static void main(String args[])
{
Cuboid c1=new Cuboid(10,8,9);
Cuboid c2=new Cuboid(7,6,5);
int a=c1.volume();
int b=c2.volume();
System.out.println(The volume of first cuboid is +a);
System.out.println(The volume of second cuboid is +b);
}
}
The output of the program is
The volume of first cuboid is 720
The volume of second cuboid is 210
Self-Instructional
Material 87
Java Classes and Objects
NOTES
6.8 METHOD OVERLOADING
In some cases when a similar action is to be performed on different types of data,
different methods having different names are to be defined for all types of data. This
makes the program very complex as the programmer must keep track of the names of
all the methods. To prevent such situations, Java allows the methods to be overloaded.
Method overloading allows multiple methods to have same name with different
parameters and different definitions. The application of method overloading is found in
those programs where objects in a class are needed to perform similar operations but
using different input parameters. When a method is called, Java compiler compares the
method name and then the type and number of arguments associated with it to determine
which of the method is to be called and executed. This process is known as
polymorphism.
In order to create overloaded methods in our program, we have to create different
method definitions in the class, all with same name but having different parameters. The
different methods are identified on the basis of the number of parameters, the data type
of the parameters or the order of the data type of the parameters passed to the method.
To understand the concept of method overloading, consider these method declarations.
void sum(int);
void sum(int,int);
In these statements, two methods named, sum() are different as the number of
arguments passed are different. Now, consider these statements.
void addition(int);
void addition(char);
In these statements, two methods named addition() are different as the data type
of arguments passed is different. Now, consider these statements.
void area(int,float);
void area(float,int);
In these statements, two methods named, area() are different as the order of
the data type of the arguments passed is different.
Example 6.9: A program to demonstrate the concept of method overloading
class Shapes
{
void perimeter(int a) //method with int type parameter
{
System.out.println(The perimeter of the square is +(4*a));
}
void perimeter(double a) //method with double type //parameter
{
System.out.println(The circumference of the circle is
+(2*a*(22/7)));
}
void perimeter(int a, int b) //method with two parameters
{
Self-Instructional
88 Material
Java Classes and Objects
NOTES
System.out.println(The perimeter of the rectangle is
+2*(a+b));
}
}
class MethodOverloading
{
public static void main(String args[])
{
Shapes s=new Shapes();
s.perimeter(5.5);
s.perimeter(10);
s.perimeter(15,10);
}
}
The output of the program is
The circumference of the circle is 33.0
The perimeter of the square is 40
The perimeter of the rectangle is 50
6.9 STATIC MEMBERS
So far, we have seen that members of a class can be initialized or accessed by its objects
only. However, it is possible to define members of a class without reference to a specific
object. This is done by declaring the instance variables and methods of a class as static.
Unlike non-static members, the static members are associated with the class as a
whole, rather than with individual objects. Therefore, outside the class the static members
of a class are called by using class names rather than through objects. Since the static
variables and static methods contain the properties of a class and not of the individual
objects, they are also known as class variables and class methods, respectively.
The static variables and static methods of a class are also called class variables and
class methods respectively.
The syntax to declare static variable is
static return_type variable_name;
The syntax to access static variable is
class_name.variable_name
The syntax to declare static method is
static return_type method_name(parameter_list);
The syntax to access static method is
class_name.method_name
If a class member is declared as static, only one copy of that data member is
created, regardless of the number of objects. All the objects of a class share this single
copy of the static data member.
Check Your Progress
6. The return type of
a constructor is
(a) void
(b) int
(c) float
(d) none of these
7. The process of
____________
allows multiple
methods to have
same name with
different
parameters and
different
definitions.
Self-Instructional
Material 89
Java Classes and Objects
NOTES
Example 6.10: A program to demonstrate the use of static members of a class
class StaticMembers
{
static int i=10; //static variable
static void add(int x, int y) //static method
{
System.out.println(Sum of two numbers is: +(x+y));
}
}
class StaticExample
{
public static void main(String args[])
{
StaticMembers.add(30,40); //calling static method
int i= StaticMembers.i; //accessing static
variable
System.out.println(Value of i is: +i);
}
}
The output of the program is
Sum of two numbers is: 70
Value of i is: 10
Here, variable i and method add() are declared as static. Therefore, outside
the class they are accessed using the name of the class in which they are defined.
Note: The methods declared as static can access only static data and call static
methods.
6.10 this KEYWORD
As we know that methods are invoked by the objects of the class. There may be a
situation when a method needs the reference of the object that has invoked it. In Java, it
is accomplished by using this keyword. By using this keyword in any method, we
can refer to the current object (that is the object on which the method was invoked). For
example, consider the following two code segments.
FirstConstructor(int i, int j) //first definition of
constructor
{
this.a=i;
this.b=j;
}
FirstConstructor(int i, int j) //second definition of
constructor
{
Self-Instructional
90 Material
Java Classes and Objects
NOTES
a=i;
b=j;
}
These two constructors will operate in exactly the same way. Here, the use of
this in first code segment is correct but not required. However, it has other uses like
preventing name space collision between the instance variables of a class and variables
declared inside a method.
Example 6.11: A program to demonstrate the name space collision between the instance
variables of a class and variables declared inside a method
class SecondConstructor
{
int i, j;
SecondConstructor(int i, int j)
{
//accessing variables of a constructor
i=i;
j=j;
}
void display()
{
System.out.println(Value of instance variable i:+i);
System.out.println(Value of instance variable j:+j);
}
}
class ConstructorsCall
{
public static void main(String args[])
{
SecondConstructor sc=new SecondConstructor(10, 20);
sc.display();
}
}
The output of the program is
Value of instance variable i:0
Value of instance variable j:0
In this program, the values of i and j are 0. This is because the instance variables
and variables within the constructor have same name so the instance variables i and j
are hidden by the variables of the constructor. However, we can prevent the hiding of
instance variables using this keyword.
Example 6.12: A program to demonstrate the use of this keyword to prevent name
space collision
class SecondConstructor
{
int i, j;
Self-Instructional
Material 91
Java Classes and Objects
NOTES
SecondConstructor(int i, int j)
{
//the values of variables of the constructor are //assigned
to instance variables
this.i=i;
this.j=j;
}
void display()
{
System.out.println(Value of instance variable i:+i);
System.out.println(Value of instance variable j:+j);
}
}
class ConstructorsCall
{
public static void main(String args[])
{
SecondConstructor sc=new SecondConstructor(10, 20);
sc.display();
}
}
The output of the program is
Value of instance variable i:10
Value of instance variable j:20
In this program, the use of this keyword resolves the problem of name space
collision as it refers to the current object (object that invoked the constructor).
6.11 GARBAGE COLLECTION
As already discussed, the new operator in Java is used to allocate memory space to the
objects dynamically. This memory space needs to be freed once the object occupying it
gets destroyed or is no longer needed in the program. Java provides us a mechanism
known as garbage collection, which handles the deallocation of the memory
automatically. When there are no references to an object available, the memory occupied
by the object can be reclaimed by the garbage collector without the need to explicitly
destroy the object. The process of garbage collection occurs periodically to collect the
memory space occupied by those objects that are no longer referenced either directly
(during program execution) or indirectly by other referenced objects.
6.11.1 The finalize() Method
Sometimes there might be a situation when an object is holding some non-object resources
like file descriptor which cannot be freed by the garbage collector. Then, we need to
ensure that these resources are freed before the object gets destroyed. To deal with
such situation, finalize() method is used. All the operations which must be performed
Check Your Progress
8. Which of these is a
valid method
declaration?
(a) int
sum(int x,
int y)
(b) int
sum(int x,
y)
(c) sum(int x,
int y)
(d) sum(int,
int)
9. The ___________
data members of a
class are
independent of any
particular object of
the class.
10. this keyword is
used to refer to the
current object.
(True or False)
11. What is the
function of
finalize()
method?
Self-Instructional
92 Material
Java Classes and Objects
NOTES
just before the object is destroyed are placed inside the finalize() method. The
Java runtime calls this method whenever an object is about to be recycled.
The syntax of finalize() method is
protected void finalize()
{
//finalization code
}
The keyword protected is an access specifier that prevents access to the
finalize() method by the code outside the class.
Note: Access specifiers (access modifiers) are discussed in detail in Chapter 08.
6.12 SUMMARY
In this unit, you have learned that:
The key objective of object-oriented programming is to represent the various
real-world objects as program elements.
A class is a user-defined data type that can be used to create instances of its type
called objects.
Methods are added in the class to access the instance variables of a class and
manipulate them.
Objects are variables of class type inside which they are created.
The instance variables and methods added in the program cannot be accessed
directly outside the class using their names. To access the variables and methods
outside the class dot (.) operator is used.
The argument(s) that appear in the method call statement are known as actual
arguments and those which appear in the method definition are known as formal
arguments.
There are two ways by which an argument can be passed to the methodcall by
value and call by reference.
In call-by-value method, the values of the actual arguments are copied into the
formal arguments.
In call-by-reference method, arguments reference is passed as method parameter.
A constructor is a special method which is used to initialize objects at the time of
their creation.
A parameterized constructor is a constructor that accepts one or more parameters
at the time of creation of objects and initializes the instance variables of the
objects with these parameters.
Method overloading allows multiple methods to have same name with different
parameters and different definitions.
The static members of a class are defined without reference to a specific
object. The static members are associated with the class as a whole, rather
than with individual objects.
Self-Instructional
Material 93
Java Classes and Objects
NOTES
The this keyword is used to refer to the current object (that is the object on
which the method was invoked).
All the operations that are to be performed just before the object is destroyed are
placed inside the finalize() method.
6.13 KEY TERMS
Encapsulation: It is the technique of binding or keeping the data and functions
(that operate on them) together in a single unit called a class.
Class: It is a user-defined data type that can be used to create instances of its
type called objects.
Call-by-value method: It is one of the two ways of argument passing, in which
the values of the actual arguments are copied into the formal arguments.
Constructor: It is a special method which is used to initialize objects at the time
of their creation.
Parameterized constructor: It is a constructor that accepts one or more
parameters at the time of creation of objects and initializes the instance variables
of the objects with these parameters.
6.14 ANSWERS TO CHECK YOUR PROGRESS
1. Class, object
2. (b)
3. (d)
4. Parameterized
5. Call-by-value, call-by-reference
6. (d)
7. Method overloading
8. (a)
9. Static
10. True
11. All the operations which are to be performed just before the object is destroyed
are placed inside the finalize() method.
6.15 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What is a class and how is it related to objects?
2. Find and fix the error in the following program to display the area of the rectangle
class Rectangle
{
public static void main(String args[])
Self-Instructional
94 Material
Java Classes and Objects
NOTES
{
Rectangle rect;
rect.length=10;
rect.width=7;
System.out.println(Area of the rectangle rect
is+rect.area());
}
}
3. What are the two possible ways of passing arguments to a method? What is the
difference between them?
4. Define a class Student having instance variables: roll_number, marks1,
marks2 and marks3 and method: calculate() to calculate the overall
percentage of marks and return the percentage of marks.
5. What is the difference between a method and a constructor?
6. Can the objects of a class be initialized at run-time using constructors? Give an
example.
Long-Answer Questions
1. Explain the significance of method overloading. Give example.
2. Consider the given class and identify the instance and class variables
class IdentifyVariables
{
a. float a=4.0;
b. static int b=14;
}
3. How is a static method invoked? Explain with an example.
4. Explain the importance of this keyword.
5. Explain how garbage collection is accomplished with the help of finalize()
method.
6. Define a class Teacher having instance variables: Teacher_id, Basic, DA
and HRA and method: calculate() to calculate the salary. (Hint: Salary is the
sum of Basic, DA and HRA)
Self-Instructional
Material 95
Arrays and Vectors
NOTES
UNIT 7 ARRAYS AND VECTORS
Structure
7.0 Introduction
7.1 Unit Objectives
7.2 Arrays
7.2.1 Single-Dimensional Arrays
7.2.2 Multi-Dimensional Arrays
7.3 Vectors
7.4 Wrapper Classes
7.5 Summary
7.6 Key Terms
7.7 Answers to Check Your Progress
7.8 Questions and Exercises
7.0 INTRODUCTION
Handling real-world data requires a mechanism that deals with a collection of data
items. In Java, different data types like arrays and vectors are offered to handle such
collections. These data types are capable of grouping related data items together into a
single unit. Arrays hold together few or thousands of data items of similar data types
under a single name and vectors provide a way to keep items of any data types in any
number together into a single entity.
In this unit, you will be familiarized with the basics of arrays and vectors. The
concept of wrapper classes is also discussed in the later section of this unit.
7.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Declare, initialize and manipulate single-dimensional and multi-dimensional arrays
Understand the significance of vectors
Explain the concept of wrapper classes
7.2 ARRAYS
Java uses variables of different primitive data types to store data. However, these
variables are incapable of holding more than one value at a time. For example, a single
variable cannot be used for storing the marks of all the students in a class. For such
purposes, Java provides a different kind of data type known as arrays.
Arrays are defined as a fixed size sequence of same type of data elements.
These data elements can be of any primitive or non-primitive data type. The elements of
an array are stored in contiguous memory locations and each individual element can be
accessed using one or more indices or subscripts. A subscript or an index is a positive
integer value, which indicates the position of an element in an array. Arrays are used
when a programmer wants to store multiple data items of same type into a single list and
Self-Instructional
96 Material
Arrays and Vectors
NOTES
also wants to access and manipulate individual elements of the list. Arrays can be either
single-dimensional or multi-dimensional depending upon the number of subscripts
used.
7.2.1 Single-Dimensional Arrays
A single-dimensional array is the simplest form of an array that requires only one subscript
to access an array element. Like an ordinary variable, an array must be declared before
it is used in the program.
The syntax for declaring a single-dimensional array is
data_type array_name[];
or
data_type[]array_name;
where,
data_type is any data type
array_name is the name of the array
For example, an array marks[] of type int can be declared using either of the two
statements.
int marks[];
or
int[] marks;
After an array is declared, we need to create it by allocating space to it in memory.
Arrays are created using new operator.
The syntax for creating an array is
array_name=new data_type[size];
where,
size is the size of the array
For example, an array marks[] of type int and size five can be created using this
statement.
marks=new int[5];
The above two steps of declaration and creation of an array can be combined into a
single statement as shown below.
data_type array_name=new data_type[size];
Similarly, the statement to declare and create an array marks[] of type int and size
five is
int marks[]=new int[5];
Note: All the elements created using new operator in the array will be automatically
initialized to zero.
Initialization of Single-Dimensional Array
Once an array is declared and memory is allocated to it, the next step is to initialize each
array element with a valid and appropriate value. An array can be initialized at the time
of its declaration.
Self-Instructional
Material 97
Arrays and Vectors
NOTES
The syntax for initializing an array at the time of its declaration is
data_type array_name[]={value_1,value_2,......,value_n};
The values are assigned to the array elements in the order in which they are
listed. That is, value_1, value_2 and value_n are assigned to the first, second
and n
th
element of the array, respectively.
If an array is declared and initialized simultaneously, then specifying its size is
optional. For example, the statement int marks[]={51,62,43,74,55} is also
valid. The size of an array marks can be obtained by using marks.length()
method.
Note: If you try to store or access values outside the range of array (index with
negative value or value greater than the length of the array), run-time error is
generated.
Accessing Single-Dimensional Array Elements
Once an array is declared and initialized, the values stored in the array can be accessed
any time. Each individual array element can be accessed using the name of the array
and the subscript value. Every element in an array is associated with a unique subscript
value, starting from 0 to size-1 (where, size refers to the maximum number of
elements that can be stored in the array).
The syntax for accessing the values stored in a single-dimensional array is
array_name[subscript]
For example, the elements of the array marks can be referred to as marks[0],
marks[1], marks[2], marks[3] and marks[4], respectively. Note that index
of an array starts with 0.
Note: The memory location, where the first element of an array is stored, is known
as the base address, which is generally referred to by the name of the array.
Single-dimensional arrays are always allocated contiguous blocks of memory.
This implies that every element in an array is always stored in sequential manner next to
each other. The memory representation of the array marks is shown in Figure 7.1. As
each element is of type int (that is, 4 bytes long), the array marks occupies twenty
contiguous bytes in the memory and these bytes are reserved in the memory at compile-
time.

marks


marks[3]

marks[2]

marks[1]

marks[0]
74

62

51
marks[4]

2001

2005

2009

2013

2017

55 43

Figure 7.1 Memory Representation of an Array marks
Manipulation of Single-Dimensional Array Elements
An array can be manipulated with the help of various operations. These operations
include finding the sum, average, maximum or minimum, sorting and searching of the
array elements, etc.
Example 7.1: A program to sort the array elements
class SortingArray
Self-Instructional
98 Material
Arrays and Vectors
NOTES
{
public static void main(String args[])
{
int a[]={67, 34, 12, 98, 26}; //array initialization
//at the time of declaration
int n=a.length; //returns the length of the array
System.out.print(The list of numbers:);
for(int i=0;i<n;i++)
{
System.out.print( +a[i]);
}
//sorting elements of an array
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
System.out.print(\n);
System.out.print(The sorted list of given numbers:);
for(int i=0;i<n;i++) //displaying sorted array
{
System.out.print( +a[i]);
}
}
}
The output of the program is
The list of numbers: 67 34 12 98 26
The sorted list of given numbers: 12 26 34 67 98
7.2.2 Multi-Dimensional Arrays
Multi-dimensional arrays can be described as an array of arrays, that is, each element
of the array is itself an array. A multi-dimensional array of dimension n is a collection of
items that are accessed with the help of n subscript values.
Self-Instructional
Material 99
Arrays and Vectors
NOTES
Two-Dimensional Array
A two-dimensional array is the simplest form of a multi-dimensional array that requires
two subscript values to access an array element. Two-dimensional arrays are useful
when the data being processed are to be arranged in the form of rows and columns
(matrix form).
The syntax for declaring a two-dimensional array is
data_type array_name[][];
or
data_type[][] array_name;
The syntax for creating a two dimensional array is
array_name[][]=new data_type[row_size][column_size];
The above two steps of declaration and creation can be combined into one using a single
statement as shown below.
data_type array_name[][]=new
data_type[row_size][column_size];
For example, an array a[][] of type int having three rows and two columns can be
declared and created using this statement.
int a[][]=new int[3][2];
Here, 3 is the row size and 2 is the column size.
Initialization of Two-Dimensional Array
Like a single-dimensional array, a two-dimensional array can also be declared and
initialized at the same time. To understand how to initialize a two-dimensional array,
consider this statement.
int a[3][2]={ {101,51},
{102,67},
{103,76} };
In this statement, an array a[][] of type int having three rows and two columns
is declared and initialized. This type of initialization is generally used to increase the
readability.
Now, consider another statement.
int b[][]={ { 2,3,4}, {1,1,1} };
In this statement, an array b[][] of type int having two rows and three columns
is initialized.
Accessing Two-Dimensional Array Elements
Once a two-dimensional array is declared and initialized, the value stored in the array
elements can be accessed using two subscripts.
The syntax for accessing the two-dimensional array element is
array_name[row][column]
The first subscript value (row) specifies the row number and the second subscript
value (column) specifies the column number. Both the subscript values specify the
position of the array element within the array.
Self-Instructional
100 Material
Arrays and Vectors
NOTES
For example, the elements of array a (declared earlier) are referred to as
a[0][0], a[0][1], a[1][0], a[1][1], a[2][0] and a[2][1], respectively.
Generally, two-dimensional arrays are represented with the help of a matrix.
However, in actual implementation, two-dimensional arrays are always allocated
contiguous blocks of memory. Figure 7.2 shows matrix and memory representation of
two-dimensional array a.
101 51
105 67
103 76
101 51 105 67 103 76
a[0][0] a[0][1] a[1][0] a[1][1] a[2][0] a[2][1]

2001 2005 2009 2013 2017 2021
first row second row third row
Matrix Representation Memory Representation
Figure 7.2 Matrix and Memory Representation of Array a[][]
Manipulation of Two-Dimensional Array Elements
A two-dimensional array can be manipulated in many ways. Some of the common
operations that can be performed on a two-dimensional array include finding the sum of
row elements, column elements and diagonal elements, finding the maximum and
minimum values, etc.
Example 7.2: A program to calculate the sum of two matrices
class MatricesSummation
{
public static void main(String args[])
{
int a[][]={{3,4,5},{3,2,7}}; //initializing matrix
a
int b[][]={{2,4,7},{1,2,2}}; //initializing matrix
b
int l=a.length;
System.out.println(First matrix is: + );
for(int i=0;i<l;i++) //displaying first matrix
{
for (int j=0;j<3; j++)
{
System.out.print( +a[i][j]);
}
System.out.println();
}
int m=b.length;
System.out.println(Second matrix is:+ );
for (int i=0;i<m;i++) //displaying second matrix
{
Self-Instructional
Material 101
Arrays and Vectors
NOTES
for(int j=0;j<3;j++)
{
System.out.print( + b[i][j]);
}
System.out.println();
}
System.out.println(Summation of the two matrices
is: );
//displaying sum of two matrices
for(int i=0;i<m;i++)
{
for(int j=0;j<=m;j++)
{
System.out.print( +(a[i][j]+b[i][j]));
}
System.out.println();
}
}
}
The output of the program is
First matrix is:
3 4 5
3 2 7
Second matrix is:
2 4 7
1 2 2
Summation of the two matrices is:
5 8 12
4 4 9
Variable Size Arrays
As already mentioned, multi-dimensional arrays are arrays of arrays. In such multi-
dimensional arrays the size of each array can be varied. For example, consider these
statements.
data_type array_name[][]=new data_type[size][];
array_name[0]=new data_type[size_1];
.
.
.
array_name[n-1]=new data_type[size_n];
where,
size is the number of rows in two-dimensional array
size_1, . . . , size_n represents the number of columns in each row of two-dimensional
array
Self-Instructional
102 Material
Arrays and Vectors
NOTES
Example 7.3: A program to demonstrate a variable size array
class VariableArray
{
public static void main(String args[])
{
int a[][]=new int[4][];
a[0]=new int[2];
a[1]=new int[4];
a[2]=new int[3];
a[3]=new int[5];
int i,j;
System.out.println(The variable sized array is: );
for(i=0;i<4;i++)
{
for (j=0; j<a[i].length; j++)
{
a[i][j]=j;
System.out.print( +a[i][j]);
}
System.out.println();
}
}
}
The output of the program is
The variable sized array is:
0 1
0 1 2 3
0 1 2
0 1 2 3 4
7.3 VECTORS
The Vector class contained in the java.util package defines methods to store
objects into a single unit. It can be used to implement dynamic array called vectors
which can accommodate any number and any type of objects. Consider the following
statements.
Vector v1=new Vector( ); //creating vector without specifying
its //initial capacity
Vector v2=new Vector(n); //creating vector having initial
capacity //n
Here, the first statement creates a vector v1 having initial capacity 10. That is,
when you create a vector without specifying its initial capacity it is automatically set to
10. Similarly, the second statement creates a vector v2 with initial capacity n. Although,
we have created the vector v2 by specifying its initial capacity but this specification
Check Your Progress
1. An array is a fixed
size sequence of
elements of _____
data type.
2. A ___________ is
a positive integer
value which
indicates the
position of an
element in an array.
3. Which of these
array elements is
referred by
arr[3]?
(a) third
(b) second
(c) fourth
(d) fifth
4. A single-
dimensional array
requires ______
subscript to access
an array element.
5. In a two-
dimensional array,
elements are
arranged in the
form of ________
and ___________.
Self-Instructional
Material 103
Arrays and Vectors
NOTES
does not pose any limitation on the size of the vector. Since, the size of the vector can be
increased or decreased by adding or removing objects to it.
The Vector class provides a variety of methods which can be used to perform
different operations on vectors, some of them beeing listed in Table 7.1.
Table 7.1 Vector Methods and Their Description
Methods Description
vect1.addElement(object) Adds the specified object at the end of the
vector list vect1
vect1.size() Returns the number of objects currently present in
the vector vect1
vect1.capacity() Returns the maximum capacity of the vector
vect1
vect1.removeElement(object) Removes the specified object from the vector
vect1
vect1.elementAt(n) Returns the name of the n
th
object of the vector
vect1
vect1.removeElementAt(n) Removes the item at the n
th
position of the vector
vect1
vect1.removeAllElements() Removes all the elements in the vector vect1
vect1.firstElement() Returns the first element of the vector vect1
vect1.lastElement() Returns the last element of the vector vect1
vect1.trimToSize() Sets the capacity of the vector vect1 to the
number of objects it is currently holding
Example 7.4: A program to demonstrate the use of some of the methods of Vector
class
import java.util.*; //importing package for using vectors
public class VectorMethods
{
public static void main(String[] args)
{
Vector vect1 = new Vector();
String str1 = Hello!!!;
String str2 = How are you?;
String str3= All the best!;
//adding string object to the vector
vect1.addElement(str1);
vect1.addElement(str2);
vect1.addElement(str3);
System.out.println(The initial capacity of the
vector is: +vect1.capacity());
System.out.println(The elements of vector:
+vect1);
System.out.println(The size of vector is:
+vect1.size());
System.out.println(The first element of vector
is: +vect1.firstElement());
Self-Instructional
104 Material
Arrays and Vectors
NOTES
System.out.println(The last element of vector is:
+vect1.lastElement());
}
}
The output of the program is
The initial capacity of the vector is: 10
The elements of vector: [Hello!!!, How are you?, All the
best!]
The size of vector is: 3
The first element of vector is: Hello!!!
The last element of vector is: All the best!
Note: The String class is used to create the string object.
7.4 WRAPPER CLASSES
One limitation of using vectors is that we cannot store data items of primitive data types
like int, float, char, long, double, etc. since it can store only objects. Therefore,
primitive data types need to be converted into objects before storing them in vectors. To
accomplish this, Java provides wrapper classes contained in the java.lang package.
The wrapper classes are used to convert the primitive data types into their respective
class instances. For example, a float data type is represented as an instance of
Float class.
It should be noted that Javas primitive wrapper classes are immutable, that is,
once a value is assigned to an instance of a wrapper class it cannot be changed later.
The primitive data types and their corresponding wrapper classes are shown in the
Table 7.2.
Table 7.2 Primitive Data Types and Their Corresponding Wrapper Classes
Primitive Data Type Wrapper Class
boolean java.lang.Boolean
byte java.lang.Byte
char java.lang.Character
double java.lang.Double
float java.lang.Float
int java.lang.Integer
long java.lang.Long
short java.lang.Short
void java.lang.Void
Some of the methods of wrapper classes are listed in Table 7.37.7.
Table 7.3 Conversion of Primitive Data Types to Object Types using Constructor Methods
Constructor Calling Action Performed
Integer a=new Integer(i); coverts integer to Integer object
Float b=new Float(f); coverts float to Float object
Double c=new Double(d); coverts double to Double object
Long d=new Long(l); coverts long to Long object
Self-Instructional
Material 105
Arrays and Vectors
NOTES
Table 7.4 Conversion of Object Numbers to Primitive Numbers using typeValue() Method
Method Calling Action Performed
int i=a.intValue(); converts object to integer
float f=b.floatValue(); converts object to float
double d=c.doubleValue(); converts object to double
long l=d.longValue(); converts object to long
Table 7.5 Conversion of Primitive Numbers to Strings using toString() Method
Method Calling Action Performed
str=Integer.toString(i); converts Primitive integer to string
str=Float.toString(f); converts Primitive float to string
str=Long.toString(l); converts Primitive long to string
str=Double.toString(d); converts Primitive double to string
Table 7.6 Conversion of String Objects to Numeric Objects using valueOf() Method
Method Calling Action Performed
IntVal=Integer.valueOf(str); converts string to Integer object
FloatVal=Float.valueOf(str); converts string to Float object
LongVal=Long.valueOf(str); converts string to Long object
DoubleVal=Double.valueOf(str); converts string to Double object
Table 7.7 Conversion of Strings to Primitive Numbers using Parsing Methods
Method Calling Action Performed
int i=Integer.parseInt(str) converts string to primitive integer
long l=Long.parseLong(str) converts string to primitive long
Note: The methods defined in the wrapper classes are static.
Example 7.5: A program to demonstrate the use of wrapper classes
import java.io.*;
class WrapperClassMethod
{
public static void main(String args[])
{
Float p=new Float(0); //converting float to Float //object
Float r=new Float(0);
int t=0;
Float si=new Float(0);
try
{
DataInputStream cin=new DataInputStream(System.in);
System.out.println(Enter the value of p);
String principal=cin.readLine();
p=Float.valueOf(principal); //converting String //object to
Float //object
Self-Instructional
106 Material
Arrays and Vectors
NOTES
System.out.println(Enter the value of r);
String rate=cin.readLine();
r=Float.valueOf(rate);
System.out.println(Enter the value of t);
String time=cin.readLine();
t=Integer.parseInt(time); //converting string to //integer
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
System.out.println(The value of p entered is: +p);
System.out.println(The value of r entered is: +r);
System.out.println(The value of t entered is: +t);
si=(p*t*r)/100;
System.out.println(Simple interest of given input data is:
+si);
float total=p+(si*t);
System.out.println(Total amount after 4 years is: +total);
}
}
The output of the program is
Enter the value of p
10000
Enter the value of r
5
Enter the value of t
4
The value of p entered is: 10000.0
The value of r entered is: 5.0
The value of t entered is: 4
Simple interest of given input data is: 2000.0
Total amount after 4 years is: 18000.0
7.5 SUMMARY
In this unit, you have learned that:
Arrays are defined as a fixed size sequence of same type of data elements.
The elements of an array are stored in contiguous memory locations and each
individual element can be accessed using one or more indices or subscripts.
Check Your Progress
6. The ___________
class contains
methods to store
any number and
any type of
objects in a single
unit called vectors.
7. The initial capacity
of a default vector
is______________.
8. The vectors cannot
be used to store
primitive data
types. (True or
False)
9. The __________
classes are used to
convert primitive
data type into
objects before
storing them in the
vectors.
Self-Instructional
Material 107
Arrays and Vectors
NOTES
Arrays can be either single-dimensional or multi-dimensional depending upon the
number of subscripts used.
A single-dimensional array is the simplest form of an array that requires only one
subscript to access an array element.
Multi-dimensional arrays can be described as an array of arrays, that is, each
element of the array is itself an array.
A two-dimensional array is the simplest form of a multi-dimensional array that
requires two subscript values to access an array element.
The Vector class is used to implement dynamic array called vectors which
can accommodate any number and any type of objects.
The wrapper classes are used to convert the primitive data types into their respective
class instances.
7.6 KEY TERMS
Array: It is a systematic arrangement of objects or data, usually into rows and
columns.
Multi-dimensional array: It is a collection of items accessed via n subscript
expressions (i.e., an n-dimensional array or simply n-D array).
Single-dimensional array: It is a structured collection of components that can
be accessed individually by specifying the position of a component with a single
index value.
Vector: It is a class contained in the java.util package that defines methods
to store objects into a single unit and that can be used to implement dynamic
arrays that can accommodate any number and any type of objects.
Wrapper class: It is a class in the Java programming language provided in the
java.lang package that provides object methods.
7.7 ANSWERS TO CHECK YOUR PROGRESS
1. Similar
2. Subscript/index
3. (c)
4. One
5. Rows, columns
6. Vector
7. 10
8. True
9. Wrapper
Self-Instructional
108 Material
Arrays and Vectors
NOTES
7.8 QUESTIONS AND EXERCISES
Short-Answer Questions
1. Define what an array is.
2. What is the importance of arrays?
3. What are vectors?
4. How would you differentiate between vectors and arrays?
Long-Answer Questions
1. Differentiate between single-dimensional and multi-dimensional arrays.
2. Write a program to multiply two given matrices and print the resultant matrix.
3. Write a program to create a list of names of five students in a class and store
them in a vector. In addition perform the following operations in the list
(a) Add a name at the end of the list.
(b) Delete a name at the third position in the list.
(c) Display the final contents of the list.
4. Discuss the significance of wrapper classes in Java.
Self-Instructional
Material 109
Inheritance and
Polymorphism
NOTES
UNIT 8 INHERITANCE AND
POLYMORPHISM
Structure
8.0 Introduction
8.1 Unit Objectives
8.2 Inheritance Basics
8.2.1 Defining a Subclass
8.3 Types of Inheritance
8.3.1 Single Inheritance
8.3.2 Hierarchical Inheritance
8.3.3 Multilevel Inheritance
8.3.4 Multiple Inheritance
8.4 Access Modifiers
8.5 Subclass Constructor
8.6 Method Overriding
8.7 Polymorphism
8.8 Using final Keyword
8.8.1 Final Variables
8.8.2 Final Methods
8.8.3 Final Classes
8.9 Abstract Methods and Classes
8.10 Summary
8.11 Key Terms
8.12 Answers to Check Your Progress
8.13 Questions and Exercises
8.0 INTRODUCTION
Inheritance is one of the major strengths of object-oriented programming. It is the process
of deriving a new class from the existing one in such a way that the new class inherits all
the members (data members and methods) of the existing class. In other words, inheritance
facilitates a class to acquire the properties and functionality of another class. The new
class depicts the acquired properties and behavior of the existing class as well as its own
unique properties and behavior. Inheritance allows code reusability, that is, it facilitates
classes to reuse the existing code. The new class acquires those members of the old
class that are already tested and debugged. Hence, inheritance saves time as well as
increases the reliability. Using inheritance, we can create a general class that defines
common properties for a set of related classes.
Polymorphism, the third basic principle of object-oriented programming, is the
ability of an action or method to do different things based on the object that it is acting
upon. The two types of polymorphism are overloading and overriding.
In this unit, you will learn about inheritance and polymorphism in detail.
Self-Instructional
110 Material
Inheritance and
Polymorphism
NOTES
8.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Understand what inheritance is
Explain the benefits of inheritance such as code reusability
Understand the concept of superclass and subclass
Discuss the various types of inheritance
Explain various access modifiers supported by Java
Know about subclass constructor
Understand what method overriding and polymorphism are
Describe how the final keyword can be applied to variables, methods and
classes
Explain abstract methods and abstract classes
8.2 INHERITANCE BASICS
The class that is inherited by other classes is called a base class or superclass or
parent class. The class that inherits the properties of the superclass is called a subclass
or derived class or child class. The subclass inherits all of the instance variables and
methods defined by the superclass, at the same time it also contains its own members.
For example, in Figure 8.1, Animal is the superclass which is inherited by three subclasses
Carnivore, Herbivore and Omnivore. Hence, Carnivore, Herbivore and Omnivore
inherit all the members of the superclass Animal.
Superclass


Subclasses

Carnivore Herbivore Omnivore
Figure 8.1 Superclass and Subclass
8.2.1 Defining a Subclass
Inheritance is implemented while defining the subclass. The name of the superclass is
specified in the subclass definition. A subclass can be defined by using extends
keyword.
The syntax to define a subclass is
class sub_class extends super_class
{
//variables and methods declaration
}
where,
Self-Instructional
Material 111
Inheritance and
Polymorphism
NOTES
sub_class is the name of the subclass that inherits the superclass
super_class is the name of the superclass that is being inherited
extends is the keyword that indicates that the super_class properties have been
extended to the sub_class
8.3 TYPES OF INHERITANCE
Inheritance allows creating a logical relationship between two or more classes. Depending
on the number of classes involved and the way the classes are inherited, inheritance
may take different forms, namely, single inheritance, hierarchical inheritance,
multilevel inheritance and multiple inheritance.
8.3.1 Single Inheritance
In single inheritance, a class is derived from a single superclass. Figure 8.2 shows
single inheritance in which subclass Employee is derived from the superclass Person.
Person
Person
Employee
Figure 8.2 Example of Single Inheritance
The syntax to define the subclass that implements single inheritance is
class Class1
{
:
}
class Class2 extends Class1
{
:
}
Example 8.1: A program to demonstrate single inheritance
class FirstClass // superclass
{
int i;
int j;
void get_first(int p, int q)
{
i=p;
j=q;
}
Self-Instructional
112 Material
Inheritance and
Polymorphism
NOTES
}
class SecondClass extends FirstClass // subclass
{
int k;
void get_second(int m)
{
k=m;
}
void display()
{
System.out.println(The value of superclass i is: +i);
System.out.println(The value of superclass j is: +j);
System.out.println(The value of subclass k is: +k);
}
}
class SingleInheritance
{
public static void main(String args[])
{
SecondClass obj = new SecondClass();
obj.get_first(20,30); //accessing superclassmethod
obj.get_second(40); //accessing subclassmethod
obj.display(); //accessing subclassmethod
}
}
The output of the program is
The value of superclass i is: 20
The value of superclass j is: 30
The value of subclass k is: 40
In this example, the superclass FirstClass is inherited by the class
SecondClass. Hence, SecondClass includes variables i, j and the method
get_first() of FirstClass and also defines its own data member k and
display() method.
8.3.2 Hierarchical Inheritance
The type of inheritance in which more than one class is derived from a single superclass
is called hierarchical inheritance. In hierarchical inheritance, superclass includes all
the properties that are common to all of its subclasses. Figure 8.3 shows hierarchical
inheritance with two classes Student and Employee deriving from a single superclass
Person.
Self-Instructional
Material 113
Inheritance and
Polymorphism
NOTES

Person
Student Employee
Figure 8.3 Example of Hierarchical Inheritance
The syntax to implement hierarchical inheritance involving two subclasses is
class Class1
{
:
}
class Class2 extends Class1
{
:
}
class Class3 extends Class1
{
:
}
Example 8.2: A program to demonstrate hierarchical inheritance
class FirstClass // superclass
{
int i;
int j;
int k;
void get_first(int p, int q, int r)
{
i=p;
j=q;
k=r;
}
}
class SecondClass extends FirstClass // first subclass
{
int x;
int y;
void get_second(int a, int b)
{
x=a;
y=b;
}
void display1()
Self-Instructional
114 Material
Inheritance and
Polymorphism
NOTES
{
System.out.println(The value of superclasss i,j and k is:
+i+,+j+ and +k);
System.out.println(The value of first subclasss x and y
is: +x+ and +y);
System.out.println( );
}
}
class ThirdClass extends FirstClass // second subclass
{
int z;
void get_third(int c)
{
z=c;
}
void display2()
{
System.out.println(The value of superclasss i,j and k is:
+i+,+j+ and +k);
System.out.println(The value of second subclasss z is:
+z);
}
}
class HierarchicalInheritance
{
public static void main(String args[])
{
SecondClass obj1 = new SecondClass();
// accessing superclass method and first subclass methods.
obj1.get_first(9,8,6);
obj1.get_second(3,6);
obj1.display1();
ThirdClass obj2 = new ThirdClass();
// accessing superclass method and second subclass methods.
obj2.get_first(2,4,8);
obj2.get_third(5);
obj2.display2();
}
}
Self-Instructional
Material 115
Inheritance and
Polymorphism
NOTES
The output of the program is
The value of superclasss i,j and k is: 9,8 and 6
The value of first subclasss x and y is: 3 and 6
The value of superclasss i,j and k is: 2,4 and 8
The value of second subclasss z is: 5
In this example, the superclass FirstClass is inherited by two classes
SecondClass and ThirdClass. The subclasses SecondClass and
ThirdClass inherit all the data members i, j, k and the method get_first() of
FirstClass and also define their own data members.
8.3.3 Multilevel Inheritance
In multilevel inheritance, one class is inherited from another class, which in turn is
inherited from some other class. Multilevel inheritance comprises two or more levels.
The subclass has all the properties of its direct superclass as well as its indirect superclass.
This is known as the transitive nature of multilevel inheritance. Figure 8.4 shows
multilevel inheritance in which superclass Person is inherited by a subclass Employee,
which is again inherited by another subclass Faculty. Hence, Person is an indirect
superclass to Faculty.
Person
Employee
Faculty
Superclass
Intermediate superclass
Subclass
Figure 8.4 Example of Multilevel Inheritance
The syntax to implement multilevel inheritance is
class Class1
{
:
}
class Class2 extends Class1
{
:
}
class Class3 extends Class2
{
:
}
Self-Instructional
116 Material
Inheritance and
Polymorphism
NOTES
Example 8.3: A program to demonstrate multilevel inheritance
class FirstClass //superclass
{
int i;
int j;
void get_first(int a, int b)
{
i=a;
j=b;
}
}
class SecondClass extends FirstClass //intermediate
superclass
{
int k;
void get_second(int c)
{
k=c;
}
}
class ThirdClass extends SecondClass //subclass
{
int l;
void get_third(int m)
{
l=m;
}
void display()
{
System.out.println(The value of superclasss i and j is:
+i+ and +j);
System.out.println(The value of intermediate superclasss
k is: +k);
System.out.println(The value of subclasss l is: +l);
}
}
class MultilevelInheriatnce
{
public static void main(String args[])
{
ThirdClass obj=new ThirdClass();
//accessing superclass method
obj.get_first(9,8);
Self-Instructional
Material 117
Inheritance and
Polymorphism
NOTES
//accessing intermediate superclass method
obj.get_second(10);
//accessing subclass method
obj.get_third(11);
obj.display();
}
}
The output of the program is
The value of superclasss i and j is: 9 and 8
The value of intermediate superclasss k is: 10
The value of subclasss l is: 11
In this example, the class FirstClass is inherited by the class SecondClass,
which in turn is inherited by the class ThirdClass. This implies that FirstClass
is the superclass while SecondClass is the intermediate superclass. The subclass
ThirdClass inherits the members of both the classes FirstClass and
SecondClass. Hence, it includes data members i, j, k and get_first(),
get_second() methods.
8.3.4 Multiple Inheritance
In multiple inheritance, a class inherits properties from more than one superclass as
shown in Figure 8.5. In Java, it is not possible to implement multiple inheritance directly.
However, there is a concept known as interface through which multiple inheritance can
be implemented.
Person Company
Owner
Figure 8.5 Example of Multiple Inheritance
8.4 ACCESS MODIFIERS
In the programs discussed so far, the class members are accessible everywhere in the
program and the subclass can inherit all the variables and methods of a superclass by
using the keyword extends. However, there might be certain situations when we
want to restrict the accessibility of members of a class for various reasons, security
being one of the main reasons. For this, Java provides three types of access modifier,
namely, public, private and protected.
Public: When a member of a class is declared as public, it can be accessed
everywhere in the program.
Check Your Progress
1. Define inheritance.
2. The class that is
inherited by the
new class is called
_____________.
3. A Java subclass
can be defined by
using the
_____________
keyword.
4. Java does not
implement
multiple
inheritance
directly. (True or
False)
5. In which of the
following
inheritances, a
superclass is
inherited by more
than one subclass?
(a) single
inheritance
(b) multiple
inheritance
(c) heirarchical
inheritance
(d) multilevel
inheritance
Self-Instructional
118 Material
Inheritance and
Polymorphism
NOTES
Private: A member declared as private can be accessed only within a class.
Protected: A member declared as protected is accessible not only to all the
classes and subclasses in the same package but also to subclasses in other
packages.
Note that if no access modifier is specified, by default the data member of a class
is visible only within the same package. We may use the word friendly in connection
with the default access, however, friendly is not a Java keyword.
Apart from the access modifiers discussed, there is another access modifier namely
private protected which was used with the release of Java 1.0. However, it has
been dropped in Java 1.1 and further versions. If data members are declared as private
protected, they can be accessed by all the subclasses irrespective of the package to
which they belong. However, they are not visible in other classes of the same package
(Table 8.1).
Table 8.1 Visibility of Field inside a Class
Access location


Access modifier
Same
class
Subclass in
same
package
Non-
subclasses in
same
package
Subclass in
other
packages
Non-
subclasses in
other
packages
Public
Private
Protected
Default

These are certain rules that can be followed to select appropriate access modifier.
If the data member is to be made
visible everywhere in the program, use public access modifier.
invisible everywhere except within the same class, use private access modifier
visible everywhere in the same package and subclasses in other package, use
protected access modifier.
visible everywhere in the same package only, use the default access modifier.
visible only in the subclasses irrespective of packages, use private
protected.
Example 8.4: A program to demonstrate the use of private, public and default access
modifiers
class FirstClass
{
int i; //default variable
private int j; //private variable
public int k; //public varaible
int get_data(int l)
{
j=l;
return j;
}
Self-Instructional
Material 119
Inheritance and
Polymorphism
NOTES
}
class VisibilityTest
{
public static void main(String[] args)
{
FirstClass obj=new FirstClass();
obj.i=20; //i can be accessed directly
obj.k=60; //k can be accessed directly
//this will cause error as j cannot be
//accessed directly
//obj.j=60;
//j can be accessed through its method
int a=obj.get_data(40);
System.out.println(The value of i,j and k are: +obj.i+
,+a+ and +obj.k+ respectively.);
}
}
The output of the program is
The value of i,j and k are: 20,40 and 60 respectively.
In this example, variable i is set to default access, variable j is declared as
private and variable k is declared as public. In the class VisibilityTest,
only variables i and k can be accessed directly. The variable j can be accessed through
its method get_data().
8.5 SUBCLASS CONSTRUCTOR
In Java, we can use the subclass constructor to initialize instance variables of both the
superclass and the subclass.
Example 8.5: A program to explicitly initialize the instance variables of superclass
inside the subclass constructor
class FirstClass
{
int x,y;
int func1()
{
return (x+y);
}
}
class SecondClass extends FirstClass
{
int z;
Self-Instructional
120 Material
Inheritance and
Polymorphism
NOTES
SecondClass(int a, int b, int c) //subclass constructor
{
// initializing instance variables of superclass
x=a;
y=b;
// initializing instance variable of subclass
z=c;
}
int func2()
{
return (x+y+z);
}
}
class ExplicitInitialization
{
public static void main (String args[])
{
SecondClass obj=new SecondClass(10,20,30);
int result1=obj.func1();
int result2=obj.func2();
System.out.println(The first result is: +result1);
System.out.println(The second result is: +result2);
}
}
The output of the program is
The first result is: 30
The second result is: 60
In this example, the subclass SecondClass explicitly initializes the instance
variables x and y of the superclass. However, if instance variables of superclass are
declared as private, then subclass cannot access or initialize these instance variables
of superclass. For this, Java provides a keyword super that can be used by the
subclass to pass values to the private variables of superclass by calling its constructor.
The syntax for using super keyword is
super(parameter_list);
Here, parameter_list specifies the parameters required by the superclass
constructor.
These are certain points that should be kept in mind while using super keyword.
It is used only within a subclass constructor.
It should be the first statement to be executed inside the subclass constructor.
The parameters specified in the super() method must match the order and
type of the variables declared in the superclass constructor.
Self-Instructional
Material 121
Inheritance and
Polymorphism
NOTES
Example 8.6: A program to demonstrate the use of super keyword
class FirstClass
{
private int x,y; //private variables
FirstClass(int l, int b)
{
x=l;
y=b;
}
int func1()
{
return (x+y);
}
}
class SecondClass extends FirstClass
{
int z;
SecondClass (int l, int b, int c)
{
super(l,b); //pass values to superclass constructor
z=c;
}
int func2()
{
return (z+func1());
}
}
class UsingSuper
{
public static void main (String args[])
{
SecondClass obj=new SecondClass(10,20,30);
int result1=obj.func1();
int result2=obj.func2();
System.out.println(The first result is: +result1);
System.out.println(The second result is: +result2);
}
}
The output of the program is
The first result is: 30
The second result is: 60
In this example, the statement SecondClass obj=new
SecondClass(10,20,30) calls the constructor of SecondClass, which again
calls the constructor of FirstClass by using super keyword and passes values
10 and 20 to the variables l and b of FirstClass constructor respectively.
Check Your Progress
6. A member declared
as ____________
can be accessed
only within the
class.
7. Protected members
are accessible to
the non-subclasses
of other packages.
(True or False)
8. The superclass
constructor can be
called within the
subclass
constructor by
using
___________
keyword.
Self-Instructional
122 Material
Inheritance and
Polymorphism
NOTES
8.6 METHOD OVERRIDING
If a subclass method has the same name, same parameter list and same return type as
a superclass method, then we say that the method in the subclass overrides the method
in the superclass. When the overridden method is called, the version of the method
defined in the subclass will be invoked instead of the method defined in the superclass.
That is, the method in the subclass will hide the method defined in the superclass.
Example 8.7: A program to demonstrate method overriding
class Person
{
String name=John;
int age=30;
void result()
{
System.out.println(The name and the age of the person are:
+name+ and +age+ respectively );
}
}
class Employee extends Person
{
int salary=40000;
void result() //result() is overridden
{
System.out.println(The name and the salary of the employee
are: +name+ and +salary+ respectively );
}
}
public class MethodOverriding
{
public static void main(String[] args)
{
Employee obj=new Employee();
obj.result(); // invokes Employees result()
}
}
The output of the program is
The name and the salary of the employee are: John and 40000
respectively
In this example, when the method result() is invoked through an object obj
of type Employee , the method result()defined within Employee is executed.
That is, the method result() of the subclass Employee overrides the method
result() of the superclass Person. However, if we want to access the overridden
method result()of the superclass, we can use the keyword super. For example,
consider the class Employee defined in
Self-Instructional
Material 123
Inheritance and
Polymorphism
NOTES
Example 8.7. It can be modified using super keyword as follows:
class Employee extends Person
{
int salary=40000;
void result()
{
super.result(); // invokes result() of class Person
System.out.println(The name and the salary of the employee
are: +name+ and +salary+ respectively );
}
}
The output of the program is
The name and the age of the person are John and 30 respectively
The name and the salary of the employee are John and 40000
respectively
Now, when the method result() is invoked through an object obj of type
Employee, the superclass version of result() is invoked within the subclass
version.
8.7 POLYMORPHISM
Polymorphism is the ability of a function or a message to be processed in more than one
form. We have already seen how polymorphism can be implemented through method
overloading or method overriding. Other than overloading and overriding, another type
of polymorphism is dynamic binding.
Dynamic binding is the process of linking of a method call to the actual code of
the method at run-time. That is, in dynamic binding, the actual code to be executed is not
known to the compiler until run-time.
Consider an example in which three different classes, Square, Rectangle
and Circle are derived from the base class GeometricalShapes. To understand
dynamic binding, consider the code segment given here.
class DynamicBinding
{
public static void main(String[] args)
{
GeomatricalShapes gs = new GeomatricalShapes();
Square obj1=new Square();
Rectangle obj2=new Rectangle();
Circle obj3=new Circle();
gs=obj1; gs.area(); //invokes Squares area()
gs=obj2; gs.area(); //invokes Rectangles area()
gs=obj3; gs.area(); //invokes Circles area()
}
}
Self-Instructional
124 Material
Inheritance and
Polymorphism
NOTES
Here, the method area()of the base class is implemented in different ways in
all its derived classes. At run-time, depending on the object being referenced, the desired
method will be called.
8.8 USING final KEYWORD
Java provides a keyword final that can be applied to variables, methods and classes.
The meaning of the final keyword when applied to variables is different from its
meaning when it is applied to methods and classes.
8.8.1 Final Variables
The value of a variable can be prevented from being modified by declaring a variable as
final.
The syntax for declaring a final variable is
final data_type variable_name=constant_value;
An attempt to alter the value of a final variable will generate a compile-time error.
Note that a final variable does not occupy memory for each instance of the class.
Hence, final variable is a constant.
Example 8.8: A program to demonstrate the use of a final variable
class Person
{
final int salary=30000; // final variable
}
class FinalVariable
{
public static void main(String args[])
{
Person obj=new Person();
obj.salary=3000+2000; // error
}
}
In this example, a compile-time error will be generated as the final variable
salary cannot be modified.
8.8.2 Final Methods
As stated earlier, whenever a method is defined in the subclass with the same name and
same signature as in the superclass, it is by default overridden in the subclass. However,
a method can be prevented from being overridden by the subclass by declaring the
method as final.
The syntax for declaring a final method is
final data_type method_name()
{
:
Self-Instructional
Material 125
Inheritance and
Polymorphism
NOTES
}
Example 8.9: A program to demonstrate the use of final method
class Person
{
String name=John;
int age=25;
final void result() // final method
{
System.out.println(The name and the age of the person is:
+name+ and +age);
}
}
class Employee extends Person
{
int salary=30000;
void result() //error
{
System.out.println(The salary of the employee is: + salary);
}
}
class FinalMethod
{
public static void main(String args[])
{
Employee obj=new Employee();
obj.result();
}
}
This program will generate a compile-time error as the method result() is
declared final and it cannot be overridden in the subclass.
8.8.3 Final Classes
A class which cannot be further inherited or cannot have any subclass is known as final
class. To make a class final, the class declaration is preceded by the final keyword.
If a class is declared as final, all of its methods are automatically declared as final.
The syntax for declaring a final class is
final class class_name
{
:
}
Example 8.10: A program to demonstrate the implementation of final class
final class Person // final class
{
Check Your Progress
9. When is a
superclass method
said to be
overridden in the
subclass?
10. Which keyword
prevents a method
in a superclass
from being
overridden by its
subclass?
11. Java enables us to
specify that a
method must be
overridden in the
subclass by using
_______ keyword.
12. Which of the
following classes
cannot be
inherited?
(a) abstract
class A
{
:
}
(b) class B
{
:
}
(c) final
class C
{
:
}
(d) none of these
Self-Instructional
126 Material
Inheritance and
Polymorphism
NOTES
String name=John;
int age=25;
void result()
{
System.out.println(The name and the age of the person are:
+name+ and +age+respectively);
}
}
class Employee extends Person //error
{
int salary=30000;
void display()
{
System.out.println(The salary of the employee is: +salary);
}
}
class FinalClass
{
public static void main(String args[])
{
Employee obj=new Employee();
obj.result();
obj.display();
}
}
This program will generate a compile-time error since the class Person is a
final class and cannot be further inherited.
8.9 ABSTRACT METHODS AND CLASSES
As discussed earlier, a method can be prevented from being overridden in the subclass
by using the final keyword. However, sometimes there might be a situation, when the
method in the superclass always needs to be redefined in the subclass and for this
overriding becomes necessary. This kind of situation can arise when the superclass is
not able to provide meaningful implementation for its methods. In such a case, the
superclass provides a generalized structure of the method and leaves the implementation
part to its subclass. To deal with such situation, Java allows us to specify that a method
must always be overridden in the subclass by using the keyword abstract in the
method declaration.
The syntax for declaring an abstract method is
abstract data_type method_name();
If a class has one or more abstract methods, the class must also be declared as
abstract by using the keyword abstract.
The syntax for declaring an abstract class is
Self-Instructional
Material 127
Inheritance and
Polymorphism
NOTES
abstract class class_name
{
:
abstract data_type method_name();
}
The class which inherits the abstract class must provide implementation for all
the methods or the class should declare itself as abstract.HHHefwf
These are certain points that should be kept in mind while using abstract class.
An abstract class cannot be instantiated.
Abstract methods of an abstract class must always be implemented in the
subclass.
Abstract methods must end with semicolon (;) because they do not have
any functionality.
There can be both defined and undefined methods in an abstract class.
Constructors or static methods cannot be declared as abstract.
Example 8.11: A program to demonstrate the concept of abstract class
abstract class Person //abstract class
{
String name;
int age;
Person(String n, int a)
{
name=n;
age=a;
}
abstract void display(); //abstract method
}
class Employee extends Person
{
int salary;
Employee(String n, int a, int s)
{
super(n,a); //pass values to superclass
salary=s;
}
void display()
{
System.out.println(The name and the age of the employee
are: +name+ and +age+ respectively);
System.out.println(The salary of the employee is: +salary);
}
Check Your Progress
13. Abstract method
contains only
undefined methods.
(True or False)
14. Identify the error
in the following
class definition.
class A
{
int i=10;
abstract
void
display();
}
Self-Instructional
128 Material
Inheritance and
Polymorphism
NOTES
}
class AbstractClass
{
public static void main(String args[])
{
Employee obj=new Employee(John, 23, 2000);
obj.display();
}
}
The output of the program is
The name and the age of the employee are: John and 23
respectively
The salary of the employee is: 2000
In this example, the Person is an abstract class which contains an abstract
method display()and this method is implemented in the subclass Employee.
8.10 SUMMARY
In this unit, you have learned that:
Inheritance is the process of deriving a new class from the existing one in such a
way that the new class inherits all the members (data members and methods) of
the existing class.
The class that is inherited by other classes is called a base class or superclass or
parent class. The class that inherits the properties of the superclass is called a
subclass or derived class or child class.
A subclass can be defined by using extends keyword.
Inheritance may take different forms, namely, single inheritance, hierarchical
inheritance, multilevel inheritance and multiple inheritance.
In single inheritance, a class is derived from a single superclass. The type of
inheritance in which more than one class is derived from a single superclass is
called hierarchical inheritance. In multilevel inheritance, one class is inherited
from another class, which in turn is inherited from some other class.
In multiple inheritance, a class inherits properties from more than one superclass.
Java does not support multiple inheritance directly. It is implemented through a
concept called interface.
Access modifier controls the accessibility of class members. Java provides three
types of access modifiers, namely public, private and protected.
The method in the subclass overrides the method in the superclass if a subclass
method has the same name and same signature as in the superclass.
Polymorphism is the ability of a function or a message to be processed in more
than one form. Dynamic binding is the process of linking of a method call to the
actual code of the method at run-time.
Self-Instructional
Material 129
Inheritance and
Polymorphism
NOTES
Java provides a keyword final that can be applied to variables, methods and
classes. Variables declared as final cannot be modified. A method can be prevented
from being overridden by the subclass by declaring the method as final. A
class which cannot be further inherited or cannot have any subclass is known as
final class.
Java allows us to specify that a method must always be overridden in the subclass
by using the keyword abstract in the method declaration.
8.11 KEY TERMS
Abstract class: It is a class that is declared abstractit may or may not include
abstract methods.
Abstract method: It is a method that is declared without an implementation
(without braces, and followed by a semicolon).
Access modifiers: They are keywords used to specify the declared accessibility
of a member or a type.
Inheritance: It is the process of deriving a new class from the existing one in
such a way that the new class inherits all the members (data members and methods)
of the existing class.
Polymorphism: It is the capability of an action or method to do different things
based on the object that it is acting upon.
8.12 ANSWERS TO CHECK YOUR PROGRESS
1. Inheritance is the process of deriving a new class from the existing one in which
the new class inherits all the members (data members and methods) of the existing
class.
2. Superclass
3. extends
4. True
5. (c)
6. Private
7. False
8. super
9. A superclass method is said to be overridden in the subclass when the method in
the subclass has the same name and same signature as the method in the
superclass.
10. final
11. abstract
12. (c)
13. False
14. The class is not declared as abstract.
Self-Instructional
130 Material
Inheritance and
Polymorphism
NOTES
8.13 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What is inheritance? Explain how inheritance facilitates code reusability.
2. What are the various types of inheritance in Java? Explain with examples.
3. What is method overriding? How can we prevent overriding of a method?
4. What is the use of final keyword in Java? Explain by giving examples.
Long-Answer Questions
1. Discuss various access modifiers available in Java.
2. Write a program to show how super keyword can be used to call superclass
constructor within a subclass constructor.
3. Describe abstract methods and abstract classes. List the rules for implementing
abstract methods.
4. Give the output of the following program.
class Class1
{
int i;
Class1(int p)
{
i=p;
}
void display()
{
System.out.println(The value of i is: +i);
}
}
class Class2 extends Class1
{
int j;
Class2(int p,int q)
{
super(p);
j=q;
}
void display()
{
System.out.println(The value of j is: +j);
}
}
class SampleClass
{
Self-Instructional
Material 131
Inheritance and
Polymorphism
NOTES
public static void main(String args[])
{
Class2 obj=new Class2(30,40);
obj.display();
}
}
5. Write a program to create a Drug class. A class Tablet is derived from it,
which in turn is inherited by class Pain Reliever. Explain the type of inheritance
implemented.
Self-Instructional
Material 133
Exception Handling
Threads
NOTES
UNIT 9 EXCEPTION HANDLING
THREADS
Structure
9.0 Introduction
9.1 Unit Objectives
9.2 Concept of Threads
9.2.1 Main Thread
9.2.2 Creating Threads
9.2.3 Extending Threads
9.2.4 Implementing Runnable Interface
9.3 Life Cycle of a Thread
9.4 Thread Methods
9.4.1 Using Yield(), Sleep() and Stop() Method
9.4.2 Using isalive() and join() Method
9.5 Threads Priority
9.6 Synchronization of Threads
9.6.1 Synchronizing Methods
9.6.2 Synchronizing Statements
9.6.3 Deadlock
9.7 Inter-Thread Communication
9.8 Suspending, Resuming and Stopping Threads
9.9 Summary
9.10 Key Terms
9.11 Answers to Check Your Progress
9.12 Questions and Exercises
9.0 INTRODUCTION
Most of the modern operating systems support multitasking, that is, the ability to execute
multiple programs simultaneously. Javas multithreading is a specialized form of
multitasking. Multithreading is a programming concept in which a program (process) is
divided into two or more subprograms (subprocesses), each of which can perform
different tasks concurrently. For example, one subprogram can format text in the text
editor while another subprogram can print the same.
In this unit, you will learn about the concept of threads.
9.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Understand the concept of threads in Java
Describe the complete life cycle of a thread
Explain various methods of a thread class
Learn about thread priority
Know about the synchronization of threads
Discuss inter-thread communication
Illustrate how to suspend, resume and stop a thread in the new version of Java
Self-Instructional
134 Material
Exception Handling
Threads
NOTES
9.2 CONCEPT OF THREADS
You have learnt about programs with only a single sequential flow of control, that is, the
program simply starts, performs a series of operations and eventually ends. There is
only one statement under execution at any given point of time and they are called single-
threaded programs. A thread is just like a program which has a single flow of control. It
also has a starting point, the part of execution and an end. Java also allows you to use
multiple flows of control in a program and such a program is known as a multithreaded
program. In a multithreaded program, each thread is a separate tiny module which runs
parallel with other threads. However, running in parallel does not mean that they are
running at the same time. As most of the time the threads run on the single processor, in
reality, only one thread is executed at a given time. However, the switching from one
thread to another occurs so fast that it gives an illusion to the user that all the threads are
being executed at the same time. Threads are called lightweight processes. This is
because all the threads in a main application program share the same address space in
the memory.
There are several advantages of using multithreaded programs over single-threaded
programs. In a traditional single-threaded environment, the central processing unit (CPU)
sits idle most of the time, as the program has to wait for each of the task to complete
before proceeding to the next task. In a multithreaded environment, since different tasks
can be assigned to different threads, the program makes maximum utilization of the
CPU, keeping the idle time of the CPU to minimum. For example, one thread can read
data, another thread can process it and a third thread can write it thus improving the
overall performance. Multithreading is best-suited for those applications that require
multiple tasks to be done simultaneously.
9.2.1 Main Thread
Any Java program always contains at least one thread even if you do not create one.
This thread is called the main thread and it is the one which immediately starts executing
when you start a program. The main thread can be used to create and start other child
threads and it must often be the last thread to finish execution because it performs
various other actions such as, shutdown action and releasing resources which are used
by the program. The main thread is created automatically but it can be controlled through
a Thread object. For this, its reference is needed which can be obtained by calling the
method currentThread(), which is a public static member of Thread class.
This method returns a reference to the thread on which it is called. You can control the
main thread just like any other thread, once you have a reference to it.
Example 9.1: A program to control the main thread
class MainThread
{
public static void main(String[] args)
{
Thread th=Thread.currentThread();
System.out.println(The name of the current thread is: +th);
//changing the name of the thread
th.setName(MyThread);
Self-Instructional
Material 135
Exception Handling
Threads
NOTES
System.out.println(The name of the current thread after
changing the name is: +th);
System.out.println(Main Thread exiting);
}
}
The output of the program is
The name of the current thread is: Thread[main,5,main]
The name of the current thread after changing the name is:
Thread[MyThread,5,main]
Main Thread exiting
In this example, the method currentThread() is called to obtain a reference
to the main thread and this reference is stored in the variable th. Here, the name of the
main thread is changed by calling the method setName() and the new thread name is
redisplayed.
9.2.2 Creating Threads
In Java, threads can be created in two ways which are as follows:
By defining a class that extends the Thread class
By implementing the Runnable interface
In both the approaches, threads are implemented in the form of objects which
contain a method called run(). It is the most important method in the Thread class.
It is the entry point of a new thread and it is the place where the task to be performed by
the thread is defined. The execution of a thread starts with the call to run() method.
The run() method is automatically invoked when you invoke another method of Thread
class called start().
9.2.3 Extending Threads
You can create a thread by creating a new class that extends the Thread class
defined in java.lang package and creating an instance of the class. The extending
class must override the run() method. Inside the run() method, the code that needs
to be executed by the thread will be defined.
The code segment to extend the Thread class and override the run() method
is
class ThreadName extends Thread
{
public void run()
{
: // code for the new thread
}
}
Now the instance of the class ThreadName can be created and run using the
statements as follows:
ThreadName objectname=new ThreadName();
objectname.start();
Self-Instructional
136 Material
Exception Handling
Threads
NOTES
The second statement invokes the start() method after which the thread will
be ready to run. It will start running once the Java runtime invokes its run() method.
Example 9.2: A program to demonstrate creating threads by extending the Thread
class
class Thread1 extends Thread
{
public void run() //entry point of Thread1
{
int i=0;
while(i<5)
{
System.out.println(First Child Thread:+i);
i=i+1;
}
System.out.println(\t First child exited);
}
}
class Thread2 extends Thread
{
public void run() //entry point of Thread2
{
int j=0;
while(j<5)
{
System.out.println(Second Child Thread:+j);
j=j+1;
}
System.out.println(\t Second child exited);
}
}
class ExtendingThread
{
public static void main(String[] args)
{
Thread1 firstthread=new Thread1();
firstthread.start(); // starts the first thread
Thread2 secondthread=new Thread2();
secondthread.start(); // starts the second thread
int k=0;
while(k<5)
{
System.out.println(Main Thread:+k);
Self-Instructional
Material 137
Exception Handling
Threads
NOTES
k=k+1;
}
System.out.println(\t Main thread exiting);
}
}
The output of the program is
First Child Thread:0
Main Thread:0
Second Child Thread:0
First Child Thread:1
Main Thread:1
Second Child Thread:1
First Child Thread:2
Main Thread:2
Second Child Thread:2
First Child Thread:3
Main Thread:3
Second Child Thread:3
First Child Thread:4
Main Thread:4
Second Child Thread:4
First child exited
Main thread exiting
Second child exited
When you start the program, the main thread immediately starts running. The
main thread then starts two child threads Thread1 and Thread2, both of which will
perform different tasks. Once the main thread reaches the end of the main() method,
there will be altogether three threads running concurrently on their own in the program,
Thread1, Thread2 and the main thread. These three threads will run independently
whenever CPU is available to them. There is no specific order of their execution. Hence,
the program may generate different output every time we run it.
9.2.4 Implementing Runnable Interface
Another way of creating a thread is to create a class that implements the Runnable
interface. The Runnable interface consists of a single method run() which is required
for implementing thread. You can create a thread and pass the object of the class that
implements the Runnable interface as an argument of the Thread classs constructor.
The thread will now be activated by calling the start() method. Implementing
Runnable is much more convenient than extending a Thread class when a program
needs to inherit from a class apart from the Thread class since Java allows only a
single base class.
The code segment to implement Runnable interface is as follows:
class MyNewThread implements Runnable
{
Self-Instructional
138 Material
Exception Handling
Threads
NOTES
public void run()
{
: // code for the new thread
}
}
Example 9.3: A program to demonstrate creating threads by implementing Runnable
interface
class MyNewThread implements Runnable // implements Runnable
{
public void run() // implements run() method
{
int i=0;
while(i<=4)
{
System.out.println(Child Thread: +i);
i++;
}
}
}
class RunnableInterface
{
public static void main(String[] args)
{
/*an object of class implementing Runnable interface*/
MyNewThread runnableobj=new MyNewThread();
/*an object of Thread class taking runnable object as
argument*/
Thread threadobj=new Thread(runnableobj);
threadobj.start();
int j=0;
while(j<=4)
{
System.out.println(Main Thread: +j);
j++;
}
System.out.println(Main Thread Exiting);
}
}
The output of the program is
Main Thread: 0
Child Thread: 0
Main Thread: 1
Child Thread: 1
Self-Instructional
Material 139
Exception Handling
Threads
NOTES
Main Thread: 2
Child Thread: 2
Main Thread: 3
Child Thread: 3
Main Thread: 4
Child Thread: 4
Main Thread Exiting
In this example, MyNewThread is a class which implements the Runnable
interface. Inside the main() method, an instance runnableobj of MyNewThread
is created which is passed as an argument to the Thread classs constructor. When
the new thread starts, the run() method of runnableobj is called.
9.3 LIFE CYCLE OF A THREAD
There are various states that a Java thread can enter during its life cyclenewborn,
runnable, running, blocked and dead state. A thread is always in either one of these five
states. The thread can transit from one state to another as shown in Figure 9.1.
Newborn
Blocked
Dead
stop()
stop()
stop()
start()
suspend()
sleep()
wait()
resume()
Running
Runnable
yield()
notify()
Figure 9.1 Life Cycle of a Thread
Newborn State
When a thread is created, it enters a state called the newborn state. It is the first state in
the life cycle of a thread in which the thread is just newly born and it is not yet ready to
run. That is, the thread is considered not active. During this stage, you can either schedule
the thread for running by calling the start() method or kill it using stop() method.
You cannot use any other method in the newborn state otherwise it will throw exception.
Runnable State
The thread enters the runnable state when it is ready to run and waiting for the CPU to
be allocated to it. Whenever a thread is ready to run, it is placed in the queue of threads
that are waiting for the availability of the CPU. The thread scheduler picks one of the
threads in the queue based on their priority. If all the threads in the queue have equal
priority, the scheduler gives time slots for execution in round robin fashion. A thread can
voluntarily give up its turn and give the control to another thread of equal priority using a
static method called yield(). It then joins the queue at the end and waits for its turn
to come.
Self-Instructional
140 Material
Exception Handling
Threads
NOTES
Running State
A thread is said to be in the running state when it gets the processor for execution, that
is, when the thread scheduler picks it to be the currently executing thread. The thread
will be executed by the processor and will keep running until it gets preempted by a
thread of higher priority or it gives up the control in either of the following conditions.
When being suspended using suspend() method: If we want to suspend
a thread for sometime but do not want to kill it, then we can use the suspend()
method. The suspended thread can be brought back to the execution state by
invoking a method called resume().
When it is made to sleep using sleep() method: The sleep() method
makes the thread sleep for the specified period of time. The thread will
automatically return back to its execution state once the specified time is elapsed.
When it is made to wait using wait() method: A thread can be made to
wait until some events occur by calling wait() method. We can make the
thread run again by using the notify() method.
Blocked State
A thread is in blocked state when the thread is either suspended or sleeping or waiting.
The thread in this state is not considered dead, so it can re-enter the runnable state and
subsequently run if the CPU is available.
Dead State
A thread is said to be in dead state if its run() method completes or it has been killed
deliberately by invoking the stop() method at any state. Once a thread enters the
dead state, it cannot re-enter any other state even if the start() method is invoked.
Note: The predefined methods stop(), suspend() and resume() have been deprecated from the later
versions of Java.
9.4 THREAD METHODS
You have seen the use of the start() and run() method. There are various other
methods of Thread class. They are yield(), sleep(), stop(), isAlive()
and join() method.
9.4.1 Using yield(), sleep() and stop() method
The yield(), sleep() and stop() methods are responsible for controlling the
behavior of a thread and the transition of thread from one state to another.
The general form of sleep() method is
static void sleep(long milliseconds) throws Interrupted
Exception
where, milliseconds is the number of milliseconds to suspend. As the
sleep() method throws an exception, the call to sleep() method must be enclosed
in a try block followed by a catch block otherwise the program will not compile.
The general form of stop() method is
static void stop()
Self-Instructional
Material 141
Exception Handling
Threads
NOTES
The general form of yield() method is
static void yield()
Example 9.4: A program to demonstrate the use of yield(), sleep() and stop()
method
class Thread1 extends Thread
{
public void run()
{
int i=0;
while(i<5)
{
if(i==2)
yield(); //calls yield() method on Thread1
System.out.println(First Child Thread:+i);
i=i+1;
}
System.out.println(\t First child exited);
}
}
class Thread2 extends Thread
{
public void run()
{
int j=0;
while(j<5)
{
System.out.println(Second Child Thread:+j);
if(j==3)
stop(); //calls stop() method on Thread2
j=j+1;
}
System.out.println(\t Second child exited);
}
}
class Thread3 extends Thread
{
public void run()
{
int k=0;
while(k<5)
{
System.out.println(Third Child Thread:+k);
if(k==3)
try
Self-Instructional
142 Material
Exception Handling
Threads
NOTES
{
sleep(1000); /*calls sleep() method on
Thread3*/
}
catch(Exception e)
{
}
k=k+1;
}
System.out.println(\t Third child exited);
}
}
class ThreadMethods
{
public static void main(String[] args)
{
Thread1 th1=new Thread1();
Thread2 th2=new Thread2();
Thread3 th3=new Thread3();
th1.start();
th2.start();
th3.start();
int k=0;
while(k<5)
{
System.out.println(Main Thread:+k);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(Main Thread interrupted);
}
k=k+1;
}
System.out.println(\t Main thread exiting);
}
}
Self-Instructional
Material 143
Exception Handling
Threads
NOTES
The output of the program is
First Child Thread:0
First Child Thread:1
Main Thread:0
First Child Thread:2
First Child Thread:3
First Child Thread:4
First child exited
Second Child Thread:0
Second Child Thread:1
Second Child Thread:2
Second Child Thread:3
Third Child Thread:0
Third Child Thread:1
Third Child Thread:2
Third Child Thread:3
Main Thread:1
Third Child Thread:4
Third child exited
Main Thread:2
Main Thread:3
Main Thread:4
Main thread exiting
In this example, although Thread1 started first, it relinquishes its control after
implementing the while loop only two times, as the yield() method is invoked.
Thread2 starts running and it is killed by invoking the stop() method. Thread3
while running goes to sleep for 1000 milliseconds on the invocation of sleep() method.
9.4.2 Using isAlive() and join() method
As you know, the main thread must often be the last thread to terminate since it performs
several other tasks. For this, we can invoke sleep() method within main() method
as in the Example 9.4 which makes the main thread sleep for specified period of time
until all the child threads complete their execution. However, it is not considered to be a
good approach as the main thread has no information when a child thread will finish its
execution. In this case, the main thread has to sleep for a period long enough to assure
the termination of child threads prior to its termination. For example, if the main thread is
made to sleep for 2500 milliseconds and the child threads altogether take 1000 milliseconds
to terminate, then there will be a delay of 1500 milliseconds for the main thread to
terminate. Thus, it is necessary for the main thread to know when the child threads have
finished. There are two ways to determine whether a thread has ended, which are as
follows:
First, we can call isAlive() method. The general form of isAlive() method
is
final boolean isAlive()
Self-Instructional
144 Material
Exception Handling
Threads
NOTES
This method is used to test whether a thread is still alive. It returns true if the
thread is running, otherwise it returns false. The isAlive() method is used
occasionally.
The method which is more commonly used to wait for a thread to finish is join()
method. The general form of join() method is
final void join() throws InterruptedException
This method is used to halt the execution of current thread (calling thread) until
the thread on which the method is called terminates. It ensures that the current
thread will wait until the called thread finishes its execution. There is another
form of join() method which takes the parameter in milliseconds which
is the maximum amount of time that a thread can wait for the specified thread to
terminate. As the join() method throws an exception, it must be enclosed in a
try block followed by a catch block.
Example 9.5: A program to demonstrate the use of isAlive() and join() methods
class Thread1 extends Thread
{
public void run() //entry point of Thread1
{
int i=0;
while(i<5)
{
System.out.println(First Child Thread:+i);
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println(First Child Thread interrupted);
}
i=i+1;
}
System.out.println(\t First child exited);
}
}
class Thread2 extends Thread
{
public void run() //entry point of Thread2
{
int j=0;
while(j<5)
{
System.out.println(Second Child Thread:+j);
try
{
Self-Instructional
Material 145
Exception Handling
Threads
NOTES
sleep(1000);
}
catch(Exception e)
{
System.out.println(Second Child Thread interrupted);
}
j=j+1;
}
System.out.println(\t Second child exited);
}
}
class JoinMethod
{
public static void main(String[] args)
{
Thread1 firstthread=new Thread1();
firstthread.start();
Thread2 secondthread=new Thread2();
secondthread.start();
//Checks if the child threads are alive
System.out.println(Is first thread
alive?+firstthread.isAlive());
System.out.println(Is second thread
alive?+secondthread.isAlive());
//Wait for Threads to finish
try
{
System.out.println(Waiting for the child threads to finish);
firstthread.join();
secondthread.join();
}
catch(Exception e)
{
System.out.println(Exception caught);
}
//Checks if the child threads are still alive
System.out.println(Is first thread
alive?+firstthread.isAlive());
System.out.println(Is second thread
alive?+secondthread.isAlive());
Self-Instructional
146 Material
Exception Handling
Threads
NOTES
System.out.println(\t Main Thread exiting);
}
}
The output of the program is
First Child Thread:0
Is first thread alive?true
Second Child Thread:0
Is second thread alive?true
Waiting for the child threads to finish
First Child Thread:1
Second Child Thread:1
First Child Thread:2
Second Child Thread:2
First Child Thread:3
Second Child Thread:3
Second Child Thread:4
First Child Thread:4
Second child exited
First child exited
Is first thread alive?false
Is second thread alive?false
Main Thread exiting
Note: The join() method is called on the child threads Thread1 and Thread2 to ensure that the main
thread waits for these child threads to finish.
9.5 THREADS PRIORITY
The threads you have seen so far are of equal priority in which the Java scheduler
selects the thread for execution on the first-come, first-serve basis. However, each
thread can be assigned different priority which will decide the order in which it is scheduled
for running. Priorities are the integers which specify the relative priority of one thread to
another. When a thread is created, it inherits its priority from the thread that created it.
However, the priority of a thread can be changed by using the setPriority()
method of the Thread class.
The syntax to set the priority of a thread is
ThreadName.setPriority(n);
where, n is an integer value which ranges from MIN_PRIORITY (1) and
MAX_PRIORITY (10). The default priority is NORM_PRIORITY whose value is 5.
MIN_PRIORITY, MAX_PRIORITY and NORM_PRIORITY are the constants
defined in Thread class.
Check Your Progress
1. Define a thread.
2. How do you start
a thread?
3. The only method
which is available
in Runnable
interface is
.
4. What are the two
conditions in
which a thread
dies?
5.
thread is the
default thread
which starts
executing
immediately when
we start the
program.
6. What is the
difference between
suspending and
stopping a thread?
7. A thread in a dead
state can run again
on the invocation
of start()
method. (True or
False)
Self-Instructional
Material 147
Exception Handling
Threads
NOTES
When there are multiple threads ready to execute, the highest priority thread is
chosen and executed. Only when the high priority thread stops, yields or enters blocked
state, the low priority thread starts running. However, if any higher priority thread enters,
it will preempt the currently running thread forcing it to move to the runnable state.
Example 9.6: A program to demonstrate the assigning of priority to a thread
class Thread1 extends Thread
{
public void run() //entry point of the Thread1
{
int i=0;
while(i<5)
{
System.out.println(First Child Thread:+i);
i=i+1;
}
System.out.println(\t First child exited);
}
}
class Thread2 extends Thread
{
public void run() //entry point of the Thread2
{
int j=0;
while(j<5)
{
System.out.println(Second Child Thread:+j);
j=j+1;
}
System.out.println(\t Second child exited);
}
}
class ThreadPriority
{
public static void main(String[] args)
{
Thread1 firstthread=new Thread1();
Thread2 secondthread=new Thread2();
// Thread2 assigned highest priority
secondthread.setPriority(Thread.MAX_PRIORITY);
// Thread1 assigned lowest priority
firstthread.setPriority(Thread.MIN_PRIORITY);
firstthread.start();
Self-Instructional
148 Material
Exception Handling
Threads
NOTES
secondthread.start();
System.out.println(\t Main Thread Exiting);
}
}
The output of the program is
Second Child Thread:0
Second Child Thread:1
Second Child Thread:2
Second Child Thread:3
Second Child Thread:4
Second child exited
Main Thread Exiting
First Child Thread:0
First Child Thread:1
First Child Thread:2
First Child Thread:3
First Child Thread:4
First child exited
The first child thread Thread1 has been assigned the minimum priority and
the second child thread Thread2 has been assigned the maximum priority. So despite
Thread1 being the first on which start() method is called, its output is printed in
the last as it has been preempted by the higher priority thread Thread2.
Note: The amount of CPU time a thread gets depends not only on its priority but also on other factors such
as how an operating system implements multithreading.
9.6 SYNCHRONIZATION OF THREADS
When multiple threads need access to a single resource, there must be a way to ensure
that only one thread will use the resource at any given point of time otherwise it may
lead to a severe problem. For example, if one thread in a program reads salary from a
file and another thread tries to update it, then the program may produce an undesirable
output. The solution to this problem can be achieved by using a technique known as
synchronization. The objective of synchronization is to control the access to shared
resources.
Synchronization uses the concept of monitor. A monitor is an object which is used
as a mutually exclusive lock. That is, it can be owned by only one thread at any given
point of time. A thread is said to have entered the monitor when it acquires a lock. Any
other thread which attempts to acquire the lock has to wait until the first thread comes
out of the monitor. There are two ways to implement synchronization, which are as
follows:
Synchronizing methods
Synchronizing statements
Self-Instructional
Material 149
Exception Handling
Threads
NOTES
9.6.1 Synchronizing Methods
You can synchronize a subset (or all) of the methods of any class by using
synchronized keyword. When a method is declared synchronized, Java creates a
monitor. To enter the monitor, you need to call a synchronized method. Only one of the
synchronized methods in a class object can execute at any given time. Java hands over
the monitor to the thread that calls the method first. As long as a thread is inside a
synchronized method, other threads trying to call it (or any other synchronized method)
on the same instance have to wait. Only when the currently executing thread finishes
executing and exits the monitor another waiting thread can enter the monitor.
The syntax to declare a method as synchronized is
synchronized data_type method_name()
{
// code for the method
}
To understand synchronization, let us first consider a program which is not synchronized.
Example 9.7: A program to demonstrate the need of synchronization
class A
{
void display(String msg)
{
System.out.print(( +msg);
try
{
Thread.sleep(1000);
}catch(InterruptedException e)
{
System.out.println(Interrupted);
}
System.out.println());
}
}
class MyThread extends Thread
{
String str;
A obj;
MyThread (A obj1,String s)
{
obj=obj1;
str=new String (s);
}
public void run()
{
obj.display(str);
Self-Instructional
150 Material
Exception Handling
Threads
NOTES
}
}
class UnsynchronizedMethod
{
public static void main(String[] args)
{
A obj=new A();
MyThread th1=new MyThread(obj,THIS);
MyThread th2=new MyThread(obj,IS);
MyThread th3=new MyThread(obj,SYNCHRONIZATION);
th1.start();
th2.start();
th3.start();
}
}
The output of the program is
(THIS(IS(SYNCHRONIZATION)
)
)
The class A has a method named display() which takes a parameter msg of
String type. This method will print the msg string enclosed in the first brackets.
Note that the sleep() method is invoked after the display() method prints the
opening bracket and the string msg which causes the current thread to halt for one
second. The constructor of class MyThread takes two arguments, a reference to an
instance of class A and a string. When the first thread starts, the objects run()
method is invoked. The run() method invokes the display()method on the instance
obj of A, and passes the string str. The call to sleep() method allows execution
to switch to another thread before the first thread could complete the method. Thus, the
output of the program is not as expected and the strings are in mixed up form. This is
because, the three threads call the same method display() without anything to stop
them from competing each other to complete the method.
Now try to modify the program in Example 9.7 by preceding the definition of
display() method with synchronized keyword. This will serialize access to
display() method by restricting its access to only one thread at a time thus producing
the correct output.
Example 9.8: A program to demonstrate synchronized method
class A
{
synchronized void display(String msg)
{
System.out.print(( +msg);
try
{
Thread.sleep(1000);
Self-Instructional
Material 151
Exception Handling
Threads
NOTES
}catch(InterruptedException e)
{
System.out.println(Interrupted);
}
System.out.println());
}
}
class MyThread extends Thread
{
String str;
A obj;
MyThread (A obj1,String s)
{
obj=obj1;
str=new String (s);
}
public void run()
{
obj.display(str);
}
}
class SynchronizedMethod
{
public static void main(String[] args)
{
A obj=new A();
MyThread th1=new MyThread(obj,THIS);
MyThread th2=new MyThread(obj,IS);
MyThread th3=new MyThread(obj,SYNCHRONIZATION);
th1.start();
th2.start();
th3.start();
}
}
The output of the program is
(THIS)
(IS)
(SYNCHRONIZATION)
Note: Once a thread is in synchronized method on an instance, no other thread can enter any other
synchronized method on the same instance. However, simultaneous execution of synchronized methods is
possible for two different instance of the same class.
Self-Instructional
152 Material
Exception Handling
Threads
NOTES
9.6.2 Synchronizing Statements
Another way of managing the execution of the thread is to synchronize a block of code
or statement and this is more powerful. Synchronizing a method does not work in all
cases. For example, the class you want to access is created by someone else, which
does not have synchronized methods and we do not have access rights to modify it. In
this case, the access to objects of this class can be synchronized by placing the call to
the methods defined by this class inside a synchronized block. Two block of codes
synchronized on the same instance cannot execute at the same time.
The general form to synchronize a block of code is
synchronized(object)
{
//statements to be synchronized
}
where,
object is a reference to the object being synchronized.
Example 9.9: A program to demonstrate synchronized statement
class A
{
void display(String msg)
{
System.out.print(( +msg);
try
{
Thread.sleep(1000);
}catch(InterruptedException e)
{
System.out.println(Interrupted);
}
System.out.println());
}
}
class MyThread extends Thread
{
String str;
A obj;
MyThread (A obj1,String s)
{
obj=obj1;
str=new String(s);
}
public void run()
{
synchronized(obj)
Self-Instructional
Material 153
Exception Handling
Threads
NOTES
{
obj.display(str);
}
}
}
class SynchronizedStatement
{
public static void main(String[] args)
{
A obj=new A();
MyThread th1=new MyThread(obj,THIS);
MyThread th2=new MyThread(obj,IS);
MyThread th3=new MyThread(obj,SYNCHRONIZATION);
th1.start();
th2.start();
th3.start();
}
}
The output of the program is
(THIS)
(IS)
(SYNCHRONIZATION)
By using the synchronized statement inside the run() method, access to the
object of the class A is restricted to only one thread at a time thus producing the same
correct output.
9.6.3 Deadlock
Deadlock is a situation that occurs when two or more threads are in a simultaneous wait
state and each of them is waiting for the release of a resource held by one of the other
waiting thread. For example, consider the following code segments.
Thread X: Thread Y:
run() run()
{ {
synchronized(obj1) synchronized(obj2)
{ {
sleep(1000); sleep(1000);
obj2.method2(); obj1.method1();
} }
} }
First, Thread X starts and synchronizes on the object obj1 which prevents
other threads to call the methods of obj1. Thread X then goes to sleep by calling
sleep() method and allows Thread Y to start. Thread Y starts and synchronizes
Self-Instructional
154 Material
Exception Handling
Threads
NOTES
on the object obj2. This prevents method of obj2 to be called by any other thread.
Thread Y goes to sleep on the invocation of sleep() method allowing Thread X to
wake up. Thread X continues execution and tries to call method2() on obj2 but
it cannot call the method on obj2 until the code in Thread Y that is synchronized on
obj2 finishes execution. As Thread X cannot proceed, Thread Y gets the control
and tries to call method1() on obj1 which is not possible until the code in Thread
X that is synchronized on obj1 finishes its execution. Here, neither of the threads can
continue because they are deadlocked.
Example 9.10: A program to demonstrate deadlock
class A
{
void display1( A obj2)
{
System.out.println(First thread waiting for second thread
to release the resource);
synchronized(obj2)
{
System.out.println(Deadlocked);
}
}
void display2(A obj1)
{
System.out.println(Second thread waiting for first thread
to release the resource);
synchronized(obj1)
{
System.out.println(Deadlocked);
}
}
}
class Thread1 extends Thread
{
A obj1,obj2;
Thread1(A i,A j)
{
obj1=i;
obj2=j;
}
public void run()
{
synchronized(obj1)
{
try
Self-Instructional
Material 155
Exception Handling
Threads
NOTES
{
sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
obj2.display1(obj2);
}
}
}
class Thread2 extends Thread
{
A obj1,obj2;
Thread2(A p,A q)
{
obj1=p;
obj2=q;
}
public void run()
{
synchronized(obj2)
{
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
obj1.display2(obj1);
}
}
}
class Deadlock
{
public static void main(String args[])
{
A obj1=new A();
A obj2=new A();
Thread1 t1=new Thread1(obj1,obj2);
Thread2 t2=new Thread2(obj1,obj2);
Self-Instructional
156 Material
Exception Handling
Threads
NOTES
t1.start();
t2.start();
}
}
The output of the program is
Second thread waiting for first thread to release the resource
First thread waiting for second thread to release the resource
In this example, the thread Thread1 owns the monitor on obj1 and waits for
the monitor on obj2. Similarly, the thread Thread2 owns the monitor on obj2 and
waits for the monitor on obj1. Thread1 will never release obj1 unless it gets hold
of obj2 and Thread2 will never release obj2 unless it gets obj1. The program will
never complete as the two threads are in the deadlock situation. We need to press
CTRL-C to end the program.
9.7 INTER-THREAD COMMUNICATION
Inter-thread communication is a process in which multiple threads exchange messages
with one another. A thread exchanges message before or after it changes its state.
There are several situations where communication between threads is important. For
example, let us consider two threads A and B in which thread B uses data produced by
thread A. After the thread A produces data, it will keep checking every now and then
whether the thread B has finished using the data so that it can generate more thus
wasting CPU cycles. Thread B would again waste many CPU cycles while it waits for
thread A to produce data. If threads A and B communicate with one another when they
have finished their tasks, then they do not have to wait and check each others status
every time. Thus, CPU cycles are not wasted.
Inter-thread communication can be achieved by using three methods namely
wait(), notify() and notifyall(). These methods can be invoked only from
within synchronized method or a synchronized block of code, otherwise an exception of
type IllegalMonitorStateException is thrown. All these methods are declared
final and they have been discussed as follows:
wait(): It informs the current thread to release the monitor and to go into sleep
state until another thread wakes it up by calling the notify() method. This
method throws InterruptedException. There is another form of wait()
method which allows us to specify the amount of time a thread can wait.
notify(): It starts the first thread that called the method wait() on the
same object.
notifyall(): It starts all the threads that called the method wait() on the
same object. In this case, the thread with the highest priority will run first.
First, consider an example where a thread uses data produced by another thread
without the use of wait() and notify() methods.
Example 9.11: A program without using wait() and notify() method
class P
{
int i;
Self-Instructional
Material 157
Exception Handling
Threads
NOTES
synchronized int recieve()
{
System.out.println(Recieved: +i);
return i;
}
synchronized void deliver(int i)
{
this.i=i;
System.out.println(Delivered: +i);
}
}
class Thread1 extends Thread
{
P obj;
Thread1(P obj1)
{
obj=obj1;
}
public void run()
{
int j=0;
while(true)
{
obj.deliver(j++);
}
}
}
class Thread2 extends Thread
{
P obj;
Thread2(P obj1)
{
obj=obj1;
}
public void run()
{
while(true)
{
obj.recieve();
}
}
}
class NoCommunication
{
Self-Instructional
158 Material
Exception Handling
Threads
NOTES
public static void main(String[] args)
{
P obj=new P();
Thread1 t1=new Thread1(obj);
Thread2 t2=new Thread2(obj);
t1.start();
t2.start();
}
}
The output of the program is
Delivered:0
Delivered:1
Delivered:2
Delivered:3
Delivered:4
Delivered:5
Delivered:6
Recieved:6
Recieved:6
Recieved:6
Recieved:6
Recieved:6
Delivered:7
Delivered:8
Delivered:9
In this example, data produced by Thread1 is used by Thread2. Note that
Thread1 produces data 0 to 6 without letting Thread2 to use it. Again, Thread2
uses data 6 five times in a row. There is no way for the two threads to communicate
with each other.
Now, see the program in Example 9.11 using wait() and notify() methods.
Example 9.12: A program to demonstrate interthread communication
class P
{
int i;
boolean flag=false;
synchronized int recieve()
{
if(!flag)
try
{
wait();
}
catch(InterruptedException e)
Self-Instructional
Material 159
Exception Handling
Threads
NOTES
{
System.out.println(Exception caught);
}
System.out.println(Recieved: +i);
flag=false;
notify();
return i;
}
synchronized void deliver(int i)
{
if(flag)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println(Exception caught);
}
this.i=i;
flag=true;
System.out.println(Delivered: +i);
notify();
}
}
class Thread1 extends Thread
{
P obj;
Thread1(P obj1)
{
obj=obj1;
}
public void run()
{
int j=0;
while(true)
{
obj.deliver(j++);
}
}
}
class Thread2 extends Thread
{
P obj;
Self-Instructional
160 Material
Exception Handling
Threads
NOTES
Thread2(P obj1)
{
obj=obj1;
}
public void run()
{
while(true)
{
obj.recieve();
}
}
}
class InterThreadCommunication
{
public static void main(String[] args)
{
P obj=new P();
Thread1 t1=new Thread1(obj);
Thread2 t2=new Thread2(obj);
t1.start();
t2.start();
System.out.println(Please press CTRL-C to stop);
}
}
The output of the program is
Delivered:0
Recieved:0
Delivered:1
Recieved:1
Delivered:2
Recieved:2
Delivered:3
Recieved:3
Delivered:4
Recieved:4
Delivered:5
Recieved:5
Delivered:6
Recieved:6
In this example, the methods wait() and notify() are invoked inside
receive() and deliver()method. It enables Thread1 to notify Thread2 after
producing data and waits until Thread2 finishes using. In the same way, Thread2
after using the data notifies Thread1 and waits until Thread1 produces the next
data. Thus, the output is in the synchronized form.
Check Your Progress
8. Define
synchronization.
9. The keyword
is used to
synchronize a
method or a block
of statement.
10. At any given point
of time, only one
thread can own the
monitor. (True or
False)
11. Which of the
following is the
default priority of
a thread?
(a) 0 (b) 5
(c) 1 (d) 10
12. The situation in
which two or more
threads are in a
simultaneous wait
state waiting for
the release of the
resource held by
one of the other
waiting thread is
called .
13. Which of the
following is used in
inter-thread
communication?
(a) wait(),
notify(),
notifyall()
(b) wait(),
join()
(c) notify(),
join(),
notifyall()
(d) none of these
Self-Instructional
Material 161
Exception Handling
Threads
NOTES
9.8 SUSPENDING, RESUMING AND STOPPING
THREADS
As mentioned earlier, the predefined methods suspend(), resume() and stop()
have been deprecated in Java 2 though they are a convenient way for managing the
execution of threads. These methods were deprecated as they may cause deadlocks
and serious system failures in a multithreaded environment. However, in new version of
Java, suspending, resuming and stopping a thread can be performed using boolean
type flags. The run() method of a thread will work based on the current flag values
that indicate the execution state of a thread. For example, if the running flag is set to
true, the run() method must let the thread execute. For the run() method to
suspend the execution of the currently running thread, the suspend flag must be set to
true. Likewise, the thread will die once the stop flag is set to true.
Example 9.13: A program to demonstrate - suspend, resume and stop operations
class ChildThread extends Thread
{
boolean suspend_flag,stop_flag;
String name;
ChildThread(String str)
{
name=str;
suspend_flag=false;
stop_flag=false;
}
public void run()
{
try
{
int i=5;
while(i>=1)
{
System.out.println(name+ +i);
sleep(1000);
i;
synchronized(this)
{
while(suspend_flag)
{
wait();
if(stop_flag)
{
break;
}
}
Self-Instructional
162 Material
Exception Handling
Threads
NOTES
}
}
}catch(InterruptedException e)
{
System.out.println(Thread interrupted);
}
}
synchronized void my_suspend()
{
suspend_flag=true;
}
synchronized void my_resume()
{
suspend_flag=false;
notify();
}
synchronized void my_stop()
{
suspend_flag=false;
stop_flag=true;
notify();
}
}
class SRS
{
public static void main(String[] args)
{
try
{
ChildThread obj=new ChildThread(Thread);
obj.start();
System.out.println(Thread started);
Thread.sleep(2000);
obj.my_suspend();
System.out.println(Thread is suspended);
Thread.sleep(2000);
obj.my_resume();
System.out.println(Thread is resumed);
Thread.sleep(2000);
obj.my_suspend();
System.out.println(Thread is suspended);
Thread.sleep(2000);
obj.my_resume();
System.out.println(Thread is resumed);
Self-Instructional
Material 163
Exception Handling
Threads
NOTES
Thread.sleep(2000);
obj.my_stop();
System.out.println(Thread stopped);
}
catch(InterruptedException e)
{
System.out.println(Thread interrupted);
}
}
}
The output of the program is
Thread started
Thread 5
Thread 4
Thread 3
Thread is suspended
Thread is resumed
Thread 2
Thread 1
Thread is suspended
Thread is resumed
Thread stopped
9.9 SUMMARY
In this unit, you have learned that:
Multithreading is a programming concept in which a program (process) is divided
into two or more subprograms (subprocesses), each of which can perform different
task concurrently.
A thread is just like a program which has a single flow of control. It also has a
starting point, the execution part and an end. Threads are called lightweight
processes. This is because all the threads in a main application program share the
same address space in the memory.
Java program always contains at least one thread even if we do not create one.
This thread is called main thread and it is the one which immediately starts executing
when we start a program.
In Java, threads can be created in two ways, by extending the Thread class and
by implementing the Runnable interface. In both the approaches, threads are
implemented in the form of objects which contain a method called run(). It is
the entry point of a new thread and it is the place where the task to be performed
by the thread is defined.
There are various states that a Java thread can enter during its life cycle. They
are newborn, runnable, running, blocked and dead state. A thread is always in one
of these five states.
Self-Instructional
164 Material
Exception Handling
Threads
NOTES
The yield(), sleep() and stop() methods are responsible for controlling
the behavior of a thread and the transition of thread from one state to another.
There are two ways to determine whether a thread has ended. The isAlive()
method is used to test whether a thread is still alive. The join() method is used
to halt the execution of current thread (calling thread) until the thread on which
the method is called terminates. It ensures that the current thread will wait until
the called thread finishes its execution.
Priorities are the integers which specify the relative priority of one thread to
another. When a thread is created, it inherits its priority from the thread that
created it. The priority of a thread can be changed by using the setPriority()
method of the Thread class.
When multiple threads need access to a single resource, there is a technique
called synchronization to ensure that only one thread will use the resource at any
given point of time. Synchronization uses the concept of monitor.
A monitor is an object which is used as a mutually exclusive lock. That is, it can
be owned by only one thread at any given point of time.
There are two ways to implement synchronization. One is to synchronize method
and another is to synchronize statements. The keyword synchronized is
used in both the cases.
Deadlock is a situation that occurs when two or more threads are in a simultaneous
wait state and each of them is waiting for the release of a resource held by one of
the other waiting thread.
Inter-thread communication is a process in which multiple threads exchange
messages with one another. A thread exchanges message before or after it changes
its state. Inter-thread communication can be achieved by using three methods
namely wait(), notify() and notifyall().
The predefined methods suspend(), resume() and stop() have been
deprecated in Java 2 as they may cause deadlocks and serious system failures in
a multithreaded environment. In the new version of Java, suspending, resuming
and stopping a thread can be performed using boolean type flags.
9.10 KEY TERMS
Thread: It is a program which has a single flow of control.
Synchronization: It is a technique to ensure that only one thread will use the
resource at any given point of time, when multiple threads try to access a single
resource.
Deadlock: It is a situation that occurs when two or more threads are in a
simultaneous wait state and each of them is waiting for the release of a resource
held by one of the other waiting thread.
Self-Instructional
Material 165
Exception Handling
Threads
NOTES
9.11 ANSWERS TO CHECK YOUR PROGRESS
1. A thread is a program which has a single flow of control. It has a starting point,
the execution part and an end.
2. A thread can be started by calling the start() method.
3. run()
4. A thread dies when its run() method completes or when it is killed deliberately
by calling stop() method.
5. Main
6. Suspending a thread blocks the thread temporarily and makes the thread go to the
blocked state. The suspended thread can be brought back to the execution state
by calling resume() method. Stopping a thread kills the thread and makes the
thread go to the dead state. It cannot run again even if the start() method is
invoked.
7. False
8. Synchronization is a technique to ensure that only one thread will use the resource
at any given point of time, when multiple threads try to access a single resource.
9. synchronized
10. True
11. (b)
12. Deadlock
13. (a)
9.12 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What is multithreading?
2. What is the advantage of using multithreaded program over single-threaded
program?
3. What are the two ways of creating a thread in Java? Give an example of each.
4. How do you set priorities for threads? Give examples.
Long-Answer Questions
1. Describe the complete life cycle of a thread.
2. Write a program to illustrate the use of stop() and suspend() methods.
3. What is synchronization? When is it used? Explain by giving examples of the
different ways to implement synchronization.
4. When are two threads said to be deadlocked? Write a simple application program
to illustrate the deadlock situation.
5. The following code demonstrates the sleep() method. Will the code compile
successfully? Justify your answer.
class P extends Thread
{
Self-Instructional
166 Material
Exception Handling
Threads
NOTES
public void run()
{
for(int j=0;j<4;j++)
{
System.out.println(j);
sleep(1000);
}
}
}
class Demo
{
public static void main(String[] args)
{
P obj=new P()
obj.start();
}
}
6. Consider the following code which implements Runnable interface. Will the
code compile? If not why?
class P implements Runnable
{
public void run(String message)
{
System.out.println(Inside run() method +message);
}
}
class Test
{
public static void main(String args[])
{
P p=new P();
Thread t=new Thread(p);
t.start();
}
}
Self-Instructional
Material 167
Exception Handling
NOTES
UNIT 10 EXCEPTION HANDLING
Structure
10.0 Introduction
10.1 Unit Objectives
10.2 Exceptions
10.2.1 Keywords Used in Exception Handling
10.2.2 Types of Exceptions
10.3 Using try and catch Blocks
10.3.1 Multiple catch Blocks
10.3.2 Nested try Blocks
10.4 Using finally Block
10.5 Using throw Block
10.6 Using throws Keyword
10.7 Creating Your Own Exceptions
10.8 Summary
10.9 Key Terms
10.10 Answers to Check Your Progress
10.11 Questions and Exercises
10.0 INTRODUCTION
The main concern of programmers while developing any program is to write an error-
free code. The presence of a single error in the program may result in many undesirable
situations, such as unintended results may be produced, an abrupt termination of program
may occur or in the extreme case the system may crash. To avoid these unwanted
occurrences, the errors in the program code must be detected and handled in a proper
manner so that the program produces the expected output.
However, when a program is written for the first time it usually contains errors.
These errors are mainly classified into two types, namely, compile-time errors and run-
time errors. The compile-time errors occur due to syntactical errors, like missing
semicolons, missing brackets, wrongly spelt keywords, use of undeclared variables and
so on. These errors can be detected and removed by exhaustive testing and debugging.
Unlike compile-time errors, run-time errors are difficult to detect and trap. They may
occur due to problems in arithmetic calculations like dividing by zero, trying to access an
out-of-bound array element, converting invalid string to a number and so on. These run-
time errors are usually referred to as exceptions.
In this unit, you will learn about the basic concepts of exception handling.
10.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Understand exceptions in Java
Learn how to use try and catch blocks
Know how to use the finally block
Use the finally block
Learn how to use the throws keyword in exception handling
Create your own exceptions
Self-Instructional
168 Material
Exception Handling
NOTES
10.2 EXCEPTIONS
The term exception is an abbreviation of the phrase exceptional event. It is an
unpredictable event that occurs while the program is executing and thus disrupts the
normal flow of the program or terminates the program abnormally. The errors that
cause exception can range from simple programming errors such as opening or reading
an invalid file or accessing an invalid index of an array to severe errors such as running
out of memory.
When an error occurs within a method, the Java runtime system creates an
exception object. This exception object contains information about the exception which
includes its type and the state of the program when the error occurred. Once an exception
object is created, it is thrown and the runtime system searches for a method to handle
the exception. It keeps on searching for a method that contains an appropriate exception
handler. An exception handler is considered appropriate if the type of exception handled
by the handler is same as the type of exception thrown.
Before understanding the significance of exception handling mechanism, it is
necessary to see what happens if the exceptions are not handled.
Example 10.1: A program to demonstrate an unhandled exception
class ExceptionExample
{
public static void main(String args[])
{
int a=15;
int b=3;
int c=a/(a-(5*b)); //exception occurs here
System.out.println(Result: +c);
}
}
In this program, no compile-time error occurs. However, when the division by
zero statement is executed a run-time error is generated. At this point, the Java runtime
system creates an exception object and throws it. This thrown object expects an exception
handler to handle it. Since no exception handler has been provided in this program,
Javas default exception handler is invoked. The default exception handler will display
the following error message and terminate the program abruptly.
Exception in thread main java.lang.ArithmeticException: /
by zero at ExceptionExample.main(ExceptionExample.java:7)
10.2.1 Keywords Used in Exception Handling
The Java exception handling mechanism not only guarantees the detection and handling
of run-time errors but also provides a way to separate the error-handling codes from the
rest of the program. This makes the program less complex, more readable and efficient,
as the normal execution path is not interrupted for checking errors. Moreover, the exception
handling routine (called exception handler) is invoked automatically whenever an error
occurs.
Self-Instructional
Material 169
Exception Handling
NOTES
Java exception handling is governed by the following five keywords:
try
catch
finally
throw
throws
A set of statements that needs to be monitored for the exceptions is contained in
the try block. Whenever an exception occurs within the try block, it is thrown. This
passes the control to the catch block which handles the exception appropriately. Java
runtime system automatically throws system generated exceptions. If the user wants to
throw the exception explicitly, the throw keyword is used. Sometimes, a method may
throw exceptions which it cannot handle; this must be specified by using the throws
keyword. The code which must be executed whether an exception is thrown or not is
kept within the finally block, which is optional.
10.2.2 Types of Exceptions
Java provides several built-in classes which define all types of exceptions. These
exception classes are arranged in a hierarchy having Throwable class on the top
(Figure 10.1). That is, the Throwable class is the superclass and all the exception
classes inherit methods defined by it. Two immediate subclasses of the Throwable
class are as follows:
Exception class: It defines those exceptions which are thrown by methods of
the standard Java class library or methods defined in users program and can be
trapped within the program. That is, the program can reasonably recover from
these types of exceptions. This class is also used (inherited) when the users want
to create their own exceptions in the application.
Error class: It defines those exceptions that do not occur frequently and are
difficult to be recovered from. For example, a class file is missing or system runs
out of memory.
Error
Throwable
Exception
Figure 10.1 Java Exception Hierarchy
Some of the most commonly used exceptions that will be encountered are listed
in Table 10.1.
Self-Instructional
170 Material
Exception Handling
NOTES
Table 10.1 Some Common Exceptions in Java
Exception Description
ArithmeticException Thrown when arithmetic error occurs in the
program such as divide-by-zero
NullPointerException

Thrown when the user tries to use an object
without initializing the object or in other words
when an object that has not been allocated
memory is used
IOException Thrown when error occurs during input/output of
data
ArrayIndexOutOfBoundsEx
ception
Thrown when an attempt is made to access an
array element with invalid index value
ArrayStoreException Thrown when an attempt is made to store the
incompatible type of data in an array
IllegalAccessException Thrown when an illegal attempt is made to access
a class
NumberFormatException Thrown when an invalid conversion of a string to
a numeric format takes place
StringIndexOutOfBoundsE
xception
Thrown when an attempt is made to access a
string element that is beyond the index of the
string
IllegalArgumentExceptio
n
Thrown when an illegal argument is used to
invoke a method
NegativeArraySizeExcept
ion
Thrown when an array of negative size is created

10.3 USING try AND catch BLOCKS
The default exception handler provided by the Java runtime system does not prevent the
abrupt termination of the program. To prevent this, Java provides us the facility to construct
our own exception handler. By constructing our own exception handler, we can fix the
errors ourselves. This can be achieved by enclosing the code that may throw an exception
within a try block. The try block is enclosed by curly braces and preceded by the
keyword try. Whenever an exception occurs within the try block, it is thrown. This
passes the control to the catch block associated with the try block.
The syntax to define try-catch block is
try //try block begins
{
//code that may cause an exception
} //try block ends
catch(exception_type ex)
{
//code to handle the exception
}
If the first statement of the try block causes an exception, the remaining
statements are not executed and the control passes to the catch block. The catch
statement requires single argument which is of the same type as of exception that needs
Check Your Progress
1. The errors in a
program are mainly
classified into two
types, namely,
___________ and
____________.
2. An exception is
caused by a
____________
error.
3. A program will
continue to execute
even after an
exception has
occurred. (True or
False)
4. Java exception
handling
mechanism mainly
uses five
keywords,
_____________,
_____________,
_____________,
_____________
and
_____________.
5. All the exception
classes inherit
which of the
following built-in
class?
(a) Exception
(b) Throwable
(c) Error
(d) Runtime
Exception
Self-Instructional
Material 171
Exception Handling
NOTES
to be handled. This exception type must be a subclass of Throwable class. It is not
necessary that every time the program is executed, an exception occurs. If an exception
is not thrown, the catch block is skipped and the control passes to the statement
immediately following the catch block.
The try and catch blocks form a logical unit. The scope of the catch block
is limited only to those statements which are enclosed within the immediately preceding
try block.
Note: Compile-time error is generated if the try statement is not followed by any
catch statement.
Example 10.2: A program to illustrate handling of an exception using try and catch
blocks
class TryCatchBlock
{
public static void main(String args[])
{
int a=15;
int b=3;
int c=0;
try
{
System.out.println(try block begins);
c=a/(a-(5*b)); //exception generated
System.out.println(try block ends);
}
catch(ArithmeticException ae)
{
System.out.println(Arithmetic Exception is caught here);
System.out.println(The resultant value of c is: +c);
}
c=a/b;
System.out.println(New value of c is: +c);
}
}
The output of the program is
try block begins
Arithmetic Exception is caught here
The resultant value of c is: 0
New value of c is: 5
In this example, the exception generated within the try block is caught inside the
catch block thus, preventing the abnormal termination of the program as seen in
Example 10.1.
Self-Instructional
172 Material
Exception Handling
NOTES
10.3.1 Multiple catch Blocks
It is not necessary that the code enclosed within the try block throws a single exception.
In case, multiple exceptions are thrown within a try block, Java allows using multiple
catch blocks for handling all these exceptions.
The syntax to define multiple catch blocks is
try //try block
{
//code that may cause exceptions
}
catch (exception_type e1) //catch block 1
{
.
.
}
catch (exception_type e2) //catch block 2
{
.
.
}
.
.
.
catch(exception_type en) //catch block N
{
.
.
}
Note that there is only one try block from which the exception is thrown and
depending on the type of exception thrown, the corresponding catch block will be
executed. Whenever an exception is thrown, the catch blocks are searched in sequential
order for an appropriate match. The first catch block whose parameter type matches
with the type of exception gets executed and other catch blocks are ignored. Once the
execution of the appropriate catch block gets over, the control passes to the statement
immediately following the last catch block.
Example 10.3: A program to demonstrate the concept of multiple catch statements
class MultipleCatchExceptions
{
public static void main(String args[])
{
try
{
int a=0;
int b=7/a; //divide by zero exception
Self-Instructional
Material 173
Exception Handling
NOTES
int c[]={1,2,3,4,5};
c[6]=15; //array out of bound exception
}
//this block handles array out of bounds exception
catch(ArrayIndexOutOfBoundsException aioe)
{
System.out.println(Array out of bounds Exception);
}
//this block handles arithmetic exception
catch(ArithmeticException ae)
{
System.out.println(Division by zero error);
}
catch(Exception e)
{
System.out.println(Exception +e.getMessage());
}
}
}
The output of the program is
Division by zero error
In this program, the divide by zero error is caught by the second catch block
containing the instance of ArithmeticException class.
It should be noted that the exception superclasses must be placed after their
subclasses. This is because if we place the catch block containing the superclass
before its subclasses then this superclass will handle all the exception of its type as well
as of its subclasses. As a result subsequent catch blocks will never get executed and
compile-time error is generated. This problem is known as an unreachable code problem.
In Example 10.3, if we place Exception class before ArithmeticException
and ArrayIndexOutOfBoundsException classes, then compiling this program
will display the error message as shown below.
M u l t i p l e C a t c h E x c e p t i o n s . j a v a : 1 7 : e x c e p t i o n
java.lang.ArrayIndexOutOfBoundsException has already been
caught
catch(ArrayIndexOutOfBoundsException aioe)
^
M u l t i p l e C a t c h E x c e p t i o n s . j a v a : 2 2 : e x c e p t i o n
java.lang.ArithmeticException has already been caught
catch(ArithmeticException ae) //this block handles
arithmetic exception
^
2 errors
Self-Instructional
174 Material
Exception Handling
NOTES
This is because ArrayIndexOutOfBoundsException class and
ArithmeticException class are the subclasses of Exception class. Thus,
Exception class catches all the thrown exception relative to these classes and their
corresponding catch blocks are never executed.
10.3.2 Nested try Blocks
The try blocks can be nested, that is, one try-catch block can be placed inside
another try-catch block. If an exception occurs within a particular try block, then
the catch blocks associated with this try block are searched for an appropriate
match. If no match is found then the control passes to the next outer try-catch
block. This process continues until an appropriate match is found. If no match is found,
the program terminates abnormally.
The syntax of nested try block is
try //outer try block
{
try //inner try block
{
.
.
}
catch //inner catch block
{
.
.
}
}
catch //outer catch block
{
.
.
}
Example 10.4: A program to demonstrate the concept of nested try blocks
class NestedTryBlock
{
public static void main(String args[])
{
//outer try-catch block
try
{
int a[]={0,1};
//inner try-catch block
try
{
int b[]={0,5};
Self-Instructional
Material 175
Exception Handling
NOTES
int d=b[1]/b[0];//exception thrown
System.out.println(Division of two numbers is : +d);
}
catch(ArrayIndexOutOfBoundsException ai)
{
System.out.println(Inside inner try-catch block);
System.out.println(ai.getMessage());
}
}
catch(ArithmeticException a)
{
System.out.println(Inside outer try-catch block);//the
thrown exception is caught here
System.out.println(a);
}
}
}
The output of the program is
Inside outer try-catch block
java.lang.ArithmeticException: / by zero
In this program, the division by zero error is thrown by the inner try block but it
could not be handled by the inner catch block as the type of exception defined by the
inner catch does not match with the exception thrown by the inner try. The matching
catch block is then searched in sequential order for an appropriate match and the
exception is caught inside the outer catch block.
10.4 USING finally BLOCK
It has been observed that when an exception is thrown in the program, the remaining
statements in the try block are not executed and the control directly gets transferred to
the subsequent catch block. However, there are certain statements in the program
that need to be executed whether or not exception is raised. For this, Java provides
finally keyword. The code within the finally block will always be executed
whether or not the exception is thrown. If an exception is raised with a matching catch
block, then the finally block gets executed after the execution of that catch block.
On the other hand, if no matching catch block is found then also the finally block
is executed after the execution of the try block. The finally block is optional;
however, it is necessary to include either catch or finally block with try block.
The diagrammatic representation of working of try-catch-finally block
can be shown in Figure 10.2.
Self-Instructional
176 Material
Exception Handling
NOTES
Execute try block
Find catch block to execute
Execute catch block
for Exceptiontype2

Execute catch block
for Exceptiontypen

Execute catch block
for Exceptiontype1


Execute finally
block
[exception]
[no exception]
[exception1] [exception2] [exceptionn]
Figure 10.2 try-catch-finally Block
Example 10.5: A program to illustrate the use of finally block
class FinallyBlock
{
public static void main(String args[])
{
int a=67;
int b=0;
try
{
System.out.println(The value of a: +a);
System.out.println(The value of b: +b);
int c=(a/b); //exception thrown
System.out.println(Result is: +c);
}
catch(Exception e)
{
System.out.println(e); //prints the corresponding exception
}
finally
{
System.out.println(Denominator cannot be zero);
}
}
}
Self-Instructional
Material 177
Exception Handling
NOTES
The output of the program is
The value of a: 67
The value of b: 0
java.lang.ArithmeticException: / by zero
Denominator cannot be zero
Here, the thrown exception is caught in the catch block and an appropriate
error message is displayed. After that, the statement within the finally block is
executed.
10.5 USING throw BLOCK
As stated earlier, the Java runtime system automatically throws system-generated
exceptions. However, Java provides a mechanism to throw an exception explicitly by
using the throw keyword.
The syntax of throw statement is
throw ExceptionObject;
where,
ExceptionObject is an object of Throwable class or its subclass
When a throw statement is encountered in the program, the execution of the
subsequent statements in the try block stops and corresponding catch block is
searched. The nearest try block is checked to determine if it contains a catch block
to match the exception of its type. If it is found, then that catch block is executed else
subsequent try blocks are inspected. In case, if no matching catch block is found,
then the default exception handler comes into action and stops the normal execution of
the program and displays the error message on the output screen.
It should be noted that instances of classes other than Throwable class or its
subclasses cannot be used as exception objects. The Throwable object can be created
using a new operator or using a parameter inside catch clause.
Example 10.6: A program to demonstrate the use of throw keyword
class ThrowExampleDemo
{
public static void main(String args[])
{
try
{
ThrowExample(); //invoking ThrowExample() method
}
catch(ArithmeticException ae)
{
System.out.println(The exception is recaught here: +ae);
}
}
static void ThrowExample()
{
Check Your Progress
6. A set of statements
that may throw an
exception in a
program code is
enclosed within the
__________ block.
7. What is the
significance of
catch block?
8. The ordering of
catch statements is
significant in a
multiple catch
block. (True or
False)
9. It is valid to
include some code
between the try
and catch or
finally block
following it. (True
or False)
10. Which of the
following will not
generate an error?
(a) A catch block
without a try
block
(b) Presence of
code between
try and
catch blocks
(c) A try block
with either a
catch or a
finally
block
(d) A finally
block without a
try block
Self-Instructional
178 Material
Exception Handling
NOTES
int a=0;
int b=6;
try
{
int c=b/a; //system-generated exception
System.out.println(c);
}
catch(ArithmeticException aoe)
{
System.out.println(The exception is caught inside the method
ThrowExample);
throw aoe; //exception thrown explicitly
}
}
}
The output of the program is
The exception is caught inside the method ThrowExample
The exception is recaught here :java.lang.ArithmeticException:
/ by zero
In this example, the ArithmeticException occurs inside the
ThrowExample(). This exception is caught inside the catch block inside the same
method, which explicitly rethrows it using the throw keyword. This is called rethrowing
of the exception. Now the control passes back to the catch block of the main()
method and the thrown exception is again caught here.
10.6 USING throws KEYWORD
Sometimes a method may generate an exception but cannot handle it. That is, there may
be a method in the program which is generating (throwing) an exception but it does not
have the appropriate exception handing mechanism. The methods which are calling
such methods must be cautioned about this behavior so that calling methods can take
appropriate measures to safeguard themselves against the exceptions. This is done by
appending throws keyword after method name in the method declaration statement.
The throws clause includes all types of exceptions excluding those belonging to Error
or Runtime classes or their subclasses. All other exceptions which a method may
throw must be listed after the throws keyword in the method declaration; otherwise
compile-time error is generated.
The syntax of the throws clause is
return_type method_name() throws exception_list
{
//body of the method
}
where,
exception_list includes all the exceptions that the method might throw
Self-Instructional
Material 179
Exception Handling
NOTES
Example 10.7: A program to illustrate the use of throws clause
class ThrowsExample
{
//ClassExample method throwing ClassNotFounfException
static void ClassExample() throws ClassNotFoundException
{
System.out.println(Inside ClassExample);
throw new ClassNotFoundException(This is an example of Class
not found Exception);
}
public static void main(String args[])
{
try
{
ClassExample();
}
catch(ClassNotFoundException c)
{
System.out.println(Exception caught: +c);
}
}
}
The output of the program is
Inside ClassExample
Exception caught: java.lang.ClassNotFoundException: This is
an example of Class not found Exception
In this program, we are explicitly throwing the ClassNotFoundException
in the method ClassExample. Since we are not handling the thrown exception in the
same method therefore we use the throws statement after the method name and
catching the exception inside the main() method.
10.7 CREATING YOUR OWN EXCEPTIONS
In the earlier section, you have learnt about some of the built-in exceptions provided by
the Java platform. These built-in exceptions are used to handle the errors occurring in
the program. But sometimes the programmer wants to create his own application specific
exceptions. User-defined exceptions can be created simply by defining a subclass of
Exception class and using the throw keyword.
Example 10.8: A program to demonstrate creation of user-defined exceptions
class OwnException extends Exception
{
public OwnException(String message) //Constructor
{
System.out.println(OwnException class constructor);
Self-Instructional
180 Material
Exception Handling
NOTES
}
}
public class CreateOwnException
{
public static int divide(int i,int j) throws OwnException
{
if(j==0)
throw new OwnException(This statement is not executed);
return i/j;
}
public static void main(String[] args)
{
int i=70;
int j=0;
try
{
System.out.println(The value of i: +i);
System.out.println(The value of j: +j);
System.out.println(Division of two numbers is:
+divide(i,j));
}
catch (OwnException oe)
{
System.out.println(Denominator can not be zero);
oe.printStackTrace();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
The output of the program is
The value of i: 70
The value of j: 0
OwnException class constructor
Denominator can not be zero
OwnException
at CreateOwnException.divide(CreateOwnException.java:13)
at CreateOwnException.main(CreateOwnException.java:24)
This example defines a subclass of Exception called OwnException.
Thus, this class will inherit the methods defined by the Throwable class through
Exception class. The CreateOwnException class defines a method divide()
Self-Instructional
Material 181
Exception Handling
NOTES
which throws an object oe of OwnException type when the denominator of the
fraction is zero. The printStackTrace() method of the Throwable class is
overridden to display the message which contains all the information that lead to the
error, such as the name of the method which caused the error, the name of the caller of
the method which lead to the error, the line number in which that error has occurred, etc.
10.8 SUMMARY
In this unit, you have learned that:
The errors in a program are mainly classified into two types, namely, compile-
time errors and run-time errors.
The compile-time errors mostly occur due to syntactical errors, like missing
semicolons, missing brackets, miss spelt keywords, use of undeclared variables
and so on.
Run-time errors may occur due to problems in arithmetic calculations like divide
by zero, trying to access an out-of-bound array element, converting invalid string
to a number and so on. These run-time errors are usually referred to as exceptions.
The term exception is an abbreviation for the phrase exceptional event. It is an
unpredicted event that occurs while the program is executing and thus disrupts
the normal flow of the program or terminates the program abnormally.
Java exception handling mechanism not only guarantees the detection and handling
of run-time errors but also provides a way to separate the error-handling code
from the rest of the program.
Java exception classes are inherited by Throwable class.
Java exception handling is governed by the five keywords, namely, try, catch,
finally, throw and throws.
A set of statements that needs to be monitored for the exceptions is contained in
the try block.
Whenever an exception occurs within the try block, it is thrown. This passes
the control to the catch block associated with the try block.
In case multiple exceptions are thrown within a try block, Java allows using
multiple catch blocks for handling all these exceptions.
The try blocks can be nested, that is, one try-catch block can be placed
inside another try-catch block.
The code within the finally block will always be executed whether or not the
exception is thrown.
Java provides a mechanism to throw an exception explicitly by using the throw
keyword.
Sometimes a method may throw exceptions which it cannot handle, this must be
specified using throws keyword.
Java allows the programmer to create user-defined exceptions simply by defining
a subclass of Exception class and using the throw keyword.
Check Your Progress
11. What is the
difference between
throw and
throws
keywords?
12. A catch block
can throw an
exception caught
by itself. (True or
False)
13. What do you
understand by
user-defined
exceptions?
14. The descriptive
information about
the exception
occurred during
program execution
can be retrieved
using method of
the Throwable
class.
Self-Instructional
182 Material
Exception Handling
NOTES
10.9 KEY TERMS
Exception: It is an unpredicted event that occurs while the program is executing,
thereby disrupting the normal flow of the program or terminating the program
abnormally.
User-defined exceptions: They are exceptions added by the user in Java by
extending the Exception class and using the throw keyword.
10.10 ANSWERS TO CHECK YOUR PROGRESS
1. Compile-time errors, run-time errors
2. Run-time error
3. False
4. try, catch, finally, throw, throws
5. (b)
6. try
7. The catch block catches and handles the exception thrown by the statements
within the try block. The exceptions must belong to Exception or Error
class.
8. True
9. False
10. (c)
11. The throw keyword is used to explicitly throw an exception. The exception
thrown must be an instance of Throwable class or its subclass. The throws
keyword is used with the method signature and is followed by all the exceptions
which the method may throw, but the method does not have the appropriate code
to handle all those exceptions.
12. True
13. In addition to the exceptions already defined in Java, the user can also define his
own exceptions by extending Exception class and using throw keyword.
These are called user-defined exceptions.
14. printStackTrace()
10.11 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What is an exception? What happens when an exception is not handled in Java?
2. What is exception handling mechanism? List five keywords which rule Java
exception handling.
3. What is unreachable code problem? Give an example.
4. What is the significance of throws keyword in Java?
Self-Instructional
Material 183
Exception Handling
NOTES
Long-Answer Questions
1. Explain Java exception hierarchy. What is the difference between instances of
Exception class and Error class?
2. Describe, with an example, the significance of try-catch block in exception
handling.
3. Once the control transfers to the catch block, it does not return to the try
block to execute the remaining code. Justify with an example.
4. What is the output of the following code? Give reason to your answer.
class NestedTry
{
public static void main(String args[])
{
try
{
int a[] = {0,1};
System.out.println(a[1]);
try
{
int b[] = {0,5};
int d = b[1]/b[0];
System.out.println(Division of two number is : +d);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
}
}
catch(NullPointerException aibe)
{
System.out.println(aibe.getMessage());
}
}
}
5. Is it compulsory to include finally block? Justify your answer.
6. Check the output of the following program and find the error (if any).
class NestedFinally
{
public static void main(String args[])
{
try
{
int b[] = {0,5};
int d = b[1]/b[0];
Self-Instructional
184 Material
Exception Handling
NOTES
System.out.println(Division of two number is : +d);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
System.out.println(This is the first finally Block);
}
finally
{
System.out.println(This is the second finally Block);
}
}
}
7. What is the role of throw keyword? Explain.
8. Give an example of creating your own exception in Java.
Self-Instructional
Material 185
Event Handling
NOTES
UNIT 11 EVENT HANDLING
Structure
11.0 Introduction
11.1 Unit Objectives
11.2 Events
11.3 Event Handling Model
11.3.1 Java 1.0 Event Model
11.3.2 Delegation Event Model
11.4 Event Handling: Classes, Sources and Listner Interfaces
11.4.1 Event Classes
11.4.2 Event Sources
11.4.3 Event Listener Interfaces
11.5 Summary
11.6 Key Terms
11.7 Answers to Check Your Progress
11.8 Questions and Exercises
11.0 INTRODUCTION
Java applets are used to create graphical and user-interactive applications. Although the
applets designed earlier were graphical in nature, they did very little when it came to
demonstrating their user-interactive capability. User interaction means a specific action
is generated and an appropriate result is displayed to the user when he interacts with an
application say by clicking mouse or by entering a character with the help of the keyboard.
In Java, all the activities that occur between the user and the application are termed as
events. They play a significant role in applet programming as they facilitate inclusion
user-interactivity in applets.
11.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Understand what an event is
Learn about event handling model
Understand the various types of events supported by Java
11.2 EVENTS
In Java, an event is an object, which specifies the change of state in the source. It is
generated whenever an action takes place like a mouse button is clicked or text is
modified. Javas abstract window toolkit (AWT) is responsible for communicating these
actions between the program and the user. Java packages such as java.util,
java.awt and java.awt.event support event handling mechanism.
When an action takes place, an event is generated. The generated event and all
the information about it such as time of its occurrence, type of event, etc. are sent to the
appropriate event handling code provided within the program. This code determines
Self-Instructional
186 Material
Event Handling
NOTES
how the allocated event will be handled so that an appropriate response can be sent to
the user.
11.3 EVENT HANDLING MODEL
The working of an event-driven program is governed by its underlying event-handling
model. Till now two models have been introduced in Java for receiving and processing
events. The event handling mechanisms of these models differ a lot from each other.
11.3.1 Java 1.0 Event Model
The Java 1.0 Event model for event processing was based on the concept of containment.
In this approach, when a user-initiated event is generated it is first sent to the component
in which the event has occurred. However, in case the event is not handled at this
component, it is automatically propagated to the container of that component. This process
is continued until the event is processed or it reaches the root of the containment hierarchy.
For example, as shown in the Figure 11.1, button is contained in the panel, which
itself is contained within the frame. When the mouse is clicked on button, an event is
generated, which is first sent to the button. If it is not handled by it then this event is
forwarded to the panel and if it cannot handle the event, it is further sent to the frame.
Frame being the root of the given hierarchy processes this event. So, the event is forwarded
up the containment hierarchy until it is handled by a component.







Frame
Panel
Button
Event generated
at button
Unhandled event
propagated
Event handled at
frame
Figure 11.1 Java 1.0 Event Handling Mechanism
The major drawback in this approach is that events could be handled by the
component that generated it or by the container of that component. Another problem is
that events are frequently sent to those components that cannot process them, thus
wasting a lot of CPU cycles.
11.3.2 Delegation Event Model
The advanced versions of Java ruled out the limitations of Java 1.0 event model. This
model is referred to as the delegation event model, which defines a logical approach to
handle events. It is based on the concept of source and listener. A source generates an
event and sends it to one or more listeners. On receiving the event, listener processes
the event and returns it. The notable feature of this model is that the source has a
registered list of listeners, which will receive the events as they occur. Only the listeners
that have been registered actually receive the notification when a specific event is
generated.
Self-Instructional
Material 187
Event Handling
NOTES
For example, as shown in the Figure 11.2, when the mouse is clicked on button, an
event is generated. If the button has a registered listener to handle the event, this event
is sent to button, processed and the output is returned to the user. However, if it has no
registered listener the event will not be propagated upwards to panel or frame.
Frame
Panel
Button
Event generated
Event handler
Figure 11.2 Java 1.1 Event Handling Mechanism
Event Source
An event source is an object that generates a particular kind of event. An event is
generated when the internal state of the event source is changed. A source may generate
more than one type of event. Every source must register a list of listeners that are
interested to receive the notifications regarding the type of event. Event source provides
methods to add or remove listeners.
The general form of method to register (add) a listener is
public void addTypeListener(TypeListener eventlistener)
Similarly, the general form of method to unregister (remove) a listener is
public void removeTypeListener(TypeListener eventlistener)
where,
Type is the name of the event
eventlistener is a reference to the event listener
Event Listener
An event listener is an object, which receives notification when an event occurs. Only
registered listeners can receive notifications from sources about specific types of events.
The role of event listener is to receive these notifications and process them.
11.4 EVENT HANDLING: CLASSES, SOURCES AND
LISTNER INTERFACES
Java provides various classes and interfaces to handle the generated events.
11.4.1 Event Classes
Java 1.1 event classes encapsulate all types of events occurring in the system. A
successful handling of the events requires in-depth understanding of these classes. All
these classes have been arranged in a hierarchy having EventObject class as its
root element. This class acts as the superclass of all the event classes. EventObject
class belongs to java.util package. Some of the event classes are discussed as
follows:
Check Your Progress
1. How does the
delegation event
model handle
events?
2. How is an event
represented?
3. Which is the
highest class in
delegation event
model?
Self-Instructional
188 Material
Event Handling
NOTES
The ActionEvent Class
The ActionEvent class represents the event that is generated when a user selects a
menu item, presses button or double-clicks a list item.
The ActionEvent class defines the following constructors.
ActionEvent(Object source, int event_type, String
command_name)
ActionEvent(Object source, int event_type, String
command_name, int modifier_key)
ActionEvent(Object source, int event_type, String
command_name, long event_time, int modifier_key)
where,
source is a reference to the object that originated the event. The reference to the
object can be obtained by using getSource()method.
event_type specifies the type of the event. The getId()method returns
the type of the event.
command_name is the name of the command which invoked the ActionEvent
object which can be obtained by invoking the getActionCommand() method.
event_time represents the system time at which the event has occurred.
The getWhen() method returns the time of occurrence of the event.
modifier_key is the value of the modifier key(Alt, Ctrl, Meta, Shift), which
was pressed when the event was generated. The getModifiers() method returns
the value of the modifier key.
The AdjustmentEvent Class
An AdjustmentEvent represents an event that is generated when a change has
occurred in the scrollbar. The AdjustmentEvent class defines an integer constant,
ADJUSTMENT_VALUE_CHANGED signals that some change has occurred. In addition,
this class defines following integer constants to determine what kind of event is generated
by the scrollbar.
UNIT_INCREMENT: It indicates that the user has clicked the left arrow of the
horizontal or the top arrow of the vertical scrollbar to increase its value.
UNIT_DECREMENT: It indicates that the user has clicked the right arrow of
the horizontal or the bottom arrow of the vertical scrollbar to decrease its value.
BLOCK_INCREMENT: It indicates that the user has clicked inside the scrollbar
to increase its value.
BLOCK_DECREMENT: It indicates that the user has clicked inside the scrollbar
to decrease its value.
TRACK: It represents that the user has dragged the slider.
One of the constructors of the AdjustmentEvent class is as follows:
AdjustmentEvent(Adjustable source, int id, int event_type,
int data)
where,
source is a reference to the object that originated this event. The object that
generated the event can be obtained using getAdjustment()method.
Self-Instructional
Material 189
Event Handling
NOTES
id is the value equal to the ADJUSTMENT_VALUE_CHANGED
event_type specifies the type of the event. The type of the adjustment event
can be obtained using the getAdjustmentType()method.
data is the data associated with the event.
The ComponentEvent Class
The ComponentEvent class represents the event that is generated when the position,
size or visibility of a component alters.
The ComponentEvent class defines the following constructor:
Component(Component source, int event_type)
where,
source is a reference to the component that originated the event. The reference
to the component can be obtained by using getComponent()method.
event_type specifies the type of the event. The different types of component
events are represented by integer constantsCOMPONENT_MOVED,
COMPONENT_RESIZED, COMPONENT_HIDDEN, COMPONENT_SHOWN.
The ContainerEvent Class
The ContainerEvent class inherits ComponentEvent class. The container
event is generated when a component is added to or removed from a container.
The ContainerEvent class defines the following constructor:
ContainerEvent(Component source, int type, Component
component)
where,
source is a reference to the component that originated the event. The reference
to the component can be obtained by using getContainer()method.
event_type specifies the type of the event. The different types of events are
represented by integer constantsCOMPONENT_ADDED, COMPONENT_REMOVED.
component represents the component that has been added to or removed from
the container and can be obtained by using getChild() method
The FocusEvent Class
The FocusEventclass represents event that is generated when a component gains or
loses the focus of the input. The FocusEvent class is a subclass of ComponentEvent
class.
The FocusEventclass defines the following constructors:
FocusEvent(Component source, int event_type)
FocusEvent(Component source, int event_type, Boolean
tempflag)
FocusEvent(Component source, int event_type, Boolean
tempflag, Component opp_component)
where,
source is a reference to the component that originated the event.
event_type specifies the type of the event. The different types of events are
represented by integer constantsFOCUS_GAINED, FOCUS_LOST.
Self-Instructional
190 Material
Event Handling
NOTES
tempflag specifies whether the focus event is temporary. To determine if the
focus event is temporary isTemporaray() method is used.
opp_component represents another component that takes part in the focus
change. It means if the FOCUS_GAINED event takes place then the opp_component
is that component, which lost focus. On the other hand, if FOCUS_LOST event occurs
then the opp_component is that component which gains focus.
The ItemEvent Class
The ItemEvent class represents the event, which is generated when a menu item is
selected or deselected, checkbox item is clicked or a list item is selected.
The ItemEvent class defines the following constructor:
ItemEvent(ItemSelectable source, int event_type, Object
item, int item_state)
where,
source is a reference to the component that originated the event. The
getItemSelectable() method returns the reference to the component that
originated this event.
event_type specifies the type of the event. The different types of events are
represented by integer constantsITEM_SELECTED, ITEM_DESELECTED.
item is a reference to the item that originated the event which can be obtained
by using getItem()method.
item_state returns the current state of the item (selected or deselected),
which generated the item event. The getStateChange() method returns the current
state of the item.
The KeyEvent Class
The KeyEvent class represents the event that is generated when the user interacts
with the application through keys. Java supports key events through KeyEvent class.
The KeyEvent class defines the following constructor:
KeyEvent(Component source, int event_type, long
event_time, int modifier_key, int code, char character)
where,
source is a reference to the component that originated the event.
event_type specifies the type of the event. The different types of events are
represented by integer constantsKEY_PRESSED, KEY_RELEASED,
KEY_TYPED.
event_time represents the system time at which the event has occurred.
modifier_key is the value of the modifier key(Alt, Ctrl, Meta, Shift), which
was pressed when the event was generated.
code returns the value of virtual key codesVK_0 to VK_9, VK_A to
VK_Z, VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT etc. The getKeyCode()
method returns the value of the virtual key.
character specifies the character that has been entered and can be obtained
by using getKeyChar() method.
Self-Instructional
Material 191
Event Handling
NOTES
The MouseEvent Class
The MouseEvent class represents the event that is generated when the user interacts
with the application through the mouse. The MouseEvent class encapsulates mouse
events.
The MouseEventclass defines the following constructor:
MouseEvent(Component source, int item_type, long
event_time, int modifier_key, int a, int b, int
clicks_count, boolean popuptriggers)
where,
source is a reference to the component that originated the event.
event_type specifies the type of the event. The different types of events are
represented by integer constantsMOUSE_CLICKED, MOUSE_EXITED,
MOUSE_ENTERED, MOUSE_PRESSED, MOUSE_RELEASED,
MOUSE_DRAGGED, MOUSE_MOVED, MOUSE_WHEEL.
event_time represents the system time at which the event occurred
modifier_key is the value of the modifier key(ALT, CTRL, META, SHIFT)
which was pressed when the event was generated.
int a, int b represents the X, Y coordinates of the position of the mouse
within the component respectively. The getX() and getY() methods return the
X,Y coordinates respectively. Alternatively, getPoint()method can be used to obtain
both the coordinates
clicks_count represents the total number of mouse clicks took place for
this event. The getClickCount() method returns the total number of mouse clicks.
popuptriggers specifies whether the pop-up window will appear. To determine if
the pop-up window appears isPopupTrigger() method is used.
The TextEvent Class
The TextEvent class represents the event that is generated when the user enters or
changes text in text fields or text areas. The TextEvent encapsulates text events.
The TextEvent class defines the following constructor:
TextEvent(Object source, int event_type)
where,
source represents the object that originated the event.
event_type specifies the type of the event. The event is represented by
integer constantTEXT_VALUE_CHANGED.
The WindowEvent Class
The WindowEvent class represents the event that is generated when the state of the
window changes. The WindowEvent class is a subclass of ComponentEvent
class.
The WindowEvent class defines the following constructors:
WindowEvent(Window Source, int event_type)
WindowEvent(Window Source, int event_type, Window opposite)
WindowEvent(Window Source, int event_type, int from_State,
Self-Instructional
192 Material
Event Handling
NOTES
int to_State)
WindowEvent(Window Source, int event_type, Window another,
int from_State, int to_State)
where,
source is a reference to the component that originated the event. The reference
to the component is obtained by using getWindow() method.
event_type specifies the type of the event. The event is represented by
integer constantWINDOW_ACTIVATED, WINDOW_DEACTIVATED,
WINDOW_GAINED_FOCUS, WINDOW_LOST_FOCUS, WINDOW_OPENED,
WINDOW_CLOSED, WINDOW_CLOSING, WINDOW_ICONIFIED,
WINDOW_DEICONIFIED, WINDOW_STATE_CHANGED.
opposite represents the another window when the window focus or window
activation events took place and can be obtained by using getOppositeWindow()
method.
from_State specifies the old state of the window, that is, the state before the
state of the window changed. The getOldState() method returns the old state of
the window.
to_State specifies the new state of the window, that is, the state after the
state of the window changed. The getNewState() method returns the new state of
the window.
11.4.2 Event Sources
Event sources are the objects, which generate events. Some of the examples of event
sources are listed in the Table 11.1.
Table 11.1 Event Sources
Event source Description
Button generates action events when the button is pressed
Choice generates item events when choice changes
Window generates window events when the state of the
window changes
Text
components
generates text events when a text is entered in text
field or text area
Menu item generates action events when a menu item is selected,
generates item events when a checkable menu is
selected or deselected
Checkbox generates item events when a checkbox is selected or
deselected.
List generates action events when an item is double-
clicked, generates action events when an item is
selected or deselected
Scrollbar generates events when the scroll bar is manipulated
Self-Instructional
Material 193
Event Handling
NOTES
11.4.3 Event Listener Interfaces
Events generated by the event source are sent to event listeners, which handle them in
an appropriate manner. Event listeners implement various interfaces. Some of the
interfaces are discussed as follows:
The ActionListener Interface
When an action event occurs, the actionPerformed() method defined by the
ActionListener interface is invoked.
The general form of the actionPerformed()method is
void actionPerformed(ActionEvent e)
where,
e is the reference to an object of ActionEvent class
The AdjustmentListener Class
When an adjustment event occurs, the adjustmentValueChanged()method
defined by the AdjustmentListener interface is invoked.
The general form of the adjustmentValueChanged() method is
void adjustmentValueChanged(AdjustmentEvent e)
where,
e is the reference to an object of AdjustmentEvent class
The ComponentListener Interface
The methods provided by the ComponentListener interface are invoked when the
state of the component changes, that is, the component is resized, moved, shown or
hidden.
The general form of the methods defined in ComponentListener interface is
void componentShown(ComponentEvent com)
void componentHidden(ComponentEvent com)
void componentMoved(ComponentEvent com)
void componentResized(ComponentEvent com)
where,
com is the reference to an object of ComponentEvent class
The ContainerListener Interface
The methods defined by the ContainerListener interface are invoked when the
component is added to or removed from a container. The object of ContainerEvent
class is passed as method parameter.
The general form of the methods defined in ContainerListener interface is as
follows:
void componentAdded(ContainerEvent con)
void componentRemoved(ContainerEvent con)
Self-Instructional
194 Material
Event Handling
NOTES
The FocusListener Interface
The methods defined by the FocusListener interface are invoked when the focus
of the keyboard is lost or gained by the component. The object of FocusEvent class
is passed as method parameter.
The general form of the methods defined in FocusListener interface is as
follows:
void focusGained(FocusEvent foc)
void focusLost(FocusEvent foc)
The ItemListener Interface
The method itemStateChanged() defined by the ItemListener interface is
invoked when the state of an item is changed. The object of ItemEvent class is
passed as method parameter.
The general form of the method defined in ItemListener interface is void
itemStateChanged(ItemEvent item)
The KeyListener Interface
The methods defined by the KeyListener interface are invoked when any key is
pressed or released, or a character is entered. The object of KeyEvent class is passed
as method parameter.
The general form of the methods defined in KeyListener interface is
void keyPressed(KeyEvent key)
void keyReleased(KeyEvent key)
void keyTyped(KeyEvent key)
Note: If a key B is pressed and released, three events (key pressed, key typed and key released) are
generated.
The MouseListener Interface and MouseMotionListener Interface
The methods defined by the MouseListener interface are invoked when the mouse
is clicked, pressed, released, when the mouse enters or exits the component. Similarly,
the methods defined by the MouseMotionListener interface are invoked when
the mouse is dragged or moved from one position to another. The object of MouseEvent
class is passed as method parameter.
The general form of the methods defined in MouseListener interface is as
follows:
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
The general form of the methods defined in MouseMotionListener interface
is as follows:
void mouseMoved(MouseEvent me)
void mouseDragged(MouseEvent me)
Self-Instructional
Material 195
Event Handling
NOTES
The TextListener Interface
The method textValueChanged()defined by the TextListener interface is
invoked when the text inside the text area or text field alters. The object of TextEvent
class is passed as method parameter.
The general form of the method defined in TextListener interface is as
follows:
void textValueChanged(TextEvent te)
The WindowListener Interface
The methods defined by the WindowListener interface are invoked when the state
of the window changes. The object of WindowEvent class is passed as method
parameter.
The general form of the methods defined in WindowListener interface is
void windowOpened(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowActivated(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowIconified(WindowEvent we)
void windowDeiconified(WindowEvent we)
To understand the concept of event handling, consider Example 11.1. This program
demonstrates the generation of key events when the user presses or releases any keyboard
key. The methods of the KeyListener interface are invoked when the key is pressed
or released and output is displayed to the user in the status bar of the applet window.
Example 11.1: An applet to demonstrate the event handling mechanism using
KeyListener interface
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Applet implements
KeyListener
{
String pstr = This is your Key Listener Class;
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent e)
{
showStatus(You have pressed a key); /*displays the string
on the applet window*/
}
public void keyReleased(KeyEvent e)
{
showStatus(You have released a key);
Self-Instructional
196 Material
Event Handling
NOTES
}
public void keyTyped(KeyEvent e)
{
}
public void paint(Graphics g)
{
g.drawString(pstr, 10, 20);
}
}
The HTML code for KeyListenerExample is
<HTML>
<HEAD>
</HEAD>
<BODY>
<CENTER>
<APPLET
CODE= KeyListenerExample.class
WIDTH=600
HEIGHT=250>
</APPLET>
</CENTER>
</BODY>
</HTML>
The output of the HTML code is
In this example, the KeyListenerExample class extends Applet class
and implements KeyListener interface. In the init() method, the applet registers
itself as a listener for key events. It should be noted that here the applet itself is the
source and listener for these events. This applet implements all the methods defined by
the KeyListener interface.
Check Your Progress
4. What does the
ActionEvent
class represent?
5. How does the
ItemEvent class
define a
constructor?
6. What do you
understand by
event sources?
Self-Instructional
Material 197
Event Handling
NOTES
11.5 SUMMARY
In this unit, you have learned that:
In Java, all the activities that occur between the user and the application are
termed as events.
An event is an object which specifies the change of state in the source.
An event gets generated, whenever an action takes place like a mouse button is
clicked or text is modified.
Java packages such as java.util, java.awt and java.awt.event support event handling
mechanism.
The working of an event-driven program is governed by its underlying event-
handling model.
The Java 1.0 Event model of Java for event processing was based on the concept
of containment.
The delegation event model defines a logical approach to handle events. It is
based on the concept of source and listener.
A source generates an event and sends it to one or more listeners that can handle
the event.
Java provides various classes and interfaces to handle the generated events.
Some of the event classes are ActionEvent, AdjustmentEvent
ComponentEvent, ContainerEvent, FocusEvent,
ItemEvent, KeyEvent, WindowEvent, etc.
Some of the event listener interfaces are ActionListener,
AdjustmentEventListener, ComponentListener,
ConatinerListener, FocusListener, ItemListener,
KeyListener, WindowListener, etc.
11.6 KEY TERMS
Event: It is an object, which specifies the change of state in the source
Event source: It is an object that generates a particular kind of event.
Event listener: It is an object, which receives notification when an event occurs.
Abstract window toolkit: It is a set of application program interfaces used by
Java programmers to create graphical user interface.
11.7 ANSWERS TO CHECK YOUR PROGRESS
1. The delegation event model uses event listeners and handleEvent() to
handle events.
2. An event is represented by an object, which specifies the change of state in the
source.
3. EventObject is the highest class in the delegation event model.
Self-Instructional
198 Material
Event Handling
NOTES
4. The ActionEvent class represents the event that is generated when a user
selects a menu item, presses button or double-clicks a list item.
5. The ItemEvent class defines the constructor in the following manner:
ItemEvent(ItemSelectable source, int event_type, Object
item, int item_state).
6. Event sources are the objects which generate events.
11.8 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What is the usage of an event?
2. What is the difference between event source and event listener?
3. List the various event handling classes in Java.
Long-Answer Questions
1. Discuss the models proposed for event handling in Java.
2. Describe about the delegation event model in detail.
3. Describe the interfaces that support the event handling in Java.
Self-Instructional
Material 199
Network Programming
NOTES
UNIT 12 NETWORK PROGRAMMING
Structure
12.0 Introduction
12.1 Unit Objectives
12.2 Networking Fundamentals
12.2.1 TCP/IP Protocols
12.2.2 Internet Addressing
12.2.3 Ports
12.2.4 Sockets
12.3 The Networking Classes and Interfaces
12.4 The InetAddress Class
12.5 TCP/IP Socket Programming
12.5.1 Creating a TCP Server
12.5.2 Creating a TCP Client
12.6 UDP Socket Programming
12.6.1 Creating a UDP Server Program
12.6.2 Creating a UDP Client Program
12.7 Summary
12.8 Key Terms
12.9 Answers to Check Your Progress
12.10 Questions and Exercises
12.0 INTRODUCTION
At the core of the network programming is the concept of a socket. A socket is one
endpoint of a two-way communication link between two programs running on the network.
Java supports creation of sockets and exchange information using different protocols
through the classes defined in java.net package. To use these classes, one must
know the fundamentals of networking like working of TCP/IP protocols, Internet
Addressing and ports. You will learn about all these topics in this unit before learning
network programming.
12.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Understand the networking fundamentals, such as TCP/IP Protocols, UDP, etc.
Describe the networking classes and interfaces
Understand the significance of InetAddress class
Explain TCP/IP socket programming and UDP socket programming
12.2 NETWORKING FUNDAMENTALS
The network systems comprise a server, client and communication media (See Figure
12.1). A machine running a process that sends request for the services is known as
client. On the other hand, a machine running a process that responds to the clients
request by offering requested services is known as server. A server can handle many
Self-Instructional
200 Material
Network Programming
NOTES
clients at the same time. To make the clients and the server communicate, a connecting
medium is required. The communication medium may be wired or wireless network.










Network
Client Machine
Server Machine
Request
Respons
Figure 12.1 ClientServer Communication
A network can be small (having two computers) or as vast as Internet.
Communication over network requires some reliable delivery services that can carry
information between two machines. The delivery services must work regardless of the
hardware and software used on the network. The Internet provides delivery services
using a suite of protocols known as TCP/IP named after its two primary protocols,
namely, Transport Control Protocol and Internet Protocol. The TCP/IP consists of
four layers, namely, Application, Transport, Network, and Link layer. All the layers
along with their corresponding protocols are shown in Figure 12.2.
(http, telnet, ftp, )
(IP, )
(Device Driver, )
(TCP, UDP, )

Application Layer

Transport Layer

Network Layer

Link Layer

Figure 12.2 TCP/IP Model
12.2.1 TCP/IP Protocols
The three most commonly used protocols within the TCP/IP suite are IP, TCP and UDP.
To develop network application, one must have a clear understanding of these protocols.
TCP (Transmission Control Protocol)
The TCP (Transmission Control Protocol) is a reliable and connection-oriented protocol
that allows the data that originates from source machine to be delivered without error to
the destination. TCP sets up a connection between the source machine and the destination
machine by transmitting control information before initiating the communication. This
mechanism is known as handshake. Once the connection is established, data transfer
between the two machines begins. TCP fragments the data into discrete messages
(known as TCP segments) and passes them to the internet layer. At the destination,
the receiving TCP sends an acknowledgement that guarantees that the data has been
received. It then reassembles the segments to form the original message. In case the
segments are lost or corrupted, TCP is responsible for retransmitting the necessary
segments. When all the data has been exchanged between these machines, it closes the
connection.
Self-Instructional
Material 201
Network Programming
NOTES
IP (Internet Protocol)
IP (Internet Protocol) is an unreliable and connectionless protocol that manages the
address part of each packet (the basic unit of IP transmissions) so that the packet
reaches the right destination. Being a connectionless protocol, IP does not transmit control
information before initiating communication between the source and the destination. It
sends data from the source to the destination expecting that the data will be delivered at
the receiving end properly. It is unreliable as it does not retransmit lost or corrupted
packets, that is, it does not guarantee the safe delivery of packets.
UDP (User Datagram Protocol)
Unlike TCP based applications, some network applications do not require a host-to-host
and reliable channel of communication. Instead they require a mode of communication
which transmits independent, self-contained messages whose time of arrival, order of
arrival, content, etc. are not guaranteed. This mode of network communication is governed
by the UDP protocol. The UDP (User Datagram protocol) is an unreliable and
connectionless protocol which enables application to send independent, selfcontained
messages known as datagrams over the network. It has no mechanism for detecting
errors or retransmitting lost or corrupted information. It is used in the applications that
require prompt delivery instead of accurate delivery such as weather forecasting, clock
server, video, games, audio, etc.
12.2.2 Internet Addressing
Every machine on the Internet is identified by a numerical address known as IP address.
An IP address consists of 32-bit number, organized as four 8-bit values. It is represented
in a format known as dotted-decimal notation. In this representation, each group of
bit is represented by its decimal equivalent which is between 0 and 255. For example,
1.160.10.240 could be an IP address. This address type was specified by IPv4 (Internet
Protocol, version 4).
Since this representation is not user friendly, IP address is mapped to domain
name like www.google.com which is easier to remember. Special servers on the Internet
perform this mapping called Domain Name Servers. It allows users to work with
domain names, however, Internet operates on the IP addresses.
Note: New addressing scheme (known as IPv6) uses 128-bit value to represent an address.
12.2.3 Ports
A machine provides a variety of services including electronic mail, Telnet, FTP, etc.
Using IP address, a client can connect to the machine but cannot connect to the desired
service. To resolve this, with each service, a port number is associated. A port is a
logical number assigned to a particular service through which the service is requested.
Clearly, to avail a service of server, a client machine does not just connect to the
server, it connects to a port on that server. Each packet that is sent over a network
contains the IP address of the host machine and the port number to identify the particular
application running on that host machine. An IP address can be considered as the house
address where a letter is sent via post and port number is the name of the person to
whom letter is to be delivered.
Note: The port numbers below 1024 are known as well-known ports and are reserved for standard
services. For example, the port number used for Telnet is 23.
Self-Instructional
202 Material
Network Programming
NOTES
12.2.4 Sockets
The combination of IP address and port number is known as socket. A socket identifies
an endpoint of a two-way communication link between two programs running on the
network. When a client requests for a connection on a particular port, the server identifies
and keeps track of the socket that it will use to communicate with that client. A server
can communicate on the same port with many clients using sockets to determine the
destination and source of the communication.
Socket-based Communication
In socket-based communication, the server (program) running on a computer binds a
socket to a specific port. The server listens to this socket for any clients connection
request as shown in Figure 12.3(a). When a request is made, the server accepts the
request. Once the request is accepted, the server binds a new socket to a different port
[see Figure 12.3(b)]. The new socket is required so that the server can continue to listen
to the original socket for new connection requests and at the same time keep serving the
connected clients.
(a) Client requests for a connection with server











(b) Server obtains a new local port
2003
listen for
connections
Server
2003
Client
connection
request
2003
new local port
Server
2003
Client
Tells client to use
new local port
1099
Figure 12.3 Establishment of Path for Two-Way Communication
12.3 THE NETWORKING CLASSES AND
INTERFACES
Java facilitates creation of network applications through the classes and interfaces defined
in the java.net package. Some of the classes defined in this package are listed in
Table 12.1.
Check Your Progress
1. The Internet
provides delivery
services using a
suite of protocols
known as ______.
2. UDP (User
Datagram
protocol) is a
reliable and
connectionless
protocol which
enables application
to send
independent, self
contained messages
known as
datagrams. (True
or False)
3. Which of these
protocols
implements the
network layer?
(a) TCP (b) IP
(c) UDP
(d) Both (a) and (c)
4. The port numbers
below _____ are
known as _____
ports and are
reserved for
standard services.
5. How many bits
does IPv6 use to
represent an
address?
6. The combination
of IP address and
port number is
known
as_________.
Self-Instructional
Material 203
Network Programming
NOTES
Table 12.1 Some of the Classes of the java.net Package
Class Description
Authenticator represents an object that obtains authentication for a
network connection
ContentHandler an abstract classsuperclass of all the classes that
contains methods to read an object from a
URLConnection
DatagramPacket contains methods to implement a connectionless
packet delivery service
DatagramSocket represents a socket for sending and receiving
datagram packets
DatagramSocketImpl an abstract datagram and multicast socket
implementation superclass
HttpURLConnection
represents a URLConnection having support for
HTTP-specific features
InetAddress represents an IP address
ServerSocket implements server sockets
Socket implements client sockets
SocketImpl an abstract classsuperclass of all classes that
implements sockets
URL represents a Uniform Resource Locator, a pointer to a
resource on the WWW
URLConnection an abstract classsuperclass of all classes that
represent a communication link between the
application and a URL
URLStreamHandler an abstract classsuperclass of all stream protocol
handlers
Some of the interfaces defined in java.net package are listed in Table 12.2.
Table 12.2 Interfaces of java.net Package

Interface Description
ContentHandlerFactory defines factory for content handlers
CookiePolicy provides a mechanism to decide which
cookie should be accepted and which
should be rejected
CookieStore represents a storage for cookie
DatagramSocketImplFactory defines factory for the implementation of
datagram socket
FileNameMap provides a mechanism to map between a
file name and a MIME type string
SocketImplFactory defines factory for the implementation of
socket
SocketOptions defines methods to get or set socket
options
URLStreamHandlerFactory defines factory for URL stream protocol
handlers
Note: Factory methods are simply a convention by which the static methods in a class return an instance
of that class.
12.4 THE InetAddress CLASS
As stated earlier, users use the domain names, whereas, Internet operates on IP addresses.
In Java, the domain names can be resolved to their IP addresses and vice versa by using
the InetAddress class.
Self-Instructional
204 Material
Network Programming
NOTES
An InetAddress object can be created using one of the available factory methods.
Commonly used factory methods of InetAddress class are listed in Table 12.3.
Table 12.3 Methods of the InetAddress Class
Method Description
static InetAddress
getLocalHost()

returns the InetAddress object that
represents the local host
static InetAddress
getByName(String
hostname)
returns an InetAddress for a host
name passed to it
static InetAddress[]
getAllByName(String
hostname)
returns an array of InetAddress
that represents all of the addresses
resolved for a host name passed to it;
used in case a single name represents
several machines
All these methods throw an UnknownHostException. The methods
getLocalHost()and getByName(String hostname)throw this exception
if they are unable to resolve the host name. The method getAllByName() throws
this exception if it is unable to resolve the name to even a single address.
12.5 TCP/IP SOCKET PROGRAMMING
In Java, there are two types of TCP sockets; one is for servers and other is for clients.
These two sockets are implemented using two different classes of java.net package,
namely, ServerSocket class and Socket class.
The ServerSocket class is used to listen for incoming connections, that is, to
wait for clients to connect. The constructors defined in class ServerSocket are
listed in Table 12.4.
Table 12.4 Constructors of the ServerSocket Class
Constructor Description
ServerSocket() creates an unbound server socket
ServerSocket(int
portnumber)
creates a server socket and binds it to the
port number specified by portnumber
ServerSocket(int
portnumber, int
qlength)
creates a server socket, binds it to the
specified port number and creates a queue
of length specified by qlength for that
port. The queue length specifies the
number of client requests that can be kept
in the waiting list.
ServerSocket(int
portnumber, int
qlength, InetAddress
address)
creates a server socket, binds it to the
specified port number, creates a queue of
length specified by qlength and binds it
to the IP address specified by address.
The Socket class is used by the client to connect to the server sockets and
exchange data using input and output streams. When a Socket object is created, a
connection is established implicitly between the client and the server. Some of the
constructors defined in this class are listed in Table 12.5.
Self-Instructional
Material 205
Network Programming
NOTES
Table 12.5 Some of the Constructors of the Socket Class

Constructor Description
Socket() creates an unconnected socket
Socket(InetAddress
address, int
portnumber)
creates a socket and connects it to the
specified port number at the specified IP
address
Socket(String host,
int portnumber)
creates a socket and connects it to the
specified port number on the named host
The Socket class defines various methods; two of which are
getInputStream() and getOutputStream(). These methods return the
InputStream and OutputStream object respectively associated with a socket.
These streams are used in the same way as I/O streams to receive and send the data.
12.5.1 Creating a TCP Server
The following steps are involved in creating a server program:
1. Open the server socket: To open a socket, one of the constructors of class
ServerSocket given in Table 12.4 can be used.
2. Wait for the client request: The server socket waits until a connection request
is made by some client and then returns an actual Socket object representing
that connection. It is accomplished by the accept() method of the
ServerSocket class. The accept() method is a blocking call that waits
until a client tries to connect to it. When a connection is made, it returns the
Socket object.
3. Create I/O streams for communicating to the client: Once a dedicated
connection is established between client and server, obtain the InputStream
and OutputStream object associated with a socket using
getInputStream() and getOutputStream() methods respectively.
4. Communicate with the client: Data can be read from or written to the client
using the objects declared for input and output stream respectively.
5. Close the socket: Finally, the socket must be closed. To close the socket on the
server side, the close() method is used. Note that before closing the socket,
the input and output stream must be closed.
Example 12.1: A program to demonstrate a server program
import java.net.*;
import java.io.*;
public class ServerExample
{
public static void main(String args[])
{
int port = 2316;
try
{
//creates a socket on port 2316
ServerSocket ss = new ServerSocket(port);
//waits and accepts a connection
Self-Instructional
206 Material
Network Programming
NOTES
Socket socket = ss.accept();
//associates stream with the socket
OutputStream sout = socket.getOutputStream();
DataOutputStream out = new DataOutputStream(sout);
//sends output to the standard output device
System.out.println(Hello! this is your socket
programming );
// sends a string to the client
out.writeUTF(Server is Ready!);
//sends output to the standard output device
System.out.println(Waiting for the next
line...);
//Closes the connection except server socket
out.close();
sout.close();
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
12.5.2 Creating a TCP Client
The steps involved in creating a client program are:
1. Create a Socket object
2. Create I/O streams for communicating with the server
3. Communicate with the server
4. Close the socket when the communication ends
Example 12.2: A program to demonstrate a client program
import java.net.*;
import java.io.*;
public class ClientExample
{
public static void main(String args[])
{
int port = 2316;
try
{
//obtains the IP address for the localhost
InetAddress ipAddress =
Self-Instructional
Material 207
Network Programming
NOTES
InetAddress.getByName(localhost);
System.out.println(Address and the port no is:
+ ipAddress + and port + port + ?);
// opens connection to the server at port no 2316
Socket socket = new Socket(ipAddress, port);
System.out.println(I am the Client.);
// obtains an input file handle from the socket /
/and read the input
InputStream sin = socket.getInputStream();
DataInputStream in = new
DataInputStream(sin);
String pstr = new String(in.readUTF());
System.out.println(pstr);
// closes the connection
sin.close();
in.close();
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Note that in this program, at the time of creation of Socket, both the IP address
and port number where the client is trying to connect are provided.
12.6 UDP SOCKET PROGRAMMING
Java supports UDP by providing two classes, namely, DatagramPacket and
DatagramSocket.
DatagramSocket
The DatagramSocket class is used to send or receive the datagram packets. It
defines four constructors that are listed in Table 12.6.
Table 12.6 Constructors Defined in DatagramSocket Class
Constructor Description
DatagramSocket() creates a datagram socket
DatagramSocket(int
portnumber)
creates a datagram socket and binds it to
the port number specified by
portnumber
DatagramSocket(int
portnumber, InetAddress
ipAddress)
creates a datagram socket and binds it to
the port and the InetAddress specified
by portnumber and the ipAddress
respectively
DatagramSocket(SocketA
ddress address)
creates a datagram socket and binds it to
the SocketAddress specified by the
address
Self-Instructional
208 Material
Network Programming
NOTES
Note: While creating the datagram socket, if any error occurs, all these constructors throw a
SocketException.
The class DatagramSocket defines many methods. Two important methods
are listed in Table 12.7.
Table 12.7 Methods of the DatagramSocket Class
Method Description
void send(DatagramPacket
packet)
sends packet to the port
void receive(DatagramPacket
packet)
receives packet specified by
packet from the port
Note: Both the methods send() and receive() throw a IOException when an error occurs.
DatagramPacket
The DatagramPacket class is used to contain the data. It defines many constructors;
some of them are listed in Table 12.8.
Table 12.8 Constructors Defined in DatagramPacket Class

Constructor Description
DatagramPacket(byte
data[], int length)
creates a DatagramPacket for
receiving the packets of length length in
the buffer
DatagramPacket( byte
data[],int offset, int
length )
creates a DatagramPacket for
receiving the packets of length length,
specifying an offset into the buffer
DatagramPacket( byte
data[], int offset, int
length , InetAddress
ipAddress, int
portnumber)

creates a DatagramPacket for sending
packets of length length to the specified
port number on the specified host
Some of the commonly used methods defined in DatagramPacket class are
listed in Table 12.9.
Table 12.9 Methods of the DatagramPacket Class


Method Description
InetAddress getAddress() returns the address of the machine to
which the datagram is sent or from which
the datagram is received
byte[] getData() returns the data contained in the datagram
int getLength() returns the length of the valid data
contained in the byte array that is returned
from the getData() method
int getPort() returns the port number on the remote host
VoidsetAddress(InetAddress
ipAddress)
sets the address specified by ipAddress
to which a packet is to be sent
void setData(byte[] data)
sets the data to data
void setLength(int length)
sets the size of the packet to length
void setPort(int
portnumber)
sets the port number specified by
portnumber on the remote host
Self-Instructional
Material 209
Network Programming
NOTES
12.6.1 Creating a UDP Server Program
The following steps are involved in creating a UDP server program.
1. Open the Datagram Socket: To open a Datagram socket, one of the constructors
of class DatagramSocket can b used.
2. Obtain the IP address for the local host: To obtain the IP address for local
host, the statement InetAddress ipadd=InetAddress
.getLocalHost() is used.
3. Create the data input/output stream for communication with the client: A
string of data is created, then that string is converted in to datagram packets.
4. Perform communication with the client: Data can be read from or written to
the client using datagram packets.
5. Close the Datagram socket: Finally, the socket must be closed. To close the
socket on the server side, the close() method is used. Note that before closing
the socket, the input and output stream must be closed.
Example 12.3: A program to demonstrate a UDP server program
import java.net.*;
import java.io.*;
import java.util.*;
class UDPServerExample
{
public static void main(String args[]) throws Exception
{
int serverportno = 1139;
int clientportno = 1140;
try
{
//creates a socket and binds to port no 1139
DatagramSocket ds = new
DatagramSocket(serverportno);
//obtains the IP address for the localhost
InetAddress ipadd=InetAddress.getLocalHost();
String pstr = Hello this is your message;
byte buf[]=pstr.getBytes();
// creates a DatagramPacket for sending the packets
DatagramPacket send_packet = new
DatagramPacket(buf,buf.length,ipadd,clientportno);
ds.send(send_packet); //sends packets
ds.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
Self-Instructional
210 Material
Network Programming
NOTES
}
}
}
12.6.2 Creating a UDP Client Program
The steps involved in creating a UDP client program are as follows:
1. Create the Datagram Socket for communicating with server.
2. Create the data input/output stream for the communication with the server.
3. Communicate with the server.
4. Close the Datagram socket.
Example 12.4: A program to demonstrate a UDP client program
import java.net.*;
import java.io.*;
class UDPClientExample
{
public static void main(String args[]) throws Exception
{
int serverportno = 1139;
int clientportno = 1140;
try
{
//creates a socket and binds to port no 1140
DatagramSocket ds = new DatagramSocket(clientportno);
byte b[]=new byte[1024];
//creates a DatagramPacket for receiving the packets
DatagramPacket dp = new DatagramPacket(b,b.length);
ds.receive(dp); //receives packets
System.out.println(new String(dp.getData()));
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Note that both the server and client programs are running between two ports on
the local machine. The server and clients are running on port numbers, 1139 and 1140
respectively. So, run these programs on different command prompt windows.
Check Your Progress
7. For which purpose
is the InetAddress
class used?
8. TCP server and
client sockets are
implemented using
classes ____ and
____, respectively.
9. The
DatagramSocket
class is used to
send or receive the
datagram packets.
(True or False)
10. If any error occurs
while creating the
datagram socket,
which type of
exception is
thrown?
Self-Instructional
Material 211
Network Programming
NOTES
12.7 SUMMARY
In this unit, you have learned that:
The network systems comprise a server, client and communication media.
A network can be small (having two computers) or as vast as Internet.
Communication over network requires some reliable delivery services that can
carry information between two machines.
The delivery services must work regardless of the hardware and software used
on the network. The Internet provides delivery services using a suite of protocols
known as TCP/IP
The three most commonly used protocols within the TCP/IP suite are IP, TCP
and UDP
The TCP (Transmission Control Protocol) is a reliable and connection-oriented
protocol that allows the data that originates from source machine to be delivered
without error to the destination.
IP (Internet Protocol) is an unreliable and connectionless protocol that manages
the address part of each packet (the basic unit of IP transmissions) so that the
packet reaches the right destination.
The UDP (User Datagram Protocol) is an unreliable and connectionless protocol
which enables application to send independent, selfcontained messages known
as datagrams over the network.
Every machine on the Internet is identified by a numerical address known as IP
address. An IP address consists of 32-bit number, organized as four 8-bit values.
It is represented in a format known as dotted-decimal notation.
A port is a logical number assigned to a particular service through which the
service is requested.
The combination of IP address and port number is known as socket. A socket
identifies an endpoint of a two-way communication link between two programs
running on the network.
Java facilitates creation of network applications through the classes and interfaces
defined in the java.net package.
The domain names can be resolved to their IP addresses and vice versa by using
the InetAddress class.
In Java, there are two types of TCP sockets; one is for servers and other is for
clients. These two sockets are implemented using two different classes of
java.net package, namely, ServerSocket class and Socket class.
The ServerSocket class is used to listen for incoming connections, that is, to
wait for clients to connect.
The Socket class is used by the client to connect to the server sockets and
exchange data using input and output streams.
Java supports UDP by providing two classes, namely, DatagramPacket and
DatagramSocket.
Self-Instructional
212 Material
Network Programming
NOTES
12.8 KEY TERMS
Server: It refers to a machine running a process that responds to the clients
request by offering requested services.
TCP protocol: It is a reliable and connection-oriented protocol that allows the
data that originates from source machine to be delivered without error to the
destination.
IP address: It refers to the numerical address that identifies every machine on
the Internet.
Port: It is a logical number assigned to a particular service through which the
service is requested.
Socket: It is the combination of IP address and port number.
12.9 ANSWERS TO CHECK YOUR PROGRESS
1. TCP/IP
2. False
3. (b)
4. 1024, well-known
5. IPv6 uses 128-bit value to represent an address.
6. Socket
7. The InetAddress class is used to resolve the domain names to their IP
addresses and vice versa.
8. ServerSocket, Socket
9. True
10. If any error occurs while creating the datagram socket, SocketException is
thrown.
12.10 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What is the name of the IP address format?
2. State one function of socket.
3. What are the steps involved in creating a TCP client program?
4. Define User Datagram Protocol.
Long-Answer Questions
1. Explain the various interfaces defined in java.net package.
2. Discuss the role of IP (Internet Protocol) in the TCP/IP model.
3. Explain the constructors of the ServerSocket class.
4. Illustrate the steps involved in creating TCP Server/Client programs using socket.
Self-Instructional
Material 213
Java and Database
NOTES
UNIT 13 JAVA AND DATABASE
Structure
13.0 Introduction
13.1 Unit Objectives
13.2 Architecture of JDBC
13.3 JDBCODBC Bridge
13.4 The java.sql Package
13.4.1 The DriverManager Class
13.4.2 The Connection Interface
13.4.3 The Statement Interface
13.4.4 The ResultSet Interface
13.4.5 The PreparedStatement Interface
13.4.6 The ResultSetMetaData Interface
13.4.7 The SQLException Class
13.5 Summary
13.6 Key Terms
13.7 Answers to Check Your Progress
13.8 Questions and Exercises
13.0 INTRODUCTION
Accessing a database in Java requires Java Database Connectivity (JDBC). JDBC
provides a standard API that is used to access databases, through Java, regardless of
the DBMS. All the direct interactions with specific DBMSs are accomplished by DBMS
specific driver. It acts as wrapper that sends SQL requests to the server.
In this unit, you will learn how to deal with database in Java.
13.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Explain the architecture of JDBC
Explain JDBC ODBC bridge
Understand the classes and interfaces of java.sql
Discuss the SQLException class
13.2 ARCHITECTURE OF JDBC
The architecture of JDBC has four components, namely application, driver manager,
data source specific drivers and corresponding data sources.
An application establishes and terminates the connection with a data source. The
main goal of driver manager is to load JDBC drivers and pass JDBC function calls from
the application to the corresponding driver. The driver establishes the connection with
data source. The driver performs various basic functions like submitting requests and
returning results. In addition, the driver translates data, error formats and error codes
Self-Instructional
214 Material
Java and Database
NOTES
from a form that is specific to data source into the JDBC standard. The data source
processes commands from the driver and returns the results.
JDBC Drivers can be classified into four categories as follows:
JDBC-ODBC (open data base connectivity)-Bridge Driver: This type of
driver is used to access data through drivers using ODBC standard.
Native API partly-Java Driver: This driver is specific to every database and
converts the JDBC calls to database specific calls. For example, Oracle database
will have its own oracle native API, and Sybase will have its own native API.
Net protocol all-Java client Driver: This driver is server based driver that
uses network protocol and middleware for communicating with the server which
in turn translates it to the DBMS specific function calls.
Native protocol all-Java Driver: This driver is entirely written in Java, which
directly communicates with the database server without including any translation
steps.
13.3 JDBCODBC BRIDGE
Microsofts ODBC , short for open database connectivity is the most commonly used
driver to connect to the database as it can connect to almost all databases on most of the
platforms. However, ODBC uses the concept of pointers and other constructs that are
not supported by Java. Therefore, JDBCODBC bridge driver was developed which
translates the JDBC API to the ODBC API and vice versa. This bridge acts as interface
that enables all DBMS which support ODBC (Open Data Base Connectivity) to interact
with Java Applications. JDBC-ODBC bridge is implemented as a class file and a native
library. The name of the class file is JdbcOdbc.class. On windows platform, native
library called JDBCODBC.DLL is used.
Figure 13.1 shows the JDBC application architecture in which a front-end
application uses JDBC API for interacting with JDBC Driver Manager. Here, JDBC
Driver Manager is the backbone of JDBC architecture. It acts as interface that connects
a Java application to the driver specified in the Java program. Next, is the JDBC-ODBC
bridge which helps the JDBC to access ODBC data sources.

Java Application
JDBC API
JDBC Driver
JDBC-ODBC Bridge
Driver
ODBC Driver
Access
Driver
SQL
Driver
MS
Access
Database
MS SQL
Database
Figure 13.1 JDBC Architecture with JDBCODBC Bridge
Self-Instructional
Material 215
Java and Database
NOTES
13.4 THE java.sql PACKAGE
To work with the database, Java provides java.sql package. It contains various
classes and interfaces that can be used for establishing connection with database and
retrieve data from it. This section discusses one of the important class DriverManager
and some of the important interfaces included in this package.
13.4.1 The DriverManager Class
The DriverManager class is responsible for loading the driver specific classes. The
drivers are registered with the DriverManager class either when an instance of
driver is created using registerDriver(Driver driver) method of the
DriverManager class or DriverManager class is initialized.
The static method forName() of the Class class can be used by
DriverManager class to locate and load the drivers listed in system variable
jdbc.drivers is as follows:
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver)
Here, the driver class specified in the string parameter is loaded dynamically at
the run time.
Some of the methods of the DriverManager are as follows:
Connection getConnection(String url): This method attempts
to establish a connection to a given database URLdoes not require password.
Connection getConnection(String url, String user,
String password): This method attempts to establish a connection to a
given database URL.
void registerDriver(Driver driver): This method is used to
register a driver specified by driver with the DriverManager.
void deregisterDriver(Driver driver): This method removes
the driver specified by driver from the DriverManagers list.
13.4.2 The Connection Interface
The Connection interface helps to establish a connection with the required database.
Other than establishing connection, it provides lot of functionality including transaction
management, maintaining database sessions and creating SQL statements.
Some of the commonly used methods of connection interface are as follows:
void close(): This method closes database connection associated with
Connections object and releases JDBC resources.
Statement createStatement(): This method creates a Statement
object which is used to send SQL statement to the database. It is usually used
when SQL statement without parameters is to be executed.
CallableStatement prepareCall(String sql): This method
creates an instance of CallableStatement which is used to handle database
stored procedures.
Self-Instructional
216 Material
Java and Database
NOTES
PreparedStatement prepareStatement(String sql): This
method creates PreparedStatement object which is used to create SQL
statement specified in string sql. It is usually used when parameterized SQL
statement is to be executed.
13.4.3 The Statement Interface
The statement interface provides methods that are used to execute static SQL
statements. The SQL statements are queries, insertions, updates and deletions etc.
Some of the methods of the Statement interface are as follows:
void close(): This method closes database connections associated with
Statements object and releases JDBC resources.
boolean execute(String sql): This method is used to execute an
SQL statement that might produce multiple result sets or multiple counts. It returns
true if multiple result sets are produced and returns false if multiple counts
are generated.
int executeUpdate(String sql): This method is used to execute an
SQL statement that gives information about number of affected rows. For example,
if we execute the statements like INSERT, DELETE, the result will only be a
number of rows affected.
ResultSet executeQuery(String sql): This method executes a
query and returns a ResultSet object. A result set is just like a table containing
the resultant data.
ResultSet getResultSet(): This method returns the first result set or
multiple count generated on the execution of execute(String sql) method.
If there is no result set, it returns null value.
int getUpdateCount(): After the execution of the execute(String
sql) method updates counts may be generated. This method returns the first
update count and clears it. More update counts can be retrieved by
getMoreResults(). Note that this method returns value -1 if there is no
update count or when only result sets are generated on execution of
execute(String sql) method.
boolean getMoreResults(): This method is used to retrieve the next
result set in multiple result set or to the next count in multiple update count generated
on execution of execute(String sql)method. It returns a true value if
multiple sets are available and returns a false value if multiple update counts
are available.
13.4.4 The ResultSet Interface
The execution of SQL statement results in table which consists of rows and columns
containing the resultant data. The data can be retrieved from the table by using methods
of the ResultSet interface. Some methods of the ResultSet interface are as
follows:
boolean next(): This method is used to move the ResultSet cursor to
the next row of the data. Initially, the ResultSet cursor is pointed before the
first row. It returns the false value if there are no more rows in the ResultSet
object.
Self-Instructional
Material 217
Java and Database
NOTES
String getString(int index): This method returns the string value
that is stored in the column indicated by the column number, index. For example,
if the value of index is 2 then it will return the value stored in second column
number.
String getString(String column): This method returns the string
value that is stored in the column indicated by the column name column.
Example 13.1: A program to establish connection and retrieve data from Student
database
import java.sql.*;
public class SimpleJDBCProgram
{
public static void main(String args[])
{
try
{
//loading the driver class
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
//defines the datasource for the driver
String url = jdbc:odbc:ITLESL;
//creating the connection through DriverManager
Connection con = DriverManager.getConnection (url, login,
password);
//creating the statement object
Statement st = con.createStatement();
//executing the query through Resultset object
ResultSet rs = st.executeQuery(Select Roll, Marks, Grade
FROM Student);
//output the resultset data
while (rs.next())
{
//retrieve columns
int roll = rs.getInt(Roll);
int marks = rs.getInt(Marks);
String grade = rs.getString(Grade);
//display values
System.out.println(Roll No :+ roll);
System.out.println(Marks :+ marks);
System.out.println(Grade :+ grade);
Self-Instructional
218 Material
Java and Database
NOTES
}
//cleaning up the environment
rs.close();
st.close();
con.close();
}
catch(Exception e)
{
System.out.println(Error +e);
}
}
}
In this program, following steps are followed to access the data from the database.
1. Appropriate drivers for the database are loaded by using Class.forName().
2. The getConnection() method of DriverManager class of JDBC is
used to create the Connection object. An application may have more than
one connection objects to connect with one or more databases.
3. The first parameter URL(jdbc:odbc:ITLESL) identifies the database.
This URL has three parts: protocol, subprotocol and DSN name. To connect to
the database username and password are also required which are specified by
the other two parameters of getConnection()method, login and
password.
4. The statement Statement st = con.createStatement()is used to
create Statement object, st for querying the database. It is created by calling
the createStatement() method using the Connection object, con.
5. In this example, st.executeQuery is used to execute the SELECT
statement of SQL. The try{..} catch {..} is used to catch any exceptions
that may arise as a result of executing this query statement. The result of this
query may consist of set of tuples, which is assigned to rs object of type
ResultSet. Initially, it places the cursor at the beginning of the first tuple. The
statement rs.next() moves the cursor to the next tuple
6. The next() method is used to fetch one tuple at a time from the result set rs.
The statement int roll = rs.getInt(Roll); is used to access
data from the database and System.out.println(Roll No :+
roll); is used to display data.
7. The connection must be closed after it is no more required at the end of the
procedure. The statement rs.close(), st.close(), con.close()
closes all the open connections.
Example 13.2: A program to establish connection and retrieve data from Employee
database
import java.io.*;
import java.sql.*;
Self-Instructional
Material 219
Java and Database
NOTES
public class ExampleSelectStatement
{
public static void main(String args[])
{
Connection con=null;
try
{
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
//loads driver
con=DriverManager.getConnection(jdbc:odbc:
Emp);
// establishes connection
Statement st = con.createStatement();
//creates Statement object
ResultSet rs = st.executeQuery(select * from
Employee);
// creates ResultSet object
System.out.println(
Employee Details);
System.out.println(\n);
System.out.print(Eno );
System.out.print(Name );
System.out.print(Department );
System.out.print(Designation );
System.out.println(Salary );
System.out.println(
);
// displays data till there are no more //
rows
while(rs.next())
{
System.out.print(rs.getString(ENumber));
System.out.print( );
System.out.print(rs.getString(EName));
System.out.print( );
System.out.print(rs.getString(
Department));
System.out.print( );
System.out.print(rs.getString(
Designation));
System.out.print( );
System.out.println(rs.getString(Salary));
Self-Instructional
220 Material
Java and Database
NOTES
}
// closes the connection
rs.close();
st.close();
con.close();
System.in.read();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
The output of the program is
Employee Details
Eno Name Department Designation Salary

1 Prem IT PL 30000
2 Samee IT SSE 29500
3 Preeti IT TL 29500
4 Mili IT SE 28000
5 Niti Math TL 28000
6 Surabhi IT SE 25000
7 Milendu IT SE 25000
13.4.5 The PreparedStatement Interface
PreparedStatement interface extends the Statement interface so it has access
to all the methods of Statement interface. It is used to execute precompiled
parameterized SQL statements. This helps statements to execute much faster thus
increases the efficiency of the program. It allows you to specify SQL query, in which
unknown values are replaced by ?. The user provides the unknown values later at the
run-time. The setString() and setInt() methods can be used to specify the
values for the parameters. To understand the concept of prepared statement, consider
the following statements.
PreparedStatement ps = con.prepareStatement(INSERT INTO
Student
VALUES(?,?,?));
ps.setString(1, A010);//assigns value to first attribute
ps.setInt(2, 90); //assigns value to second attribute
ps.setString(3, A); //assigns value to third attribute
ps.executeUpdate();
The values can be assigned to the corresponding attributes through variable name
also instead of using literal values representing index value. Like, setString() and
Self-Instructional
Material 221
Java and Database
NOTES
setInt() methods, there are various methods for setting value of other data type.
Some of these are setBoolean(), setFloat(), setByte(), setDate(),
etc. The method void clearParameters() can be used to clear all the values
held currently in the parameters.
Note: The methods execute(), executeQuery() and executeUpdate() have same functionality
as the methods of Statement interface, but with a difference that here no parameters are passed.
Example 13.3: A program to demonstrate implementation of PreparedStatement
interface
import java.io.*;
import java.sql.*;
public class ExamplePreparedStatement
{
public static void main(String args[])
{
Connection con=null;
int i = 0;
try
{
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
con=DriverManager.getConnection(jdbc:odbc:Emp);
Statement st = con.createStatement();
PreparedStatement ps =
con.prepareStatement(INSERT INTO Employee
VALUES(?,?,?,?,?));
ps.setInt(1,8);
ps.setString(2,Meenu);
ps.setString(3,IT);
ps.setString(4,SE);
ps.setInt(5,30000);
i = ps.executeUpdate();
System.out.println(Number of rows effected:
+i);
ResultSet rs = st.executeQuery(select * from
Employee);
System.out.print(Eno );
System.out.print(Name );
System.out.print(Depatment );
System.out.print(Designation );
System.out.println(Salary );
System.out.println(
);
while(rs.next())
Self-Instructional
222 Material
Java and Database
NOTES
{
System.out.print(rs.getString(ENumber));
System.out.print( );
System.out.print(rs.getString(EName));
System.out.print( );
System.out.print(rs.getString(
Department));
System.out.print( );
System.out.print(rs.getString(
Designation));
System.out.print( );
System.out.println(rs.getString(Salary));
}
rs.close();
System.in.read();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
The output of the program is
Number of rows effected: 1
Employee Details
Eno Name Department Designation Salary

1 Prem IT PL 30000
2 Samee IT SSE 29500
3 Preeti IT TL 29500
4 Mili IT SE 28000
5 Niti Math TL 28000
6 Surabhi IT SE 25000
7 Milendu IT SE 25000
8 Meenu IT SE 30000
13.4.6 The ResultSetMetaData Interface
The ResultSetMetaData interface provides methods that allow you to get metadata
for the resultset, that is, the number, types and properties of the columns in a ResultSet
object. This information is used to collect the data with same semantics but stored in
different databases in different formats.
Self-Instructional
Material 223
Java and Database
NOTES
To get this information of columns in the ResultSet object using methods of
the ResultSetMetaData interface, it is required to invoke the getMetaData()
method of the ResultSet object that returns a reference to an object of type
ResultSetMetaData.
Some of the methods of ResultSetMetaData interface are as follows:
int getColumnCount():This method returns the number of columns in
the resultset.
String getColumnName(int index):This method returns the name
of column specified by index value index in the resultset.
int getColumnType(int index):This method returns the type of
column specified by index value index in the resultset.
Example 13.4: A program to demonstrate implementation of ResultSetMetaData
and ResultSet interface
import java.sql.*;
class ExampleResultSetMetaData
{
public static void main(String args[])
{
Connection con;
Statement stmt;
ResultSet rs;
try
{
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
con = DriverManager.getConnection(jdbc:odbc:
Emp);
stmt = con.createStatement();
rs = stmt.executeQuery(Select * from Employee WHERE
Department=Math);
ResultSetMetaData rsmd = rs.getMetaData();
int col = rsmd.getColumnCount();
//returns number of columns
int row = 1;
while (rs.next())
{
System.out.println(Row + row + : );
for (int i = 1; i <= col; i++)
{
System.out.print( Column + i + : );
System.out.println(rs.getString(i));
}
System.out.println( );
row++;
Self-Instructional
224 Material
Java and Database
NOTES
}
stmt.close();
con.close();
}
catch(Exception e)
{
System.err.print(ClassNotFoundException: );
System.err.println(e.getMessage());
}
}
}
The output of the program is
Row 1:
Column 1: 5
Column 2: Niti
Column 3: Math
Column 4: TL
Column 5: 28000
13.4.7 The SQLException class
While accessing the database, the developer may encounter various types of errors. If
any JDBC object encounters an error, it throws the SQLException. The
SQLException class extends the java.lang.Exception class. Some of the
methods of the SQLException class are as follows:
SQLException getNextException(): This method is used to obtain
the next exception object in the chain of errors (if any exists).
String getSQLState(): This method provides the information about the
state of SQL, which helps in taking appropriate decisions.
int getErrorCode(): This method provides information about the vendor
specific errors whose meaning is defined by the driver vendor only.
Example 13.5: A program to demonstrate how exceptions related to JDBC are handled
import java.io.*;
import java.sql.*;
public class FinalExceptionExample
{
public static void main(String args[])
{
Connection con=null;
try
{
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
Self-Instructional
Material 225
Java and Database
NOTES
con=DriverManager.getConnection(jdbc:odbc:
Emp);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(select * from
EmployeeDB);
System.out.print(Employee Number );
System.out.print(Employee Name );
System.out.print(Department );
System.out.print(Designation );
System.out.println(Salary );
System.out.println(
);
while(rs.next())
{
System.out.print(rs.getString(ENumber));
System.out.print( );
System.out.print(rs.getString(EName));
System.out.print( );
System.out.print(rs.getString(
Department));
System.out.print( );
System.out.print(rs.getString(
Designation));
System.out.print( );
System.out.println(rs.getString(Salary));
}
rs.close();
}
catch(SQLException e)
{
while(e != null)
{
System.out.println(\nSQL Exception:);
System.out.println(e.getMessage());
System.out.println(SQL State: +
e.getSQLState());
System.out.println(Error Code: +
e.getErrorCode());
Self-Instructional
226 Material
Java and Database
NOTES
e = e.getNextException();
}
}
catch(ClassNotFoundException cnfe)
{
System.out.println(cnfe.getMessage());
}
}
}
The output of the program is
SQL Exception:
[Microsoft][SQL Server Native Client 10.0][SQL Server]Invalid
object name EmployeeDB.
SQL State: S0002
Error Code: 208
Note that if Class.forName() syntax is used for registering the driver, you
may encounter the ClassNotFoundException. This type of exception is
encountered if the class loader is unable to find the specified database driver.
13.5 SUMMARY
In this unit, you have learned that:
JDBC provides a standard API that is used to access databases, through Java,
regardless of the DBMS. All the direct interactions with specific DBMSs are
accomplished by DBMS specific driver.
The architecture of JDBC has four components, which are, application, driver
manager, data source specific drivers and corresponding data sources.
JDBC-ODBC acts as interface that enables all DBMS which support ODBC
(Open Data Base Connectivity) to interact with Java Applications.
To work with the database, Java provides java.sql package. It contains various
classes and interfaces that can be used for establishing connection with database
and retrieve data from it.
The DriverManager class is responsible for loading the driver specific classes.
The Connection interface helps to establish a connection with the required
database. Other than establishing connection, it provides lot of functionality including
transaction management, maintaining database sessions and creating SQL
statements.
The statement interface provides methods that are used to execute static
SQL statements. The SQL statements are queries, insertions, updates and deletions
etc.
The execution of SQL statement results in table which consists of rows and
columns containing the resultant data. The data can be retrieved from the table
by using methods of the ResultSet interface.
Check Your Progress
1. List the
components of
architecture of
JDBC.
2. List the different
categories of JDBC
drivers.
3. _________ driver
is used to access
data through
drivers using
ODBC standard.
4. The Driver class
is responsible for
loading the driver
specific classes.
(True or False)
5. _____allows you
to specify SQL
query, in which
unknown values
are replaced by ?.
6. ______method
provides
information about
the vendor specific
errors whose
meaning is defined
by the driver
vendor only.
7. What is SQL
Exception
class?
8. List the methods
available in SQL-
Exception class.
Self-Instructional
Material 227
Java and Database
NOTES
PreparedStatement interface extends the Statement interface so it has
access to all the methods of Statement interface. It is used to execute
precompiled parameterised SQL statements. Using this, the statements execute
much faster thus increases the efficiency of the program.
The ResultSetMetaData interface provides methods that allow you to get
metadata for the resultset, that is, the number, types and properties of the columns
in a ResultSet object.
While accessing the database, the developer may encounter various types of
errors. If any JDBC object encounters an error, it throws the SQLException.
13.6 KEY TERMS
Open database connectivity (ODBC): It is the most commonly used driver to
connect to the database as it can connect to almost all databases on most of the
platforms.
Connection interface: It is an interface that helps to establish a connection
with the required database.
boolean next(): It is a method that is used to move the ResultSet
cursor to the next row of the data.
ResultSetMetaData interface: It is an interface that provides methods
allowing to get metadata for the resultset, that is, the number, types and properties
of the columns in a ResultSet object.
13.7 ANSWERS TO CHECK YOUR PROGRESS
1. The architecture of JDBC has four components, namely application, driver
manager, data source specific drivers and corresponding data sources.
2. JDBC Drivers can be classified into the following four categories:
(i) JDBC-ODBC-Bridge Driver
(ii) Native API partly-Java Driver
(iii) Net protocol all-Java client Driver
(iv) Native protocol all-Java Driver
3. JDBC-ODBC Bridge
4. False
5. PreparedStatement
6. getErrorCode()
7. While accessing the database, the developer may encounter various types of
errors. If any JDBC object encounters an error, it throws the SQLException
which must be handled by the SQLException class. The SQLException
class extends the java.lang.Exception class.
8. Some of the methods of the SQLException class are as follows:
SQLException getNextException(): This method is used to obtain
the next exception object in the chain of errors (if any exists).
Self-Instructional
228 Material
Java and Database
NOTES
String getSQLState(): This method provides the information about
the state of SQL, which helps in taking appropriate decisions.
int getErrorCode(): This method provides information about the vendor
specific errors whose meaning is defined by the driver vendor only.
13.8 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What is the role of the DriverManager class of java.sql package?
2. Write a code segment to show the usage of the next() method of class
ResultSet.
3. For which purpose is the getMetaData()method used?
4. Differentiate between the Statement interface and the
PreparedStatement interface.
Long-Answer Questions
1. Discuss the architecture of JDBC.
2. Describe JDBCODBC bridge with the help of a suitable diagram.
3. Write a program to demonstrate how exceptions related to JDBC are handled.
CAREER OPPORTUNITIES
Java is used in all areas associated with the Internet, Web
development and Web technologies. Java programmers will
find job opportunities in all areas related to e-commerce, portals,
content management, databases, data warehousing and custom
applications development.
Those wishing to take up software programming jobs
would be expected to work on adding new functionality to
existing systems. Java programming skills would be required
to prepare user and technical support manuals for different
applications.
Java programmers can use their skills to work on various
aspects of video game programming. Experienced video game
programmers can go on to become project managers in charge
of making sure that all the different programming components
are working smoothly together. Being a vast field, the
opportunities are many, depending on the field that the student
wants to specialize in. Coupled with a degree in management,
Java programmers can climb the corporate ladder very fast
Section I
Introduction: Internet Architecture Board, Understanding
the Internet.
Concept: Working, Surfing and Security on the Internet.
Internet protocols Internet Addressing, Internet Routing
Protocols Internet Message Protocol, Internet Group
Management protocols, Internet mail protocol.
Internet applications: E-mail, multi cost backbone, net news.
Web: World Wide Web advantages of web, web terminology,
web access using web browser, locating information on the
web.
Section II
Introduction to Java: Applets, application & JDK, different
b/w Java & C++, working with Java objects: Encapsulation,
inheritance & polymorphism, constructors. Garbage
collection & finalisers, data types, modifies & expressions,
array & flow control statements.
Section III
Exception handling threads, Event handling, Network
programming & Java virtual machines, Java & databases.
PTU DEP SYLLABI-BOOK MAPPING TABLE
Internet Applications and Java
Syllabi Mapping in Book
Unit 1: Internet
(Pages 316);
Unit 2: Web: World Wide Web
(Pages 1727);
Unit 3: Java and the Internet
(Pages 2938)
Unit 4: Programming Elements of Java
(Pages 3957)
Unit 5: Control Statements
(Pages 5976);
Unit 6: Java Classes and Objects
(Pages 7794);
Unit 7: Arrays and Vectors
(Pages 95108);
Unit 8: Inheritance and Polymorphism
(Pages 109131)
Unit 3: Java and the Internet
(Pages 2937);
Unit 9: Exception Handling Threads
(Pages 133166);
Unit 10: Exception Handling
(Pages 167184);
Unit 11: Event Handling
(Pages 185198);
Unit 12: Network Programming
(Pages 199212)
Unit 13: Java and Database
(Pages 213228)
CONTENTS
INTRODUCTION 1
UNIT 1 INTERNET 316
1.0 Introduction
1.1 Unit Objectives
1.2 Understanding the Basics of the Internet
1.2.1 Evolution of the Internet
1.2.2 Internet Architecture Board
1.2.3 Accessing the Internet
1.2.4 Working of the Internet
1.2.5 Surfing on the Internet
1.3 Security on the Internet
1.4 Internet Protocols
1.5 Internet Addressing
1.6 Internet Routing Protocols
1.7 Internet Message Protocol (Internet Control Message Protocol)
1.8 Internet Group Management Protocols
1.9 Internet Mail Protocols
1.10 Internet Applications
1.11 Summary
1.12 Key Terms
1.13 Answers to Check Your Progress
1.14 Questions and Exercises
UNIT 2 WEB: WORLD WIDE WEB 1727
2.0 Introduction
2.1 Unit Objectives
2.2 The Web: Advantages and Terminology
2.2.1 Web Terminology
2.3 Web Access Using Web Browser
2.4 Locating Information on the Web
2.5 Summary
2.6 Key Terms
2.7 Answers to Check Your Progress
2.8 Questions and Exercises
UNIT 3 JAVA AND THE INTERNET 2938
3.0 Introduction
3.1 Unit Objectives
3.2 Basic Features of Java Programming Language
3.3 Difference between Java and C++
3.4 Java Applications and Applets
3.5 Java Compiler
3.6 Java Virtual Machine Concepts
3.7 Java Development Kit (JDK)
3.8 A First Look at Java Program
3.9 Running Java Applications
3.10 Command Line Arguments
3.11 Summary
3.12 Key Terms
3.13 Answers to Check Your Progress
3.14 Questions and Exercises
UNIT 4 PROGRAMMING ELEMENTS OF JAVA 3957
4.0 Introduction
4.1 Unit Objectives
4.2 Character Set
4.3 Tokens
4.3.1 Keywords
4.3.2 Identifiers
4.3.3 Constants
4.3.4 Operators
4.3.5 Punctuators
4.4 Structure of a Java Program
4.5 Data Types
4.5.1 Primitives Data types
4.5.2 Non-Primitive Data types
4.6 Variables
4.7 Type Casting
4.8 Operators and Operations
4.8.1 Arithmetic Operators
4.8.2 Increment and Decrement Operators
4.8.3 Relational Operators
4.8.4 Logical Operators
4.8.5 Conditional Operator
4.8.6 Assignment Operators
4.8.7 Other Operators
4.8.8 Operators Precedence and Associativity
4.9 Summary
4.10 Key Terms
4.11 Answers to Check Your Progress
4.12 Questions and Exercises
UNIT 5 CONTROL STATEMENTS 5976
5.0 Introduction
5.1 Unit Objectives
5.2 Selection Statements
5.3 Iteration Statements
5.3.1 The for Loop
5.3.2 The while Loop
5.3.3 The do-while Loop
5.4 Jump Statements
5.5 Labelled Loops
5.6 Summary
5.7 Key Terms
5.8 Answers to Check Your Progress
5.9 Questions and Exercises
UNIT 6 JAVA CLASSES AND OBJECTS 7794
6.0 Introduction
6.1 Unit Objectives
6.2 Encapsulation
6.3 Defining a Class
6.3.1 Defining Methods
6.4 Creating Objects
6.5 Accessing Members of a Class
6.6 Argument Passing
6.6.1 Call-by-Value
6.6.2 Call-by-Reference
6.7 Constructors
6.7.1 Parameterized Constructors
6.8 Method Overloading
6.9 Static Members
6.10 this Keyword
6.11 Garbage Collection
6.11.1 The finalize() Method
6.12 Summary
6.13 Key Terms
6.14 Answers to Check Your Progress
6.15 Questions and Exercises
UNIT 7 ARRAYS AND VECTORS 95108
7.0 Introduction
7.1 Unit Objectives
7.2 Arrays
7.2.1 Single-Dimensional Arrays
7.2.2 Multi-Dimensional Arrays
7.3 Vectors
7.4 Wrapper Classes
7.5 Summary
7.6 Key Terms
7.7 Answers to Check Your Progress
7.8 Questions and Exercises
UNIT 8 INHERITANCE AND POLYMORPHISM 109131
8.0 Introduction
8.1 Unit Objectives
8.2 Inheritance Basics
8.2.1 Defining a Subclass
8.3 Types of Inheritance
8.3.1 Single Inheritance
8.3.2 Hierarchical Inheritance
8.3.3 Multilevel Inheritance
8.3.4 Multiple Inheritance
8.4 Access Modifiers
8.5 Subclass Constructor
8.6 Method Overriding
8.7 Polymorphism
8.8 Using final Keyword
8.8.1 Final Variables
8.8.2 Final Methods
8.8.3 Final Classes
8.9 Abstract Methods and Classes
8.10 Summary
8.11 Key Terms
8.12 Answers to Check Your Progress
8.13 Questions and Exercises
UNIT 9 EXCEPTION HANDLING THREADS 133166
9.0 Introduction
9.1 Unit Objectives
9.2 Concept of Threads
9.2.1 Main Thread
9.2.2 Creating Threads
9.2.3 Extending Threads
9.2.4 Implementing Runnable Interface
9.3 Life Cycle of a Thread
9.4 Thread Methods
9.4.1 Using Yield(), Sleep() and Stop() Method
9.4.2 Using isalive() and join() Method
9.5 Threads Priority
9.6 Synchronization of Threads
9.6.1 Synchronizing Methods
9.6.2 Synchronizing Statements
9.6.3 Deadlock
9.7 Inter-Thread Communication
9.8 Suspending, Resuming and Stopping Threads
9.9 Summary
9.10 Key Terms
9.11 Answers to Check Your Progress
9.12 Questions and Exercises
UNIT 10 EXCEPTION HANDLING 167184
10.0 Introduction
10.1 Unit Objectives
10.2 Exceptions
10.2.1 Keywords Used in Exception Handling
10.2.2 Types of Exceptions
10.3 Using try and catch Blocks
10.3.1 Multiple catch Blocks
10.3.2 Nested try Blocks
10.4 Using finally Block
10.5 Using throw Block
10.6 Using throws Keyword
10.7 Creating Your Own Exceptions
10.8 Summary
10.9 Key Terms
10.10 Answers to Check Your Progress
10.11 Questions and Exercises
UNIT 11 EVENT HANDLING 185198
11.0 Introduction
11.1 Unit Objectives
11.2 Events
11.3 Event Handling Model
11.3.1 Java 1.0 Event Model
11.3.2 Delegation Event Model
11.4 Event Handling: Classes, Sources and Listner Interfaces
11.4.1 Event Classes
11.4.2 Event Sources
11.4.3 Event Listener Interfaces
11.5 Summary
11.6 Key Terms
11.7 Answers to Check Your Progress
11.8 Questions and Exercises
UNIT 12 NETWORK PROGRAMMING 199212
12.0 Introduction
12.1 Unit Objectives
12.2 Networking Fundamentals
12.2.1 TCP/IP Protocols
12.2.2 Internet Addressing
12.2.3 Ports
12.2.4 Sockets
12.3 The Networking Classes and Interfaces
12.4 The InetAddress Class
12.5 TCP/IP Socket Programming
12.5.1 Creating a TCP Server
12.5.2 Creating a TCP Client
12.6 UDP Socket Programming
12.6.1 Creating a UDP Server Program
12.6.2 Creating a UDP Client Program
12.7 Summary
12.8 Key Terms
12.9 Answers to Check Your Progress
12.10 Questions and Exercises
UNIT 13 JAVA AND DATABASE 213228
13.0 Introduction
13.1 Unit Objectives
13.2 Architecture of JDBC
13.3 JDBCODBC Bridge
13.4 The java.sql Package
13.4.1 The DriverManager Class
13.4.2 The Connection Interface
13.4.3 The Statement Interface
13.4.4 The ResultSet Interface
13.4.5 The PreparedStatement Interface
13.4.6 The ResultSetMetaData Interface
13.4.7 The SQLException Class
13.5 Summary
13.6 Key Terms
13.7 Answers to Check Your Progress
13.8 Questions and Exercises
Self-Instructional
Material 1
Introduction
NOTES
INTRODUCTION
Java is a programming language that has been developed by Sun Microsystems and is
one of the most popular programming languages in use. It is widely used in various ways
ranging from application software to Web applications. It is a general-purpose, class-
based and object-oriented language that is specifically designed to have the least number
of implementation dependencies possible. All these features led to the process of using
it as the language for the Internet. It also supports various Internet protocols and Web
services and is used for all applications of the Internet.
This book, Internet Applications and Java, is divided into thirteen units. The
first unit deals with the basics of the Internet, including its evolution and various
applications. The next unit provides an introduction to the World Wide Web. The
relationship between Java and the Internet has been analysed in the third unit. The
fourth unit deals with the programming elements of Java, while the control statements in
Java have been shown in the fifth unit. The following unit highlights Java classes and
objects. The seventh unit deals with arrays and vectors. The eighth unit deals with
inheritance and polymorphism. The next unit discusses the exception handling threads.
The tenth unit explains exception handling, while the eleventh unit deals with event
handling. Network programming has been discussed in the twelfth unit. Accessing a
database in Java has been dealt with in the last unit.
The book follows the self-instructional mode wherein each unit begins with an
Introduction to the topic. The Unit Objectives are then outlined before going on to the
presentation of the detailed content in a simple and structured format. Check Your
Progress questions are provided at regular intervals to test the student's understanding
of the subject. A Summary, a list of Key Terms and a set of Questions and Exercises are
provided at the end of each unit for recapitulation.
Self-Instructional
Material 3
Internet
NOTES
UNIT 1 INTERNET
Structure
1.0 Introduction
1.1 Unit Objectives
1.2 Understanding the Basics of the Internet
1.2.1 Evolution of the Internet
1.2.2 Internet Architecture Board
1.2.3 Accessing the Internet
1.2.4 Working of the Internet
1.2.5 Surfing on the Internet
1.3 Security on the Internet
1.4 Internet Protocols
1.5 Internet Addressing
1.6 Internet Routing Protocols
1.7 Internet Message Protocol (Internet Control Message Protocol)
1.8 Internet Group Management Protocols
1.9 Internet Mail Protocols
1.10 Internet Applications
1.11 Summary
1.12 Key Terms
1.13 Answers to Check Your Progress
1.14 Questions and Exercises
1.0 INTRODUCTION
The word Internet is derived from two words: Interconnection and Network. The
Internet is basically a network of networks that facilitates data transmission and exchange,
across the million of domestic, academic, business and government networks. It is a
global, publicly accessible network that enables sharing of files and other resources
using protocols through the transmission media. With the two hundred computers in
1980, the Internet has now evolved to millions of computers linked worldwide.
The Internet has grown from a small network to todays biggest network of
computers. Due to this colossal growth, the Internet has become the biggest domain of
information. Nowadays, an Internet user has access to a wide variety of services, such
as electronic mail, file transfer, vast information resources, interest group membership,
interactive collaboration, multimedia displays, real-time broadcasting, shopping
opportunities, and much more.
1.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Understand the basics of the Internet
Discuss the working of Internet
Describe the various protocols that are used for communication between different
devices
Self-Instructional
4 Material
Internet
NOTES
Understand the Internet addressing
Explain Internet routing protocols, Internet message control protocols, Internet
group management protocols and Internet mail protocols
Explain few applications of Internet
1.2 UNDERSTANDING THE BASICS OF THE
INTERNET
The Internet refers to a global system of interconnected computer networks that use the
standard Internet Protocol Suite (TCP/IP) for serving millions of users worldwide. It is
a network of networks comprising millions of private, public, academic, business and
government networks.
This section deals with the basic aspects of the Internet, such as how it evolved,
how it is accessed, how it works, and so on.
1.2.1 Evolution of the Internet
The foundation of the Internet was laid in 1969 by the Department of Defense (DOD)
of the United States of America. The DOD wanted to create a computer network that
could continue to function in the event of a disaster, such as a nuclear war. Even if a part
of the network was damaged or destroyed, the rest of the system would continue to
work. That network was known as Advanced Research Projects Agency Network
(ARPANET), which linked US scientific and academic researchers. It was the forerunner
of todays Internet.
Later in 1980, another agency, the National Science Foundation (NSF) created a
new network of computers based on ARPANET, called NSFNET, which turned out to
be more efficient and capable. Initially, NSFNET was designed to link five super
computers situated at the major universities of NSF and allowed only academic research.
Over the time, this network expanded to include sites for business, universities,
government, etc. and finally becoming a network consisting of millions of computers,
now known as the Internet.
1.2.2 Internet Architecture Board
When ARPANET was developed, the DOD established a committee known as Internet
Activities Board (IAB) to monitor and control the development of Internet. This board
was later renamed to Internet Architecture Board. This committee was responsible for
deciding the standards required and how these standards should be implemented to
control the working of Internet. Some of the other responsibilities of IAB include:
It monitors the structure of protocols used by the Internet.
It monitors the procedures used to create the Internet standards.
It acts as a representative of the interests of the Internet Society.
The members of IAB regularly met and discussed the outcomes of the research
and reported to the DOD and NSF. In 1989, the IAB committee was divided into two
groups, namely, Internet Research Task Force (IRTF) and Internet Engineering Task
Force (IETF). The idea underlying the reorganization is to make IRTF focus on long
term research and IETF to handle short term engineering issues. The main purpose of
IRTF is to create research groups that focus on Internet protocols, applications,
Self-Instructional
Material 5
Internet
NOTES
architecture, and technology, whereas, IETF is a large open community of network
designers, operators, vendors and researchers that focuses on solving technical problems
on the Internet.
1.2.3 Accessing the Internet
As you know, the Internet is a vast collection of different networks that allows the
computers to exchange information with each other. It is a huge cooperative community
that is not under the control of anyone. However, there are several organizations that
propose standards and the guidelines for its proper usage. As a result, anyone having
Internet access can communicate directly with anyone on the Internet, post information,
use distant applications and services or buy and sell products. For accessing the Internet,
you need to buy an Internet connection from an authorized Internet Service Provider
(ISP). An ISP is an organization that provides access to the Internet. It charges a monthly
fee and subscribes you as a user to connect to the Internet. Once you get subscribed,
you can log on to the Internet and browse the Web any time as per your convenience.
There are thousands of ISPs established all over India. Some of the common ISPs
include Mahanagar Telephone Nigam Limited (MTNL), Videsh Sanchar Nigam Limited
(VSNL), Satyam Online, etc.
ISP provides a variety of Internet connections varying in the speed of accessing
the Internet. Following are the types of Internet connections provided by ISPs.
Dial-up access
Integrated services digital network (ISDN)
Cable
Digital subscriber line (DSL)
Leased line
1.2.4 Working of the Internet
Most of the computers are not directly connected to the Internet, instead they are part of
small networks which in turn are connected to Internet backbone through gateways.
Internet backbone act as interconnecting structure used to connect one or more networks
and gateway is a device used to connect dissimilar networks.
Now, let us see how messages are transferred from one system to another on the
Internet. The message sent by the source computer is divided into small parts known as
packets. Each packet is assigned a sequence number 1, 2, 3, so on. All these packets
are then sent to the destination computer with the help of routers. At the destination
computer, the packets may be received in random order, thus the packets are rearranged
according to their sequence number and reassembled together to form the original
message. If any of the packets is lost or corrupted, it is resent from the source computer.
1.2.5 Surfing on the Internet
Internet contains a huge wealth of information which can help us in many ways. There
are different websites on the Internet which are hosted by various companies,
organizations, educational institutions, newspapers, magazines, individuals, etc. With the
help of the web browser, one can easily visit these websites and gather competitive
information, conduct market research, and stay in touch with the current happenings.
The process of locating information on the Internet is called Internet surfing or Internet
browsing. Details of locating information on the Internet are discussed in Unit 2.
Self-Instructional
6 Material
Internet
NOTES
1.3 SECURITY ON THE INTERNET
Internet, being a vital source of data and information, plays an important role in the
growth of organizations, business, etc. However, at the same time, it has been a cause of
many security risks. This is because computer systems on the Internet are vulnerable to
various kinds of threats. Some of the common security threats that are faced today are
as follows:
Password cracking: Password cracking is a way for illegally accessing someones
computer without his or her permission to do so.
E-mail spoofing: Sometimes, a user can receive e-mail that appears to have
been sent by one person but was actually sent by some other person and it results
to spoofing. The aim of spoofing is to make the user divulge the confidential
information.
Virus intrusion: Viruses are short programs which are attached to other programs
with the intent to corrupt executable codes. Viruses are exposed when we receive
e-mails, send documents over the network and even when we install software or
copy files from another hard disk. They are of various types, such as file infecting
virus, boot sector virus, polymorphic virus, multipartite virus, stealth virus, etc.
They can affect the system in many ways like slowing down the system, formatting
the hard disk, corrupting the data, etc.
Hackers: Hackers are the people who focus on finding some weak points in the
security mechanism of websites and other computer systems in order to gain
unauthorized access. The activities of hackers are not limited to only gaining the
unauthorized access of systems, but also include theft of confidential information
and damage the information systems. They can also introduce viruses in the
network which can enter database or other applications and crash the whole
server.
There are various ways through which Internet security can be provided. Some of them
are as follows:
Authentication: It is the process of determining whether the user is allowed to
access the computer. Identification is usually done on the basis of username and
password and it can also be done on the basis of fingerprints, voice recognition,
signature, etc.
Authorization: It is the process of specifying whether the user is granted
permission to use certain resources. The computer resource is thus protected
from unauthorized users. The resources comprise data, programs, files, application,
devices, etc. Usually the permission is granted by the system administrators.
Cryptography: It is the process of encrypting or modifying the messages to hide
its meaning from the unauthorized users who try to intercept it. With the help of
this technique, the sensitive data which is sent across the Internet can be protected.
Firewall: A firewall is a part of a computer system or network which is placed
between an internal network and Internet. It is configured with a set of rules to
determine which network traffic should be allowed to pass and which one should
be blocked, that is, it blocks the unauthorized access. It is implemented in either
software or hardware or, a combination of both.
Check Your Progress
1. The Department of
Defense of USA
laid the foundation
of Internet in the
year 1969. That
network was
known as_______.
2. What was the
purpose of
establishing the
Internet
Architecture
Board?
3. _________ is a
device used to
connect dissimilar
networks.
4. Define Internet
surfing.
Self-Instructional
Material 7
Internet
NOTES
Cyber laws: Cyber laws are enforced to control the cyber crime. The laws
address the legal issues related to the communication technology.
Digital signature: In order to prevent spoofing, the original sender of the e-mail
must put the electronic signature in the message. This electronic signature is also
known as digital signature. Electronic signature ensures that the original messages
are not changed during the transmission process and the messages are also from
the person which is in the sender list.
1.4 INTERNET PROTOCOLS
A protocol is referred to as the formal set of rules and conventions that govern how
different computer devices communicate with each other. Some of the protocols used
for communication between different devices are discussed here.
TCP/IP
The TCP/IP is a layered set of protocols that handles the way data is transmitted across
the Internet. The TCP/IP has two major components, namely, Transmission Control
Protocol (TCP) and Internet Protocol (IP).
The TCP is a reliable and connection-oriented protocol that allows the data that
originates from source machine, to be delivered without error to the destination. It
fragments the incoming data into discrete messages called packets. TCP at
receiving the data, sends an acknowledgement that guarantees that the data is
received and then reassembles the packets into original form.
IP is an unreliable and connectionless protocol. It does not require a connection to
be established to transmit the data and does not guarantee the delivery of data to
its destination. IP is primarily responsible for delivering the packets to the destination.
HyperText Transfer Protocol (HTTP)
HTTP is a protocol that facilitates accessing hypertext documents. It is designed
specifically for the WWW at CERN. It is based on the client/server principle that allows
the client to make a connection with the server and then place a request. The server
services that request and sends an appropriate reply to the client. The HTTP is used as
a protocol for communication between the user agent and gateways to other IP protocols
like SMTP, FTP, etc.
File Transfer Protocol (FTP)
FTP is a set of rules that enables a user to transfer files from one system to another. It
allows the user to get access to the files stored in the directory of a remote computer
that is connected to the Internet. Using FTP, one can upload and download files from the
remote computer (known as FTP Server), if he has access permission on the remote
machine.
Some FTP servers allow users to use a method called anonymous FTP, which
allows users to access files without any specific permission to access. One can download
FTP files using either web browser or a special software known as FTP client program
such as Cube or Fetch.
Self-Instructional
8 Material
Internet
NOTES
Network News Transfer Protocol (NNTP)
NNTP is a protocol which is used by computer clients and servers to manage the news
posted on newsgroup. It is used to transfer news messages over the Internet. NNTP is
a replacement of original Usenet protocol. A copy of news messages posted by the
users can be collected from the newsgroups by NNTP server, which can later be read
by other users. These users can send their own messages to the same group. NNTP has
been created for the efficient transmission of Netnews articles over a full duplex 8-bit-
wide data stream communication channel.
1.5 INTERNET ADDRESSING
Every machine on the Internet is identified by a numerical address known as IP address.
It is a 32 bit number which is assigned to each computer connected to the Internet. An
IP address comprises four sections that are separated by periods (.). Each section consists
of a number which ranges from 0 to 255. An example of a typical IP address is:
216.27.61.137. Note that, no two computers can share the same IP address. As IP
addresses are in the form of numerical strings, they are hard to remember. Thus, there
exists a domain name that corresponds to an IP address. Domain names are human-
readable addresses and are much easier to remember. A domain name consists of two
or more parts separated by periods (.). Some of the examples of domain name are
www.yahoo.com, www.nasa.org, etc. The domain name represents the name of the
web server where the desired web page or other resources resides. The last part of the
domain name is the top-level name which represents the type of organization or country
to which the server belongs. Three-letter abbreviations are used for organizations and
two-letter abbreviations are used for countries. Some of the abbreviations which are
reserved for various organizations are listed in Table 1.1.
Table 1.1 Reserved Abbreviations for Organizations
Domain Name Organization Type
.com Commercial / profit organizations
.edu Educational institutions
.net Networking organizations
.gov Government agencies
.org Non-profit organizations
.mil United states military
Some of the abbreviations which are reserved for various countries are listed in
Table 1.2.
Table 1.2 Reserved Abbreviations for Organizations
Domain Name Country Name
.in India
.uk United Kingdom
.au Australia
.nz New Zealand
.dk Denmark
.jp Japan
Check Your Progress
5. Which of the
following method
should be used to
prevent E-mail
spoofing?
(a) Cryptography
(b) Cyber laws
(c) Firewalls
(d) Digital
signature
6. Differentiate
between
authentication and
authorization.
7. TCP is an
unreliable and
connectionless
protocol of TCP/
IP. (True or False)
8. Which of the
following protocol
facilitates accessing
hypertext
documents?
(a) TCP/IP
(b) FTP
(c) HTTP
(d) NNTP
9. The mapping
between the
domain name and
its associated IP
address is
performed by an
Internet service
known as ______.
Self-Instructional
Material 9
Internet
NOTES
The mapping between the domain name and its associated IP address is performed
by an Internet service known as domain name system (DNS). It allows users to work
with domain names; however, Internet operates in IP address.
1.6 INTERNET ROUTING PROTOCOLS
Internet routers are specialized computers that interconnect several different networks.
A computer on the Internet communicates with other computer by forwarding packets
containing other computers IP address to the closest Internet router. The router maintains
the information required for routing purposes in the routing table. The routing table can
be either static or dynamic. If the routing table is updated with change in the topology of
any network the routing table is said to be dynamic otherwise static. Today dynamic
tables are needed by the Internet. For handling dynamic routing tables, routing protocols
have been developed. A routing protocol is a set of rules and procedures which specifies
how routers share information with each other for routing purposes.
As the Internet is so vast, the updation of routing tables cannot be handled by one
routing protocol, thus, the Internet is divided into a number of independent networks
known as autonomous systems. An autonomous system (AS) is a group of networks
and routers which is controlled by a single administration. On the basis of routing inside
an autonomous system or between autonomous systems, routing protocols are divided
into types:
Interior Gateway Protocol (IGP)
Exterior Gateway Protocol (EGP)
Interior Gateway Protocol (IGP)
The Interior gateway protocol is a routing protocol which is used for routing purpose
within an AS. The two of the commonly used IGP protocols are Routing Information
Protocol (RIP) and Open Shortest Path First (OSPF).
RIP: It is based on an algorithm known as distance vector algorithm. It uses
hop count as its metric (cost) which represents the number of networks passed to
reach the destination. This protocol treats all the networks equally, that is, the cost
of passing through any of the networks is same; the hop value for passing each
network is 1. In this protocol, while crossing several networks, if the hop value for
a particular network reaches 16, then that network is said to be unreachable.
Hence, this protocol is not suitable for very large networks.
OSPF: It supports large networks and has become the main interior gateway
protocol. It divides an autonomous system into areas, which is a set of routers,
hosts and networks comprised in an AS. All the areas inside an AS are connected
to a special area called backbone. Routers within an area are called internal
routers and those located at area borders are known as area border routers.
Area border routers summarize routing information of an area and exchange it
with neighbouring areas. This protocol allows assigning a metric to each route
and the metric or cost is based on the type of services on a particular route like
minimum delay, maximum throughput, etc. This protocol maintains several routing
tables based on the different types of services. These routing tables can be used
for selecting optimal route for sending the packets.
Self-Instructional
10 Material
Internet
NOTES
Exterior Gateway Protocol
The exterior gateway protocol is a routing protocol which is used for routing purpose
across one or more autonomous systems. One of the most common EGP protocols is
Border Gateway Protocol (BGP).
BGP is based on an algorithm known as path vector routing. In this algorithm,
the routing table maintains the information containing details of the path used to reach a
destination along with addresses of destination network and the next router. Every BGP
router evaluates the different paths used for reaching a destination and provides rating
to them. It then shares this information with other routers. The other routers, if required
can update their own routing tables and propagate this information to other neighbouring
routers. However, the route which is optimal for one router may not be optimal for other
router; therefore router has to decide whether to update its routing table.
1.7 INTERNET MESSAGE PROTOCOL (INTERNET
CONTROL MESSAGE PROTOCOL)
The Internet Control Message Protocol (ICMP) is a network layer protocol which was
designed to overcome the limitations of IP. The limitations included lack of error reporting
messages and lack of procedures for handling host and management queries. An ICMP
packet is encapsulated inside an IP packet and is responsible for error free transmission
of IP packets over the network. Some of the important ICMP messages are as follows:
Destination unreachable: This message is used when the router or subnet is
not able to reach the destination.
Time exceeded: This message is used when the counter associated with the
packet hits zero and the packet is dropped. It indicates looping of packets due to
congestion or setting very low timer values.
Source quench: This message is sent to the host which sends too many packets
leading to congestion in the network.
Redirect: This message is used by the router to tell the source host about wrong
routing of a packet.
Echo: This message is used to check whether a destination host is reachable and
alive.
Echo reply: This message is generated by the destination host in response to the
Echo message received.
Timestamp request: This message is used to determine the round trip time
needed for an IP packet to travel between two machines.
Timestamp reply: This message is generated in response to Timestamp Request
message. It is similar to Timestamp Request message except that it also contains
the arrival time of Timestamp Request message and departure time of the reply.
1.8 INTERNET GROUP MANAGEMENT PROTOCOLS
The Internet Group Management Protocol (IGMP) protocol is designed to support
multicasting. Multicasting is a process in which a message is sent to a large number of
hosts belonging to a group. To implement multicasting, a host must acquire a class D
address (each class D address identifies a group of hosts). Whenever a message is sent
Check Your Progress
10. The two of the
commonly used
IGP protocols are
____________ and
___________.
11. BGP is based on
an algorithm
known as
______________.
12. _____________
message is sent to
the host which
sends too many
packets leading to
congestion in the
network.
Self-Instructional
Material 11
Internet
NOTES
to the address by a process, it is sent to all the members of the group associated with that
address. The host can join or leave the group as required by the process. Each host
maintains the list of groups to which its processes currently belongs to.
Each multicast router sends the queries regularly to determine the hosts running
the processes belonging to any of the groups. Each host in turn sends a response message
for each group currently running one or more processes. The messages sent by the
router and hosts are called IGMP query packet and IGMP response packet,
respectively. Both these packets use a simple and fixed format with control information.
It consists of several fields which are as follows:
Ver: It specifies the version of the IGMP protocol.
Message type: It specifies the type of message which can be a query message
or a response message.
Maximum response time: It specifies the maximum amount of time in which a
query must be answered.
Checksum: It specifies the checksum, calculated for the message.
Group address: It contains the class D IP address of the group.
1.9 INTERNET MAIL PROTOCOLS
An Internet mail protocol is a protocol which is used by mail clients to exchange information
with the mail servers. The three main protocols which are commonly used are Simple
Mail Transfer Protocol (SMTP), Post Office Protocol Version 3 (POP3) and Internet
Message Access Protocol Version 4 (IMAP4).
Simple Mail Transfer Protocol (SMTP)
SMTP is used for sending a mail from one machine to another over the Internet. It is a
push protocol, that is, it sends the message from source machine to destination machine
whether the destination machine wants it or not.
When a source machine wants to send a message, it establishes a TCP connection
with the destination machine. Once the TCP connection is established, the sending machine
(that acts as client) waits for the destination machine (that acts as server) to be ready.
The server initiates by sending a text message containing its id to tell the client, it is
ready. In case the server is not ready, the connection is released by the client and is tried
again.
If the server is ready for receiving mail, the client tells it the sender and the
recipient of the message. If that recipient exists, the server allows the client to send the
message. Once the message is received by the server, it sends the acknowledgement to
the client.
Post Office Protocol Version 3 (POP3)
POP3 is a standardized protocol that allows a user to access the mail box on the mail
server. POP3 begins when the user runs the mail reader. The mail reader establishes the
TCP connection with the server. Once the connection is established, POP3 passes through
three stages which are as follows:
Authorization: It deals with the login of the user. After the successful login, user
can access his mail box.
Self-Instructional
12 Material
Internet
NOTES
Transaction: During this state, user can retrieve and download messages on the
local system.
Update: In this phase, all the messages are deleted on the server side and TCP
connection is broken.
Internet Message Access Protocol Version 4 (IMAP4)
Like POP3, IMAP4 is a protocol that allows to access the mail box. However, unlike
POP3, in which generally all the stored messages are downloaded and mail box is cleared
off, in IMAP4, all the messages remain stored on the server for indefinite period. This
protocol assumes that all the messages are not transferred to the local system.
1.10 INTERNET APPLICATIONS
Internet user has access to a wide variety of services such as electronic mail, file transfer,
vast information resources, interest group membership, interactive collaboration,
multimedia displays, real-time broadcasting, shopping opportunities, and much more.
Some of the Internet applications are described in this section.
E-mail
E-mail or electronic mail is the most commonly used Internet service. It refers to the
facility of sending and receiving messages electronically over a network of computers.
Sending and receiving e-mails requires a user to have an e-mail address (sometimes
called an e-mail account or an e-mail ID) in any of the websites that provides e-mail
service. A number of websites, such as www.yahoo.com, www.gmail.com,
www.rediffmail.com and www.hotmail.com, provide the facility to create free e-mail
account. Note that since, multiple users can access the Internet at the same time; the e-
mail address must be unique for each Internet user.
An e-mail address is divided into two parts, namely, username and the mail server
name. The two parts are separated by the symbol @. The structure of an e-mail address
is as follows:
username@mailservername.com
For example, itl.esl@gmail.com is an e-mail address where,
itl.esl = the username
gmail = the name of the mail server
.com = a commercial website
Though e-mail is a very popular service of the Internet because of its numerous
advantages, it has few disadvantages also. The advantages and disadvantages of e-mail
are as follows:
Advantages
The advantages of e-mail are as follows:
It is very fast medium of communication. The messages can be sent in no time
irrespective of the distance.
It is a very economic medium of communication. You are only charged the cost of
being online whether you are sending it overseas or down the road.
Self-Instructional
Material 13
Internet
NOTES
Any form of data such as text, graphics, sound, or video can be sent through
e-mails.
It is secure medium of communication, that is, no one can access anybodys
e-mail account without knowing the password.
Disadvantages
The disadvantages of e-mail are as follows:
A slight error in the e-mail address of the recipient is enough to prevent the
delivery of the message and even when you do everything right, there is always a
chance of failure in one of the links between you and your recipient.
Sometimes viruses can enter into your system through the attachments received
in e-mails.
Multicast Backbone
Mbone (Multicast Backbone) is a kind of virtual network running over the top of Internet.
Mbone finds its application in conducting audio and video conference among users located
geographically apart. Today, many researchers use Mbone to develop protocols and
applications for group communication. Earlier, it was almost impossible to transmit audio
or video files over the Internet. However, today with Mbone, the audio or video conference
can be conducted without any difficulty in spite of limited bandwidth available and variable
packet delivery delays on the Internet. Moreover, Mbone also compresses the data and
provides privacy by using encryption techniques.
Usenet (Net News)
On the Internet, one can also share news, views, ideas and information on any topic like
politics, science, computers, etc. This can be accomplished using a newsgroup service.
A newsgroup, also known as a Usenet, is an online discussion group on the Internet
who share a common interest. Many websites, like www.NewsOne.net, www.google.com,
www.Usenet-Replayer.com, etc., provide the facility of newsgroups.
People interested in a specific topic write articles and post them to the bulletin
board of the newsgroup server (a machine that posts the message for everyone to read)
so that others can read, reply and comment on them. You can read and post newsgroup
articles using newsreader software such as Microsoft Outlook Express News or Netscape
News or using a web browser like Internet Explorer.
1.11 SUMMARY
In this unit, you have learned that:
The Internet is basically a network of networks that facilitates data transmission
and exchange, across the million of domestic, academic, business and government
networks.
When ARPANET was developed, the DOD established a committee known as
Internet Activities Board (IAB) to monitor and control the development of Internet.
In 1989, the IAB committee was divided into two groups, namely, Internet Research
Task Force (IRTF) and Internet Engineering Task Force (IETF). The idea
underlying the reorganization is to make IRTF focus on long term research and
IETF to handle short term engineering issues.
Check Your Progress
13. Which of these
protocols is
designed to
support
multicasting?
(a) SMTP
(b) IGMP
(c) ICMP
(d) none of these
14. In which of these
Internet mail
protocols do all the
messages remain
stored on the
server for
indefinite period?
(a) SMTP
(b) POP3
(c) IMAP4
(d) none of these
15. Which of these is
used in conducting
audio and video
conference among
users located
geographically
apart?
(a) Mbone
(b) E-mail
(c) Usenet
(d) all of these
Self-Instructional
14 Material
Internet
NOTES
An ISP is an organization that provides access to the Internet. It charges a monthly
fee and subscribes you as a user to connect to the Internet.
Internet backbone acts as interconnecting structure used to connect one or more
networks and gateway is a device used to connect dissimilar networks.
The process of locating information on the Internet is called Internet surfing or
Internet browsing.
Some of the ways through which Internet security can be provided are
authentication, authorization, cryptography, firewall, cyber laws, digital signature,
etc.
The TCP/IP is a layered set of protocols that handles the way data is transmitted
across the Internet.
The File Transfer Protocol is a set of rules that enables a user to transfer files
from one system to another.
Network News Transfer Protocol is a protocol, which is used by computer clients
and servers to manage the news posted on newsgroup.
Every machine on the Internet is identified by a numerical address known as IP
address. There exists a domain name that corresponds to an IP address. The
mapping between the domain name and its associated IP address is performed by
an Internet service known as domain name system (DNS).
A routing protocol is a set of rules and procedures which specifies how routers
share information with each other for routing purposes.
An autonomous system (AS) is a group of networks and routers which is controlled
by a single administration. Interior gateway protocol is a routing protocol which is
used for routing purpose within an AS. Exterior gateway protocol is a routing
protocol which is used for routing purpose across one or more autonomous systems.
An ICMP packet is encapsulated inside an IP packet and is responsible for error
free transmission of IP packets over the network.
Internet Group Management Protocol (IGMP) protocol is designed to support
multicasting. Multicasting is a process in which a message is sent to a large
number of hosts belonging to a group.
Simple Mail Transfer Protocol (SMTP) is used for sending a mail from one machine
to another over the Internet.
Post Office Protocol Version 3 (POP3) is a standardized protocol that allows a
user to access the mail box on the mail server.
IMAP4 is a protocol that allows accessing the mail box. In IMAP4, all the messages
remain stored on the server for indefinite period.
E-mail or electronic mail is the most commonly used Internet service which refers
to the facility of sending and receiving messages electronically over a network of
computers.
Mbone (Multicast Backbone) is a kind of virtual network running over the top of
Internet. Mbone finds its application in conducting audio and video conference
among users located geographically apart.
A newsgroup, also known as a Usenet, is an online discussion group on the Internet
who share a common interest.
Self-Instructional
Material 15
Internet
NOTES
1.12 KEY TERMS
Internet Service Provider (ISP): It is an organization that provides access to
the Internet.
Internet surfing or Internet browsing: It is the process of locating information
on the Internet.
Authentication: It is the process of determining whether the user is allowed to
access the computer.
Authorization: It is the process of specifying whether the user is granted
permission to use certain resources.
Cryptography: It is the process of encrypting or modifying the messages to hide
its meaning from the unauthorized users who try to intercept it.
Firewall: A firewall is a part of a computer system or network which is placed
between an internal network and Internet.
Protocol: It is referred to as the formal set of rules and conventions that govern
how different computer devices communicate with each other.
TCP/IP: It is a layered set of protocols that handles the way data is transmitted
across the Internet.
Hypertext transfer protocol (HTTP): It is a protocol that facilitates accessing
hypertext documents.
File Transfer Protocol (FTP): It is a set of rules that enables a user to transfer
files from one system to another.
Network News Transfer Protocol (NNTP): It is a protocol, that is used by
computer clients and servers to manage the news posted on newsgroup.
Routing protocol: It is a set of rules and procedures which specifies how routers
share information with each other for routing purposes.
Autonomous System (AS): It is a group of networks and routers which is
controlled by a single administration.
Multicasting: It is a process in which a message is sent to a large number of
hosts belonging to a group.
Internet mail protocol: It is a protocol which is used by mail clients to exchange
information with the mail servers.
1.13 ANSWERS TO CHECK YOUR PROGRESS
1. ARPANET
2. The Internet Architecture Board was established to monitor and control the
development of Internet. It was responsible for deciding the standards required
and how these standards should be implemented to control the working of Internet.
3. Gateway
4. The process of locating information on the Internet is called Internet surfing or
Internet browsing.
5. (d)
Self-Instructional
16 Material
Internet
NOTES
6. Authentication is the process of determining whether the user is allowed to access
the computer, whereas authorization is the process of specifying whether the
user is granted permission to use certain resources.
7. False
8. (c)
9. Domain name system (DNS)
10. Routing Information Protocol (RIP), Open Shortest Path First (OSPF)
11. Path vector routing
12. Source quench
13. (b)
14. (c)
15. (a)
1.14 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What are the types of Internet connections provided by ISPs?
2. How does the Internet work?
3. What do you understand by Internet addressing?
4. What is the role IGMP protocol?
5. What are the various Internet routing protocols?
Long-Answer Questions
1. What are the common Internet security threats faced today? Also describe some
of the ways through which Internet security can be provided.
2. Discuss some Internet protocols used for communication between different
devices.
3. Explain various ICMP messages.
4. Describe the various Internet mail protocols.
5. Write short notes on the following Internet applications:
(a) E-mail
(b) Multicast Backbone
(c) Usenet
Self-Instructional
Material 17
Web: World Wide Web
NOTES
UNIT 2 WEB: WORLD WIDE WEB
Structure
2.0 Introduction
2.1 Unit Objectives
2.2 The Web: Advantages and Terminology
2.2.1 Web Terminology
2.3 Web Access Using Web Browser
2.4 Locating Information on the Web
2.5 Summary
2.6 Key Terms
2.7 Answers to Check Your Progress
2.8 Questions and Exercises
2.0 INTRODUCTION
The concept of the Web emerged at CERN (the European Council for Nuclear Research)
Geneva, Switzerland, in the year 1989. Since then, WWW is the most popularly used
Internet sub network. The CERN team developed the protocol based on hypertext that
makes it possible to connect content on the Web with hyperlinks. Earlier, the Internet
was largely a text-based system. However, the WWW permitted access to information
using a Graphical User Interface (GUI) and the use of hypertext links to access
information across the network without being a computer expert and without knowing
the exact physical location.
2.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Understand World Wide Web and its advantages
Define some Web-related terms and technologies
Understand how to access Web using a Web browser
Explain how to locate information on the Web
2.2 THE WEB: ADVANTAGES AND TERMINOLOGY
The World Wide Web (WWW) or W3 or simply the Web is a collection of linked documents
or pages, stored on millions of computers and distributed across the Internet. Some of
the advantages of WWW that led to its popularity are as follows:
It provides information in multimedia form, that is, in more than one medium such
as text, graphics, video and audio.
It provides a simple and consistent way of accessing the information available on
the Internet by using hypertext. The hypertext is a system in which the documents
contain links to other pages on the Internet. These links are called hyperlinks.
Note: The term World Wide Web is not a synonym of the Internet; it is one of the
services provided by the Internet.
Self-Instructional
18 Material
Web: World Wide Web
NOTES
2.2.1 Web Terminology
Some of the terms and technologies related to the Web are discussed in this section.
Web Page
A Web page is a document on the WWW that can include text, images, audio, video, etc.
A Web page is of two types, namely, static Web page and dynamic Web page. A static
Web page sends the same information to every end-user, whereas a dynamic Web page
customises the information according to the end-user.
Website
A collection of related Web pages stored on a Web server is known as a Website. A
Website is owned and maintained by a person, group, company or an organisation. Each
Website is accessed by its address known as URL (Uniform Resource Locator). All
the Websites on the Internet constitute the World Wide Web.
Home Page
A home page (also called index page) refers to the Web page that identifies the Website
and contains the hyperlinks to other Web pages in a Website. A Website may have
hundreds of pages or may consist of one page only.
Web Portal
A Website that acts as a gateway to a broad range of other sites on the Internet is
known as Web portal or simply a portal. In other words, a portal has a catalogue of
other Websites. It may also offer various other resources and services like a search
engine, e-mail, chatting, on-line shopping, horoscopes, latest news, etc. The first Web
portal was America Online (AOL). Some of the popular Web portals used today are
yahoo.com, rediff.com and indiatimes.com.
Web Browser
A Web browser is a software application that enables to view and navigate information
on the Web. A Web browser uses the HTTP protocol to request Web pages from the
Web. A Web browser may be text or graphical browser. For example, Lynx is the text-
based Web browser whereas Netscape Navigator and Internet Explorer are commonly
used graphical Web browsers.
Web Server
The Web pages on the Internet are stored on the computers that are connected to the
Internet. These computers are known as Web servers. Any computer that has a server
software installed on it and is connected to the Internet can act as a Web server. The
Web browsers and the Web servers are linked together using the client/server architecture.
The Client/Server Architecture
The client/server architecture is a network architecture in which each computer on the
network is either a client or a server. Servers are the computers that provide services to
other computers attached to them. The services may include file transfer, printing files,
sharing data, sending information, etc. On the other hand, clients are PCs or workstations
that request for different types of services provided by the server. In terms of the
Internet, Web browsers are the clients that request for the Web pages residing on the
Self-Instructional
Material 19
Web: World Wide Web
NOTES
Web server and the Web server fulfills their requests by sending the Web pages. Web
servers provide services to Web browser using the HTTP protocol.
2.3 WEB ACCESS USING WEB BROWSER
A Web browser is a software application that is used to view and browse information on
the Web. With the help of a Web browser, one can easily visit various Websites and
gather competitive information, conduct market research, and stay in touch with the
current happenings.
Internet Explorer is the most widely used Web browser developed by Microsoft.
Let us take an example to illustrate how Web can be accessed using Internet Explorer.
Open and Navigate a Website
Open Internet Explorer by double clicking the Internet Explorer shortcut icon placed on
the desktop. After opening the Internet Explorer, enter the address of the Website, that
is, URL in the address bar and press Enter to open the Website. The home page of the
Website is displayed. You can move around the home page using various methods, which
are as follows:
Using the vertical or horizontal scroll bars to move around a document.
Pressing the Up and Down arrow keys to move up or down one line.
Pressing the Page Up key to move up one window length and Page Down to
move down one window length.
Pressing Ctrl+Home and Ctrl+End to go to the beginning of the document and
the end of the document, respectively.
The home page displays various hyperlinks which link to other Web pages or to the other
parts of the same Web page. To open a hyperlink, just click any of the hyperlinks to open
the linked document. Alternatively, right-click on the hyperlink and select the Open
option from the shortcut menu to open the Web page in the same window or select the
Open in New Window to open the Web page in a new window (see Figure 2.1).
Figure 2.1 Home Page of a Website
Check Your Progress
1. WWW is a simple
way of accessing
information
available on the
Internet by using
_________.
2. Which of these is a
software
application that
helps to view and
navigate
information on the
Web?
(a) Web page
(b) Web portal
(c) Web browser
(d) Web server
3. What is the client/
server architecture?
Self-Instructional
20 Material
Web: World Wide Web
NOTES
After browsing through several pages in a window, you can move backward and forward
by clicking the Back and Forward button on the Standard toolbar.
Save Text and Images
Internet Explorer helps not only to find the required information from the Internet but it
also allows saving the retrieved information on the local system for future reference. To
save part of the text from a Web page, select the text that has to be saved. Right-click
the selected text and then click Copy option from the shortcut menu that appears. Now
you can paste the selected text in any of the word processor such as Notepad, Wordpad,
MS Word, etc., and save it for future reference, as shown in Figure 2.2.
Figure 2.2 Saving the Text
Similarly, images can also be saved from a Web page. To save the image, right-
click the image and then click the Save Picture As option from the shortcut menu. This
displays the Save Picture dialog box. Select the location for the image from the Save in
drop-down list box and enter a name for the image in the File name box. Click Save to
save the image at the desired location, as shown in Figure 2.3.
Figure 2.3 Saving the Image
Self-Instructional
Material 21
Web: World Wide Web
NOTES
If you want to save the entire Web page, click the File menu and the click Save
As option to displays the Save Web Page dialog box. Select the location for the Web
page from the Save in drop-down list box and enter a name for the Web page in the File
name box. Click Save to save the Web page, as shown in Figure 2.4.
Figure 2.4 Saving a Web Page
Add to Favorites
Internet Explorer provides a feature called Favorites. This feature maintains a list
called the Favorites list, of all the Web pages that you visited and want to visit again. To
add a Web page to the Favorites list, follow these steps.
1. Open the Web page that you want to add to your favorites. Click Add to Favorites
option on the Favorites menu. The Add Favorite dialog box appears (see Figure
2.5).
2. Enter a different name for the Web page, if required, in the Name box.
3. Select the Make available offline check box to view the page even when you
are not connected to the Internet and click OK.
Figure 2.5 Add Favorite Dialog Box
Self-Instructional
22 Material
Web: World Wide Web
NOTES
After the Website is added to the favorites list, you can view it by clicking on the
desired link on the Favorites menu.
2.4 LOCATING INFORMATION ON THE WEB
Locating information on the Web is one of the most popular services provided on the
Internet. You can find information on various topics, such as science, travel, politics,
education, health, etc., on the Internet. In addition, the Internet can be used to find
people and retrieve information about them.
A search engine is software that enables you to search information on the Internet.
It displays the results of a search based on the criteria entered by the user. That is, the
user provides a keyword or a phrase that helps the search engine to start the search. For
example, to find information about the various generations of the computer, enter the
phrase generations of computer and the search engine will display a list of Web pages
containing the desired information.
A search engine mainlys uses three tools for searching, namely, a spider or a
crawler, an indexer and a search algorithm. A crawler searches the Internet for new
terms and stores the searched terms in a database. An indexer then indexes all the
terms in the database to make the searching process fast. A search algorithm is simply
a method by which the search engine performs a search based on the keywords entered
by the user. Google, Yahoo and Altavista are some popular search engines.
To find information using a search engine, follow these steps.
1. Start Internet Explorer.
2. Open the home page of any search engine. For example, open www.google.com.
Figure 2.6 Google Home Page
Self-Instructional
Material 23
Web: World Wide Web
NOTES
3. Enter the search keyword, for example, Internet in the search text box (see
Figure 2.6).
or
Click Advanced Search if you want to perform advanced search. A page with
various Advanced Search options appears (see Figure 2.7). Select the required
options from the page to set your Advanced Search.
Figure 2.7 Advanced Search Page
4. Click the Advanced Search button when you finish setting the options. A Web
page with a list of hyperlinks appears (see Figure 2.8).
Figure 2.8 List of Hyperlinks
Self-Instructional
24 Material
Web: World Wide Web
NOTES
5. Choose any hyperlink and click it to open the Web page in the same window.
or
Right-click the hyperlink and click Open in New Window from the shortcut
menu to open the Web page in a new window.
6. Keep clicking the hyperlinks on the main search page till you find the required
information.
The Internet also helps you in finding the information about your friends, relatives
and other people online. You can find and get any persons e-mail address, telephone
number, mailing address or any other information through the Internet (if available on the
Internet). To find information about a person, initially you have to provide some basic
information about that person like the first and the last name, city, state or country name,
etc. The Internet retrieves and displays a list of people from where you can search the
required information.
Some of the Websites that provide the facility of finding people online are
www.people.yahoo.com, www.batchmates.com and www.orkut.com. To find any of
your friends or relatives using the Internet, follow these steps.
1. Open the Website for people search. For example, open www.people.yahoo.com.
2. To make a phone and address search, enter the First name, last name, City/Town
and State in the respective text boxes and then click the corresponding Search
button (see Figure 2.9). A Web page with phone numbers and address information
appears.
Figure 2.9 Finding People
3. To search for the e-mail address, enter the First Name and Last Name in the
respective text boxes and then click the corresponding Search button (see Figure
2.9). A Web page with the e-mail information appears (see Figure 2.10).
Self-Instructional
Material 25
Web: World Wide Web
NOTES
Figure 2.10 Finding E-mail Address
4. Enter the required information in the respective text boxes and click Search. A
Web page with the e-mail information appears.
2.5 SUMMARY
In this unit, you have learned that:
The concept of the Web began at CERN (the European Center for Nuclear
Research) Geneva, Switzerland, in the year 1989. Since then, WWW is the most
popularly used Internet sub network.
The hypertext is a system in which the documents contain links to other pages on
the Internet. These links are called hyperlinks.
The World Wide Web (WWW) or W3 or simply the Web is a collection of linked
documents or pages, stored on millions of computers and distributed across the
Internet.
A collection of related Web pages stored on a Web server is known as a Website.
A Website that acts as a gateway to a broad range of other sites on the Internet
is known as Web portal
A Web browser is a software application that enables to view and navigate
information on the Web. A Web browser may be text or graphical browser.
The Web pages on the Internet are stored on the computers that are connected to
the Internet. These computers are known as Web servers.
The client/server architecture is a network architecture in which each computer
on the network is either a client or a server. Web servers provide services to Web
browser using the HTTP protocol.
Check Your Progress
4. Which of these
searches new terms
on Internet and
stores the searched
terms in a
database?
(a) Crawler
(b) Indexer
(c) Search
algorithm
(d) None of these
5. Define search
engine.
6. What shortcut
keys can be used
to go to the
beginning of the
document and the
end of the
document,
respectively?
7. Which feature of
Internet Explorer is
used to organize
the frequently
visited Websites?
Self-Instructional
26 Material
Web: World Wide Web
NOTES
Locating information on the Web is one of the most popular services provided on
the Internet.
A search engine is software that enables you to search information on the Internet.
It displays the results of a search based on the criteria entered by the user. A
search engine mainly uses three tools for searching, namely, a spider or a crawler,
an indexer and a search algorithm.
2.6 KEY TERMS
World Wide Web (WWW) or W3: It is a collection of linked documents or
pages, stored on millions of computers and distributed across the Internet.
Web page: It is a document on the WWW that can include text, images, audio,
video, etc.
Website: It is a collection of related Web pages stored on a Web server.
Home page (index page): It refers to the Web page that identifies the Website
and contains the hyperlinks to other Web pages in a Website.
Web portal (or simply a portal): It refers to a Website that acts as a gateway
to a broad range of other sites on the Internet.
Web browser: It is a software application that enables to view and navigate
information on the Web.
Client/server architecture: It is a network architecture in which each computer
on the network is either a client or a server.
Servers: They are the computers that provide services to other computers
attached to them.
2.7 ANSWERS TO CHECK YOUR PROGRESS
1. Hypertext
2. (c)
3. The client/server architecture is a network architecture in which each computer
on the network is either a client or a server. Servers are the computers that
provide services to other computers attached to them. On the other hand, clients
are PCs or workstations that request for different types of services provided by
the server.
4. (a)
5. A search engine is software that enables to search information on the Internet. It
displays the results of a search based on the criteria entered by the user.
6. To go to the beginning of the document, the Ctrl + Home key is pressed, while to
go to the end of the document, the Ctrl + End key is pressed.
7. Internet Explorer provides a feature called Favorites, which maintains a list called
the Favorites list of all the Web pages that the visited and wants to visit again.
Self-Instructional
Material 27
Web: World Wide Web
NOTES
2.8 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What is the reason for the popularity of WWW?
2. What is the difference between a static Web page and a dynamic Web page?
3. What do you understand by Web portal?
4. Differentiate between a Web browser and a Web server.
5. What are the main tools used by a search engine?
6. What type of information can be located on the Web?
Long-Answer Questions
1. Discuss the various methods that can be used to move around the home page.
2. Write short notes on:
(i) Web page
(ii) Website
(iii) Web browser
(iv) Client/server architecture
3. Describe the various steps to be taken to find information using a search engine.
4. Explain the various steps you would take to find any of your friends or relatives
using the Internet.
Self-Instructional
Material 29
Java and the Internet
NOTES
UNIT 3 JAVA AND THE INTERNET
Structure
3.0 Introduction
3.1 Unit Objectives
3.2 Basic Features of Java Programming Language
3.3 Difference between Java and C++
3.4 Java Applications and Applets
3.5 Java Compiler
3.6 Java Virtual Machine Concepts
3.7 Java Development Kit (JDK)
3.8 A First Look at Java Program
3.9 Running Java Applications
3.10 Command Line Arguments
3.11 Summary
3.12 Key Terms
3.13 Answers to Check Your Progress
3.14 Questions and Exercises
3.0 INTRODUCTION
Java, initially named as Oak, was developed by the team headed by James Gosling at
Sun Microsystems, USA in 1991. The first and foremost reason behind the development
of Java was the need for a platform-independent and portable software to be embedded
in the consumers electronic devices like remote controls, microwave ovens, etc. The
second reason that led to the growth of Java is the Internet and World Wide Web as
these media need portable and platform-independent programs. Gosling and other team
members developed Web applets using the new language that could run on all types of
computers. During 1993, first Web browser, namely HotJava was developed to locate
and run applet programs. This development made Java language popular for the Internet.
By the year 1996, Java became a general-purpose, object-oriented programming language
which was used for Internet programming. Soon, Java became popular and many Web
browsers, such as Internet Explorer, Netscape Navigator etc., incorporated the ability to
run Java applets. In this unit, you will learn about the various features of Java which
have made it a popular language for various Internet applications.
3.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Describe Java programming language and explain its features
Differentiate between Java and C++
Explain Java applications and applets
Understand the role of Java compiler
Explain the features of Java Virtual Machine
Identify the various tools in the Java Development Kit
Self-Instructional
30 Material
Java and the Internet
NOTES
Understand the simple Java program
Run Java application
Explain command line arguments
3.2 BASIC FEATURES OF JAVA PROGRAMMING
LANGUAGE
Java is a third generation programming language which implements most of the concepts
of OOPs. Java has become a popular language for Internet applications because of
various features which are as follows.
Simple: Java inherits the syntax of C/C++ and many of the OOPs features of
C++ thus one who has understood the concepts of object-oriented language can
learn Java with least effort. Moreover Java omits the complex and unreliable
code of C and C++ like operator overloading, pointers, preprocessor header files.
Java provides small and convenient ways to accomplish a given task.
Interpreted: Unlike other languages Java uses two-stage system as it uses both
compiler and interpreter for its program execution. First, the compiler converts
the program code to bytecode which in turn is converted to machine code on any
machine using the interpreter. The machine code so generated can be executed
irrespective of the system on which it is being executed.
Architecture-neutral (platform-independent): This feature makes Java
language very special. Java programs can run on any platform that is they can
run on different CPUs and on different operating system architectures. The
bytecode produced by Java compiler can be run on any machine which has Java
runtime environment.
Object-Oriented language: Java is an object-oriented language as everything
in Java is an object. The objects and classes contain the program code and data.
The Java object model is easily extensible and classes can be used anywhere in
the program in the form of packages.
Robust: Java is a robust language because of mainly two reasons. Firstly, it is a
strictly typed language that checks the code at the compile time. Secondly, Java
does memory management in an effective way. In C++, the programmer has to
manually deallocate the dynamic memory used by the objects. Java automatically
deallocates free memory that is no longer referenced by the objects (with the
help of garbage collector).
Distributed: Since Java is platform independent, it is suitable for developing
applications for the networks. Java can handle TCP/IP protocols and hence
applications developed in Java can access remote objects on Internet like any
object on a local system.
Multithreaded: Java supports multithreaded programming which allows us to
write a program that can perform more than one task simultaneously. User need
not wait for one program to finish one task before starting next task. For example,
user can listen to an audio clip while downloading the applet. This feature helps to
improve the performance of graphical applications.
Self-Instructional
Material 31
Java and the Internet
NOTES
High Performance: As stated earlier, the Java program is converted to bytecode
which is then converted to machine code using interpreter. Since bytecode is
highly optimized, it enables the JVM to execute programs at much faster rate.
Dynamic: It is dynamic in nature that is Java programs can link to new class
libraries, objects, methods, etc., at the run-time. Java language also provides the
facility to include the functions of other languages like C and C++. They are
referred to as native methods. These methods are also linked dynamically at
run-time.
3.3 DIFFERENCE BETWEEN JAVA AND C++
Both C++ and Java are object-oriented languages but they are very different from each
other. Some of the features of C++ language were deliberately removed and some new
features were added to make Java more flexible and reliable language. Some of the
differences between Java and C++ are as follows:
Java does not support multiple inheritance of classes directly.
The concept of multithreading is supported by Java.
The destructor function in Java is replaced by finalize method.
The keyword typedef is not supported by Java.
Java does not support pointers instead it uses implicit object references.
The virtual keyword is not supported in Java.
Java does not support the concept of global variables.
Java supports exception handling in different way than C++. It provides finally
clause for cleanup.
The non-primitive data types are allocated memory by using the new operator.
Java adds many features that are necessary for object-oriented programming.
3.4 JAVA APPLICATIONS AND APPLETS
In recent years, Java has become popular language for the programs that are required to
run on different systems. Java enables us to create three types of applications. First,
Java can be used to create a normal Java application. A Java application is quite
similar to any program written in C or C++ which gets the user input, performs calculations
and displays the result.
Second, Java can be used to create Web-based applications called applets. It
has completely changed the Internet programming. Applets are tiny programs that are
designed in such a way that they can be transmitted over the Internet. They can be
downloaded on demand and executed automatically by Java compatible Web browser.
They are used to handle user input, data supplied by the server and simple functions that
executes locally on the client machine.
Applet is dynamic, self-executing program and is intelligent enough that can change
it with the user inputs. The dynamic programs when downloaded and executed can
cause serious harms to the computer as it may contain viruses like Trojan horse and
Check Your Progress
1. Java was
developed at Sun
Microsystems in
1991 by the team
headed by______
2. First Web browser
HotJava was
developed in year
1993.
(True or False)
3. Java used both
_______ and
_________ for its
program execution.
4. Bytecode is
platform
independent.
(True or False)
5. Native methods
can be linked
dynamically
at_____.
Self-Instructional
32 Material
Java and the Internet
NOTES
malicious programs. These harmful programs may search the contents on local file
system of the client computer and may gather private information like credit card numbers,
passwords, etc. Earlier viruses were scanned before executing the downloaded program,
but Java has resolved the issue by confining the Java programs to Java execution
environment only.
3.5 JAVA COMPILER
In most of the programming languages, the program is converted to machine code either
by using compiler or interpreter. The machine code so generated is machine dependent
that is it may not run on the machine other than the one on which it is generated. Unlike
in case of other programming languages, the Java compiler does not convert source
code to machine code rather it converts source code to a special intermediate code
known as bytecode. The bytecode so generated is in the form of class files that can be
interpreted. The command used for compilation in Java is javac which converts the
corresponding Java file into class file. The bytecode is machine independent that is it can
be run on any machine with the help of Java virtual machine (JVM), which is discussed
in the next section.
Source Code Bytecode
Compiler
.java file .class file
Figure 3.1 Compilation of a Java Program
3.6 JAVA VIRTUAL MACHINE CONCEPTS
As discussed earlier, Java uses both compiler and interpreter. Source code written in
Java is compiled to generate bytecode and then this bytecode is interpreted to machine
instructions for specific machine. The bytecode generated by the compiler is not machine
specific. It is generated for the virtual machine that exists only inside the computer
memory known as Java Virtual Machine (JVM). This virtual machine is designed in
such a way that it can be implemented on the top of any existing processor and itself
acts as virtual processor chip. It hides the underlying operating system details from Java
applications. The process of converting source code to machine code is shown in
Figure 3.2.



Source Code Bytecode
Compiler Interpreter
Machine Code
JVM
Figure 3.2 Conversion of Source Code to Machine Code
JVM obtains the bytecode stream from the .class file in the form of series of
instruction. Each instruction consists of a one-byte opcode (a valid and understandable
command which tells the JVM what to do) and zero or more operands, which are
required to complete the opcode.
Self-Instructional
Material 33
Java and the Internet
NOTES
Some of the main components of JVM are stack, registers, garbage-collection heap and
method area.
Stack: JVM stacks are similar to the stacks used in C or other conventional
languages. It consists of frames that hold the state of Java method invocation. It
holds the local variables, parameters, its return value and the intermediate results.
JVM stack can not be manipulated directly and only pushing and popping of
frames can take place. When a method is invoked, the JVM pushes a new frame
into the stack and after the completion of execution of the method the frame is
popped and discarded by the virtual machine. The size of the JVM stack can be
fixed or may dynamically increase and decrease according to the requirement.
Registers: JVM uses different types of registers to control the stacks. Some of
the important JVM registers are:
o Optop: It points to the top of operand stack.
o Frame: It points to the current execution environment.
o Vars: It points to the local variables.
o Program counter: It keeps record of the next instruction in a program to
be executed.
Garbage-collection heap: Heap is a free memory space used for allocations to
the variables like arrays, class instances, etc., at runtime. Whenever memory is
allocated with the help of new operator, that memory space is allocated from the
heap. Heap provides an automatic storage management system known as garbage-
collection heap. Whenever there are objects which are no longer referenced,
then the runtime environment automatically reclaims the memory occupied by the
objects. Size of the heap may be fixed or may increase or decrease according to
the requirement.
Method area: Method area is a storage area for the compiled code. Although
the method area is a part of heap, there is no specific area where it exists. This
feature makes JVM more portable and secure. Size of the method area may be
fixed or may increase or decrease according to the requirement. Method area is
used to store:
o Runtime constant pool
o Field information
o Method information
o Code for methods and constructors
o Special methods that are used in class and instance initialization.
o Interface type initialization
The primitive data types that can be handled by the JVM are byte(8 bits), char(16
bits), short(16 bits), int(32 bits), float(32 bits), long(64 bits), double(64 bits).
3.7 JAVA DEVELOPMENT KIT (JDK)
JDK consists of various tools that are used to develop and execute Java programs. The
tools included in JDK are listed in Table 3.1.
Self-Instructional
34 Material
Java and the Internet
NOTES
Table 3.1 Tools in Java Development Kit
Tool Function
javac Java compiler that converts source code to Java bytecode
java Java interpreter that interprets class files generated by java compiler
and converts it to machine code
javadoc Document generator which automatically generates documentation
form source code
javah Generates C headers and a stub generator used for writing native
methods
javap The class file disassembler which enables to convert bytecode files to
a program description
jdb Java debugger which helps in tracking errors in the program
appletviewer Used for running and debugging Java applets without a web browser
3.8 A FIRST LOOK AT JAVA PROGRAM
Let us start learning Java with a simple Java program that prints a string on the screen.
Example 3.1: A simple Java program
class Sample
{
public static void main (String args[])
{
System.out.println(Welcome to Java Programming);
System.out.println(Its easy and simple.);
}
}
Though this program is the simplest one, it includes the basic features that every
Java program has. Let us now look at the features one by one.
Class Definition
The first statement class Sample declares a class where class is a keyword and
Sample is the identifier that indicates the name of the class. The opening and closing
curly braces { } enclose the definition of a class.
The Main Statement
The statement public static void main (String args[]) indicates the
main method. This method is the point where the execution of Java program begins.
Since, it is the startup point of any Java program, it is the most essential part of any Java
program.
This statement has keywords, namely, public, static and void. The descriptions
of these keywords are as follows.
public: It is an access specifier which specifies that the main method is
accessible to all other classes.
static: The main method is declared static which specifies that this method
belongs to the entire class. Interpreter use this method before the creation of
objects.
Check Your Progress
6. _________method
replaces destructor
function in Java.
7. Global variables
are supported in
Java. (True or
False)
8. Applets are tiny
programs that can
be downloaded
from the internet
and can be run on
Java compatible
Web browser.
(True or False)
9. _________command
converts the source
code to
intermediate
bytecode.
10. Name some of the
important JVM
registers.
11. What is the role of
garbage-collection
heap?
12. JDK is a set of
various tools used
to develop and
execute java
programs.
(True or False)
Self-Instructional
Material 35
Java and the Internet
NOTES
void: The void keyword specifies that the main method does not return a
value. The pair of parentheses contains the declaration of the parameters of the
methods. In the above statement, the String args[ ] declares a parameter
args, that contains an array of objects of the class type String.
The Output Statement
The statements System.out.println(Welcome to Java
Programming.);
and System.out.println(Its easy and simple.); are used to
display information on the standard output device, that is the println() is a method
of the out object, which is the static member of class System. These statements will
display the following strings on the monitor.
Welcome to Java Programming.
Its easy and simple.
The statements will be printed in separate lines as the method println()
appends a newline character at the end of the string. However, if we use print()
method instead of println() newline character is not appended at the end of the
string. Note that like C++, every statement in Java must end with a semicolon.
3.9 RUNNING JAVA APPLICATIONS
A program can be created using any text editor. Nowadays, there are several text
editors available for writing programs like Notepad, Jcreator, etc. After creating the file,
save the file with the name <filename>.Java. The name of the file must be same
as that of the class name containing the main() method.
Once the file is created, it can be compiled to generate the bytecode using Java compiler
javac as given here.
javac Sample.java
If the source code is error free then the compiler creates a file containing the
bytecode and the file will be named as <filename>.class. In our example, the
name of file will be Sample.class.
Even though after compilation, the source code is converted into its equivalent
bytecode, it cannot be executed. To execute this bytecode, it needs to be converted to
machine code using the interpreter. The command for converting bytecode to machine
code and run it is as follows:
java Sample
After giving this command, the interpreter searches for the main() method in
the source code and starts executing the instructions written in this method and displays
the corresponding output.
3.10 COMMAND LINE ARGUMENTS
Like C++, Java enables to pass arguments to the main() method also. These arguments
are passed by typing them after the program name on the command line. Hence, these
arguments are known as command line arguments. They help in providing data to the
program.
Self-Instructional
36 Material
Java and the Internet
NOTES
As stated earlier, the argument named as args of String type is passed to the
main method. It is this argument which will receive any data passed to the program
through command line.
Example 3.2: A program to demonstrate the use of command line arguments
class CommandLineArg
{
public static void main(String args[])
{
System.out.println(The arguments entered are: );
int a;
for (a=0;a<args.length;a++)
{
System.out.print(args[ + a + ]: );
System.out.println(args[a]);
}
int b=args.length; // returns the number of
arguments
System.out.println(The number of arguments is:
+b);
}
}
The command entered on the command prompt is as follows:
java CommandLineArg Hello! How are you?
The output of the program is as follows:
The arguments entered are:
args[0]: Hello!
args[1]: How
args[2]: are
args[3]: you?
The number of arguments is: 4
3.11 SUMMARY
In this unit, you have learned that:
Java, initially, named Oak was developed by the team headed by James Gosling
at Sun Microsystems of USA in 1991.
Java inherits the syntax of C/C++ and many of the OOPs features of C++. Thus,
one who is familiar with the concepts of object-oriented language can learn Java
with least effort.
Java uses two-stage system as it uses both compiler and interpreter for its program
execution.
Applets are tiny programs that are designed in such a way that they can be
transmitted over the Internet.
Check Your Progress
13. The statement
class sample
declares a class
with name
sample. (True or
False)
14. ________ access
specifier states
that main()
method is
accessible to all
other classes.
15. String args[]
declares a
parameter args
which contains an
array of objects.
(True or False)
16. ___________
statement is used
to display
information on the
standard output
device.
17. What are command
line arguments?
Self-Instructional
Material 37
Java and the Internet
NOTES
Java compiler does not convert source code to machine code rather it converts
source code to a special intermediate code known as bytecode.
The command used for compilation in Java is javac which converts the
corresponding Java file into class file.
Bytecode is generated for the virtual machine that exists only inside the computer
memory known as Java Virtual Machine (JVM).
JDK consists of various tools that are used to develop and execute Java programs.
Some of the tools included in JDK are javac, java, javadoc, javap, etc.
The access specifier public specifies that the main method is accessible to
all other classes.
The void keyword specifies that the main method does not return a value.
3.12 KEY TERMS
Bytecode: It is one of the codes which gets converted to machine code by the
compiler for its program execution.
Native Method: It refers to the facility provided by the Java language to include
the functions of other languages like C and C++.
Architecture-neutral: It is one of the features of Java which helps Java programs
to run on any platform.
Java Compiler: It helps to convert the source code to a special intermediate
code.
Command line arguments: These are arguments which are passed by Java to
the main( ) method.
Java Virtual Machine: It refers to the virtual machine that exists only inside the
computer memory.
3.13 ANSWERS TO CHECK YOUR PROGRESS
1. James Gosling
2. True
3. Compiler, interpreter
4. True
5. run-time
6. finalize
7. False
8. True
9. javac
10. Some of the important JVM registers are:
Optop
Frame
Vars
Program counter
Self-Instructional
38 Material
Java and the Internet
NOTES
11. Heap provides an automatic storage management system known as garbage-
collection heap. Whenever there are objects which are no longer referenced,
then the runtime environment automatically reclaims the memory occupied by the
objects.
12. True
13. True
14. public
15. True
16. System.out.println()
17. Java enables to pass arguments to the main() method also. Command line
arguments are passed by typing them after the program name on the command
line. Hence, these arguments are known as command line arguments.
3.14 QUESTIONS AND EXERCISES
Short-Answer Questions
1. Why is Java called an object-oriented language?
2. What are applets?
3. What is the benefit of multithreaded programming?
4. What is the function of javap?
Long-Answer Questions
1. Explain all the tools of Java Development Kit along with their functions.
2. Mention some of the differences between Java and C++.
3. Explain the steps involved in running Java applications.
4. Explain all the basic features of Java in detail.
Self-Instructional
Material 39
Programming
Elements of Java
NOTES
UNIT 4 PROGRAMMING ELEMENTS
OF JAVA
Structure
4.0 Introduction
4.1 Unit Objectives
4.2 Character Set
4.3 Tokens
4.3.1 Keywords
4.3.2 Identifiers
4.3.3 Constants
4.3.4 Operators
4.3.5 Punctuators
4.4 Structure of a Java Program
4.5 Data Types
4.5.1 Primitives Data types
4.5.2 Non-Primitive Data types
4.6 Variables
4.7 Type Casting
4.8 Operators and Operations
4.8.1 Arithmetic Operators
4.8.2 Increment and Decrement Operators
4.8.3 Relational Operators
4.8.4 Logical Operators
4.8.5 Conditional Operator
4.8.6 Assignment Operators
4.8.7 Other Operators
4.8.8 Operators Precedence and Associativity
4.9 Summary
4.10 Key Terms
4.11 Answers to Check Your Progress
4.12 Questions and Exercises
4.0 INTRODUCTION
In any programming language, writing even an elementary program requires the knowledge
and clear understanding of various data types, variables, constants and operators provided
by that language. All these constitute the most basic elements of a language which are
combined to form an instruction and a set of these instructions constitute a program. In
this unit, you will learn about these basic programming elements of Java.
4.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Discuss the character set and different tokens supported by Java
Describe the structure of a Java program
Discuss various primitive and non-primitive data types supported by Java
Self-Instructional
40 Material
Programming
Elements of Java
NOTES
Explain how to declare, initialize and assign values to a variable
Describe type casting
Explain the different types of operators and the operations that can be performed
4.2 CHARACTER SET
A character set can be defined as a set of characters that either individually or in
combination, represent information. Unlike other programming languages like C and
C++, Java uses a standard known as unicode to define characters. Unicode is a 16 bit
character code set which defines all of the characters available in all human languages
like English, Hindi, French, German, Chinese, Japanese, etc. This makes Java a worldwide
programming language. However, the characters of many languages can be represented
using the standard 8 bit character set (ASCII characters) which include letters, digits
and punctuation marks.
4.3 TOKENS
A token is defined as the smallest unit of a program. When a program is compiled, the
compiler scans the source code and parses it into tokens to find the syntax errors. Java
tokens are broadly classified into keywords, identifiers, constants, operators and
punctuators.
4.3.1 Keywords
Keywords are the predefined words that have special significance in any language.
Every keyword is reserved for a specific purpose and hence cannot be used as user-
defined names (identifiers). There are various keywords in Java, which are listed in
Table 4.1.
Table 4.1 Java Keywords
Keywords
abstract const final interface short transient
assert continue finally long static try
boolean default for native strictfp void
break do goto new super volatile
byte double if package switch while
case else instanceof private synchronized
catch enum implements protected this
char extends import public throw
class float int return throws
Notes: The keywords const and goto are reserved words but they are not used.
4.3.2 Identifiers
Identifiers are the names given to uniquely identify various programming elements like
variables, arrays, methods, classes, objects, packages, interface and so on. While
defining identifiers in Java, programmers must follow the rules listed below.
Self-Instructional
Material 41
Programming
Elements of Java
NOTES
An identifier must be unique in a program.
Alphabets, digits, underscore and dollar sign characters can be used in an identifier.
An identifier must not start with a digit.
An identifier in upper case is different from that in lower case.
An identifier must not contain other characters such as *, ; and white space
characters (tabs, space and newline).
Some valid and invalid identifiers in Java are listed here.
Pol78_ddm //valid
hh$gl //valid
_78hhvt4 //valid
902gt1 //invalid as it starts with a digit
Tyy;ui8 //invalid as it contains the ; character
for //invalid as it is a Java keyword
Fg026 neo //invalid as it contains spaces
4.3.3 Constants
Constants, also known as literals, are the values that a program cannot alter during its
execution. For example, 391, Byron, 51.072 and p are all constants. Based on
the type of value (data), Java constants are broadly classified into four categories, namely,
numeric constants, character constants, string constants and boolean constants.
Numeric Constants
Numeric constants refer to the numbers consisting of a sequence of digits (with or
without decimal point) that can be either positive or negative. By default, numeric constants
are positive. Numeric constants can be further classified as integer constants and
floating-point constants which are listed in Table 4.2.
Table 4.2 Types of Numeric Constants
Type Description Example
Integer Constants Integer constants refer to integer-valued
numbers. Integer constants can be represented
by three different number systems namely,
decimal (base 10), octal (base 8) and
hexadecimal numbers (base 16). The octal
constants are preceded by a 0 (zero) and
hexadecimal constants are preceded by a 0x or
0X.
54, -646, 01612,
0x38A
Floating Point Constants Floating-point constants refer to the real
numbers, that is, the numbers with a decimal
point. Floating-point constants are also written
in the floating-point notation in which the
constant is divided into a mantissa and an
exponent. Floating point constants default to
double precision, so we should append an F or
f to the constant in order to specify a float
constant.
64.23f, -74.32f,
537E-9f, 15e-3f
Note: Use of special characters like comma ,, semicolon ;and question mark ?
are not permitted in numeric constants.
Self-Instructional
42 Material
Programming
Elements of Java
NOTES
Character Constants
Character constants refer to a single character enclosed in single quotes (). The
examples of character constants are f, M, 8, &, etc. All character constants are
internally stored as integer value.
Character constants can represent either the printable characters or the non-
printable characters. The examples of printable character constants are a, 5, #,
;, etc. However, there are a few character constants that cannot be included in a
program directly through a keyboard such as backspace, new line and so on. These
character constants are known as non-printable constants and are included in a program
using the escape sequences. An escape sequence refers to a character preceded by
the backslash character (\). Some of the escape sequences used in Java are listed in
Table 4.3.
Table 4.3 Escape Sequences
Escape Sequences Character Constants
\b Backspace
\f Form feed
\n Newline (Linefeed)
\r Carriage return
\t Tab
\ Single quote
\ Double quote
\\ Backslash
String Constants
String constants refer to a sequence of any number of characters enclosed in the
double quotes (). The characters can be alphabets, digits, special characters and blank
spaces. The examples of string constants are hello java, 2009, !...?, 6+9,
Y, etc.
Boolean Constants
Boolean constants can represent only two values, true and false. In Java, there is
no numerical representation for these values, that is, true is not equal to 1 and false
is not equal to 0.
4.3.4 Operators
Operators are the symbols which perform operations (such as addition, subtraction,
multiplication etc.) on various data items to produce a result. These data items on which
operators act are known as operands. For example, in a*b, a and b are operands and
* is an operator.
4.3.5 Punctuators
Punctuators, also known as separators, are the symbols that define the structure of a
program by dividing and arranging a set of codes. The various punctuators defined are
braces { }, brackets [ ], colon :, comma ,, period ., semicolon ; and parentheses
( ).
Check Your Progress
1. In Java,_______ is
a 16 bit character
set which defines
characters found in
all human
languages.
2. Why do we need to
append an f or F
to a floating point
constant?
3. A keyword can be
used as an
identifier.
(True or False)
4. Briefly state the
rules for defining
an identifier in
Java.
5. _____is the
starting point of a
Java program.
6. Which of the
following is an
invalid identifier?
(a) pq_hr
(b) void
(c) na60f
(d) t$ggl
Self-Instructional
Material 43
Programming
Elements of Java
NOTES
4.4 STRUCTURE OF A JAVA PROGRAM
The Java program structure is divided into various sections, namely, documentation
section, package statement, import statements, interface statements, class definitions
and main method class (see Figure 4.1).

Documentation Section

Package Statement

Import Statements

Interface Statements

Class Definitions

Main Method Class
Figure 4.1 Java Program Structure
These sections are discussed as follows:
Documentation Section: Comments are vital elements of a program that are
used to increase its readability and describe its functionality. They may also include
information like program name and the author of the program, etc.
Package Statement: It is the first statement in Java program that tells the compiler
that all the classes defined in the file belong to this package. For example, consider
this statement.
package employee;
Here, employee is the name of the package. It is not necessary that our classes
are part of package, so this statement is optional.
Import Statements: It allows us to access a class which belongs to some other
package. For example, consider this statement.
import employee.EName;
Here, employee is the name of the package and EName is the class which we
want to access. There can be a number of import statements in a program.
Interface Statements: An interface is way for implementing multiple inheritance
in Java. It is just like a class but contains only method declarations.
Class Definitions: Class is the most important element of a program. A program
may consist of any number of class definitions.
Main Method Class: It is an essential part of a Java program as it contains the
main method which is the starting point of a program. Inside the main method
class, the objects of several classes can be created, accessed and manipulated.
Once all the instructions in the main method are executed, the control is transferred
out of the class thus terminating the entire program.
Self-Instructional
44 Material
Programming
Elements of Java
NOTES
4.5 DATA TYPES
A data type determines the type and the operations that can be performed on the data.
Java provides various data types and each data type is represented differently within the
computers memory. The type of data selected by a programmer depends on the particular
application. The various data types provided by Java are categorized into primitive data
types and non-primitive data types. (see Figure 4.2).

Data Types
Primitive
Data types
Non-primitive
Data types
Classes Arrays Interface
Integer
Floating-point Character Boolean
Figure 4.2 Data Types
4.5.1 Primitives Data Types
Primitive data types also known as built-in data types are the fundamental data types
provided by a programming language. In Java, primitive data types include integer,
floating point, character and boolean.
Integer Type
The integer data type is used to store integers like 4, 42, 5233, -32, -745. Java
supports four types of integers namely, byte, short, int and long. The default
value of these integer types is 0. There is no concept of unsigned integer in Java. The
various integer data types with their size and range are listed in Table 4.4.
Table 4.4 Size and Range of Integer Types
Type Size(bytes) Range
byte One -128 to 127
short Two -32,768 to 32,767
int Four -2,147,483,648 to 2,147,483,647
long Eight -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Note: It is recommended to use smaller data types whenever possible. This is
because larger the data type we choose, more time the program will take for
execution.
Floating Point Type
A floating point data type is used to store real numbers such as 3.28, 64.755765, -
8.01, -24.53. Java supports two floating point data types, namely, float and
double.
Self-Instructional
Material 45
Programming
Elements of Java
NOTES
float: The float type represents a single-precision number. Single precision
occupies lesser space than double precision but becomes inaccurate when the
values are large. For example, it can be used to represent value of marks of the
students. The default value of float data type is 0.0f.
double: The double type specifies a double-precision number. It is the best
choice when we need to store large-valued numbers. For example, it can be used
when we want to use mathematical functions like sin(), cos(), sqrt().
The default value of double data type is 0.0d.
The various floating point data types with their size and range are listed in
Table 4.5.
Table 4.5 Size and Range of Floating Point Types
Type Size(bytes) Range
float Four 3.4e-038 to 3.4e+038
double Eight 1.7e-308 to 1.7e+308
Character Type
The character data type is used to store single character enclosed in single quotes. It is
represented by using char keyword. It occupies 16 bits of memory. The range of the
character data type is 0 to 65,536. The default value of char data type is null
character.
Boolean Type
The boolean data type can hold only boolean values, that is, either true or false. The
keyword boolean is used to denote the boolean data type. The default value of
boolean data type is false.
4.5.2 Non-Primitive Data types
Non-primitive data types (user-defined data types) also known as reference types are
derived from the primitive data types. In Java, these include classes, interface and
arrays.
Note: The non- primitive data types classes and arrays are discussed in detail in
the later chapters.
4.6 VARIABLES
A variable is an identifier that represents a memory location that is used to store data
value. Data stored at a particular location can be accessed using the variable name. The
value of a variable can be changed anytime during the program execution. The variable
name we choose must be meaningful so as to understand what it represents in the
program.
Declaring Variables
Variables must be declared in a program before they are used. The declaration of a
variable informs the compiler, the specific data type to which a variable is associated
and allocates sufficient memory for it.
Self-Instructional
46 Material
Programming
Elements of Java
NOTES
The syntax for declaring a variable is
data_type variable_name;
For example, a variable a of type int can be declared using this statement.
int a;
At the time of the variable declaration, more than one variable of the same data type can
be declared in a single statement. For example, consider this statement.
int x, y, z;
Initializing Variables
Declaration of variables allocates memory for variables but it does not store any data at
the time of declaration. To store data in the variables, they need to be initialized. For
example, consider these statements.
int i;
i=10;
Here, a variable i of the integer type is declared and the value 10 is assigned to it. We
can combine both the statements into a single statement as follows
int i=10;
Besides initializing the variable with the constant values, variables can also be
initialized at run-time using expressions. Initialization of variables at run-time is known
as dynamic initialization.
Example 4.1: A program to demonstrate initialization of variable
public class dynamic_initializaton
{
public static void main(String[] args)
{
int x=40,y=40,z=10; //initialization with constant
values
int result=(x*y)+z; //dynamic initialization
System.out.println(The value of z is:+result);
}
}
The output of the program is
The value of z is:1610
Receiving input through keyboard
Variables can also be given values interactively through the keyboard using the
readLine() method.
Example 4.2: A program to demonstrate reading data from the keyboard
//importing package for using DataInputStream class
import java.io.*;
public class ReadingData
{
public static void main(String[] args)
{
Self-Instructional
Material 47
Programming
Elements of Java
NOTES
DataInputStream in=new DataInputStream(System.in);
int num1=0;
float num2=0;
try
{
System.out.println(Enter integer value);
num1=Integer.parseInt(in.readLine());
System.out.println(Enter float value);
num2=Float.valueOf(in.readLine()).floatValue();
}
catch(Exception e)
{
}
System.out.println(The integer value is +num1);
System.out.println(The float value is +num2);
}
}
The output of the program is
Enter integer value
4
Enter float value
6.7
The integer value is 4
The float value is 6.7
The method readLine() of class DataInputStream is used to read string
from the keyboard which is then converted to the corresponding data type, int and
float. To handle the error which may occur while reading data from the keyboard, we
have provided try and catch statements. Error handling will be discussed in detail in
Unit 10.
4.7 TYPE CASTING
While programming we might come across some situations where a value of one data
type needs to be stored into a variable of another data type. If both the data types are
compatible and the data type of the target variable is large enough to store the value of
the source variable, Java automatically converts the source type into target type. This is
known as automatic type conversion. For example, the value of int data type can
be assigned to a variable of long data type since long is larger than int. This type
of conversion in which data of smaller type is assigned to a larger type is called widening
conversion.
However, if the target type is smaller than the source type, conversion cannot be
performed automatically. For example, the value of int data type cannot be assigned to
a variable of byte type. For such conversion, Java provides a mechanism known as
type casting. Type casting refers to the type conversion that is performed explicitly.
Self-Instructional
48 Material
Programming
Elements of Java
NOTES
The syntax for type casting is
data_type variable1 = (data_type) variable2;
where,
data_type is the data type
variable1 is the target variable
variable2 is the source variable
For example, consider these statements.
int x = 20;
byte y = (byte) x;
In these statements, type casting is performed to convert int data type to byte
data type.
Following points should be kept in mind while type casting.
All the integer data types can be cast to any other data type except boolean.
Casting into smaller data type may lead to loss of data.
Casting a floating point value to an integer type may result in truncation of the
fractional part.
Example 4.3: A program to demonstrate type casting
class ExampleTypecast
{
public static void main(String[] args)
{
byte b = 20;
short s = 26;
int i = 123456789;
float f = 3.98f;
System.out.println(The existing variables and their
values are:);
System.out.println(b=+b);
System.out.println(s=+s);
System.out.println(i=+i);
System.out.println(f=+f);
System.out.println(The existing variables and their
values after conversion are:);
System.out.println( );
// type conversion
int i1=(int)b; // conversion from byte to int
short s1=(short)b; // conversion from byte to short
Self-Instructional
Material 49
Programming
Elements of Java
NOTES
short s2=(short)i; // conversion from int to short
int i2 =(int)f; // conversion from float to int
System.out.println((int)b: +i1);
System.out.println((short)b: +s1);
System.out.println((short)i: +s2);
System.out.println((int)f: +i2);
}
}
The output of the program is
The existing variables and their values are:
b=20
s=26
i=123456789
f=3.98
The existing variables and their values after conversion
are:
(int)b: 20
(short)b: 20
(short)i: -13035
(int)f: 3
4.8 OPERATORS AND OPERATIONS
As stated earlier, operators are the symbols which perform operations on various data
items known as operands. For example, in a + b, a and b are operands and + is an
operator. Note that to perform an operation, operators and operands are combined together
forming an expression. For example, to perform an addition operation on operands a
and b, the addition (+) operator is combined with the operands a and b forming an
expression.
Depending on the function performed, the Java operators can be classified into
various categories. These include arithmetic operators, increment and decrement
operators, relational operators, logical operators, conditional operator, assignment
operators, bitwise operators and special operators.
4.8.1 Arithmetic Operators
Arithmetic operators perform the basic arithmetic operations on operands. They can
work on any built-in data type of Java except on boolean type.
Java provides various arithmetic operators that are, +(addition or unary plus), -
(subtraction or unary minus), *(multiplication), /(division) and %(modulus). For example,
some of the expressions which involve arithmetic operators are x + y, x y, x * y,
x / y and x % y. When the unary minus operator is used with a single operand, the
operand is multiplied by -1.
Check Your Progress
7. The default value
of a boolean data
type is_______.
8. What are the four
types of integer in
Java?
9. Define variable.
10. Initializing a
variable at run-time
is called dynamic
initialization.
(True or False)
11. The process of
explicitly
converting one data
type to another
data type is
called______.
Self-Instructional
50 Material
Programming
Elements of Java
NOTES
Expressions formed by using arithmetic operators can be of these types:
Integer expression: The arithmetic expression where both the operands are
integers is called an integer expression.
Real expression: The arithmetic expression where both the operands are real is
called real expression.
Mixed mode expression: The expression is mixed mode if one operand is real
and the other is integer. In this case, the integer operand is converted to real and
the result is also of type real.
Note: Unlike C and C++, the modulus operator can be applied to the floating
point data type also in Java.
4.8.2 Increment and Decrement Operators
Java provides two special unary arithmetic operators, namely the increment operator
(represented by ++) and the decrement operator (represented by ). The operator ++
increases the value of operand by 1 and the operator decreases the value of operand
by 1.
The increment and decrement operators can be used in two forms which are as follows:
Prefix form: In this form, the increment or the decrement operator precedes its
operand. The prefix increment operator is represented as ++operand and the
prefix decrement operator is represented as operand. The prefix increment
or the prefix decrement operator increments or decrements the value of an operand
respectively before its value is used in an expression.
To understand prefix operators, consider this example.
Example 4.4: Evaluate these statements
x=10;
y=++x;
z=x;
In this example, the statement y=++x first increments the value of x by 1 and
then assigns the incremented value to y. Similarly, the decrement operator is used
to decrement the value of x by 1 and then assign the decremented value to z.
Thus, the value of y and z are 11 and 10 respectively.
Postfix form: In this form, the increment or the decrement operator succeeds its
operand. The postfix increment operator is represented as operand++, and the
postfix decrement operator is represented as operand. The postfix increment
or the decrement operator increments or decrements the value of an operand,
respectively after using it in the expression.
To understand postfix operators, consider this example.
Example 4.5: Evaluate these statements
x=10;
y=x++;
z=x;
Self-Instructional
Material 51
Programming
Elements of Java
NOTES
In this example, the statement y=x++ first assigns the value of x to y and then
increments the value of x by 1. Similarly, the statement z=x assigns the value of x to
z and then decrements the value of x by 1. Thus, the value of y and z are 10 and 11,
respectively.
4.8.3 Relational Operators
Relational operators are used for comparing two values or expressions. The various
relational operators provided by Java are less than <, less than or equal to <=, greater
than >, greater than or equal to >=, equal to == and not equal to != operator.
They return values of boolean type, that is, either true or false. For example, consider
two variables a and b having values 20 and 30 respectively. In this case, the expression
a<b returns true whereas the expression a>b returns false.
The operators == and != are also known as equality operators as they are
used for checking the equality of operands.
Note: All relational operators can work on integer, floating-point and character
data types.
4.8.4 Logical Operators
Logical operators combine expressions and then return true or false. The various
logical operators provided by Java are listed here.
AND (&&) operator: It returns true only if all the expressions evaluate to
true, otherwise it returns false.
OR (||) operator: It returns true if any one or all the expressions evaluate to
true and returns false only if all the expressions evaluate to false.
Negation (!) operator: It returns true if the expression on which it is operating
is false and vice versa.
For example, consider two expressions Exp1 and Exp2. Table 4.6 shows the
result after the logical operators are applied on these expressions.
Table 4.6 Truth Table
Exp1 Exp2 Exp1 && Exp2 Exp1 || Exp2 !Exp1
true true true true false
true false false true false
false true false true true
false false false false true
4.8.5 Conditional Operator
The conditional operator selects a value based on specified condition. Note that the
conditional operator is a ternary operator, that is, this operator involves three operands.
The syntax of the conditional operator is
expression1 ? expression2: expression3
If expression1 is true, then expression2 is evaluated, otherwise
expression3 is evaluated.
Self-Instructional
52 Material
Programming
Elements of Java
NOTES
To understand the working of conditional operator, consider this example.
Example 4.6: Evaluate this statement
(x==5) ? 8 : 9;
In this example, if the value of x is equal to 5, then the expression returns 8,
otherwise the expression returns 9.
4.8.6 Assignment Operators
Assignment operator assigns the value of an expression to a variable. Assignment
operators are of two types, namely, the simple assignment operator and compound
assignment operators.
Simple Assignment Operator
The simple assignment operator assigns the value on its right hand side to the variable on
its left hand side. Note that the left hand side of an assignment expression should be a
variable. It cannot be a constant or an expression. However, the right hand side of an
assignment expression can be a variable, constant or an expression.
To understand the simple assignment operator, consider this example.
Example 4.7: Evaluate this statement
x=8;
In this example, the value 8 is assigned to the variable x.
With the help of the assignment operator, several variables can be assigned a
common value. This is accomplished by using multiple assignments in a single statement.
For example, in the statement x=y=z=5, the value 5 is assigned to the three variable x,
y and z.
Compound Assignment Operators
Java provides compound assignment operators (also known as Java shorthands) which
is in the following form.
v op=exp;
Here, v is a variable, op is the binary operator and exp is an expression. This
form is equivalent to the statement v=v op(exp);
where we need to access v only once.
For example, the expression x=x+6 can be written as x+=6. In this expression,
x is incremented by 6 and then the result is assigned to x. The various compound
assignment operators used in Java are +=, -=, *=, /= and %=.
4.8.7 Other Operators
In addition to the operators discussed, Java supports some other operators which include
bitwise operators and special operators.
Bitwise operators
The bitwise operators are used to manipulate the data values at bit level. This operator
can be applied to all the primitive data types such as long, int, short, char and
Self-Instructional
Material 53
Programming
Elements of Java
NOTES
byte. Various bitwise operators are bitwise AND (&), bitwise OR (!), bitwise exclusive
OR (^), ones complement (~), shift left (<<), shift right (>>), shift right with zero
fill (>>>).
Special Operators
Java provides two special operators namely, instanceof and dot operator (.).
instanceof Operator: The instanceof operator is an operator which is used to
check whether the object belongs to a particular class or not. For example, consider this
statement.
novel instanceof book
This statement returns true if the object novel belongs to the class book,
otherwise, false.
Dot Operator: The instance variables and the methods of a class are accessed through
objects with the help of dot operator. Dot operator links the name of the object with the
name of the variable or method which needs to be accessed. For example, consider
these statements.
obj.name; // accessing instance variable of the class
obj.marks(); // accessing method of the class
Note: The instance variables and the methods are explained in Chapter 06.
4.8.8 Operators Precedence and Associativity
An expression consisting of more than one operator leads to a confusion as to which
operator is to be evaluated first. For example, consider this expression.
a + b * c - d
In this expression, the compiler needs to know which operator is evaluated first. For this,
it is important to determine the precedence and associativity of operators.
Precedence: The order or priority in which various operators in an expression
are evaluated is known as precedence. Every operator in Java has a precedence
associated with it. The operators with a higher precedence are evaluated before
the operators with a lower precedence. For example, multiplication is performed
before addition as the multiplication operator has higher precedence than the
addition operator.
Associativity: The order or priority in which operators of the same precedence
are evaluated is known as associativity. For example, the addition and subtraction
operators have the same precedence. However, addition or subtraction may be
performed on the expression depending upon the order of their occurrence.
The associativity of an operator can be either from left to right or from right to
left. The operators with left to right associativity are evaluated from the left hand side
while the operators with right to left associativity are evaluated from the right hand side.
The precedence and the associativity of Java operators are listed in Table 4.7.
Note that the precedence of operators decreases from top to bottom, that is, the priority
is highest at the top.
Self-Instructional
54 Material
Programming
Elements of Java
NOTES
Table 4.7 Precedence and Associativity of Java Operators
Operators Description Associativity
.
()
[]

Direct member selector
Function Call
Array subscript

Left to right
Left to right
Left to right
-
++
--
!
~
(type)

Unary minus
Increment
Decrement
Logical negation
Ones complement
Casting

Right to left
Right to left
Right to left
Right to left
Right to left
Right to left
*
/
%
Multiplication
Division
Modulus
Left to right
Left to right
Left to right

+
-
Addition
Subtraction
Left to right
Left to right

<<
>>
>>>
Left shift
Right shift
Right shift with zero fill
Left to right
Left to right
Left to right

<
<=
>
>=
instanceof
Less than
Less than or equal to
Greater than
Greater than or equal to
Type comparison
Left to right
Left to right
Left to right
Left to right
Left to right

= =
=!
Equal to
Not equal to
Left to right
Left to right
& Bitwise AND Left to right
^ Bitwise XOR Left to right
| Bitwise OR Left to right
&& Logical AND Left to right
|| Logical OR Left to right
?: Conditional operator Right to left
=
Op=
Assignment Operator
Shorthand assignment
Right to left

Note: The operators in the same row have same precedence.
4.9 SUMMARY
In this unit, you have learned that:
A character set can be defined as a set of characters that either individually or in
combination, represents information. Unlike C and C++, Java uses a standard
known as Unicode to define characters.
Unicode is a 16 bit character code set which defines all of the characters available
in all human languages.
Check Your Progress
12. Which of the
following is an
invalid arithmetic
expression?
(a) 14+20/5
(b) (10/5)*
3+6%2
(c) 64+/8.5
(d) (2+3)*9/3
13. Given a=10, b=2
and c=7, give the
result of the
following logical
expressions.
(a) a>b&&a<c
(b) a>b&&b<c
(c) a>c||b==c
(d) a/b==c|
|a==c
14. Which of these is
an example of
compound
assignment
operator?
(a) a=5
(b) a=b=c=8
(c) a=b+c
(d) a+=b/c
15. ________operator
is used to check
whether an object
belongs to a
specified class.
Self-Instructional
Material 55
Programming
Elements of Java
NOTES
A token is defined as the smallest unit of a program. Java tokens are broadly
classified into keywords, identifiers, constants, operators and punctuators.
Keywords are the predefined words that have special significance in any language.
Every keyword is reserved for a specific purpose and hence cannot be used as
user-defined names (identifiers).
Identifiers are the names given to uniquely identify various programming elements
like variables, arrays, methods, classes, objects, packages, interface and so on.
Constants, also known as literals, are the values that a program cannot alter
during its execution. Java constants are broadly classified into four categories,
namely, numeric constants, character constants, string constants and boolean
constants.
Punctuators, also known as separators, are the symbols that define the structure
of a program by dividing and arranging a set of codes.
The Java program structure is divided into various sections, namely, documentation
section, package statement, import statements, interface statements, class
definitions and main method class.
A data type determines the type and the operations that can be performed on the
data. The various data types provided by Java are categorized into primitive data
types and non-primitive data types.
Primitive data types also known as built-in data types are the fundamental data
types provided by a programming language. In Java, primitive data types include
integer, floating point, character and boolean.
Java supports four types of integer namely, byte, short, int and long. It
supports two floating point data types namely, float and double.
A variable is an identifier that represents a memory location that is used to store
data value. The value of a variable can be changed anytime during the program
execution.
Type casting is the process of explicitly converting one data type to another data
type.
Operators are symbols which represent various operations (such as addition,
subtraction, multiplication, etc.) performed on variables or constants.
Java operators can be classified into various categories. These include arithmetic
operators, increment and decrement operators, relational operators, logical
operators, conditional operators, assignment operators, bitwise operators and
special operators.
4.10 KEY TERMS
Character set: It is a set of characters that either individually or in combination
represent information.
Unicode: It is a 16-bit character code set which defines all of the characters
available in all human languages like English, Hindi, French, German, etc.
Token: It is defined as the smallest unit of a program.
Keyword: It is the predefined word that has special significance in any language.
Self-Instructional
56 Material
Programming
Elements of Java
NOTES
Identifier: It is the name given to uniquely identify various programming elements
like variables, arrays, methods, classes, objects, packages, interface, and so on.
Constants: It is a value that a program cannot alter during its execution.
Operators: They are symbols which perform operations such as addition,
subtraction etc. on various data items to produce a result.
Punctuators: They are symbols that define the structure of a program by dividing
and arranging a set of codes.
Reference type: They are non-primitive data types which are derived from
primitive data types.
Variables: It is an identifier that represents a memory location that is used to
store data value.
Type casting: It refers to the type conversion that is performed explicitly.
Widening conversion: It is a type of conversion in which data of smaller type is
assigned to a larger type.
instanceof operator: It is an operator which is used to check whether the
object belongs to a particular class or not.
Precedence: It is an order or priority in which various operators in an expression
are evaluated.
4.11 ANSWERS TO CHECK YOUR PROGRESS
1. unicode
2. If we do not append f or F to a floating point constant, it defaults to double
precision.
3. False
4. Rules for defining an identifier are:
(i) An identifier must not start with a digit.
(ii) An identifier can contain alphabets, digits, underscore and dollar sign
characters.
(iii) Characters such as *, ; and white spaces cannot be used in an identifier.
(iv) An identifier in uppercase is different from that in lowercase.
5. main()
6. (b)
7. false
8. The four types of integer in Java are int, byte, short and long.
9. A variable is an identifier which represents memory location that is used to store
data value. Data stored at a particular location can be accessed using a variable
name.
10. True
11. type casting
12. (c)
Self-Instructional
Material 57
Programming
Elements of Java
NOTES
13. (a) False (b) True
(c) True (d) False
14. (d)
15. instanceof
4.12 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What are keywords?
2. What are punctuators?
3. What are the different types of Java tokens?
4. What are Boolean constants?
5. What are relational operators?
Long-Answer Questions
1. Describe a Java program structure.
2. What are the various primitive data types in Java? Explain them in detail.
3. What are the different ways of initializing a variable? Explain with example.
4. What is type casting? State a program to demonstrate type casting?
5. Differentiate between the following:
(a) Simple assignment operator and compound assignment operator
(b) instanceof and dot operators
Self-Instructional
Material 59
Control Statements
NOTES
UNIT 5 CONTROL STATEMENTS
Structure
5.0 Introduction
5.1 Unit Objectives
5.2 Selection Statements
5.3 Iteration Statements
5.3.1 The for Loop
5.3.2 The while Loop
5.3.3 The do-while Loop
5.4 Jump Statements
5.5 Labelled Loops
5.6 Summary
5.7 Key Terms
5.8 Answers to Check Your Progress
5.9 Questions and Exercises
5.0 INTRODUCTION
A statement is an instruction given to the computer to perform a specific action. In Java,
a statement can either be a single statement or a compound statement. A single statement
specifies a single action and is always terminated by a semicolon ;. A compound
statement, also known as a block, is a set of statements that are always enclosed within
curly braces {}.
By default, the statements are executed in the same order in which they appear in
the program and each statement is executed only once. However, the serial execution of
statements makes a program inflexible and unsuitable for most of the practical applications.
To make a program more flexible, control statements are used to alter the flow of
control of the program. In Java, the control statements are broadly classified into three
categories, namely, conditional statements, iteration statements and jump statements.
All these control statements are commonly used with the logical tests or test conditions
to alter the flow of control conditionally or unconditionally.
In this unit, you will learn about the various types of control statements.
5.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Understand the different types of control statements in Java
Explain the various types of conditional statements
Discuss the different types of iteration statements
Understand the different types of jump statements
Understand the basic concept of labels
Self-Instructional
60 Material
Control Statements
NOTES
5.2 SELECTION STATEMENTS
Conditional statements, also known as selection statements, are used to make decisions
based on a given condition. If the condition evaluates to true, a set of statements is
executed, otherwise another set of statements is executed.
The if Statement
The if statement selects and executes the statement(s) based on a given condition.
The syntax of the if statement is
For a single statement
if(condition)
statement1;
nextstatement;
For a set of statements
if(condition)
{
statement1;
statement2;
}
nextstatement;
Here, if the condition evaluates to true, then a given set of statement(s) is
executed. However, if the condition evaluates to false, then the given set of statements
is skipped and the program control passes to the statement following the if statement
(Figure 5.1).
Is
condition
true?
nextstatement
statement1
No
Yes
Figure 5.1 Flow of Control in if Statement
The if-else Statement
The if-else statement causes one of the two possible statement(s) to execute
depending upon the result of condition.
Self-Instructional
Material 61
Control Statements
NOTES
The syntax of the if-else statements is
if(condition) //if part
{
statement1;
}
else //else part
statement2;
nextstatement;
Here, the if-else statement comprises two parts, namely, if and else. If
the condition is true, the statements within if part is executed. However, if the condition
is false, the statements within else part is executed (Figure 5.2).
Is
condition
true?
nextstatement
statement1
No Yes
statement2
Figure 5.2 Flow of Control in if-else Statement
Example 5.1: A program to demonstrate the use of if-else statement
class ConditionalStatement
{
public static void main (String args[])
{
int i=5;
if (i > 0)
System.out.println(i is a positive number);
else
System.out.println(i is a negative number);
}
}
Self-Instructional
62 Material
Control Statements
NOTES
The output of the program is
i is a positive number
Nested if-else Statement
A nested if-else statement contains one or more if-else statements. In other
words, if-else statement within another if-else statement is called nested if-
else statement. The if-else statement can be nested in three different ways
which are discussed here.
The if-else statement is nested within the if part.
The syntax is
if(condition1)
{
statement1;
if(condition2)
statement2;
else
statement3;
}
else
statement4;
nextstatement;
The if-else statement is nested within the else part.
The syntax is
if (condition1)
statement1;
else
{
statement2;
if (condition2)
statement3;
else
statement4;
}
nextstatement;
The if-else statement is nested within both the if and the else parts.
The syntax is
if(condition1)
{
statement1;
if(condition2)
statement2;
else
statement3;
}
Self-Instructional
Material 63
Control Statements
NOTES
else
{
statement4;
if(condition3)
statement5;
else
statement6;
}
nextstatement;
The if-else-if Ladder
The if-else-if ladder, also known as the if-else-if staircase, has an if-
else statement within the outermost else statement. The inner else statement can
further have other if-else statements.
The syntax of the if-else-if ladders is
if (condition1)
statement1;
else
if (condition2)
statement2;
else
if (condition3)
statement3;
else
statement4;
Third
if-else
nextstatement;
Second
if-else
First
if-else
Example 5.2: A program to demonstrate if-else-if statement
import java.io.*;
public class Grade
{
public static void main(String[] args)
{
int marks=0;
DataInputStream cin=new DataInputStream(System.in);
try
{
System.out.print(Enter the marks: );
//reading integer from keyboard
marks=Integer.parseInt(cin.readLine());
if(marks>90)
System.out.println(Grade is A);
else
if(marks>75)
Self-Instructional
64 Material
Control Statements
NOTES
System.out.println(Grade is B);
else
if(marks>60)
System.out.println(Grade is C);
else
System.out.println(Grade is D);
}
catch(Exception e)
{}
}
}
The output of the program is
Enter the marks: 78
Grade is B
Conditional Operator as an Alternative
The conditional operator ? : selects one of the two values or expressions based on a
given condition. Due to this decision-making nature of the conditional operator, it is
sometimes used as an alternative to if-else statements. Note that the conditional
operator selects one of the two values or expressions and not the statements as in the
case of an if-else statement. In addition, it cannot select more than one value at a
time, whereas if-else statement can select and execute more than one statement at
a time. For example, consider this statement.
max=(x>y ? x : y)
This statement assigns maximum of x and y to max.
The switch Statement
The switch statement selects a set of statements from the available sets of statements.
The switch statement evaluates the value of an expression and compares it with the
list of integer, character, short or byte constants. It should be noted that the case constants
must be compatible with the expression type. When a match is found, all the statements
associated with that constant are executed (Figure 5.3).
The syntax of the switch statement is
switch(expression)
{
case <constant1>: statement1;
[break;]
case <constant2>: statement2;
[break;]
case <constant3>: statement3;
[break;]
[default: statement4;]
}
nextstatement;
Self-Instructional
Material 65
Control Statements
NOTES
Is
constant1=
expression?
expression
statement1
Is
constant2=
expression?
Is
constant3=
expression?
statement2
statement3
nextstatement
No
No
Yes
Yes
Yes
No
Figure 5.3 Flow of Control in switch Statement
The Java keywords case and default provide the list of alternatives. Note
that it is not necessary for every case label to specify a unique set of statements. The
same set of statements can be shared by multiple case labels.
The keyword default specifies the set of statements to be executed in case
no match is found. Note that there can be multiple case labels but there can be only
one default label. However, default is an optional statement.
The break statements in the switch block are optional. However, it is used in
the switch block to prevent a fall through. Fall through is a situation that causes the
execution of the remaining cases even after a match has been found. In order to prevent
this, break statements are used at the end of statements specified by each case and
default. This causes the control to immediately break out of the switch block and
execute the next statement.
Similar to if and if-else statements, switch statements can also be nested
within one another. A nested switch statement contains one or more switch statements
within its case label or default label (if any).
Note: Switch statement cannot be used for testing floating-point values or string values.
Example 5.3: A program to demonstrate the use of switch statement
class SwitchStatement
{
public static void main(String args[])
{
Self-Instructional
66 Material
Control Statements
NOTES
int x=2;
switch(x)
{
case 1: System.out.println(Day is Monday);
break;
case 2: System.out.println(Day is Tuesday);
break;
case 3: System.out.println(Day is Wednesday);
break;
case 4: System.out.println(Day is Thursday);
break;
case 5: System.out.println(Day is Friday);
break;
case 6: System.out.println(Day is Saturday);
break;
case 7: System.out.println(Day is Sunday);
break;
default: System.out.println(Invalid option!);
}
}
}
The output of the program is
Day is Tuesday
In this example, since the value of x is 2 therefore the message Day is Tuesday is
displayed. In case the value of x is 8, the output Invalid option! is displayed.
5.3 ITERATION STATEMENTS
The statements that cause a set of statements to be executed repeatedly either for a
specific number of times or until some condition is satisfied are known as iteration
statements. That is, as long as the condition evaluates to true, the set of statement(s)
is executed. The various iteration statements used in Java are for loop, while loop and
do-while loop.
5.3.1 The for Loop
The for loop (Figure 5.4) is one of the most widely used loops in Java. The for loop
is a deterministic loop, that is, the number of times the body of the loop is executed is
known in advance.
The syntax of the for loop is
for(initialize; condition; update)
{
//body of the for loop
}
Check Your Progress
1. Conditional
statements are also
known as
____________
statements.
2. The set of
statements in the
else part of the if-
else statement are
executed when the
condition evaluates
to
_____________.
3. The
____________
operator can be
used as an
alternative to if-
else statement.
4. A switch block can
have more than one
default label. (True
or False)
5. The
____________
statement is used
to immediately exit
from the switch
block.
6. Which of the
following is an
invalid switch
expression?
(a) int
choice=4;
(b) char
choice=x;
switch(choice)
switch(choice)
(c) String
choice=Monday;
(d) short
choice=5;
switch(choice)
switch(choice)
Self-Instructional
Material 67
Control Statements
NOTES
initialize
Is
condition
true?
statement
update
nextstatement
No
Yes
Figure 5.4 Flow of Control in for Loop
The initialize expression in for loop can initialize one or more control variables.
A for loop can also update more than one variable in its update expression. Note that
initialize, condition and update are optional expressions and are always
specified in parentheses. All the three expressions are separated by semicolons. We can
also create an infinite loop by excluding all the three expressions as follows:
for( ; ; )
{
.
.
}
Example 5.4: A program to display a count down using for loop
class UpdateStatement
{
public static void main(String args[])
{
for (int i=10;i>=1;i)
{
System.out.print( +i);
}
System.out.println();
System.out.print(This is an example of for loop);
}
}
Self-Instructional
68 Material
Control Statements
NOTES
The output of the program is
10 9 8 7 6 5 4 3 2 1
This is an example of for loop
for loop using comma operator
for loop allows multiple variables to control the loop using comma operator. That is,
two or more variables can be used in the initialize and the update part of the
loop. For example, consider this statement.
for (i=1,j=50;i<10;i++,j)
This statement initializes two variables, namely i and j and updates them. Note
that for loop cannot have more than one condition separated by comma.
5.3.2 The while Loop
The while loop (Figure 5.5) is used to perform looping operations when the number of
iterations is not known in advance. That is, unlike for loop, the while loop is non-
deterministic in nature.
The syntax of the while loop is
while(condition)
{
// body of the while loop
}
initialize
Is
condition
true?
statement
update
nextstatement
No
Yes
Figure 5.5 Flow of Control in while Loop
The following points should be noted about the while loop:
Unlike for loops where explicit initialize and update expressions are
specified, while loops do not specify any explicit initialize and update
expressions. This implies that the control variable must be declared and initialized
before the while loop and needs to be updated within the body of the while
loop.
Self-Instructional
Material 69
Control Statements
NOTES
The while loop executes as long as condition evaluates to true. If
condition evaluates to false, then the body of while loop does not execute.
Example 5.5: A program to determine the sum of first n consecutive positive integers
import java.io.*;
public class Sum
{
public static void main(String[] args)
{
int n;
int sum=0;
DataInputStream cin=new DataInputStream (System.in);
try
{
System.out.print(Enter n: );
//reading input from the user
n=Integer.parseInt(cin.readLine());
//loop to calculate the sum
while(n>0)
{
sum=sum+n;
n=n-1;
}
System.out.print(The sum is + sum);
}
catch(Exception e)
{}
}
}
The output of the program is
Enter n: 7
The sum is 28
5.3.3 The do-while Loop
As discussed earlier, in a while loop, the condition is evaluated at the beginning of the
loop and if the condition evaluates to false, the body of the loop is not executed even
once. However, if the body of the loop is to be executed at least once, no matter whether
the initial state of the condition is true or false, the do-while loop is used. This
loop places the condition to be evaluated at the end of the loop (Figure 5.6).
The syntax of the do-while loop is
do
{
//body of do-while loop
}
while(condition);
Self-Instructional
70 Material
Control Statements
NOTES
Is
condition
true?
statement
Yes
nextstatement
No
Figure 5.6 Flow of Control in do-while Loop
Example 5.6: A program to calculate the sum of an Arithmetic Progression (AP)
class APSeries
{
public static void main(String args[])
{
int first_term=1;
int number_of_terms=5;
int term=0;
int i=1;
int common_difference=2;
int sum=0;
System.out.print(The terms are: );
do
{
term =first_term+(i-1)*common_difference;
sum+=term;
System.out.print( +term);
++i;
}
while(i<=number_of_terms);
System.out.println();
System.out.println(The sum of A.P is: +sum);
}
}
The output of the program is
The terms are: 1 3 5 7 9
The sum of A.P is: 25
Self-Instructional
Material 71
Control Statements
NOTES
Nested Loops
Nested loops are the loops present within the body of another loop. All the three loops
(for, while and do-while) can be nested.
Example 5.7: A program to demonstrate the nested for loop
class NestedLoop
{
public static void main(String args[])
{
int a,b;
for(a=0;a<5;a++) //outer loop
{
for(b=a;b<5;b++) //inner loop
{
System.out.print(*);
}
System.out.println();
}
}
}
The output of the program is
*****
****
***
**
*
5.4 JUMP STATEMENTS
Jump statements are used to alter the flow of control unconditionally. That is, jump
statements transfer the program control unconditionally. The jump statements defined in
Java are break, continue and return.
The break Statement
The break statement is extensively used in loops and switch statements. It immediately
terminates the loop or the switch statement, bypassing the remaining statements. The
control then passes to the statement that immediately follows the loop or the switch
statement. A break statement can be used in any of the three Java loops. In case of
nested loops, the break will exit the only the single loop, that is, the loop in which it is
placed.
The continue Statement
The continue statement is used to continue the loop with its next iteration. In other
words, it skips any remaining statements in the current iteration and immediately passes
the control to the next iteration. It does not terminate the loop (as in the case of break
statements) rather it only terminates the current iteration of the loop. Like a break
statement, a continue statement can be used in any of the three loops.
Check Your Progress
7. The control
statement that
executes a set of
statements
repeatedly based
on a condition is
known as an
____________
statement.
8. Declaration or
initialization of
more than one
variable is allowed
in a for loop. (True
or False)
9. What is the
difference between
while and do-
while loop?
10. Placing a loop
within the body of
another loop is
known as
____________ of
loops.
Self-Instructional
72 Material
Control Statements
NOTES
The return Statement
The return statement is used to transfer the control out of the method explicitly. It
transfers the control back to the caller and terminates the method in which it is present.
When the return statement is encountered in the main() method, it transfers the
control back to the Java run-time system and terminates the program execution.
Example 5.8: A program to add the factors of a number using break and continue
statements
class Jump
{
public static void main(String args[])
{
int factor=0, number=10, sum=0;
System.out.println(Number= +number);
while(true)
{
factor++;
if(factor>number)
break;
if(number%factor!=0)
continue;
sum=sum+factor;
}
System.out.println(Sum of factors= +sum);
if(sum>0)
return;
System.out.println(This statement is not executed);
}
}
The output of the program is
Number=10
Sum of factors=18
5.5 LABELLED LOOPS
As discussed earlier, break and continue statements allow the programmer to
break out of the loop. However, they do not allow you to simply jump to another part of
the program or out of the nested loop or switch statement. Java allows to jump from
one block of statement to another with the help of labels. A label is an identifier which
must follow the rules for naming identifiers in Java. It can be placed before the block of
statements or loop followed by a colon (:). For example, consider this statement.
LabelName: for( ; ; )
{
.
.
}
Self-Instructional
Material 73
Control Statements
NOTES
The break statement passes the control out of the innermost loop or the innermost
switch statement and the continue statement continues with the next iteration of
the innermost loop only. However, with the help of labels, break statement can be used
to cause the control to jump out of the outer loop or switch statement. For example,
consider these statements.
outerloop: for(i=0;i<5;i++)
{
innerloop: for(j=1;j<5;j++)
{
System.out.println(*);
if(i=j)
break outerloop;
.
.
}
}
In this case, the break statement placed inside the innerloop will force the
control to jump out of both the inner and outer loops. Similarly, with the help of labels,
continue statement can be used to continue with the next iteration of the outer loop.
Example 5.9: A program to demonstrate the use of continue statement in a labelled
loop
class LabelExample
{
public static void main(String args[])
{
outerloop: for(int i=0;i<3;i++)
{
for(int j=0;j<5;j++)
{
if(j>i)
continue outerloop;
System.out.println( i +i+ j +j);
}
}
System.out.println(Loop Ends);
}
}
The output of the program is
i 0 j 0
i 1 j 0
i 1 j 1
i 2 j 0
i 2 j 1
i 2 j 2
Loop Ends
Check Your Progress
11. The _________
statements are
used to transfer the
control from one
part of the
program to
another.
12. The
______________
statement when
encountered
terminates the
current iteration of
the loop.
13. What is the use of
return
statement?
14. ________ are the
names given to a
block of code
which allow you to
jump from one
loop to another
loop within a
nested loop.
Self-Instructional
74 Material
Control Statements
NOTES
In this program, if we substitute continue statement with the break statement, the
following output will be generated.
i 0 j 0
Loop Ends
5.6 SUMMARY
In this unit, you have learned that:
A statement is an instruction given to the computer to perform a specific action.
A statement can either be a single statement or a compound statement.
A single statement specifies a single action and is always terminated by a semicolon
;. A compound statement, also known as a block, is a set of statements that are
always enclosed within curly braces {}.
Control statements are used to alter the flow of control of the program. In Java,
the control statements are broadly classified into three categories, namely,
conditional statements, iteration statements and jump statements.
Conditional statements, also known as selection statements, are used to make
decisions based on a given condition.
The conditional operator ? : selects one of the two values or expressions
based on a given condition.
The switch statement selects a set of statements from the available sets of
statements.
The statements that cause a set of statements to be executed repeatedly either
for a specific number of times or until some condition is satisfied are known as
iteration statements.
The for loop is one of the most widely used loops in Java. The for loop is a
deterministic loop, that is, the number of times the body of the loop is executed is
known in advance.
The while loop is used to perform looping operations when the number of
iterations is not known in advance. In a while loop, the condition is evaluated at
the beginning of the loop and if the condition evaluates to false, the body of the
loop is not executed even once.
The do-while loop is used if the body of the loop is to be executed at least
once, no matter whether the initial state of the condition is true or false.
Nested loops are the loops present within the body of another loop.
Jump statements are used to alter the flow of control unconditionally. That is,
jump statements transfer the program control unconditionally. The jump statements
defined in Java are break, continue and return.
Labels are used to jump from one block of statement to another.
Self-Instructional
Material 75
Control Statements
NOTES
5.7 KEY TERMS
Selection statements: Also known as conditional statements, they are used to
make decisions based on a given condition.
Default: This is a keyword that specifies the set of statements to be executed
in case no match is found.
Iteration statements: They are the statements that cause a set of statements
to be executed repeatedly either for a specific number of times or until some
condition is satisfied.
for loop: It is a deterministic loop, that is, the number of times the body of the
loop is executed, is known in advance.
while loop: This is an is used to perform looping operations when the number
of iterations is not known in advance.
Jump statements: These are statements which are used to alter the flow of
control unconditionally.
5.8 ANSWERS TO CHECK YOUR PROGRESS
1. Selection
2. false
3. Conditional
4. False
5. break
6. (c)
7. Iteration
8. True
9. In a while loop, the condition is evaluated at the beginning of the loop and if the
condition evaluates to false, the body of the loop is not executed even once.
The do-while loop is used if the body of the loop is to be executed at least
once, no matter whether the initial state of the condition is true or false.
10. Nesting
11. jump
12. continue
13. The return statement is used to transfer the control out of the method explicitly.
It transfers the control back to the caller and terminates the method in which it is
present.
14. Labels
Self-Instructional
76 Material
Control Statements
NOTES
5.9 QUESTIONS AND EXERCISES
Short-Answer Questions
1. Write a program to find and print the multiples of 9 between 100 and 200 using
for loop.
2. State the difference between the executions of while and do-while loop.
3. Write a program to demonstrate the use of switch statement.
4. What is a return statement?
5. Write a short note on labelled loops.
Long-Answer Questions
1. What are control statements? Explain the different types of control statements
with examples?
2. Consider the following code segment
if(x%2>=0)
{
if(x%2==0)
System.out.println(x is an even number);
if(x%2>0)
System.out.println(x is an odd number);
}
Rewrite the code using:
(a) if-else statement (b) conditional operator
3. Explain the use of break and default in switch statements.
4. Write a program to print the following output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
5. Write a program to check whether the number is palindrome or not. (Hint:
Palindrome numbers are those which read the same from left to right and from
right to left.)
6. Write a program to calculate the sum of this series.
1+x+x
2
+x
3
++x
n
Self-Instructional
Material 77
Java Classes and Objects
NOTES
UNIT 6 JAVA CLASSES AND OBJECTS
Structure
6.0 Introduction
6.1 Unit Objectives
6.2 Encapsulation
6.3 Defining a Class
6.3.1 Defining Methods
6.4 Creating Objects
6.5 Accessing Members of a Class
6.6 Argument Passing
6.6.1 Call-by-Value
6.6.2 Call-by-Reference
6.7 Constructors
6.7.1 Parameterized Constructors
6.8 Method Overloading
6.9 Static Members
6.10 this Keyword
6.11 Garbage Collection
6.11.1 The finalize() Method
6.12 Summary
6.13 Key Terms
6.14 Answers to Check Your Progress
6.15 Questions and Exercises
6.0 INTRODUCTION
The key objective of object-oriented programming is to represent the various real-world
objects as program elements. In Java, this objective is accomplished with the help of
class that binds data and the methods to manipulate that data together under a single
entity.
All the OOP concepts, such as data abstraction, encapsulation, inheritance and
polymorphism, are implemented with the help of classes. A class serves as a template
that provides a layout common to all of its instances known as objects. In other words,
a class is only a logical abstraction that specifies what data and methods its objects will
have, whereas the objects are the physical entities through which those data and methods
can be used in a program. Thus, objects are considered as the building blocks of object-
oriented programming. This unit discusses the concept of classes and objects in detail.
6.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Explain classes and objects that form the basis of object-oriented programming
Create and use non parameterized and parameterized methods
Understand the significance of dot operator
Learn how to pass arguments to a method by value or by reference
Self-Instructional
78 Material
Java Classes and Objects
NOTES
Explain the purpose of constructor and its types
Understand the concept of method overloading
Explain the use of static members in a class
Understand the significance of this keyword and finalize method
6.2 ENCAPSULATION
Encapsulation is the technique of binding or keeping the data and functions (that operate
on them) together in a single unit called a class. Encapsulation is the way to implement
data abstraction. A well-encapsulated object acts as a black box for other parts of the
program. That is, it provides services to the external functions or other objects that
interact with it. However, these external functions or the objects do not need to know its
internal details.
6.3 DEFINING A CLASS
A class is a user-defined data type that can be used to create instances of its type called
objects. Like any other user-defined data type, it also needs to be declared and defined
in the program. A class definition specifies a new data type that can be treated as a built-
in data type.
The syntax for defining a class is
class class_name
{
//variables declaration
//methods declaration
}
The variables declared in the class are known as instance variables. The variables
and methods declared within the curly braces are collectively known as members of
the class.
A class can also be empty. That is, the class definition given below is also valid.
class class_name
{
}
Here, since the body of the class is empty, it does not contain any variables and
methods so it cannot perform any useful action. However, this class can be successfully
compiled and we can also create objects using it.
Note: In Java, there is no semicolon after closing brace in class definition.
Example 6.1: A simple class definition without any method
class Cuboid
{
int length;
int width; //variables declaration
Self-Instructional
Material 79
Java Classes and Objects
NOTES
int height;
}
In this example, a class named Cuboid with three instance variables of type
int, namely, length, width and height is created.
6.3.1 Defining Methods
As discussed earlier, a class consists of instance variables and methods. A class which
consists of only variables (and without methods which manipulate them) cannot perform
any useful operation. Therefore, to access the instance variables of a class and manipulate
them, we must add methods in the class.
The syntax for defining a method is
return_type method_name(parameter_list)
{
body of the method
}
where,
return_type is the type of data that is returned by the method
method_name specifies the name of the method. This can be any name other than
the keywords in Java
parameter_list consists of a series of pairs of data type and identifiers separated
by commas
Note: The parameter_list can be empty and if a method does not return any
value, its return type must be void.
For example, consider the following method definition.
int volume()
{
body of the method
}
Here, the method volume() does not accept any parameter and returns a
value of type int.
Example 6.2: A class definition with method
class Cuboid
{
int length;
int width; //variables declaration
int height;
int volume() //method definition
{
return(length*width*height);
}
}
Note: Methods must be declared immediately after the declaration of the instance
variables inside the body of the class.
Self-Instructional
80 Material
Java Classes and Objects
NOTES
6.4 CREATING OBJECTS
Once a class is defined, it can be used to create variables of its type known as objects.
The relationship between an object and a class is same as that of any variable and its
data type. To create an object, we need to first declare it.
The syntax for declaring an object is
class_name object_name;
where,
class_name is the name of the class
object_name is the name of the object of class_name type
For example, the statement to declare an object of Cuboid type is
Cuboid cobj;
This statement declares a variable cobj as a reference to an object of Cuboid
type. After the execution of this statement, cobj contains the null value, which
indicates that it does not point to an actual object. Once the object is declared, we need
to create it by allocating the required memory space to it. In Java, this is done with the
help of the new operator.
The syntax for creating an object is
object_name=new class_name;
For example, the statement to create an object of Cuboid type is
cobj=new Cuboid();
This statement creates an actual object by dynamically allocating memory space
to it and returns a reference to cobj.
The above two statements can be combined into one statement as shown below.
Cuboid cobj=new Cuboid ();
Note: Since an object is an instance of a class, the process of creating an object of
a class is known as instantiation.
6.5 ACCESSING MEMBERS OF A CLASS
Each object of a class has its own set of variables. These variables should be assigned
values before using them in the program. The instance variables and methods added in
the program cannot be accessed directly outside the class using their names. To access
the variables and methods outside the class, dot (.) operator is used as follows:
object_name.variable_name
object_name.method_name(parameter_list)
where,
object_name is the name of the object
variable_name is the name of the instance variable that is to be accessed
method_name is the name of the method which is to be called
parameter_list is the series of pairs of data types and their respective identifiers
Check Your Progress
1. A _________ has
the same relation
to an _________
that a basic data
type has to a
variable of that
type.
2. Which of these
operator is used
for creating an
object and
allocating memory
space to it?
(a) dot operator
(b) new operator
(c) instanceof
operator
(d) none of these
Self-Instructional
Material 81
Java Classes and Objects
NOTES
For example, the instance variable length of Cuboid class can be accessed as
follows:
cobj.length;
Similarly, the method volume()of Cuboid class can be accessed as follows:
cobj.volume();
Example 6.3: A program to demonstrate the accessing of members of a class
class Cuboid
{
int length;
int width;
int height;
int volume() //method definition
{
return(length*width*height);
}
}
class ClassDemo
{
public static void main(String args[])
{
Cuboid cobj=new Cuboid(); //object creation
cobj.length=60;
cobj.width=20; //accessing variables
cobj.height=40;
int vol=cobj.volume(); //calling method
System.out.println(The volume of the cuboid is:
+vol);
}
}
The output of the program is
The volume of the cuboid is: 48000
In this example, the instance variables length, width and height of the
object cobj are assigned values outside the class using the dot operator. Alternatively,
the instance variables can be assigned values by using a parameterized method.
Example 6.4: A program to demonstrate the use of parameterized method
class Cuboid
{
int length;
int width;
int height;
void initialize(int l, int w, int h) //parameterized
method
{
Self-Instructional
82 Material
Java Classes and Objects
NOTES
length=l;
width=w;
height=h;
}
int volume()
{
return(length*width*height);
}
}
class ParameterizedMethod
{
public static void main(String args[])
{
Cuboid c1=new Cuboid(); //creating object
Cuboid c2=new Cuboid();
c1.initialize(12,10,8); //calling initialize
method
int vol1=c1.volume(); //calling volume method
c2.initialize(13,11,9);
int vol2=c2.volume();
System.out.println(The volume of the Cuboid is:
+vol1);
System.out.println(The volume of the Cuboid is:
+vol2);
}
}
The output of the program is
The Volume of the Cuboid is: 960
The Volume of the Cuboid is: 1287
Here, the initialize() method accepts three parameters (arguments) namely, l,
w and h and assigns them to the instance variables, namely, length, width and
height, respectively of the appropriate object.
6.6 ARGUMENT PASSING
The argument(s) that appear in the method call statement are known as actual arguments
and those which appear in the method definition are known as formal arguments. The
number of actual arguments, their order and type in the method call must match with
that of the formal arguments. There are two ways by which an argument can be passed
to the methodcall by value and call by reference.
6.6.1 Call-by-Value
In call-by-value method, the values of the actual arguments are copied into the formal
arguments. Putting in simple words, the method creates a copy of argument values and
then works with these copied values. As a result any changes made to this set of copied
Self-Instructional
Material 83
Java Classes and Objects
NOTES
values in the called method do not affect the values of the actual arguments in the calling
method. In Java, when arguments of primitive type are passed to a method, they are
passed by value.
Example 6.5: A program to demonstrate the call-by-value mechanism
class FirstCall
{
void vol(int i, int j, int k)
{
i+=5;
j+=5;
k+=5;
}
}
class CallByValue
{
public static void main(String args[])
{
FirstCall fc =new FirstCall();
int l=10;
int w=20;
int h=15;
System.out.println(Length, Width, Height before
call is : +l+ +w+ +h);
fc.vol(l, w, h) //passing values as arguments
System.out.println(Length, Breadth, Height
after call is : +l+ +w+ +h);
}
}
The output of the program is
Length, Breadth, Height before call is :10 20 15
Length, Breadth, Height after call is :10 20 15
In this program, the values of l, w and h remain same before and after the call.
This is because when the method vol() is invoked l, w and h are passed by value and
their values gets copied into formal arguments i, j and k. Hence, the method
vol()works with i, j and k and not with l, w and h. As a result, the values of l, w
and h remain unaltered.
6.6.2 Call-by-Reference
In call-by-reference method, arguments reference is passed as method parameter. Unlike
call-by-value method, call-by-reference does not create a copy of the actual argument
and the called method works with the original values. This implies that any changes
made to the variable in the method body are reflected in the calling method. In Java,
when an object of a class is passed to a method as an argument it is passed by reference.
Self-Instructional
84 Material
Java Classes and Objects
NOTES
Example 6.6: A program to demonstrate the call-by-reference mechanism
class SecondCall
{
int length, breadth, height; //variables declaration
void vol(SecondCall s) //method definition
{
s.length+=5;
s.breadth+=5;
s.height+=5;
}
}
class CallByRefernce
{
public static void main(String args[])
{
SecondCall sc=new SecondCall();
sc.length=10;
sc.breadth=20;
sc.height=30;
System.out.println(The values of Length, Breadth and
Height before method call: +sc.length +
+sc.breadth + +sc.height);
sc.vol(sc); //passing object as method argument
System.out.println(The values of Length, Breadth and
Height after method call: +sc.length + +sc.breadth
+ +sc.height);
}
}
The output of the program is
The values of Length, Breadth and Height before method call:
10 20 30
The values of Length, Breadth and Height after method call:
15 25 35
In this program, the values of length, breadth and height of object sc
changes after invoking the method. Because here when the method vol() is called,
the object of a class is passed as parameter. As a result changes made to the length,
breadth and height of this passed object in the vol() method are reflected in the
original values.
6.7 CONSTRUCTORS
A constructor is a special method which is used to initialize objects at the time of their
creation. The name of the constructor is same as the name of the class in which it
resides. Unlike other methods in Java, a constructor does not have any return type (not
even void). This is because the implicit return type of constructor is the instance of the
class to which it belongs.
Check Your Progress
3. Which of these
entities is the
correct syntax for
accessing the
members of a
class?
(a)
class_member.
class_object
(b)
class_object.
class_name
(c) class_name.
class_member
(d)
class_object.
class_member
4. The____________
method allows the
programmer to
pass different
values to the
instance variables
of different
objects.
5. There are two
ways by which an
argument can be
passed to the
method, ________
and______________.
Self-Instructional
Material 85
Java Classes and Objects
NOTES
The syntax to define a constructor is
class class_name
{
//Variable declaration
class_name(parameter_list) //constructor definition
{
//body of the constructor
}
}
It should be noted that if you do not explicitly define any constructor, then the
Java compiler automatically provides a default constructor that initializes all the instance
variables to 0.
Example 6.7: A program to demonstrate the concept of a constructor
class Cuboid
{
int length;
int width;
int height;
Cuboid() //constructor definition without parameters
{
length=20;
width=10;
height=15;
}
int volume()
{
return (length*width*height);
}
}
class Constructor
{
public static void main(String args[])
{
Cuboid c1=new Cuboid();
Cuboid c2=new Cuboid();
int a=c1.volume();
int b=c2.volume();
System.out.println(The volume of first cuboid is +a);
System.out.println(The volume of second cuboid is +b);
}
}
The output of the program is
The volume of first cuboid is 3000
The volume of second cuboid is 3000
Self-Instructional
86 Material
Java Classes and Objects
NOTES
In this example, the constructor initializes both the objects c1 and c2 of Cuboid
type with the same values, as a result the volume of both the cuboids is same. Clearly, a
non-parameterized constructor provides same values to all the objects of a class.
6.7.1 Parameterized Constructors
When different objects of a class need to be initialized with different values, a
parameterized constructor can be defined. A parameterized constructor is a constructor
that accepts one or more parameters at the time of creation of objects and initializes the
instance variables of the objects with these parameters. It makes the program more
flexible, because using it we can assign different values to the instance variables of the
objects of a class.
Example 6.8: A program to demonstrate the concept of a parameterized constructor
class Cuboid
{
int length;
int width;
int height;
Cuboid(int l, int w, int h) //parameterized Constructor
{
length=l;
width=w;
height=h;
}
int volume() //method definition
{
return (length*width*height);
}
}
class ParameterizedConstructor
{
public static void main(String args[])
{
Cuboid c1=new Cuboid(10,8,9);
Cuboid c2=new Cuboid(7,6,5);
int a=c1.volume();
int b=c2.volume();
System.out.println(The volume of first cuboid is +a);
System.out.println(The volume of second cuboid is +b);
}
}
The output of the program is
The volume of first cuboid is 720
The volume of second cuboid is 210
Self-Instructional
Material 87
Java Classes and Objects
NOTES
6.8 METHOD OVERLOADING
In some cases when a similar action is to be performed on different types of data,
different methods having different names are to be defined for all types of data. This
makes the program very complex as the programmer must keep track of the names of
all the methods. To prevent such situations, Java allows the methods to be overloaded.
Method overloading allows multiple methods to have same name with different
parameters and different definitions. The application of method overloading is found in
those programs where objects in a class are needed to perform similar operations but
using different input parameters. When a method is called, Java compiler compares the
method name and then the type and number of arguments associated with it to determine
which of the method is to be called and executed. This process is known as
polymorphism.
In order to create overloaded methods in our program, we have to create different
method definitions in the class, all with same name but having different parameters. The
different methods are identified on the basis of the number of parameters, the data type
of the parameters or the order of the data type of the parameters passed to the method.
To understand the concept of method overloading, consider these method declarations.
void sum(int);
void sum(int,int);
In these statements, two methods named, sum() are different as the number of
arguments passed are different. Now, consider these statements.
void addition(int);
void addition(char);
In these statements, two methods named addition() are different as the data type
of arguments passed is different. Now, consider these statements.
void area(int,float);
void area(float,int);
In these statements, two methods named, area() are different as the order of
the data type of the arguments passed is different.
Example 6.9: A program to demonstrate the concept of method overloading
class Shapes
{
void perimeter(int a) //method with int type parameter
{
System.out.println(The perimeter of the square is +(4*a));
}
void perimeter(double a) //method with double type //parameter
{
System.out.println(The circumference of the circle is
+(2*a*(22/7)));
}
void perimeter(int a, int b) //method with two parameters
{
Self-Instructional
88 Material
Java Classes and Objects
NOTES
System.out.println(The perimeter of the rectangle is
+2*(a+b));
}
}
class MethodOverloading
{
public static void main(String args[])
{
Shapes s=new Shapes();
s.perimeter(5.5);
s.perimeter(10);
s.perimeter(15,10);
}
}
The output of the program is
The circumference of the circle is 33.0
The perimeter of the square is 40
The perimeter of the rectangle is 50
6.9 STATIC MEMBERS
So far, we have seen that members of a class can be initialized or accessed by its objects
only. However, it is possible to define members of a class without reference to a specific
object. This is done by declaring the instance variables and methods of a class as static.
Unlike non-static members, the static members are associated with the class as a
whole, rather than with individual objects. Therefore, outside the class the static members
of a class are called by using class names rather than through objects. Since the static
variables and static methods contain the properties of a class and not of the individual
objects, they are also known as class variables and class methods, respectively.
The static variables and static methods of a class are also called class variables and
class methods respectively.
The syntax to declare static variable is
static return_type variable_name;
The syntax to access static variable is
class_name.variable_name
The syntax to declare static method is
static return_type method_name(parameter_list);
The syntax to access static method is
class_name.method_name
If a class member is declared as static, only one copy of that data member is
created, regardless of the number of objects. All the objects of a class share this single
copy of the static data member.
Check Your Progress
6. The return type of
a constructor is
(a) void
(b) int
(c) float
(d) none of these
7. The process of
____________
allows multiple
methods to have
same name with
different
parameters and
different
definitions.
Self-Instructional
Material 89
Java Classes and Objects
NOTES
Example 6.10: A program to demonstrate the use of static members of a class
class StaticMembers
{
static int i=10; //static variable
static void add(int x, int y) //static method
{
System.out.println(Sum of two numbers is: +(x+y));
}
}
class StaticExample
{
public static void main(String args[])
{
StaticMembers.add(30,40); //calling static method
int i= StaticMembers.i; //accessing static
variable
System.out.println(Value of i is: +i);
}
}
The output of the program is
Sum of two numbers is: 70
Value of i is: 10
Here, variable i and method add() are declared as static. Therefore, outside
the class they are accessed using the name of the class in which they are defined.
Note: The methods declared as static can access only static data and call static
methods.
6.10 this KEYWORD
As we know that methods are invoked by the objects of the class. There may be a
situation when a method needs the reference of the object that has invoked it. In Java, it
is accomplished by using this keyword. By using this keyword in any method, we
can refer to the current object (that is the object on which the method was invoked). For
example, consider the following two code segments.
FirstConstructor(int i, int j) //first definition of
constructor
{
this.a=i;
this.b=j;
}
FirstConstructor(int i, int j) //second definition of
constructor
{
Self-Instructional
90 Material
Java Classes and Objects
NOTES
a=i;
b=j;
}
These two constructors will operate in exactly the same way. Here, the use of
this in first code segment is correct but not required. However, it has other uses like
preventing name space collision between the instance variables of a class and variables
declared inside a method.
Example 6.11: A program to demonstrate the name space collision between the instance
variables of a class and variables declared inside a method
class SecondConstructor
{
int i, j;
SecondConstructor(int i, int j)
{
//accessing variables of a constructor
i=i;
j=j;
}
void display()
{
System.out.println(Value of instance variable i:+i);
System.out.println(Value of instance variable j:+j);
}
}
class ConstructorsCall
{
public static void main(String args[])
{
SecondConstructor sc=new SecondConstructor(10, 20);
sc.display();
}
}
The output of the program is
Value of instance variable i:0
Value of instance variable j:0
In this program, the values of i and j are 0. This is because the instance variables
and variables within the constructor have same name so the instance variables i and j
are hidden by the variables of the constructor. However, we can prevent the hiding of
instance variables using this keyword.
Example 6.12: A program to demonstrate the use of this keyword to prevent name
space collision
class SecondConstructor
{
int i, j;
Self-Instructional
Material 91
Java Classes and Objects
NOTES
SecondConstructor(int i, int j)
{
//the values of variables of the constructor are //assigned
to instance variables
this.i=i;
this.j=j;
}
void display()
{
System.out.println(Value of instance variable i:+i);
System.out.println(Value of instance variable j:+j);
}
}
class ConstructorsCall
{
public static void main(String args[])
{
SecondConstructor sc=new SecondConstructor(10, 20);
sc.display();
}
}
The output of the program is
Value of instance variable i:10
Value of instance variable j:20
In this program, the use of this keyword resolves the problem of name space
collision as it refers to the current object (object that invoked the constructor).
6.11 GARBAGE COLLECTION
As already discussed, the new operator in Java is used to allocate memory space to the
objects dynamically. This memory space needs to be freed once the object occupying it
gets destroyed or is no longer needed in the program. Java provides us a mechanism
known as garbage collection, which handles the deallocation of the memory
automatically. When there are no references to an object available, the memory occupied
by the object can be reclaimed by the garbage collector without the need to explicitly
destroy the object. The process of garbage collection occurs periodically to collect the
memory space occupied by those objects that are no longer referenced either directly
(during program execution) or indirectly by other referenced objects.
6.11.1 The finalize() Method
Sometimes there might be a situation when an object is holding some non-object resources
like file descriptor which cannot be freed by the garbage collector. Then, we need to
ensure that these resources are freed before the object gets destroyed. To deal with
such situation, finalize() method is used. All the operations which must be performed
Check Your Progress
8. Which of these is a
valid method
declaration?
(a) int
sum(int x,
int y)
(b) int
sum(int x,
y)
(c) sum(int x,
int y)
(d) sum(int,
int)
9. The ___________
data members of a
class are
independent of any
particular object of
the class.
10. this keyword is
used to refer to the
current object.
(True or False)
11. What is the
function of
finalize()
method?
Self-Instructional
92 Material
Java Classes and Objects
NOTES
just before the object is destroyed are placed inside the finalize() method. The
Java runtime calls this method whenever an object is about to be recycled.
The syntax of finalize() method is
protected void finalize()
{
//finalization code
}
The keyword protected is an access specifier that prevents access to the
finalize() method by the code outside the class.
Note: Access specifiers (access modifiers) are discussed in detail in Chapter 08.
6.12 SUMMARY
In this unit, you have learned that:
The key objective of object-oriented programming is to represent the various
real-world objects as program elements.
A class is a user-defined data type that can be used to create instances of its type
called objects.
Methods are added in the class to access the instance variables of a class and
manipulate them.
Objects are variables of class type inside which they are created.
The instance variables and methods added in the program cannot be accessed
directly outside the class using their names. To access the variables and methods
outside the class dot (.) operator is used.
The argument(s) that appear in the method call statement are known as actual
arguments and those which appear in the method definition are known as formal
arguments.
There are two ways by which an argument can be passed to the methodcall by
value and call by reference.
In call-by-value method, the values of the actual arguments are copied into the
formal arguments.
In call-by-reference method, arguments reference is passed as method parameter.
A constructor is a special method which is used to initialize objects at the time of
their creation.
A parameterized constructor is a constructor that accepts one or more parameters
at the time of creation of objects and initializes the instance variables of the
objects with these parameters.
Method overloading allows multiple methods to have same name with different
parameters and different definitions.
The static members of a class are defined without reference to a specific
object. The static members are associated with the class as a whole, rather
than with individual objects.
Self-Instructional
Material 93
Java Classes and Objects
NOTES
The this keyword is used to refer to the current object (that is the object on
which the method was invoked).
All the operations that are to be performed just before the object is destroyed are
placed inside the finalize() method.
6.13 KEY TERMS
Encapsulation: It is the technique of binding or keeping the data and functions
(that operate on them) together in a single unit called a class.
Class: It is a user-defined data type that can be used to create instances of its
type called objects.
Call-by-value method: It is one of the two ways of argument passing, in which
the values of the actual arguments are copied into the formal arguments.
Constructor: It is a special method which is used to initialize objects at the time
of their creation.
Parameterized constructor: It is a constructor that accepts one or more
parameters at the time of creation of objects and initializes the instance variables
of the objects with these parameters.
6.14 ANSWERS TO CHECK YOUR PROGRESS
1. Class, object
2. (b)
3. (d)
4. Parameterized
5. Call-by-value, call-by-reference
6. (d)
7. Method overloading
8. (a)
9. Static
10. True
11. All the operations which are to be performed just before the object is destroyed
are placed inside the finalize() method.
6.15 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What is a class and how is it related to objects?
2. Find and fix the error in the following program to display the area of the rectangle
class Rectangle
{
public static void main(String args[])
Self-Instructional
94 Material
Java Classes and Objects
NOTES
{
Rectangle rect;
rect.length=10;
rect.width=7;
System.out.println(Area of the rectangle rect
is+rect.area());
}
}
3. What are the two possible ways of passing arguments to a method? What is the
difference between them?
4. Define a class Student having instance variables: roll_number, marks1,
marks2 and marks3 and method: calculate() to calculate the overall
percentage of marks and return the percentage of marks.
5. What is the difference between a method and a constructor?
6. Can the objects of a class be initialized at run-time using constructors? Give an
example.
Long-Answer Questions
1. Explain the significance of method overloading. Give example.
2. Consider the given class and identify the instance and class variables
class IdentifyVariables
{
a. float a=4.0;
b. static int b=14;
}
3. How is a static method invoked? Explain with an example.
4. Explain the importance of this keyword.
5. Explain how garbage collection is accomplished with the help of finalize()
method.
6. Define a class Teacher having instance variables: Teacher_id, Basic, DA
and HRA and method: calculate() to calculate the salary. (Hint: Salary is the
sum of Basic, DA and HRA)
Self-Instructional
Material 95
Arrays and Vectors
NOTES
UNIT 7 ARRAYS AND VECTORS
Structure
7.0 Introduction
7.1 Unit Objectives
7.2 Arrays
7.2.1 Single-Dimensional Arrays
7.2.2 Multi-Dimensional Arrays
7.3 Vectors
7.4 Wrapper Classes
7.5 Summary
7.6 Key Terms
7.7 Answers to Check Your Progress
7.8 Questions and Exercises
7.0 INTRODUCTION
Handling real-world data requires a mechanism that deals with a collection of data
items. In Java, different data types like arrays and vectors are offered to handle such
collections. These data types are capable of grouping related data items together into a
single unit. Arrays hold together few or thousands of data items of similar data types
under a single name and vectors provide a way to keep items of any data types in any
number together into a single entity.
In this unit, you will be familiarized with the basics of arrays and vectors. The
concept of wrapper classes is also discussed in the later section of this unit.
7.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Declare, initialize and manipulate single-dimensional and multi-dimensional arrays
Understand the significance of vectors
Explain the concept of wrapper classes
7.2 ARRAYS
Java uses variables of different primitive data types to store data. However, these
variables are incapable of holding more than one value at a time. For example, a single
variable cannot be used for storing the marks of all the students in a class. For such
purposes, Java provides a different kind of data type known as arrays.
Arrays are defined as a fixed size sequence of same type of data elements.
These data elements can be of any primitive or non-primitive data type. The elements of
an array are stored in contiguous memory locations and each individual element can be
accessed using one or more indices or subscripts. A subscript or an index is a positive
integer value, which indicates the position of an element in an array. Arrays are used
when a programmer wants to store multiple data items of same type into a single list and
Self-Instructional
96 Material
Arrays and Vectors
NOTES
also wants to access and manipulate individual elements of the list. Arrays can be either
single-dimensional or multi-dimensional depending upon the number of subscripts
used.
7.2.1 Single-Dimensional Arrays
A single-dimensional array is the simplest form of an array that requires only one subscript
to access an array element. Like an ordinary variable, an array must be declared before
it is used in the program.
The syntax for declaring a single-dimensional array is
data_type array_name[];
or
data_type[]array_name;
where,
data_type is any data type
array_name is the name of the array
For example, an array marks[] of type int can be declared using either of the two
statements.
int marks[];
or
int[] marks;
After an array is declared, we need to create it by allocating space to it in memory.
Arrays are created using new operator.
The syntax for creating an array is
array_name=new data_type[size];
where,
size is the size of the array
For example, an array marks[] of type int and size five can be created using this
statement.
marks=new int[5];
The above two steps of declaration and creation of an array can be combined into a
single statement as shown below.
data_type array_name=new data_type[size];
Similarly, the statement to declare and create an array marks[] of type int and size
five is
int marks[]=new int[5];
Note: All the elements created using new operator in the array will be automatically
initialized to zero.
Initialization of Single-Dimensional Array
Once an array is declared and memory is allocated to it, the next step is to initialize each
array element with a valid and appropriate value. An array can be initialized at the time
of its declaration.
Self-Instructional
Material 97
Arrays and Vectors
NOTES
The syntax for initializing an array at the time of its declaration is
data_type array_name[]={value_1,value_2,......,value_n};
The values are assigned to the array elements in the order in which they are
listed. That is, value_1, value_2 and value_n are assigned to the first, second
and n
th
element of the array, respectively.
If an array is declared and initialized simultaneously, then specifying its size is
optional. For example, the statement int marks[]={51,62,43,74,55} is also
valid. The size of an array marks can be obtained by using marks.length()
method.
Note: If you try to store or access values outside the range of array (index with
negative value or value greater than the length of the array), run-time error is
generated.
Accessing Single-Dimensional Array Elements
Once an array is declared and initialized, the values stored in the array can be accessed
any time. Each individual array element can be accessed using the name of the array
and the subscript value. Every element in an array is associated with a unique subscript
value, starting from 0 to size-1 (where, size refers to the maximum number of
elements that can be stored in the array).
The syntax for accessing the values stored in a single-dimensional array is
array_name[subscript]
For example, the elements of the array marks can be referred to as marks[0],
marks[1], marks[2], marks[3] and marks[4], respectively. Note that index
of an array starts with 0.
Note: The memory location, where the first element of an array is stored, is known
as the base address, which is generally referred to by the name of the array.
Single-dimensional arrays are always allocated contiguous blocks of memory.
This implies that every element in an array is always stored in sequential manner next to
each other. The memory representation of the array marks is shown in Figure 7.1. As
each element is of type int (that is, 4 bytes long), the array marks occupies twenty
contiguous bytes in the memory and these bytes are reserved in the memory at compile-
time.
marks

marks[3] marks[2] marks[1] marks[0]
74 62 51
marks[4]
2001 2005 2009 2013 2017
55 43
Figure 7.1 Memory Representation of an Array marks
Manipulation of Single-Dimensional Array Elements
An array can be manipulated with the help of various operations. These operations
include finding the sum, average, maximum or minimum, sorting and searching of the
array elements, etc.
Example 7.1: A program to sort the array elements
class SortingArray
Self-Instructional
98 Material
Arrays and Vectors
NOTES
{
public static void main(String args[])
{
int a[]={67, 34, 12, 98, 26}; //array initialization
//at the time of declaration
int n=a.length; //returns the length of the array
System.out.print(The list of numbers:);
for(int i=0;i<n;i++)
{
System.out.print( +a[i]);
}
//sorting elements of an array
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
System.out.print(\n);
System.out.print(The sorted list of given numbers:);
for(int i=0;i<n;i++) //displaying sorted array
{
System.out.print( +a[i]);
}
}
}
The output of the program is
The list of numbers: 67 34 12 98 26
The sorted list of given numbers: 12 26 34 67 98
7.2.2 Multi-Dimensional Arrays
Multi-dimensional arrays can be described as an array of arrays, that is, each element
of the array is itself an array. A multi-dimensional array of dimension n is a collection of
items that are accessed with the help of n subscript values.
Self-Instructional
Material 99
Arrays and Vectors
NOTES
Two-Dimensional Array
A two-dimensional array is the simplest form of a multi-dimensional array that requires
two subscript values to access an array element. Two-dimensional arrays are useful
when the data being processed are to be arranged in the form of rows and columns
(matrix form).
The syntax for declaring a two-dimensional array is
data_type array_name[][];
or
data_type[][] array_name;
The syntax for creating a two dimensional array is
array_name[][]=new data_type[row_size][column_size];
The above two steps of declaration and creation can be combined into one using a single
statement as shown below.
data_type array_name[][]=new
data_type[row_size][column_size];
For example, an array a[][] of type int having three rows and two columns can be
declared and created using this statement.
int a[][]=new int[3][2];
Here, 3 is the row size and 2 is the column size.
Initialization of Two-Dimensional Array
Like a single-dimensional array, a two-dimensional array can also be declared and
initialized at the same time. To understand how to initialize a two-dimensional array,
consider this statement.
int a[3][2]={ {101,51},
{102,67},
{103,76} };
In this statement, an array a[][] of type int having three rows and two columns
is declared and initialized. This type of initialization is generally used to increase the
readability.
Now, consider another statement.
int b[][]={ { 2,3,4}, {1,1,1} };
In this statement, an array b[][] of type int having two rows and three columns
is initialized.
Accessing Two-Dimensional Array Elements
Once a two-dimensional array is declared and initialized, the value stored in the array
elements can be accessed using two subscripts.
The syntax for accessing the two-dimensional array element is
array_name[row][column]
The first subscript value (row) specifies the row number and the second subscript
value (column) specifies the column number. Both the subscript values specify the
position of the array element within the array.
Self-Instructional
100 Material
Arrays and Vectors
NOTES
For example, the elements of array a (declared earlier) are referred to as
a[0][0], a[0][1], a[1][0], a[1][1], a[2][0] and a[2][1], respectively.
Generally, two-dimensional arrays are represented with the help of a matrix.
However, in actual implementation, two-dimensional arrays are always allocated
contiguous blocks of memory. Figure 7.2 shows matrix and memory representation of
two-dimensional array a.
101 51
105 67
103 76
101 51 105 67 103 76
a[0][0] a[0][1] a[1][0] a[1][1] a[2][0] a[2][1]
2001 2005 2009 2013 2017 2021
first row second row third row
Matrix Representation Memory Representation
Figure 7.2 Matrix and Memory Representation of Array a[][]
Manipulation of Two-Dimensional Array Elements
A two-dimensional array can be manipulated in many ways. Some of the common
operations that can be performed on a two-dimensional array include finding the sum of
row elements, column elements and diagonal elements, finding the maximum and
minimum values, etc.
Example 7.2: A program to calculate the sum of two matrices
class MatricesSummation
{
public static void main(String args[])
{
int a[][]={{3,4,5},{3,2,7}}; //initializing matrix
a
int b[][]={{2,4,7},{1,2,2}}; //initializing matrix
b
int l=a.length;
System.out.println(First matrix is: + );
for(int i=0;i<l;i++) //displaying first matrix
{
for (int j=0;j<3; j++)
{
System.out.print( +a[i][j]);
}
System.out.println();
}
int m=b.length;
System.out.println(Second matrix is:+ );
for (int i=0;i<m;i++) //displaying second matrix
{
Self-Instructional
Material 101
Arrays and Vectors
NOTES
for(int j=0;j<3;j++)
{
System.out.print( + b[i][j]);
}
System.out.println();
}
System.out.println(Summation of the two matrices
is: );
//displaying sum of two matrices
for(int i=0;i<m;i++)
{
for(int j=0;j<=m;j++)
{
System.out.print( +(a[i][j]+b[i][j]));
}
System.out.println();
}
}
}
The output of the program is
First matrix is:
3 4 5
3 2 7
Second matrix is:
2 4 7
1 2 2
Summation of the two matrices is:
5 8 12
4 4 9
Variable Size Arrays
As already mentioned, multi-dimensional arrays are arrays of arrays. In such multi-
dimensional arrays the size of each array can be varied. For example, consider these
statements.
data_type array_name[][]=new data_type[size][];
array_name[0]=new data_type[size_1];
.
.
.
array_name[n-1]=new data_type[size_n];
where,
size is the number of rows in two-dimensional array
size_1, . . . , size_n represents the number of columns in each row of two-dimensional
array
Self-Instructional
102 Material
Arrays and Vectors
NOTES
Example 7.3: A program to demonstrate a variable size array
class VariableArray
{
public static void main(String args[])
{
int a[][]=new int[4][];
a[0]=new int[2];
a[1]=new int[4];
a[2]=new int[3];
a[3]=new int[5];
int i,j;
System.out.println(The variable sized array is: );
for(i=0;i<4;i++)
{
for (j=0; j<a[i].length; j++)
{
a[i][j]=j;
System.out.print( +a[i][j]);
}
System.out.println();
}
}
}
The output of the program is
The variable sized array is:
0 1
0 1 2 3
0 1 2
0 1 2 3 4
7.3 VECTORS
The Vector class contained in the java.util package defines methods to store
objects into a single unit. It can be used to implement dynamic array called vectors
which can accommodate any number and any type of objects. Consider the following
statements.
Vector v1=new Vector( ); //creating vector without specifying
its //initial capacity
Vector v2=new Vector(n); //creating vector having initial
capacity //n
Here, the first statement creates a vector v1 having initial capacity 10. That is,
when you create a vector without specifying its initial capacity it is automatically set to
10. Similarly, the second statement creates a vector v2 with initial capacity n. Although,
we have created the vector v2 by specifying its initial capacity but this specification
Check Your Progress
1. An array is a fixed
size sequence of
elements of _____
data type.
2. A ___________ is
a positive integer
value which
indicates the
position of an
element in an array.
3. Which of these
array elements is
referred by
arr[3]?
(a) third
(b) second
(c) fourth
(d) fifth
4. A single-
dimensional array
requires ______
subscript to access
an array element.
5. In a two-
dimensional array,
elements are
arranged in the
form of ________
and ___________.
Self-Instructional
Material 103
Arrays and Vectors
NOTES
does not pose any limitation on the size of the vector. Since, the size of the vector can be
increased or decreased by adding or removing objects to it.
The Vector class provides a variety of methods which can be used to perform
different operations on vectors, some of them beeing listed in Table 7.1.
Table 7.1 Vector Methods and Their Description
Methods Description
vect1.addElement(object) Adds the specified object at the end of the
vector list vect1
vect1.size() Returns the number of objects currently present in
the vector vect1
vect1.capacity() Returns the maximum capacity of the vector
vect1
vect1.removeElement(object) Removes the specified object from the vector
vect1
vect1.elementAt(n) Returns the name of the n
th
object of the vector
vect1
vect1.removeElementAt(n) Removes the item at the n
th
position of the vector
vect1
vect1.removeAllElements() Removes all the elements in the vector vect1
vect1.firstElement() Returns the first element of the vector vect1
vect1.lastElement() Returns the last element of the vector vect1
vect1.trimToSize() Sets the capacity of the vector vect1 to the
number of objects it is currently holding
Example 7.4: A program to demonstrate the use of some of the methods of Vector
class
import java.util.*; //importing package for using vectors
public class VectorMethods
{
public static void main(String[] args)
{
Vector vect1 = new Vector();
String str1 = Hello!!!;
String str2 = How are you?;
String str3= All the best!;
//adding string object to the vector
vect1.addElement(str1);
vect1.addElement(str2);
vect1.addElement(str3);
System.out.println(The initial capacity of the
vector is: +vect1.capacity());
System.out.println(The elements of vector:
+vect1);
System.out.println(The size of vector is:
+vect1.size());
System.out.println(The first element of vector
is: +vect1.firstElement());
Self-Instructional
104 Material
Arrays and Vectors
NOTES
System.out.println(The last element of vector is:
+vect1.lastElement());
}
}
The output of the program is
The initial capacity of the vector is: 10
The elements of vector: [Hello!!!, How are you?, All the
best!]
The size of vector is: 3
The first element of vector is: Hello!!!
The last element of vector is: All the best!
Note: The String class is used to create the string object.
7.4 WRAPPER CLASSES
One limitation of using vectors is that we cannot store data items of primitive data types
like int, float, char, long, double, etc. since it can store only objects. Therefore,
primitive data types need to be converted into objects before storing them in vectors. To
accomplish this, Java provides wrapper classes contained in the java.lang package.
The wrapper classes are used to convert the primitive data types into their respective
class instances. For example, a float data type is represented as an instance of
Float class.
It should be noted that Javas primitive wrapper classes are immutable, that is,
once a value is assigned to an instance of a wrapper class it cannot be changed later.
The primitive data types and their corresponding wrapper classes are shown in the
Table 7.2.
Table 7.2 Primitive Data Types and Their Corresponding Wrapper Classes
Primitive Data Type Wrapper Class
boolean java.lang.Boolean
byte java.lang.Byte
char java.lang.Character
double java.lang.Double
float java.lang.Float
int java.lang.Integer
long java.lang.Long
short java.lang.Short
void java.lang.Void
Some of the methods of wrapper classes are listed in Table 7.37.7.
Table 7.3 Conversion of Primitive Data Types to Object Types using Constructor Methods
Constructor Calling Action Performed
Integer a=new Integer(i); coverts integer to Integer object
Float b=new Float(f); coverts float to Float object
Double c=new Double(d); coverts double to Double object
Long d=new Long(l); coverts long to Long object
Self-Instructional
Material 105
Arrays and Vectors
NOTES
Table 7.4 Conversion of Object Numbers to Primitive Numbers using typeValue() Method
Method Calling Action Performed
int i=a.intValue(); converts object to integer
float f=b.floatValue(); converts object to float
double d=c.doubleValue(); converts object to double
long l=d.longValue(); converts object to long
Table 7.5 Conversion of Primitive Numbers to Strings using toString() Method
Method Calling Action Performed
str=Integer.toString(i); converts Primitive integer to string
str=Float.toString(f); converts Primitive float to string
str=Long.toString(l); converts Primitive long to string
str=Double.toString(d); converts Primitive double to string
Table 7.6 Conversion of String Objects to Numeric Objects using valueOf() Method
Method Calling Action Performed
IntVal=Integer.valueOf(str); converts string to Integer object
FloatVal=Float.valueOf(str); converts string to Float object
LongVal=Long.valueOf(str); converts string to Long object
DoubleVal=Double.valueOf(str); converts string to Double object
Table 7.7 Conversion of Strings to Primitive Numbers using Parsing Methods
Method Calling Action Performed
int i=Integer.parseInt(str) converts string to primitive integer
long l=Long.parseLong(str) converts string to primitive long
Note: The methods defined in the wrapper classes are static.
Example 7.5: A program to demonstrate the use of wrapper classes
import java.io.*;
class WrapperClassMethod
{
public static void main(String args[])
{
Float p=new Float(0); //converting float to Float //object
Float r=new Float(0);
int t=0;
Float si=new Float(0);
try
{
DataInputStream cin=new DataInputStream(System.in);
System.out.println(Enter the value of p);
String principal=cin.readLine();
p=Float.valueOf(principal); //converting String //object to
Float //object
Self-Instructional
106 Material
Arrays and Vectors
NOTES
System.out.println(Enter the value of r);
String rate=cin.readLine();
r=Float.valueOf(rate);
System.out.println(Enter the value of t);
String time=cin.readLine();
t=Integer.parseInt(time); //converting string to //integer
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
System.out.println(The value of p entered is: +p);
System.out.println(The value of r entered is: +r);
System.out.println(The value of t entered is: +t);
si=(p*t*r)/100;
System.out.println(Simple interest of given input data is:
+si);
float total=p+(si*t);
System.out.println(Total amount after 4 years is: +total);
}
}
The output of the program is
Enter the value of p
10000
Enter the value of r
5
Enter the value of t
4
The value of p entered is: 10000.0
The value of r entered is: 5.0
The value of t entered is: 4
Simple interest of given input data is: 2000.0
Total amount after 4 years is: 18000.0
7.5 SUMMARY
In this unit, you have learned that:
Arrays are defined as a fixed size sequence of same type of data elements.
The elements of an array are stored in contiguous memory locations and each
individual element can be accessed using one or more indices or subscripts.
Check Your Progress
6. The ___________
class contains
methods to store
any number and
any type of
objects in a single
unit called vectors.
7. The initial capacity
of a default vector
is______________.
8. The vectors cannot
be used to store
primitive data
types. (True or
False)
9. The __________
classes are used to
convert primitive
data type into
objects before
storing them in the
vectors.
Self-Instructional
Material 107
Arrays and Vectors
NOTES
Arrays can be either single-dimensional or multi-dimensional depending upon the
number of subscripts used.
A single-dimensional array is the simplest form of an array that requires only one
subscript to access an array element.
Multi-dimensional arrays can be described as an array of arrays, that is, each
element of the array is itself an array.
A two-dimensional array is the simplest form of a multi-dimensional array that
requires two subscript values to access an array element.
The Vector class is used to implement dynamic array called vectors which
can accommodate any number and any type of objects.
The wrapper classes are used to convert the primitive data types into their respective
class instances.
7.6 KEY TERMS
Array: It is a systematic arrangement of objects or data, usually into rows and
columns.
Multi-dimensional array: It is a collection of items accessed via n subscript
expressions (i.e., an n-dimensional array or simply n-D array).
Single-dimensional array: It is a structured collection of components that can
be accessed individually by specifying the position of a component with a single
index value.
Vector: It is a class contained in the java.util package that defines methods
to store objects into a single unit and that can be used to implement dynamic
arrays that can accommodate any number and any type of objects.
Wrapper class: It is a class in the Java programming language provided in the
java.lang package that provides object methods.
7.7 ANSWERS TO CHECK YOUR PROGRESS
1. Similar
2. Subscript/index
3. (c)
4. One
5. Rows, columns
6. Vector
7. 10
8. True
9. Wrapper
Self-Instructional
108 Material
Arrays and Vectors
NOTES
7.8 QUESTIONS AND EXERCISES
Short-Answer Questions
1. Define what an array is.
2. What is the importance of arrays?
3. What are vectors?
4. How would you differentiate between vectors and arrays?
Long-Answer Questions
1. Differentiate between single-dimensional and multi-dimensional arrays.
2. Write a program to multiply two given matrices and print the resultant matrix.
3. Write a program to create a list of names of five students in a class and store
them in a vector. In addition perform the following operations in the list
(a) Add a name at the end of the list.
(b) Delete a name at the third position in the list.
(c) Display the final contents of the list.
4. Discuss the significance of wrapper classes in Java.
Self-Instructional
Material 109
Inheritance and
Polymorphism
NOTES
UNIT 8 INHERITANCE AND
POLYMORPHISM
Structure
8.0 Introduction
8.1 Unit Objectives
8.2 Inheritance Basics
8.2.1 Defining a Subclass
8.3 Types of Inheritance
8.3.1 Single Inheritance
8.3.2 Hierarchical Inheritance
8.3.3 Multilevel Inheritance
8.3.4 Multiple Inheritance
8.4 Access Modifiers
8.5 Subclass Constructor
8.6 Method Overriding
8.7 Polymorphism
8.8 Using final Keyword
8.8.1 Final Variables
8.8.2 Final Methods
8.8.3 Final Classes
8.9 Abstract Methods and Classes
8.10 Summary
8.11 Key Terms
8.12 Answers to Check Your Progress
8.13 Questions and Exercises
8.0 INTRODUCTION
Inheritance is one of the major strengths of object-oriented programming. It is the process
of deriving a new class from the existing one in such a way that the new class inherits all
the members (data members and methods) of the existing class. In other words, inheritance
facilitates a class to acquire the properties and functionality of another class. The new
class depicts the acquired properties and behavior of the existing class as well as its own
unique properties and behavior. Inheritance allows code reusability, that is, it facilitates
classes to reuse the existing code. The new class acquires those members of the old
class that are already tested and debugged. Hence, inheritance saves time as well as
increases the reliability. Using inheritance, we can create a general class that defines
common properties for a set of related classes.
Polymorphism, the third basic principle of object-oriented programming, is the
ability of an action or method to do different things based on the object that it is acting
upon. The two types of polymorphism are overloading and overriding.
In this unit, you will learn about inheritance and polymorphism in detail.
Self-Instructional
110 Material
Inheritance and
Polymorphism
NOTES
8.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Understand what inheritance is
Explain the benefits of inheritance such as code reusability
Understand the concept of superclass and subclass
Discuss the various types of inheritance
Explain various access modifiers supported by Java
Know about subclass constructor
Understand what method overriding and polymorphism are
Describe how the final keyword can be applied to variables, methods and
classes
Explain abstract methods and abstract classes
8.2 INHERITANCE BASICS
The class that is inherited by other classes is called a base class or superclass or
parent class. The class that inherits the properties of the superclass is called a subclass
or derived class or child class. The subclass inherits all of the instance variables and
methods defined by the superclass, at the same time it also contains its own members.
For example, in Figure 8.1, Animal is the superclass which is inherited by three subclasses
Carnivore, Herbivore and Omnivore. Hence, Carnivore, Herbivore and Omnivore
inherit all the members of the superclass Animal.
Superclass


Subclasses

Carnivore Herbivore Omnivore
Figure 8.1 Superclass and Subclass
8.2.1 Defining a Subclass
Inheritance is implemented while defining the subclass. The name of the superclass is
specified in the subclass definition. A subclass can be defined by using extends
keyword.
The syntax to define a subclass is
class sub_class extends super_class
{
//variables and methods declaration
}
where,
Self-Instructional
Material 111
Inheritance and
Polymorphism
NOTES
sub_class is the name of the subclass that inherits the superclass
super_class is the name of the superclass that is being inherited
extends is the keyword that indicates that the super_class properties have been
extended to the sub_class
8.3 TYPES OF INHERITANCE
Inheritance allows creating a logical relationship between two or more classes. Depending
on the number of classes involved and the way the classes are inherited, inheritance
may take different forms, namely, single inheritance, hierarchical inheritance,
multilevel inheritance and multiple inheritance.
8.3.1 Single Inheritance
In single inheritance, a class is derived from a single superclass. Figure 8.2 shows
single inheritance in which subclass Employee is derived from the superclass Person.
Person
Person
Employee
Figure 8.2 Example of Single Inheritance
The syntax to define the subclass that implements single inheritance is
class Class1
{
:
}
class Class2 extends Class1
{
:
}
Example 8.1: A program to demonstrate single inheritance
class FirstClass // superclass
{
int i;
int j;
void get_first(int p, int q)
{
i=p;
j=q;
}
Self-Instructional
112 Material
Inheritance and
Polymorphism
NOTES
}
class SecondClass extends FirstClass // subclass
{
int k;
void get_second(int m)
{
k=m;
}
void display()
{
System.out.println(The value of superclass i is: +i);
System.out.println(The value of superclass j is: +j);
System.out.println(The value of subclass k is: +k);
}
}
class SingleInheritance
{
public static void main(String args[])
{
SecondClass obj = new SecondClass();
obj.get_first(20,30); //accessing superclassmethod
obj.get_second(40); //accessing subclassmethod
obj.display(); //accessing subclassmethod
}
}
The output of the program is
The value of superclass i is: 20
The value of superclass j is: 30
The value of subclass k is: 40
In this example, the superclass FirstClass is inherited by the class
SecondClass. Hence, SecondClass includes variables i, j and the method
get_first() of FirstClass and also defines its own data member k and
display() method.
8.3.2 Hierarchical Inheritance
The type of inheritance in which more than one class is derived from a single superclass
is called hierarchical inheritance. In hierarchical inheritance, superclass includes all
the properties that are common to all of its subclasses. Figure 8.3 shows hierarchical
inheritance with two classes Student and Employee deriving from a single superclass
Person.
Self-Instructional
Material 113
Inheritance and
Polymorphism
NOTES

Person
Student Employee
Figure 8.3 Example of Hierarchical Inheritance
The syntax to implement hierarchical inheritance involving two subclasses is
class Class1
{
:
}
class Class2 extends Class1
{
:
}
class Class3 extends Class1
{
:
}
Example 8.2: A program to demonstrate hierarchical inheritance
class FirstClass // superclass
{
int i;
int j;
int k;
void get_first(int p, int q, int r)
{
i=p;
j=q;
k=r;
}
}
class SecondClass extends FirstClass // first subclass
{
int x;
int y;
void get_second(int a, int b)
{
x=a;
y=b;
}
void display1()
Self-Instructional
114 Material
Inheritance and
Polymorphism
NOTES
{
System.out.println(The value of superclasss i,j and k is:
+i+,+j+ and +k);
System.out.println(The value of first subclasss x and y
is: +x+ and +y);
System.out.println( );
}
}
class ThirdClass extends FirstClass // second subclass
{
int z;
void get_third(int c)
{
z=c;
}
void display2()
{
System.out.println(The value of superclasss i,j and k is:
+i+,+j+ and +k);
System.out.println(The value of second subclasss z is:
+z);
}
}
class HierarchicalInheritance
{
public static void main(String args[])
{
SecondClass obj1 = new SecondClass();
// accessing superclass method and first subclass methods.
obj1.get_first(9,8,6);
obj1.get_second(3,6);
obj1.display1();
ThirdClass obj2 = new ThirdClass();
// accessing superclass method and second subclass methods.
obj2.get_first(2,4,8);
obj2.get_third(5);
obj2.display2();
}
}
Self-Instructional
Material 115
Inheritance and
Polymorphism
NOTES
The output of the program is
The value of superclasss i,j and k is: 9,8 and 6
The value of first subclasss x and y is: 3 and 6
The value of superclasss i,j and k is: 2,4 and 8
The value of second subclasss z is: 5
In this example, the superclass FirstClass is inherited by two classes
SecondClass and ThirdClass. The subclasses SecondClass and
ThirdClass inherit all the data members i, j, k and the method get_first() of
FirstClass and also define their own data members.
8.3.3 Multilevel Inheritance
In multilevel inheritance, one class is inherited from another class, which in turn is
inherited from some other class. Multilevel inheritance comprises two or more levels.
The subclass has all the properties of its direct superclass as well as its indirect superclass.
This is known as the transitive nature of multilevel inheritance. Figure 8.4 shows
multilevel inheritance in which superclass Person is inherited by a subclass Employee,
which is again inherited by another subclass Faculty. Hence, Person is an indirect
superclass to Faculty.
Person
Employee
Faculty
Superclass
Intermediate superclass
Subclass
Figure 8.4 Example of Multilevel Inheritance
The syntax to implement multilevel inheritance is
class Class1
{
:
}
class Class2 extends Class1
{
:
}
class Class3 extends Class2
{
:
}
Self-Instructional
116 Material
Inheritance and
Polymorphism
NOTES
Example 8.3: A program to demonstrate multilevel inheritance
class FirstClass //superclass
{
int i;
int j;
void get_first(int a, int b)
{
i=a;
j=b;
}
}
class SecondClass extends FirstClass //intermediate
superclass
{
int k;
void get_second(int c)
{
k=c;
}
}
class ThirdClass extends SecondClass //subclass
{
int l;
void get_third(int m)
{
l=m;
}
void display()
{
System.out.println(The value of superclasss i and j is:
+i+ and +j);
System.out.println(The value of intermediate superclasss
k is: +k);
System.out.println(The value of subclasss l is: +l);
}
}
class MultilevelInheriatnce
{
public static void main(String args[])
{
ThirdClass obj=new ThirdClass();
//accessing superclass method
obj.get_first(9,8);
Self-Instructional
Material 117
Inheritance and
Polymorphism
NOTES
//accessing intermediate superclass method
obj.get_second(10);
//accessing subclass method
obj.get_third(11);
obj.display();
}
}
The output of the program is
The value of superclasss i and j is: 9 and 8
The value of intermediate superclasss k is: 10
The value of subclasss l is: 11
In this example, the class FirstClass is inherited by the class SecondClass,
which in turn is inherited by the class ThirdClass. This implies that FirstClass
is the superclass while SecondClass is the intermediate superclass. The subclass
ThirdClass inherits the members of both the classes FirstClass and
SecondClass. Hence, it includes data members i, j, k and get_first(),
get_second() methods.
8.3.4 Multiple Inheritance
In multiple inheritance, a class inherits properties from more than one superclass as
shown in Figure 8.5. In Java, it is not possible to implement multiple inheritance directly.
However, there is a concept known as interface through which multiple inheritance can
be implemented.
Person Company
Owner
Figure 8.5 Example of Multiple Inheritance
8.4 ACCESS MODIFIERS
In the programs discussed so far, the class members are accessible everywhere in the
program and the subclass can inherit all the variables and methods of a superclass by
using the keyword extends. However, there might be certain situations when we
want to restrict the accessibility of members of a class for various reasons, security
being one of the main reasons. For this, Java provides three types of access modifier,
namely, public, private and protected.
Public: When a member of a class is declared as public, it can be accessed
everywhere in the program.
Check Your Progress
1. Define inheritance.
2. The class that is
inherited by the
new class is called
_____________.
3. A Java subclass
can be defined by
using the
_____________
keyword.
4. Java does not
implement
multiple
inheritance
directly. (True or
False)
5. In which of the
following
inheritances, a
superclass is
inherited by more
than one subclass?
(a) single
inheritance
(b) multiple
inheritance
(c) heirarchical
inheritance
(d) multilevel
inheritance
Self-Instructional
118 Material
Inheritance and
Polymorphism
NOTES
Private: A member declared as private can be accessed only within a class.
Protected: A member declared as protected is accessible not only to all the
classes and subclasses in the same package but also to subclasses in other
packages.
Note that if no access modifier is specified, by default the data member of a class
is visible only within the same package. We may use the word friendly in connection
with the default access, however, friendly is not a Java keyword.
Apart from the access modifiers discussed, there is another access modifier namely
private protected which was used with the release of Java 1.0. However, it has
been dropped in Java 1.1 and further versions. If data members are declared as private
protected, they can be accessed by all the subclasses irrespective of the package to
which they belong. However, they are not visible in other classes of the same package
(Table 8.1).
Table 8.1 Visibility of Field inside a Class
Access location


Access modifier
Same
class
Subclass in
same
package
Non-
subclasses in
same
package
Subclass in
other
packages
Non-
subclasses in
other
packages
Public
Private
Protected
Default
These are certain rules that can be followed to select appropriate access modifier.
If the data member is to be made
visible everywhere in the program, use public access modifier.
invisible everywhere except within the same class, use private access modifier
visible everywhere in the same package and subclasses in other package, use
protected access modifier.
visible everywhere in the same package only, use the default access modifier.
visible only in the subclasses irrespective of packages, use private
protected.
Example 8.4: A program to demonstrate the use of private, public and default access
modifiers
class FirstClass
{
int i; //default variable
private int j; //private variable
public int k; //public varaible
int get_data(int l)
{
j=l;
return j;
}
Self-Instructional
Material 119
Inheritance and
Polymorphism
NOTES
}
class VisibilityTest
{
public static void main(String[] args)
{
FirstClass obj=new FirstClass();
obj.i=20; //i can be accessed directly
obj.k=60; //k can be accessed directly
//this will cause error as j cannot be
//accessed directly
//obj.j=60;
//j can be accessed through its method
int a=obj.get_data(40);
System.out.println(The value of i,j and k are: +obj.i+
,+a+ and +obj.k+ respectively.);
}
}
The output of the program is
The value of i,j and k are: 20,40 and 60 respectively.
In this example, variable i is set to default access, variable j is declared as
private and variable k is declared as public. In the class VisibilityTest,
only variables i and k can be accessed directly. The variable j can be accessed through
its method get_data().
8.5 SUBCLASS CONSTRUCTOR
In Java, we can use the subclass constructor to initialize instance variables of both the
superclass and the subclass.
Example 8.5: A program to explicitly initialize the instance variables of superclass
inside the subclass constructor
class FirstClass
{
int x,y;
int func1()
{
return (x+y);
}
}
class SecondClass extends FirstClass
{
int z;
Self-Instructional
120 Material
Inheritance and
Polymorphism
NOTES
SecondClass(int a, int b, int c) //subclass constructor
{
// initializing instance variables of superclass
x=a;
y=b;
// initializing instance variable of subclass
z=c;
}
int func2()
{
return (x+y+z);
}
}
class ExplicitInitialization
{
public static void main (String args[])
{
SecondClass obj=new SecondClass(10,20,30);
int result1=obj.func1();
int result2=obj.func2();
System.out.println(The first result is: +result1);
System.out.println(The second result is: +result2);
}
}
The output of the program is
The first result is: 30
The second result is: 60
In this example, the subclass SecondClass explicitly initializes the instance
variables x and y of the superclass. However, if instance variables of superclass are
declared as private, then subclass cannot access or initialize these instance variables
of superclass. For this, Java provides a keyword super that can be used by the
subclass to pass values to the private variables of superclass by calling its constructor.
The syntax for using super keyword is
super(parameter_list);
Here, parameter_list specifies the parameters required by the superclass
constructor.
These are certain points that should be kept in mind while using super keyword.
It is used only within a subclass constructor.
It should be the first statement to be executed inside the subclass constructor.
The parameters specified in the super() method must match the order and
type of the variables declared in the superclass constructor.
Self-Instructional
Material 121
Inheritance and
Polymorphism
NOTES
Example 8.6: A program to demonstrate the use of super keyword
class FirstClass
{
private int x,y; //private variables
FirstClass(int l, int b)
{
x=l;
y=b;
}
int func1()
{
return (x+y);
}
}
class SecondClass extends FirstClass
{
int z;
SecondClass (int l, int b, int c)
{
super(l,b); //pass values to superclass constructor
z=c;
}
int func2()
{
return (z+func1());
}
}
class UsingSuper
{
public static void main (String args[])
{
SecondClass obj=new SecondClass(10,20,30);
int result1=obj.func1();
int result2=obj.func2();
System.out.println(The first result is: +result1);
System.out.println(The second result is: +result2);
}
}
The output of the program is
The first result is: 30
The second result is: 60
In this example, the statement SecondClass obj=new
SecondClass(10,20,30) calls the constructor of SecondClass, which again
calls the constructor of FirstClass by using super keyword and passes values
10 and 20 to the variables l and b of FirstClass constructor respectively.
Check Your Progress
6. A member declared
as ____________
can be accessed
only within the
class.
7. Protected members
are accessible to
the non-subclasses
of other packages.
(True or False)
8. The superclass
constructor can be
called within the
subclass
constructor by
using
___________
keyword.
Self-Instructional
122 Material
Inheritance and
Polymorphism
NOTES
8.6 METHOD OVERRIDING
If a subclass method has the same name, same parameter list and same return type as
a superclass method, then we say that the method in the subclass overrides the method
in the superclass. When the overridden method is called, the version of the method
defined in the subclass will be invoked instead of the method defined in the superclass.
That is, the method in the subclass will hide the method defined in the superclass.
Example 8.7: A program to demonstrate method overriding
class Person
{
String name=John;
int age=30;
void result()
{
System.out.println(The name and the age of the person are:
+name+ and +age+ respectively );
}
}
class Employee extends Person
{
int salary=40000;
void result() //result() is overridden
{
System.out.println(The name and the salary of the employee
are: +name+ and +salary+ respectively );
}
}
public class MethodOverriding
{
public static void main(String[] args)
{
Employee obj=new Employee();
obj.result(); // invokes Employees result()
}
}
The output of the program is
The name and the salary of the employee are: John and 40000
respectively
In this example, when the method result() is invoked through an object obj
of type Employee , the method result()defined within Employee is executed.
That is, the method result() of the subclass Employee overrides the method
result() of the superclass Person. However, if we want to access the overridden
method result()of the superclass, we can use the keyword super. For example,
consider the class Employee defined in
Self-Instructional
Material 123
Inheritance and
Polymorphism
NOTES
Example 8.7. It can be modified using super keyword as follows:
class Employee extends Person
{
int salary=40000;
void result()
{
super.result(); // invokes result() of class Person
System.out.println(The name and the salary of the employee
are: +name+ and +salary+ respectively );
}
}
The output of the program is
The name and the age of the person are John and 30 respectively
The name and the salary of the employee are John and 40000
respectively
Now, when the method result() is invoked through an object obj of type
Employee, the superclass version of result() is invoked within the subclass
version.
8.7 POLYMORPHISM
Polymorphism is the ability of a function or a message to be processed in more than one
form. We have already seen how polymorphism can be implemented through method
overloading or method overriding. Other than overloading and overriding, another type
of polymorphism is dynamic binding.
Dynamic binding is the process of linking of a method call to the actual code of
the method at run-time. That is, in dynamic binding, the actual code to be executed is not
known to the compiler until run-time.
Consider an example in which three different classes, Square, Rectangle
and Circle are derived from the base class GeometricalShapes. To understand
dynamic binding, consider the code segment given here.
class DynamicBinding
{
public static void main(String[] args)
{
GeomatricalShapes gs = new GeomatricalShapes();
Square obj1=new Square();
Rectangle obj2=new Rectangle();
Circle obj3=new Circle();
gs=obj1; gs.area(); //invokes Squares area()
gs=obj2; gs.area(); //invokes Rectangles area()
gs=obj3; gs.area(); //invokes Circles area()
}
}
Self-Instructional
124 Material
Inheritance and
Polymorphism
NOTES
Here, the method area()of the base class is implemented in different ways in
all its derived classes. At run-time, depending on the object being referenced, the desired
method will be called.
8.8 USING final KEYWORD
Java provides a keyword final that can be applied to variables, methods and classes.
The meaning of the final keyword when applied to variables is different from its
meaning when it is applied to methods and classes.
8.8.1 Final Variables
The value of a variable can be prevented from being modified by declaring a variable as
final.
The syntax for declaring a final variable is
final data_type variable_name=constant_value;
An attempt to alter the value of a final variable will generate a compile-time error.
Note that a final variable does not occupy memory for each instance of the class.
Hence, final variable is a constant.
Example 8.8: A program to demonstrate the use of a final variable
class Person
{
final int salary=30000; // final variable
}
class FinalVariable
{
public static void main(String args[])
{
Person obj=new Person();
obj.salary=3000+2000; // error
}
}
In this example, a compile-time error will be generated as the final variable
salary cannot be modified.
8.8.2 Final Methods
As stated earlier, whenever a method is defined in the subclass with the same name and
same signature as in the superclass, it is by default overridden in the subclass. However,
a method can be prevented from being overridden by the subclass by declaring the
method as final.
The syntax for declaring a final method is
final data_type method_name()
{
:
Self-Instructional
Material 125
Inheritance and
Polymorphism
NOTES
}
Example 8.9: A program to demonstrate the use of final method
class Person
{
String name=John;
int age=25;
final void result() // final method
{
System.out.println(The name and the age of the person is:
+name+ and +age);
}
}
class Employee extends Person
{
int salary=30000;
void result() //error
{
System.out.println(The salary of the employee is: + salary);
}
}
class FinalMethod
{
public static void main(String args[])
{
Employee obj=new Employee();
obj.result();
}
}
This program will generate a compile-time error as the method result() is
declared final and it cannot be overridden in the subclass.
8.8.3 Final Classes
A class which cannot be further inherited or cannot have any subclass is known as final
class. To make a class final, the class declaration is preceded by the final keyword.
If a class is declared as final, all of its methods are automatically declared as final.
The syntax for declaring a final class is
final class class_name
{
:
}
Example 8.10: A program to demonstrate the implementation of final class
final class Person // final class
{
Check Your Progress
9. When is a
superclass method
said to be
overridden in the
subclass?
10. Which keyword
prevents a method
in a superclass
from being
overridden by its
subclass?
11. Java enables us to
specify that a
method must be
overridden in the
subclass by using
_______ keyword.
12. Which of the
following classes
cannot be
inherited?
(a) abstract
class A
{
:
}
(b) class B
{
:
}
(c) final
class C
{
:
}
(d) none of these
Self-Instructional
126 Material
Inheritance and
Polymorphism
NOTES
String name=John;
int age=25;
void result()
{
System.out.println(The name and the age of the person are:
+name+ and +age+respectively);
}
}
class Employee extends Person //error
{
int salary=30000;
void display()
{
System.out.println(The salary of the employee is: +salary);
}
}
class FinalClass
{
public static void main(String args[])
{
Employee obj=new Employee();
obj.result();
obj.display();
}
}
This program will generate a compile-time error since the class Person is a
final class and cannot be further inherited.
8.9 ABSTRACT METHODS AND CLASSES
As discussed earlier, a method can be prevented from being overridden in the subclass
by using the final keyword. However, sometimes there might be a situation, when the
method in the superclass always needs to be redefined in the subclass and for this
overriding becomes necessary. This kind of situation can arise when the superclass is
not able to provide meaningful implementation for its methods. In such a case, the
superclass provides a generalized structure of the method and leaves the implementation
part to its subclass. To deal with such situation, Java allows us to specify that a method
must always be overridden in the subclass by using the keyword abstract in the
method declaration.
The syntax for declaring an abstract method is
abstract data_type method_name();
If a class has one or more abstract methods, the class must also be declared as
abstract by using the keyword abstract.
The syntax for declaring an abstract class is
Self-Instructional
Material 127
Inheritance and
Polymorphism
NOTES
abstract class class_name
{
:
abstract data_type method_name();
}
The class which inherits the abstract class must provide implementation for all
the methods or the class should declare itself as abstract.HHHefwf
These are certain points that should be kept in mind while using abstract class.
An abstract class cannot be instantiated.
Abstract methods of an abstract class must always be implemented in the
subclass.
Abstract methods must end with semicolon (;) because they do not have
any functionality.
There can be both defined and undefined methods in an abstract class.
Constructors or static methods cannot be declared as abstract.
Example 8.11: A program to demonstrate the concept of abstract class
abstract class Person //abstract class
{
String name;
int age;
Person(String n, int a)
{
name=n;
age=a;
}
abstract void display(); //abstract method
}
class Employee extends Person
{
int salary;
Employee(String n, int a, int s)
{
super(n,a); //pass values to superclass
salary=s;
}
void display()
{
System.out.println(The name and the age of the employee
are: +name+ and +age+ respectively);
System.out.println(The salary of the employee is: +salary);
}
Check Your Progress
13. Abstract method
contains only
undefined methods.
(True or False)
14. Identify the error
in the following
class definition.
class A
{
int i=10;
abstract
void
display();
}
Self-Instructional
128 Material
Inheritance and
Polymorphism
NOTES
}
class AbstractClass
{
public static void main(String args[])
{
Employee obj=new Employee(John, 23, 2000);
obj.display();
}
}
The output of the program is
The name and the age of the employee are: John and 23
respectively
The salary of the employee is: 2000
In this example, the Person is an abstract class which contains an abstract
method display()and this method is implemented in the subclass Employee.
8.10 SUMMARY
In this unit, you have learned that:
Inheritance is the process of deriving a new class from the existing one in such a
way that the new class inherits all the members (data members and methods) of
the existing class.
The class that is inherited by other classes is called a base class or superclass or
parent class. The class that inherits the properties of the superclass is called a
subclass or derived class or child class.
A subclass can be defined by using extends keyword.
Inheritance may take different forms, namely, single inheritance, hierarchical
inheritance, multilevel inheritance and multiple inheritance.
In single inheritance, a class is derived from a single superclass. The type of
inheritance in which more than one class is derived from a single superclass is
called hierarchical inheritance. In multilevel inheritance, one class is inherited
from another class, which in turn is inherited from some other class.
In multiple inheritance, a class inherits properties from more than one superclass.
Java does not support multiple inheritance directly. It is implemented through a
concept called interface.
Access modifier controls the accessibility of class members. Java provides three
types of access modifiers, namely public, private and protected.
The method in the subclass overrides the method in the superclass if a subclass
method has the same name and same signature as in the superclass.
Polymorphism is the ability of a function or a message to be processed in more
than one form. Dynamic binding is the process of linking of a method call to the
actual code of the method at run-time.
Self-Instructional
Material 129
Inheritance and
Polymorphism
NOTES
Java provides a keyword final that can be applied to variables, methods and
classes. Variables declared as final cannot be modified. A method can be prevented
from being overridden by the subclass by declaring the method as final. A
class which cannot be further inherited or cannot have any subclass is known as
final class.
Java allows us to specify that a method must always be overridden in the subclass
by using the keyword abstract in the method declaration.
8.11 KEY TERMS
Abstract class: It is a class that is declared abstractit may or may not include
abstract methods.
Abstract method: It is a method that is declared without an implementation
(without braces, and followed by a semicolon).
Access modifiers: They are keywords used to specify the declared accessibility
of a member or a type.
Inheritance: It is the process of deriving a new class from the existing one in
such a way that the new class inherits all the members (data members and methods)
of the existing class.
Polymorphism: It is the capability of an action or method to do different things
based on the object that it is acting upon.
8.12 ANSWERS TO CHECK YOUR PROGRESS
1. Inheritance is the process of deriving a new class from the existing one in which
the new class inherits all the members (data members and methods) of the existing
class.
2. Superclass
3. extends
4. True
5. (c)
6. Private
7. False
8. super
9. A superclass method is said to be overridden in the subclass when the method in
the subclass has the same name and same signature as the method in the
superclass.
10. final
11. abstract
12. (c)
13. False
14. The class is not declared as abstract.
Self-Instructional
130 Material
Inheritance and
Polymorphism
NOTES
8.13 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What is inheritance? Explain how inheritance facilitates code reusability.
2. What are the various types of inheritance in Java? Explain with examples.
3. What is method overriding? How can we prevent overriding of a method?
4. What is the use of final keyword in Java? Explain by giving examples.
Long-Answer Questions
1. Discuss various access modifiers available in Java.
2. Write a program to show how super keyword can be used to call superclass
constructor within a subclass constructor.
3. Describe abstract methods and abstract classes. List the rules for implementing
abstract methods.
4. Give the output of the following program.
class Class1
{
int i;
Class1(int p)
{
i=p;
}
void display()
{
System.out.println(The value of i is: +i);
}
}
class Class2 extends Class1
{
int j;
Class2(int p,int q)
{
super(p);
j=q;
}
void display()
{
System.out.println(The value of j is: +j);
}
}
class SampleClass
{
Self-Instructional
Material 131
Inheritance and
Polymorphism
NOTES
public static void main(String args[])
{
Class2 obj=new Class2(30,40);
obj.display();
}
}
5. Write a program to create a Drug class. A class Tablet is derived from it,
which in turn is inherited by class Pain Reliever. Explain the type of inheritance
implemented.
Self-Instructional
Material 133
Exception Handling
Threads
NOTES
UNIT 9 EXCEPTION HANDLING
THREADS
Structure
9.0 Introduction
9.1 Unit Objectives
9.2 Concept of Threads
9.2.1 Main Thread
9.2.2 Creating Threads
9.2.3 Extending Threads
9.2.4 Implementing Runnable Interface
9.3 Life Cycle of a Thread
9.4 Thread Methods
9.4.1 Using Yield(), Sleep() and Stop() Method
9.4.2 Using isalive() and join() Method
9.5 Threads Priority
9.6 Synchronization of Threads
9.6.1 Synchronizing Methods
9.6.2 Synchronizing Statements
9.6.3 Deadlock
9.7 Inter-Thread Communication
9.8 Suspending, Resuming and Stopping Threads
9.9 Summary
9.10 Key Terms
9.11 Answers to Check Your Progress
9.12 Questions and Exercises
9.0 INTRODUCTION
Most of the modern operating systems support multitasking, that is, the ability to execute
multiple programs simultaneously. Javas multithreading is a specialized form of
multitasking. Multithreading is a programming concept in which a program (process) is
divided into two or more subprograms (subprocesses), each of which can perform
different tasks concurrently. For example, one subprogram can format text in the text
editor while another subprogram can print the same.
In this unit, you will learn about the concept of threads.
9.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Understand the concept of threads in Java
Describe the complete life cycle of a thread
Explain various methods of a thread class
Learn about thread priority
Know about the synchronization of threads
Discuss inter-thread communication
Illustrate how to suspend, resume and stop a thread in the new version of Java
Self-Instructional
134 Material
Exception Handling
Threads
NOTES
9.2 CONCEPT OF THREADS
You have learnt about programs with only a single sequential flow of control, that is, the
program simply starts, performs a series of operations and eventually ends. There is
only one statement under execution at any given point of time and they are called single-
threaded programs. A thread is just like a program which has a single flow of control. It
also has a starting point, the part of execution and an end. Java also allows you to use
multiple flows of control in a program and such a program is known as a multithreaded
program. In a multithreaded program, each thread is a separate tiny module which runs
parallel with other threads. However, running in parallel does not mean that they are
running at the same time. As most of the time the threads run on the single processor, in
reality, only one thread is executed at a given time. However, the switching from one
thread to another occurs so fast that it gives an illusion to the user that all the threads are
being executed at the same time. Threads are called lightweight processes. This is
because all the threads in a main application program share the same address space in
the memory.
There are several advantages of using multithreaded programs over single-threaded
programs. In a traditional single-threaded environment, the central processing unit (CPU)
sits idle most of the time, as the program has to wait for each of the task to complete
before proceeding to the next task. In a multithreaded environment, since different tasks
can be assigned to different threads, the program makes maximum utilization of the
CPU, keeping the idle time of the CPU to minimum. For example, one thread can read
data, another thread can process it and a third thread can write it thus improving the
overall performance. Multithreading is best-suited for those applications that require
multiple tasks to be done simultaneously.
9.2.1 Main Thread
Any Java program always contains at least one thread even if you do not create one.
This thread is called the main thread and it is the one which immediately starts executing
when you start a program. The main thread can be used to create and start other child
threads and it must often be the last thread to finish execution because it performs
various other actions such as, shutdown action and releasing resources which are used
by the program. The main thread is created automatically but it can be controlled through
a Thread object. For this, its reference is needed which can be obtained by calling the
method currentThread(), which is a public static member of Thread class.
This method returns a reference to the thread on which it is called. You can control the
main thread just like any other thread, once you have a reference to it.
Example 9.1: A program to control the main thread
class MainThread
{
public static void main(String[] args)
{
Thread th=Thread.currentThread();
System.out.println(The name of the current thread is: +th);
//changing the name of the thread
th.setName(MyThread);
Self-Instructional
Material 135
Exception Handling
Threads
NOTES
System.out.println(The name of the current thread after
changing the name is: +th);
System.out.println(Main Thread exiting);
}
}
The output of the program is
The name of the current thread is: Thread[main,5,main]
The name of the current thread after changing the name is:
Thread[MyThread,5,main]
Main Thread exiting
In this example, the method currentThread() is called to obtain a reference
to the main thread and this reference is stored in the variable th. Here, the name of the
main thread is changed by calling the method setName() and the new thread name is
redisplayed.
9.2.2 Creating Threads
In Java, threads can be created in two ways which are as follows:
By defining a class that extends the Thread class
By implementing the Runnable interface
In both the approaches, threads are implemented in the form of objects which
contain a method called run(). It is the most important method in the Thread class.
It is the entry point of a new thread and it is the place where the task to be performed by
the thread is defined. The execution of a thread starts with the call to run() method.
The run() method is automatically invoked when you invoke another method of Thread
class called start().
9.2.3 Extending Threads
You can create a thread by creating a new class that extends the Thread class
defined in java.lang package and creating an instance of the class. The extending
class must override the run() method. Inside the run() method, the code that needs
to be executed by the thread will be defined.
The code segment to extend the Thread class and override the run() method
is
class ThreadName extends Thread
{
public void run()
{
: // code for the new thread
}
}
Now the instance of the class ThreadName can be created and run using the
statements as follows:
ThreadName objectname=new ThreadName();
objectname.start();
Self-Instructional
136 Material
Exception Handling
Threads
NOTES
The second statement invokes the start() method after which the thread will
be ready to run. It will start running once the Java runtime invokes its run() method.
Example 9.2: A program to demonstrate creating threads by extending the Thread
class
class Thread1 extends Thread
{
public void run() //entry point of Thread1
{
int i=0;
while(i<5)
{
System.out.println(First Child Thread:+i);
i=i+1;
}
System.out.println(\t First child exited);
}
}
class Thread2 extends Thread
{
public void run() //entry point of Thread2
{
int j=0;
while(j<5)
{
System.out.println(Second Child Thread:+j);
j=j+1;
}
System.out.println(\t Second child exited);
}
}
class ExtendingThread
{
public static void main(String[] args)
{
Thread1 firstthread=new Thread1();
firstthread.start(); // starts the first thread
Thread2 secondthread=new Thread2();
secondthread.start(); // starts the second thread
int k=0;
while(k<5)
{
System.out.println(Main Thread:+k);
Self-Instructional
Material 137
Exception Handling
Threads
NOTES
k=k+1;
}
System.out.println(\t Main thread exiting);
}
}
The output of the program is
First Child Thread:0
Main Thread:0
Second Child Thread:0
First Child Thread:1
Main Thread:1
Second Child Thread:1
First Child Thread:2
Main Thread:2
Second Child Thread:2
First Child Thread:3
Main Thread:3
Second Child Thread:3
First Child Thread:4
Main Thread:4
Second Child Thread:4
First child exited
Main thread exiting
Second child exited
When you start the program, the main thread immediately starts running. The
main thread then starts two child threads Thread1 and Thread2, both of which will
perform different tasks. Once the main thread reaches the end of the main() method,
there will be altogether three threads running concurrently on their own in the program,
Thread1, Thread2 and the main thread. These three threads will run independently
whenever CPU is available to them. There is no specific order of their execution. Hence,
the program may generate different output every time we run it.
9.2.4 Implementing Runnable Interface
Another way of creating a thread is to create a class that implements the Runnable
interface. The Runnable interface consists of a single method run() which is required
for implementing thread. You can create a thread and pass the object of the class that
implements the Runnable interface as an argument of the Thread classs constructor.
The thread will now be activated by calling the start() method. Implementing
Runnable is much more convenient than extending a Thread class when a program
needs to inherit from a class apart from the Thread class since Java allows only a
single base class.
The code segment to implement Runnable interface is as follows:
class MyNewThread implements Runnable
{
Self-Instructional
138 Material
Exception Handling
Threads
NOTES
public void run()
{
: // code for the new thread
}
}
Example 9.3: A program to demonstrate creating threads by implementing Runnable
interface
class MyNewThread implements Runnable // implements Runnable
{
public void run() // implements run() method
{
int i=0;
while(i<=4)
{
System.out.println(Child Thread: +i);
i++;
}
}
}
class RunnableInterface
{
public static void main(String[] args)
{
/*an object of class implementing Runnable interface*/
MyNewThread runnableobj=new MyNewThread();
/*an object of Thread class taking runnable object as
argument*/
Thread threadobj=new Thread(runnableobj);
threadobj.start();
int j=0;
while(j<=4)
{
System.out.println(Main Thread: +j);
j++;
}
System.out.println(Main Thread Exiting);
}
}
The output of the program is
Main Thread: 0
Child Thread: 0
Main Thread: 1
Child Thread: 1
Self-Instructional
Material 139
Exception Handling
Threads
NOTES
Main Thread: 2
Child Thread: 2
Main Thread: 3
Child Thread: 3
Main Thread: 4
Child Thread: 4
Main Thread Exiting
In this example, MyNewThread is a class which implements the Runnable
interface. Inside the main() method, an instance runnableobj of MyNewThread
is created which is passed as an argument to the Thread classs constructor. When
the new thread starts, the run() method of runnableobj is called.
9.3 LIFE CYCLE OF A THREAD
There are various states that a Java thread can enter during its life cyclenewborn,
runnable, running, blocked and dead state. A thread is always in either one of these five
states. The thread can transit from one state to another as shown in Figure 9.1.
Newborn
Blocked
Dead
stop()
stop()
stop()
start()
suspend()
sleep()
wait()
resume()
Running
Runnable
yield()
notify()
Figure 9.1 Life Cycle of a Thread
Newborn State
When a thread is created, it enters a state called the newborn state. It is the first state in
the life cycle of a thread in which the thread is just newly born and it is not yet ready to
run. That is, the thread is considered not active. During this stage, you can either schedule
the thread for running by calling the start() method or kill it using stop() method.
You cannot use any other method in the newborn state otherwise it will throw exception.
Runnable State
The thread enters the runnable state when it is ready to run and waiting for the CPU to
be allocated to it. Whenever a thread is ready to run, it is placed in the queue of threads
that are waiting for the availability of the CPU. The thread scheduler picks one of the
threads in the queue based on their priority. If all the threads in the queue have equal
priority, the scheduler gives time slots for execution in round robin fashion. A thread can
voluntarily give up its turn and give the control to another thread of equal priority using a
static method called yield(). It then joins the queue at the end and waits for its turn
to come.
Self-Instructional
140 Material
Exception Handling
Threads
NOTES
Running State
A thread is said to be in the running state when it gets the processor for execution, that
is, when the thread scheduler picks it to be the currently executing thread. The thread
will be executed by the processor and will keep running until it gets preempted by a
thread of higher priority or it gives up the control in either of the following conditions.
When being suspended using suspend() method: If we want to suspend
a thread for sometime but do not want to kill it, then we can use the suspend()
method. The suspended thread can be brought back to the execution state by
invoking a method called resume().
When it is made to sleep using sleep() method: The sleep() method
makes the thread sleep for the specified period of time. The thread will
automatically return back to its execution state once the specified time is elapsed.
When it is made to wait using wait() method: A thread can be made to
wait until some events occur by calling wait() method. We can make the
thread run again by using the notify() method.
Blocked State
A thread is in blocked state when the thread is either suspended or sleeping or waiting.
The thread in this state is not considered dead, so it can re-enter the runnable state and
subsequently run if the CPU is available.
Dead State
A thread is said to be in dead state if its run() method completes or it has been killed
deliberately by invoking the stop() method at any state. Once a thread enters the
dead state, it cannot re-enter any other state even if the start() method is invoked.
Note: The predefined methods stop(), suspend() and resume() have been deprecated from the later
versions of Java.
9.4 THREAD METHODS
You have seen the use of the start() and run() method. There are various other
methods of Thread class. They are yield(), sleep(), stop(), isAlive()
and join() method.
9.4.1 Using yield(), sleep() and stop() method
The yield(), sleep() and stop() methods are responsible for controlling the
behavior of a thread and the transition of thread from one state to another.
The general form of sleep() method is
static void sleep(long milliseconds) throws Interrupted
Exception
where, milliseconds is the number of milliseconds to suspend. As the
sleep() method throws an exception, the call to sleep() method must be enclosed
in a try block followed by a catch block otherwise the program will not compile.
The general form of stop() method is
static void stop()
Self-Instructional
Material 141
Exception Handling
Threads
NOTES
The general form of yield() method is
static void yield()
Example 9.4: A program to demonstrate the use of yield(), sleep() and stop()
method
class Thread1 extends Thread
{
public void run()
{
int i=0;
while(i<5)
{
if(i==2)
yield(); //calls yield() method on Thread1
System.out.println(First Child Thread:+i);
i=i+1;
}
System.out.println(\t First child exited);
}
}
class Thread2 extends Thread
{
public void run()
{
int j=0;
while(j<5)
{
System.out.println(Second Child Thread:+j);
if(j==3)
stop(); //calls stop() method on Thread2
j=j+1;
}
System.out.println(\t Second child exited);
}
}
class Thread3 extends Thread
{
public void run()
{
int k=0;
while(k<5)
{
System.out.println(Third Child Thread:+k);
if(k==3)
try
Self-Instructional
142 Material
Exception Handling
Threads
NOTES
{
sleep(1000); /*calls sleep() method on
Thread3*/
}
catch(Exception e)
{
}
k=k+1;
}
System.out.println(\t Third child exited);
}
}
class ThreadMethods
{
public static void main(String[] args)
{
Thread1 th1=new Thread1();
Thread2 th2=new Thread2();
Thread3 th3=new Thread3();
th1.start();
th2.start();
th3.start();
int k=0;
while(k<5)
{
System.out.println(Main Thread:+k);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(Main Thread interrupted);
}
k=k+1;
}
System.out.println(\t Main thread exiting);
}
}
Self-Instructional
Material 143
Exception Handling
Threads
NOTES
The output of the program is
First Child Thread:0
First Child Thread:1
Main Thread:0
First Child Thread:2
First Child Thread:3
First Child Thread:4
First child exited
Second Child Thread:0
Second Child Thread:1
Second Child Thread:2
Second Child Thread:3
Third Child Thread:0
Third Child Thread:1
Third Child Thread:2
Third Child Thread:3
Main Thread:1
Third Child Thread:4
Third child exited
Main Thread:2
Main Thread:3
Main Thread:4
Main thread exiting
In this example, although Thread1 started first, it relinquishes its control after
implementing the while loop only two times, as the yield() method is invoked.
Thread2 starts running and it is killed by invoking the stop() method. Thread3
while running goes to sleep for 1000 milliseconds on the invocation of sleep() method.
9.4.2 Using isAlive() and join() method
As you know, the main thread must often be the last thread to terminate since it performs
several other tasks. For this, we can invoke sleep() method within main() method
as in the Example 9.4 which makes the main thread sleep for specified period of time
until all the child threads complete their execution. However, it is not considered to be a
good approach as the main thread has no information when a child thread will finish its
execution. In this case, the main thread has to sleep for a period long enough to assure
the termination of child threads prior to its termination. For example, if the main thread is
made to sleep for 2500 milliseconds and the child threads altogether take 1000 milliseconds
to terminate, then there will be a delay of 1500 milliseconds for the main thread to
terminate. Thus, it is necessary for the main thread to know when the child threads have
finished. There are two ways to determine whether a thread has ended, which are as
follows:
First, we can call isAlive() method. The general form of isAlive() method
is
final boolean isAlive()
Self-Instructional
144 Material
Exception Handling
Threads
NOTES
This method is used to test whether a thread is still alive. It returns true if the
thread is running, otherwise it returns false. The isAlive() method is used
occasionally.
The method which is more commonly used to wait for a thread to finish is join()
method. The general form of join() method is
final void join() throws InterruptedException
This method is used to halt the execution of current thread (calling thread) until
the thread on which the method is called terminates. It ensures that the current
thread will wait until the called thread finishes its execution. There is another
form of join() method which takes the parameter in milliseconds which
is the maximum amount of time that a thread can wait for the specified thread to
terminate. As the join() method throws an exception, it must be enclosed in a
try block followed by a catch block.
Example 9.5: A program to demonstrate the use of isAlive() and join() methods
class Thread1 extends Thread
{
public void run() //entry point of Thread1
{
int i=0;
while(i<5)
{
System.out.println(First Child Thread:+i);
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println(First Child Thread interrupted);
}
i=i+1;
}
System.out.println(\t First child exited);
}
}
class Thread2 extends Thread
{
public void run() //entry point of Thread2
{
int j=0;
while(j<5)
{
System.out.println(Second Child Thread:+j);
try
{
Self-Instructional
Material 145
Exception Handling
Threads
NOTES
sleep(1000);
}
catch(Exception e)
{
System.out.println(Second Child Thread interrupted);
}
j=j+1;
}
System.out.println(\t Second child exited);
}
}
class JoinMethod
{
public static void main(String[] args)
{
Thread1 firstthread=new Thread1();
firstthread.start();
Thread2 secondthread=new Thread2();
secondthread.start();
//Checks if the child threads are alive
System.out.println(Is first thread
alive?+firstthread.isAlive());
System.out.println(Is second thread
alive?+secondthread.isAlive());
//Wait for Threads to finish
try
{
System.out.println(Waiting for the child threads to finish);
firstthread.join();
secondthread.join();
}
catch(Exception e)
{
System.out.println(Exception caught);
}
//Checks if the child threads are still alive
System.out.println(Is first thread
alive?+firstthread.isAlive());
System.out.println(Is second thread
alive?+secondthread.isAlive());
Self-Instructional
146 Material
Exception Handling
Threads
NOTES
System.out.println(\t Main Thread exiting);
}
}
The output of the program is
First Child Thread:0
Is first thread alive?true
Second Child Thread:0
Is second thread alive?true
Waiting for the child threads to finish
First Child Thread:1
Second Child Thread:1
First Child Thread:2
Second Child Thread:2
First Child Thread:3
Second Child Thread:3
Second Child Thread:4
First Child Thread:4
Second child exited
First child exited
Is first thread alive?false
Is second thread alive?false
Main Thread exiting
Note: The join() method is called on the child threads Thread1 and Thread2 to ensure that the main
thread waits for these child threads to finish.
9.5 THREADS PRIORITY
The threads you have seen so far are of equal priority in which the Java scheduler
selects the thread for execution on the first-come, first-serve basis. However, each
thread can be assigned different priority which will decide the order in which it is scheduled
for running. Priorities are the integers which specify the relative priority of one thread to
another. When a thread is created, it inherits its priority from the thread that created it.
However, the priority of a thread can be changed by using the setPriority()
method of the Thread class.
The syntax to set the priority of a thread is
ThreadName.setPriority(n);
where, n is an integer value which ranges from MIN_PRIORITY (1) and
MAX_PRIORITY (10). The default priority is NORM_PRIORITY whose value is 5.
MIN_PRIORITY, MAX_PRIORITY and NORM_PRIORITY are the constants
defined in Thread class.
Check Your Progress
1. Define a thread.
2. How do you start
a thread?
3. The only method
which is available
in Runnable
interface is
.
4. What are the two
conditions in
which a thread
dies?
5.
thread is the
default thread
which starts
executing
immediately when
we start the
program.
6. What is the
difference between
suspending and
stopping a thread?
7. A thread in a dead
state can run again
on the invocation
of start()
method. (True or
False)
Self-Instructional
Material 147
Exception Handling
Threads
NOTES
When there are multiple threads ready to execute, the highest priority thread is
chosen and executed. Only when the high priority thread stops, yields or enters blocked
state, the low priority thread starts running. However, if any higher priority thread enters,
it will preempt the currently running thread forcing it to move to the runnable state.
Example 9.6: A program to demonstrate the assigning of priority to a thread
class Thread1 extends Thread
{
public void run() //entry point of the Thread1
{
int i=0;
while(i<5)
{
System.out.println(First Child Thread:+i);
i=i+1;
}
System.out.println(\t First child exited);
}
}
class Thread2 extends Thread
{
public void run() //entry point of the Thread2
{
int j=0;
while(j<5)
{
System.out.println(Second Child Thread:+j);
j=j+1;
}
System.out.println(\t Second child exited);
}
}
class ThreadPriority
{
public static void main(String[] args)
{
Thread1 firstthread=new Thread1();
Thread2 secondthread=new Thread2();
// Thread2 assigned highest priority
secondthread.setPriority(Thread.MAX_PRIORITY);
// Thread1 assigned lowest priority
firstthread.setPriority(Thread.MIN_PRIORITY);
firstthread.start();
Self-Instructional
148 Material
Exception Handling
Threads
NOTES
secondthread.start();
System.out.println(\t Main Thread Exiting);
}
}
The output of the program is
Second Child Thread:0
Second Child Thread:1
Second Child Thread:2
Second Child Thread:3
Second Child Thread:4
Second child exited
Main Thread Exiting
First Child Thread:0
First Child Thread:1
First Child Thread:2
First Child Thread:3
First Child Thread:4
First child exited
The first child thread Thread1 has been assigned the minimum priority and
the second child thread Thread2 has been assigned the maximum priority. So despite
Thread1 being the first on which start() method is called, its output is printed in
the last as it has been preempted by the higher priority thread Thread2.
Note: The amount of CPU time a thread gets depends not only on its priority but also on other factors such
as how an operating system implements multithreading.
9.6 SYNCHRONIZATION OF THREADS
When multiple threads need access to a single resource, there must be a way to ensure
that only one thread will use the resource at any given point of time otherwise it may
lead to a severe problem. For example, if one thread in a program reads salary from a
file and another thread tries to update it, then the program may produce an undesirable
output. The solution to this problem can be achieved by using a technique known as
synchronization. The objective of synchronization is to control the access to shared
resources.
Synchronization uses the concept of monitor. A monitor is an object which is used
as a mutually exclusive lock. That is, it can be owned by only one thread at any given
point of time. A thread is said to have entered the monitor when it acquires a lock. Any
other thread which attempts to acquire the lock has to wait until the first thread comes
out of the monitor. There are two ways to implement synchronization, which are as
follows:
Synchronizing methods
Synchronizing statements
Self-Instructional
Material 149
Exception Handling
Threads
NOTES
9.6.1 Synchronizing Methods
You can synchronize a subset (or all) of the methods of any class by using
synchronized keyword. When a method is declared synchronized, Java creates a
monitor. To enter the monitor, you need to call a synchronized method. Only one of the
synchronized methods in a class object can execute at any given time. Java hands over
the monitor to the thread that calls the method first. As long as a thread is inside a
synchronized method, other threads trying to call it (or any other synchronized method)
on the same instance have to wait. Only when the currently executing thread finishes
executing and exits the monitor another waiting thread can enter the monitor.
The syntax to declare a method as synchronized is
synchronized data_type method_name()
{
// code for the method
}
To understand synchronization, let us first consider a program which is not synchronized.
Example 9.7: A program to demonstrate the need of synchronization
class A
{
void display(String msg)
{
System.out.print(( +msg);
try
{
Thread.sleep(1000);
}catch(InterruptedException e)
{
System.out.println(Interrupted);
}
System.out.println());
}
}
class MyThread extends Thread
{
String str;
A obj;
MyThread (A obj1,String s)
{
obj=obj1;
str=new String (s);
}
public void run()
{
obj.display(str);
Self-Instructional
150 Material
Exception Handling
Threads
NOTES
}
}
class UnsynchronizedMethod
{
public static void main(String[] args)
{
A obj=new A();
MyThread th1=new MyThread(obj,THIS);
MyThread th2=new MyThread(obj,IS);
MyThread th3=new MyThread(obj,SYNCHRONIZATION);
th1.start();
th2.start();
th3.start();
}
}
The output of the program is
(THIS(IS(SYNCHRONIZATION)
)
)
The class A has a method named display() which takes a parameter msg of
String type. This method will print the msg string enclosed in the first brackets.
Note that the sleep() method is invoked after the display() method prints the
opening bracket and the string msg which causes the current thread to halt for one
second. The constructor of class MyThread takes two arguments, a reference to an
instance of class A and a string. When the first thread starts, the objects run()
method is invoked. The run() method invokes the display()method on the instance
obj of A, and passes the string str. The call to sleep() method allows execution
to switch to another thread before the first thread could complete the method. Thus, the
output of the program is not as expected and the strings are in mixed up form. This is
because, the three threads call the same method display() without anything to stop
them from competing each other to complete the method.
Now try to modify the program in Example 9.7 by preceding the definition of
display() method with synchronized keyword. This will serialize access to
display() method by restricting its access to only one thread at a time thus producing
the correct output.
Example 9.8: A program to demonstrate synchronized method
class A
{
synchronized void display(String msg)
{
System.out.print(( +msg);
try
{
Thread.sleep(1000);
Self-Instructional
Material 151
Exception Handling
Threads
NOTES
}catch(InterruptedException e)
{
System.out.println(Interrupted);
}
System.out.println());
}
}
class MyThread extends Thread
{
String str;
A obj;
MyThread (A obj1,String s)
{
obj=obj1;
str=new String (s);
}
public void run()
{
obj.display(str);
}
}
class SynchronizedMethod
{
public static void main(String[] args)
{
A obj=new A();
MyThread th1=new MyThread(obj,THIS);
MyThread th2=new MyThread(obj,IS);
MyThread th3=new MyThread(obj,SYNCHRONIZATION);
th1.start();
th2.start();
th3.start();
}
}
The output of the program is
(THIS)
(IS)
(SYNCHRONIZATION)
Note: Once a thread is in synchronized method on an instance, no other thread can enter any other
synchronized method on the same instance. However, simultaneous execution of synchronized methods is
possible for two different instance of the same class.
Self-Instructional
152 Material
Exception Handling
Threads
NOTES
9.6.2 Synchronizing Statements
Another way of managing the execution of the thread is to synchronize a block of code
or statement and this is more powerful. Synchronizing a method does not work in all
cases. For example, the class you want to access is created by someone else, which
does not have synchronized methods and we do not have access rights to modify it. In
this case, the access to objects of this class can be synchronized by placing the call to
the methods defined by this class inside a synchronized block. Two block of codes
synchronized on the same instance cannot execute at the same time.
The general form to synchronize a block of code is
synchronized(object)
{
//statements to be synchronized
}
where,
object is a reference to the object being synchronized.
Example 9.9: A program to demonstrate synchronized statement
class A
{
void display(String msg)
{
System.out.print(( +msg);
try
{
Thread.sleep(1000);
}catch(InterruptedException e)
{
System.out.println(Interrupted);
}
System.out.println());
}
}
class MyThread extends Thread
{
String str;
A obj;
MyThread (A obj1,String s)
{
obj=obj1;
str=new String(s);
}
public void run()
{
synchronized(obj)
Self-Instructional
Material 153
Exception Handling
Threads
NOTES
{
obj.display(str);
}
}
}
class SynchronizedStatement
{
public static void main(String[] args)
{
A obj=new A();
MyThread th1=new MyThread(obj,THIS);
MyThread th2=new MyThread(obj,IS);
MyThread th3=new MyThread(obj,SYNCHRONIZATION);
th1.start();
th2.start();
th3.start();
}
}
The output of the program is
(THIS)
(IS)
(SYNCHRONIZATION)
By using the synchronized statement inside the run() method, access to the
object of the class A is restricted to only one thread at a time thus producing the same
correct output.
9.6.3 Deadlock
Deadlock is a situation that occurs when two or more threads are in a simultaneous wait
state and each of them is waiting for the release of a resource held by one of the other
waiting thread. For example, consider the following code segments.
Thread X: Thread Y:
run() run()
{ {
synchronized(obj1) synchronized(obj2)
{ {
sleep(1000); sleep(1000);
obj2.method2(); obj1.method1();
} }
} }
First, Thread X starts and synchronizes on the object obj1 which prevents
other threads to call the methods of obj1. Thread X then goes to sleep by calling
sleep() method and allows Thread Y to start. Thread Y starts and synchronizes
Self-Instructional
154 Material
Exception Handling
Threads
NOTES
on the object obj2. This prevents method of obj2 to be called by any other thread.
Thread Y goes to sleep on the invocation of sleep() method allowing Thread X to
wake up. Thread X continues execution and tries to call method2() on obj2 but
it cannot call the method on obj2 until the code in Thread Y that is synchronized on
obj2 finishes execution. As Thread X cannot proceed, Thread Y gets the control
and tries to call method1() on obj1 which is not possible until the code in Thread
X that is synchronized on obj1 finishes its execution. Here, neither of the threads can
continue because they are deadlocked.
Example 9.10: A program to demonstrate deadlock
class A
{
void display1( A obj2)
{
System.out.println(First thread waiting for second thread
to release the resource);
synchronized(obj2)
{
System.out.println(Deadlocked);
}
}
void display2(A obj1)
{
System.out.println(Second thread waiting for first thread
to release the resource);
synchronized(obj1)
{
System.out.println(Deadlocked);
}
}
}
class Thread1 extends Thread
{
A obj1,obj2;
Thread1(A i,A j)
{
obj1=i;
obj2=j;
}
public void run()
{
synchronized(obj1)
{
try
Self-Instructional
Material 155
Exception Handling
Threads
NOTES
{
sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
obj2.display1(obj2);
}
}
}
class Thread2 extends Thread
{
A obj1,obj2;
Thread2(A p,A q)
{
obj1=p;
obj2=q;
}
public void run()
{
synchronized(obj2)
{
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
obj1.display2(obj1);
}
}
}
class Deadlock
{
public static void main(String args[])
{
A obj1=new A();
A obj2=new A();
Thread1 t1=new Thread1(obj1,obj2);
Thread2 t2=new Thread2(obj1,obj2);
Self-Instructional
156 Material
Exception Handling
Threads
NOTES
t1.start();
t2.start();
}
}
The output of the program is
Second thread waiting for first thread to release the resource
First thread waiting for second thread to release the resource
In this example, the thread Thread1 owns the monitor on obj1 and waits for
the monitor on obj2. Similarly, the thread Thread2 owns the monitor on obj2 and
waits for the monitor on obj1. Thread1 will never release obj1 unless it gets hold
of obj2 and Thread2 will never release obj2 unless it gets obj1. The program will
never complete as the two threads are in the deadlock situation. We need to press
CTRL-C to end the program.
9.7 INTER-THREAD COMMUNICATION
Inter-thread communication is a process in which multiple threads exchange messages
with one another. A thread exchanges message before or after it changes its state.
There are several situations where communication between threads is important. For
example, let us consider two threads A and B in which thread B uses data produced by
thread A. After the thread A produces data, it will keep checking every now and then
whether the thread B has finished using the data so that it can generate more thus
wasting CPU cycles. Thread B would again waste many CPU cycles while it waits for
thread A to produce data. If threads A and B communicate with one another when they
have finished their tasks, then they do not have to wait and check each others status
every time. Thus, CPU cycles are not wasted.
Inter-thread communication can be achieved by using three methods namely
wait(), notify() and notifyall(). These methods can be invoked only from
within synchronized method or a synchronized block of code, otherwise an exception of
type IllegalMonitorStateException is thrown. All these methods are declared
final and they have been discussed as follows:
wait(): It informs the current thread to release the monitor and to go into sleep
state until another thread wakes it up by calling the notify() method. This
method throws InterruptedException. There is another form of wait()
method which allows us to specify the amount of time a thread can wait.
notify(): It starts the first thread that called the method wait() on the
same object.
notifyall(): It starts all the threads that called the method wait() on the
same object. In this case, the thread with the highest priority will run first.
First, consider an example where a thread uses data produced by another thread
without the use of wait() and notify() methods.
Example 9.11: A program without using wait() and notify() method
class P
{
int i;
Self-Instructional
Material 157
Exception Handling
Threads
NOTES
synchronized int recieve()
{
System.out.println(Recieved: +i);
return i;
}
synchronized void deliver(int i)
{
this.i=i;
System.out.println(Delivered: +i);
}
}
class Thread1 extends Thread
{
P obj;
Thread1(P obj1)
{
obj=obj1;
}
public void run()
{
int j=0;
while(true)
{
obj.deliver(j++);
}
}
}
class Thread2 extends Thread
{
P obj;
Thread2(P obj1)
{
obj=obj1;
}
public void run()
{
while(true)
{
obj.recieve();
}
}
}
class NoCommunication
{
Self-Instructional
158 Material
Exception Handling
Threads
NOTES
public static void main(String[] args)
{
P obj=new P();
Thread1 t1=new Thread1(obj);
Thread2 t2=new Thread2(obj);
t1.start();
t2.start();
}
}
The output of the program is
Delivered:0
Delivered:1
Delivered:2
Delivered:3
Delivered:4
Delivered:5
Delivered:6
Recieved:6
Recieved:6
Recieved:6
Recieved:6
Recieved:6
Delivered:7
Delivered:8
Delivered:9
In this example, data produced by Thread1 is used by Thread2. Note that
Thread1 produces data 0 to 6 without letting Thread2 to use it. Again, Thread2
uses data 6 five times in a row. There is no way for the two threads to communicate
with each other.
Now, see the program in Example 9.11 using wait() and notify() methods.
Example 9.12: A program to demonstrate interthread communication
class P
{
int i;
boolean flag=false;
synchronized int recieve()
{
if(!flag)
try
{
wait();
}
catch(InterruptedException e)
Self-Instructional
Material 159
Exception Handling
Threads
NOTES
{
System.out.println(Exception caught);
}
System.out.println(Recieved: +i);
flag=false;
notify();
return i;
}
synchronized void deliver(int i)
{
if(flag)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println(Exception caught);
}
this.i=i;
flag=true;
System.out.println(Delivered: +i);
notify();
}
}
class Thread1 extends Thread
{
P obj;
Thread1(P obj1)
{
obj=obj1;
}
public void run()
{
int j=0;
while(true)
{
obj.deliver(j++);
}
}
}
class Thread2 extends Thread
{
P obj;
Self-Instructional
160 Material
Exception Handling
Threads
NOTES
Thread2(P obj1)
{
obj=obj1;
}
public void run()
{
while(true)
{
obj.recieve();
}
}
}
class InterThreadCommunication
{
public static void main(String[] args)
{
P obj=new P();
Thread1 t1=new Thread1(obj);
Thread2 t2=new Thread2(obj);
t1.start();
t2.start();
System.out.println(Please press CTRL-C to stop);
}
}
The output of the program is
Delivered:0
Recieved:0
Delivered:1
Recieved:1
Delivered:2
Recieved:2
Delivered:3
Recieved:3
Delivered:4
Recieved:4
Delivered:5
Recieved:5
Delivered:6
Recieved:6
In this example, the methods wait() and notify() are invoked inside
receive() and deliver()method. It enables Thread1 to notify Thread2 after
producing data and waits until Thread2 finishes using. In the same way, Thread2
after using the data notifies Thread1 and waits until Thread1 produces the next
data. Thus, the output is in the synchronized form.
Check Your Progress
8. Define
synchronization.
9. The keyword
is used to
synchronize a
method or a block
of statement.
10. At any given point
of time, only one
thread can own the
monitor. (True or
False)
11. Which of the
following is the
default priority of
a thread?
(a) 0 (b) 5
(c) 1 (d) 10
12. The situation in
which two or more
threads are in a
simultaneous wait
state waiting for
the release of the
resource held by
one of the other
waiting thread is
called .
13. Which of the
following is used in
inter-thread
communication?
(a) wait(),
notify(),
notifyall()
(b) wait(),
join()
(c) notify(),
join(),
notifyall()
(d) none of these
Self-Instructional
Material 161
Exception Handling
Threads
NOTES
9.8 SUSPENDING, RESUMING AND STOPPING
THREADS
As mentioned earlier, the predefined methods suspend(), resume() and stop()
have been deprecated in Java 2 though they are a convenient way for managing the
execution of threads. These methods were deprecated as they may cause deadlocks
and serious system failures in a multithreaded environment. However, in new version of
Java, suspending, resuming and stopping a thread can be performed using boolean
type flags. The run() method of a thread will work based on the current flag values
that indicate the execution state of a thread. For example, if the running flag is set to
true, the run() method must let the thread execute. For the run() method to
suspend the execution of the currently running thread, the suspend flag must be set to
true. Likewise, the thread will die once the stop flag is set to true.
Example 9.13: A program to demonstrate - suspend, resume and stop operations
class ChildThread extends Thread
{
boolean suspend_flag,stop_flag;
String name;
ChildThread(String str)
{
name=str;
suspend_flag=false;
stop_flag=false;
}
public void run()
{
try
{
int i=5;
while(i>=1)
{
System.out.println(name+ +i);
sleep(1000);
i;
synchronized(this)
{
while(suspend_flag)
{
wait();
if(stop_flag)
{
break;
}
}
Self-Instructional
162 Material
Exception Handling
Threads
NOTES
}
}
}catch(InterruptedException e)
{
System.out.println(Thread interrupted);
}
}
synchronized void my_suspend()
{
suspend_flag=true;
}
synchronized void my_resume()
{
suspend_flag=false;
notify();
}
synchronized void my_stop()
{
suspend_flag=false;
stop_flag=true;
notify();
}
}
class SRS
{
public static void main(String[] args)
{
try
{
ChildThread obj=new ChildThread(Thread);
obj.start();
System.out.println(Thread started);
Thread.sleep(2000);
obj.my_suspend();
System.out.println(Thread is suspended);
Thread.sleep(2000);
obj.my_resume();
System.out.println(Thread is resumed);
Thread.sleep(2000);
obj.my_suspend();
System.out.println(Thread is suspended);
Thread.sleep(2000);
obj.my_resume();
System.out.println(Thread is resumed);
Self-Instructional
Material 163
Exception Handling
Threads
NOTES
Thread.sleep(2000);
obj.my_stop();
System.out.println(Thread stopped);
}
catch(InterruptedException e)
{
System.out.println(Thread interrupted);
}
}
}
The output of the program is
Thread started
Thread 5
Thread 4
Thread 3
Thread is suspended
Thread is resumed
Thread 2
Thread 1
Thread is suspended
Thread is resumed
Thread stopped
9.9 SUMMARY
In this unit, you have learned that:
Multithreading is a programming concept in which a program (process) is divided
into two or more subprograms (subprocesses), each of which can perform different
task concurrently.
A thread is just like a program which has a single flow of control. It also has a
starting point, the execution part and an end. Threads are called lightweight
processes. This is because all the threads in a main application program share the
same address space in the memory.
Java program always contains at least one thread even if we do not create one.
This thread is called main thread and it is the one which immediately starts executing
when we start a program.
In Java, threads can be created in two ways, by extending the Thread class and
by implementing the Runnable interface. In both the approaches, threads are
implemented in the form of objects which contain a method called run(). It is
the entry point of a new thread and it is the place where the task to be performed
by the thread is defined.
There are various states that a Java thread can enter during its life cycle. They
are newborn, runnable, running, blocked and dead state. A thread is always in one
of these five states.
Self-Instructional
164 Material
Exception Handling
Threads
NOTES
The yield(), sleep() and stop() methods are responsible for controlling
the behavior of a thread and the transition of thread from one state to another.
There are two ways to determine whether a thread has ended. The isAlive()
method is used to test whether a thread is still alive. The join() method is used
to halt the execution of current thread (calling thread) until the thread on which
the method is called terminates. It ensures that the current thread will wait until
the called thread finishes its execution.
Priorities are the integers which specify the relative priority of one thread to
another. When a thread is created, it inherits its priority from the thread that
created it. The priority of a thread can be changed by using the setPriority()
method of the Thread class.
When multiple threads need access to a single resource, there is a technique
called synchronization to ensure that only one thread will use the resource at any
given point of time. Synchronization uses the concept of monitor.
A monitor is an object which is used as a mutually exclusive lock. That is, it can
be owned by only one thread at any given point of time.
There are two ways to implement synchronization. One is to synchronize method
and another is to synchronize statements. The keyword synchronized is
used in both the cases.
Deadlock is a situation that occurs when two or more threads are in a simultaneous
wait state and each of them is waiting for the release of a resource held by one of
the other waiting thread.
Inter-thread communication is a process in which multiple threads exchange
messages with one another. A thread exchanges message before or after it changes
its state. Inter-thread communication can be achieved by using three methods
namely wait(), notify() and notifyall().
The predefined methods suspend(), resume() and stop() have been
deprecated in Java 2 as they may cause deadlocks and serious system failures in
a multithreaded environment. In the new version of Java, suspending, resuming
and stopping a thread can be performed using boolean type flags.
9.10 KEY TERMS
Thread: It is a program which has a single flow of control.
Synchronization: It is a technique to ensure that only one thread will use the
resource at any given point of time, when multiple threads try to access a single
resource.
Deadlock: It is a situation that occurs when two or more threads are in a
simultaneous wait state and each of them is waiting for the release of a resource
held by one of the other waiting thread.
Self-Instructional
Material 165
Exception Handling
Threads
NOTES
9.11 ANSWERS TO CHECK YOUR PROGRESS
1. A thread is a program which has a single flow of control. It has a starting point,
the execution part and an end.
2. A thread can be started by calling the start() method.
3. run()
4. A thread dies when its run() method completes or when it is killed deliberately
by calling stop() method.
5. Main
6. Suspending a thread blocks the thread temporarily and makes the thread go to the
blocked state. The suspended thread can be brought back to the execution state
by calling resume() method. Stopping a thread kills the thread and makes the
thread go to the dead state. It cannot run again even if the start() method is
invoked.
7. False
8. Synchronization is a technique to ensure that only one thread will use the resource
at any given point of time, when multiple threads try to access a single resource.
9. synchronized
10. True
11. (b)
12. Deadlock
13. (a)
9.12 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What is multithreading?
2. What is the advantage of using multithreaded program over single-threaded
program?
3. What are the two ways of creating a thread in Java? Give an example of each.
4. How do you set priorities for threads? Give examples.
Long-Answer Questions
1. Describe the complete life cycle of a thread.
2. Write a program to illustrate the use of stop() and suspend() methods.
3. What is synchronization? When is it used? Explain by giving examples of the
different ways to implement synchronization.
4. When are two threads said to be deadlocked? Write a simple application program
to illustrate the deadlock situation.
5. The following code demonstrates the sleep() method. Will the code compile
successfully? Justify your answer.
class P extends Thread
{
Self-Instructional
166 Material
Exception Handling
Threads
NOTES
public void run()
{
for(int j=0;j<4;j++)
{
System.out.println(j);
sleep(1000);
}
}
}
class Demo
{
public static void main(String[] args)
{
P obj=new P()
obj.start();
}
}
6. Consider the following code which implements Runnable interface. Will the
code compile? If not why?
class P implements Runnable
{
public void run(String message)
{
System.out.println(Inside run() method +message);
}
}
class Test
{
public static void main(String args[])
{
P p=new P();
Thread t=new Thread(p);
t.start();
}
}
Self-Instructional
Material 167
Exception Handling
NOTES
UNIT 10 EXCEPTION HANDLING
Structure
10.0 Introduction
10.1 Unit Objectives
10.2 Exceptions
10.2.1 Keywords Used in Exception Handling
10.2.2 Types of Exceptions
10.3 Using try and catch Blocks
10.3.1 Multiple catch Blocks
10.3.2 Nested try Blocks
10.4 Using finally Block
10.5 Using throw Block
10.6 Using throws Keyword
10.7 Creating Your Own Exceptions
10.8 Summary
10.9 Key Terms
10.10 Answers to Check Your Progress
10.11 Questions and Exercises
10.0 INTRODUCTION
The main concern of programmers while developing any program is to write an error-
free code. The presence of a single error in the program may result in many undesirable
situations, such as unintended results may be produced, an abrupt termination of program
may occur or in the extreme case the system may crash. To avoid these unwanted
occurrences, the errors in the program code must be detected and handled in a proper
manner so that the program produces the expected output.
However, when a program is written for the first time it usually contains errors.
These errors are mainly classified into two types, namely, compile-time errors and run-
time errors. The compile-time errors occur due to syntactical errors, like missing
semicolons, missing brackets, wrongly spelt keywords, use of undeclared variables and
so on. These errors can be detected and removed by exhaustive testing and debugging.
Unlike compile-time errors, run-time errors are difficult to detect and trap. They may
occur due to problems in arithmetic calculations like dividing by zero, trying to access an
out-of-bound array element, converting invalid string to a number and so on. These run-
time errors are usually referred to as exceptions.
In this unit, you will learn about the basic concepts of exception handling.
10.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Understand exceptions in Java
Learn how to use try and catch blocks
Know how to use the finally block
Use the finally block
Learn how to use the throws keyword in exception handling
Create your own exceptions
Self-Instructional
168 Material
Exception Handling
NOTES
10.2 EXCEPTIONS
The term exception is an abbreviation of the phrase exceptional event. It is an
unpredictable event that occurs while the program is executing and thus disrupts the
normal flow of the program or terminates the program abnormally. The errors that
cause exception can range from simple programming errors such as opening or reading
an invalid file or accessing an invalid index of an array to severe errors such as running
out of memory.
When an error occurs within a method, the Java runtime system creates an
exception object. This exception object contains information about the exception which
includes its type and the state of the program when the error occurred. Once an exception
object is created, it is thrown and the runtime system searches for a method to handle
the exception. It keeps on searching for a method that contains an appropriate exception
handler. An exception handler is considered appropriate if the type of exception handled
by the handler is same as the type of exception thrown.
Before understanding the significance of exception handling mechanism, it is
necessary to see what happens if the exceptions are not handled.
Example 10.1: A program to demonstrate an unhandled exception
class ExceptionExample
{
public static void main(String args[])
{
int a=15;
int b=3;
int c=a/(a-(5*b)); //exception occurs here
System.out.println(Result: +c);
}
}
In this program, no compile-time error occurs. However, when the division by
zero statement is executed a run-time error is generated. At this point, the Java runtime
system creates an exception object and throws it. This thrown object expects an exception
handler to handle it. Since no exception handler has been provided in this program,
Javas default exception handler is invoked. The default exception handler will display
the following error message and terminate the program abruptly.
Exception in thread main java.lang.ArithmeticException: /
by zero at ExceptionExample.main(ExceptionExample.java:7)
10.2.1 Keywords Used in Exception Handling
The Java exception handling mechanism not only guarantees the detection and handling
of run-time errors but also provides a way to separate the error-handling codes from the
rest of the program. This makes the program less complex, more readable and efficient,
as the normal execution path is not interrupted for checking errors. Moreover, the exception
handling routine (called exception handler) is invoked automatically whenever an error
occurs.
Self-Instructional
Material 169
Exception Handling
NOTES
Java exception handling is governed by the following five keywords:
try
catch
finally
throw
throws
A set of statements that needs to be monitored for the exceptions is contained in
the try block. Whenever an exception occurs within the try block, it is thrown. This
passes the control to the catch block which handles the exception appropriately. Java
runtime system automatically throws system generated exceptions. If the user wants to
throw the exception explicitly, the throw keyword is used. Sometimes, a method may
throw exceptions which it cannot handle; this must be specified by using the throws
keyword. The code which must be executed whether an exception is thrown or not is
kept within the finally block, which is optional.
10.2.2 Types of Exceptions
Java provides several built-in classes which define all types of exceptions. These
exception classes are arranged in a hierarchy having Throwable class on the top
(Figure 10.1). That is, the Throwable class is the superclass and all the exception
classes inherit methods defined by it. Two immediate subclasses of the Throwable
class are as follows:
Exception class: It defines those exceptions which are thrown by methods of
the standard Java class library or methods defined in users program and can be
trapped within the program. That is, the program can reasonably recover from
these types of exceptions. This class is also used (inherited) when the users want
to create their own exceptions in the application.
Error class: It defines those exceptions that do not occur frequently and are
difficult to be recovered from. For example, a class file is missing or system runs
out of memory.
Error
Throwable
Exception
Figure 10.1 Java Exception Hierarchy
Some of the most commonly used exceptions that will be encountered are listed
in Table 10.1.
Self-Instructional
170 Material
Exception Handling
NOTES
Table 10.1 Some Common Exceptions in Java
Exception Description
ArithmeticException Thrown when arithmetic error occurs in the
program such as divide-by-zero
NullPointerException

Thrown when the user tries to use an object
without initializing the object or in other words
when an object that has not been allocated
memory is used
IOException Thrown when error occurs during input/output of
data
ArrayIndexOutOfBoundsEx
ception
Thrown when an attempt is made to access an
array element with invalid index value
ArrayStoreException Thrown when an attempt is made to store the
incompatible type of data in an array
IllegalAccessException Thrown when an illegal attempt is made to access
a class
NumberFormatException Thrown when an invalid conversion of a string to
a numeric format takes place
StringIndexOutOfBoundsE
xception
Thrown when an attempt is made to access a
string element that is beyond the index of the
string
IllegalArgumentExceptio
n
Thrown when an illegal argument is used to
invoke a method
NegativeArraySizeExcept
ion
Thrown when an array of negative size is created
10.3 USING try AND catch BLOCKS
The default exception handler provided by the Java runtime system does not prevent the
abrupt termination of the program. To prevent this, Java provides us the facility to construct
our own exception handler. By constructing our own exception handler, we can fix the
errors ourselves. This can be achieved by enclosing the code that may throw an exception
within a try block. The try block is enclosed by curly braces and preceded by the
keyword try. Whenever an exception occurs within the try block, it is thrown. This
passes the control to the catch block associated with the try block.
The syntax to define try-catch block is
try //try block begins
{
//code that may cause an exception
} //try block ends
catch(exception_type ex)
{
//code to handle the exception
}
If the first statement of the try block causes an exception, the remaining
statements are not executed and the control passes to the catch block. The catch
statement requires single argument which is of the same type as of exception that needs
Check Your Progress
1. The errors in a
program are mainly
classified into two
types, namely,
___________ and
____________.
2. An exception is
caused by a
____________
error.
3. A program will
continue to execute
even after an
exception has
occurred. (True or
False)
4. Java exception
handling
mechanism mainly
uses five
keywords,
_____________,
_____________,
_____________,
_____________
and
_____________.
5. All the exception
classes inherit
which of the
following built-in
class?
(a) Exception
(b) Throwable
(c) Error
(d) Runtime
Exception
Self-Instructional
Material 171
Exception Handling
NOTES
to be handled. This exception type must be a subclass of Throwable class. It is not
necessary that every time the program is executed, an exception occurs. If an exception
is not thrown, the catch block is skipped and the control passes to the statement
immediately following the catch block.
The try and catch blocks form a logical unit. The scope of the catch block
is limited only to those statements which are enclosed within the immediately preceding
try block.
Note: Compile-time error is generated if the try statement is not followed by any
catch statement.
Example 10.2: A program to illustrate handling of an exception using try and catch
blocks
class TryCatchBlock
{
public static void main(String args[])
{
int a=15;
int b=3;
int c=0;
try
{
System.out.println(try block begins);
c=a/(a-(5*b)); //exception generated
System.out.println(try block ends);
}
catch(ArithmeticException ae)
{
System.out.println(Arithmetic Exception is caught here);
System.out.println(The resultant value of c is: +c);
}
c=a/b;
System.out.println(New value of c is: +c);
}
}
The output of the program is
try block begins
Arithmetic Exception is caught here
The resultant value of c is: 0
New value of c is: 5
In this example, the exception generated within the try block is caught inside the
catch block thus, preventing the abnormal termination of the program as seen in
Example 10.1.
Self-Instructional
172 Material
Exception Handling
NOTES
10.3.1 Multiple catch Blocks
It is not necessary that the code enclosed within the try block throws a single exception.
In case, multiple exceptions are thrown within a try block, Java allows using multiple
catch blocks for handling all these exceptions.
The syntax to define multiple catch blocks is
try //try block
{
//code that may cause exceptions
}
catch (exception_type e1) //catch block 1
{
.
.
}
catch (exception_type e2) //catch block 2
{
.
.
}
.
.
.
catch(exception_type en) //catch block N
{
.
.
}
Note that there is only one try block from which the exception is thrown and
depending on the type of exception thrown, the corresponding catch block will be
executed. Whenever an exception is thrown, the catch blocks are searched in sequential
order for an appropriate match. The first catch block whose parameter type matches
with the type of exception gets executed and other catch blocks are ignored. Once the
execution of the appropriate catch block gets over, the control passes to the statement
immediately following the last catch block.
Example 10.3: A program to demonstrate the concept of multiple catch statements
class MultipleCatchExceptions
{
public static void main(String args[])
{
try
{
int a=0;
int b=7/a; //divide by zero exception
Self-Instructional
Material 173
Exception Handling
NOTES
int c[]={1,2,3,4,5};
c[6]=15; //array out of bound exception
}
//this block handles array out of bounds exception
catch(ArrayIndexOutOfBoundsException aioe)
{
System.out.println(Array out of bounds Exception);
}
//this block handles arithmetic exception
catch(ArithmeticException ae)
{
System.out.println(Division by zero error);
}
catch(Exception e)
{
System.out.println(Exception +e.getMessage());
}
}
}
The output of the program is
Division by zero error
In this program, the divide by zero error is caught by the second catch block
containing the instance of ArithmeticException class.
It should be noted that the exception superclasses must be placed after their
subclasses. This is because if we place the catch block containing the superclass
before its subclasses then this superclass will handle all the exception of its type as well
as of its subclasses. As a result subsequent catch blocks will never get executed and
compile-time error is generated. This problem is known as an unreachable code problem.
In Example 10.3, if we place Exception class before ArithmeticException
and ArrayIndexOutOfBoundsException classes, then compiling this program
will display the error message as shown below.
M u l t i p l e C a t c h E x c e p t i o n s . j a v a : 1 7 : e x c e p t i o n
java.lang.ArrayIndexOutOfBoundsException has already been
caught
catch(ArrayIndexOutOfBoundsException aioe)
^
M u l t i p l e C a t c h E x c e p t i o n s . j a v a : 2 2 : e x c e p t i o n
java.lang.ArithmeticException has already been caught
catch(ArithmeticException ae) //this block handles
arithmetic exception
^
2 errors
Self-Instructional
174 Material
Exception Handling
NOTES
This is because ArrayIndexOutOfBoundsException class and
ArithmeticException class are the subclasses of Exception class. Thus,
Exception class catches all the thrown exception relative to these classes and their
corresponding catch blocks are never executed.
10.3.2 Nested try Blocks
The try blocks can be nested, that is, one try-catch block can be placed inside
another try-catch block. If an exception occurs within a particular try block, then
the catch blocks associated with this try block are searched for an appropriate
match. If no match is found then the control passes to the next outer try-catch
block. This process continues until an appropriate match is found. If no match is found,
the program terminates abnormally.
The syntax of nested try block is
try //outer try block
{
try //inner try block
{
.
.
}
catch //inner catch block
{
.
.
}
}
catch //outer catch block
{
.
.
}
Example 10.4: A program to demonstrate the concept of nested try blocks
class NestedTryBlock
{
public static void main(String args[])
{
//outer try-catch block
try
{
int a[]={0,1};
//inner try-catch block
try
{
int b[]={0,5};
Self-Instructional
Material 175
Exception Handling
NOTES
int d=b[1]/b[0];//exception thrown
System.out.println(Division of two numbers is : +d);
}
catch(ArrayIndexOutOfBoundsException ai)
{
System.out.println(Inside inner try-catch block);
System.out.println(ai.getMessage());
}
}
catch(ArithmeticException a)
{
System.out.println(Inside outer try-catch block);//the
thrown exception is caught here
System.out.println(a);
}
}
}
The output of the program is
Inside outer try-catch block
java.lang.ArithmeticException: / by zero
In this program, the division by zero error is thrown by the inner try block but it
could not be handled by the inner catch block as the type of exception defined by the
inner catch does not match with the exception thrown by the inner try. The matching
catch block is then searched in sequential order for an appropriate match and the
exception is caught inside the outer catch block.
10.4 USING finally BLOCK
It has been observed that when an exception is thrown in the program, the remaining
statements in the try block are not executed and the control directly gets transferred to
the subsequent catch block. However, there are certain statements in the program
that need to be executed whether or not exception is raised. For this, Java provides
finally keyword. The code within the finally block will always be executed
whether or not the exception is thrown. If an exception is raised with a matching catch
block, then the finally block gets executed after the execution of that catch block.
On the other hand, if no matching catch block is found then also the finally block
is executed after the execution of the try block. The finally block is optional;
however, it is necessary to include either catch or finally block with try block.
The diagrammatic representation of working of try-catch-finally block
can be shown in Figure 10.2.
Self-Instructional
176 Material
Exception Handling
NOTES
Execute try block
Find catch block to execute
Execute catch block
for Exceptiontype2
Execute catch block
for Exceptiontypen
Execute catch block
for Exceptiontype1

Execute finally
block
[exception]
[no exception]
[exception1] [exception2] [exceptionn]
Figure 10.2 try-catch-finally Block
Example 10.5: A program to illustrate the use of finally block
class FinallyBlock
{
public static void main(String args[])
{
int a=67;
int b=0;
try
{
System.out.println(The value of a: +a);
System.out.println(The value of b: +b);
int c=(a/b); //exception thrown
System.out.println(Result is: +c);
}
catch(Exception e)
{
System.out.println(e); //prints the corresponding exception
}
finally
{
System.out.println(Denominator cannot be zero);
}
}
}
Self-Instructional
Material 177
Exception Handling
NOTES
The output of the program is
The value of a: 67
The value of b: 0
java.lang.ArithmeticException: / by zero
Denominator cannot be zero
Here, the thrown exception is caught in the catch block and an appropriate
error message is displayed. After that, the statement within the finally block is
executed.
10.5 USING throw BLOCK
As stated earlier, the Java runtime system automatically throws system-generated
exceptions. However, Java provides a mechanism to throw an exception explicitly by
using the throw keyword.
The syntax of throw statement is
throw ExceptionObject;
where,
ExceptionObject is an object of Throwable class or its subclass
When a throw statement is encountered in the program, the execution of the
subsequent statements in the try block stops and corresponding catch block is
searched. The nearest try block is checked to determine if it contains a catch block
to match the exception of its type. If it is found, then that catch block is executed else
subsequent try blocks are inspected. In case, if no matching catch block is found,
then the default exception handler comes into action and stops the normal execution of
the program and displays the error message on the output screen.
It should be noted that instances of classes other than Throwable class or its
subclasses cannot be used as exception objects. The Throwable object can be created
using a new operator or using a parameter inside catch clause.
Example 10.6: A program to demonstrate the use of throw keyword
class ThrowExampleDemo
{
public static void main(String args[])
{
try
{
ThrowExample(); //invoking ThrowExample() method
}
catch(ArithmeticException ae)
{
System.out.println(The exception is recaught here: +ae);
}
}
static void ThrowExample()
{
Check Your Progress
6. A set of statements
that may throw an
exception in a
program code is
enclosed within the
__________ block.
7. What is the
significance of
catch block?
8. The ordering of
catch statements is
significant in a
multiple catch
block. (True or
False)
9. It is valid to
include some code
between the try
and catch or
finally block
following it. (True
or False)
10. Which of the
following will not
generate an error?
(a) A catch block
without a try
block
(b) Presence of
code between
try and
catch blocks
(c) A try block
with either a
catch or a
finally
block
(d) A finally
block without a
try block
Self-Instructional
178 Material
Exception Handling
NOTES
int a=0;
int b=6;
try
{
int c=b/a; //system-generated exception
System.out.println(c);
}
catch(ArithmeticException aoe)
{
System.out.println(The exception is caught inside the method
ThrowExample);
throw aoe; //exception thrown explicitly
}
}
}
The output of the program is
The exception is caught inside the method ThrowExample
The exception is recaught here :java.lang.ArithmeticException:
/ by zero
In this example, the ArithmeticException occurs inside the
ThrowExample(). This exception is caught inside the catch block inside the same
method, which explicitly rethrows it using the throw keyword. This is called rethrowing
of the exception. Now the control passes back to the catch block of the main()
method and the thrown exception is again caught here.
10.6 USING throws KEYWORD
Sometimes a method may generate an exception but cannot handle it. That is, there may
be a method in the program which is generating (throwing) an exception but it does not
have the appropriate exception handing mechanism. The methods which are calling
such methods must be cautioned about this behavior so that calling methods can take
appropriate measures to safeguard themselves against the exceptions. This is done by
appending throws keyword after method name in the method declaration statement.
The throws clause includes all types of exceptions excluding those belonging to Error
or Runtime classes or their subclasses. All other exceptions which a method may
throw must be listed after the throws keyword in the method declaration; otherwise
compile-time error is generated.
The syntax of the throws clause is
return_type method_name() throws exception_list
{
//body of the method
}
where,
exception_list includes all the exceptions that the method might throw
Self-Instructional
Material 179
Exception Handling
NOTES
Example 10.7: A program to illustrate the use of throws clause
class ThrowsExample
{
//ClassExample method throwing ClassNotFounfException
static void ClassExample() throws ClassNotFoundException
{
System.out.println(Inside ClassExample);
throw new ClassNotFoundException(This is an example of Class
not found Exception);
}
public static void main(String args[])
{
try
{
ClassExample();
}
catch(ClassNotFoundException c)
{
System.out.println(Exception caught: +c);
}
}
}
The output of the program is
Inside ClassExample
Exception caught: java.lang.ClassNotFoundException: This is
an example of Class not found Exception
In this program, we are explicitly throwing the ClassNotFoundException
in the method ClassExample. Since we are not handling the thrown exception in the
same method therefore we use the throws statement after the method name and
catching the exception inside the main() method.
10.7 CREATING YOUR OWN EXCEPTIONS
In the earlier section, you have learnt about some of the built-in exceptions provided by
the Java platform. These built-in exceptions are used to handle the errors occurring in
the program. But sometimes the programmer wants to create his own application specific
exceptions. User-defined exceptions can be created simply by defining a subclass of
Exception class and using the throw keyword.
Example 10.8: A program to demonstrate creation of user-defined exceptions
class OwnException extends Exception
{
public OwnException(String message) //Constructor
{
System.out.println(OwnException class constructor);
Self-Instructional
180 Material
Exception Handling
NOTES
}
}
public class CreateOwnException
{
public static int divide(int i,int j) throws OwnException
{
if(j==0)
throw new OwnException(This statement is not executed);
return i/j;
}
public static void main(String[] args)
{
int i=70;
int j=0;
try
{
System.out.println(The value of i: +i);
System.out.println(The value of j: +j);
System.out.println(Division of two numbers is:
+divide(i,j));
}
catch (OwnException oe)
{
System.out.println(Denominator can not be zero);
oe.printStackTrace();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
The output of the program is
The value of i: 70
The value of j: 0
OwnException class constructor
Denominator can not be zero
OwnException
at CreateOwnException.divide(CreateOwnException.java:13)
at CreateOwnException.main(CreateOwnException.java:24)
This example defines a subclass of Exception called OwnException.
Thus, this class will inherit the methods defined by the Throwable class through
Exception class. The CreateOwnException class defines a method divide()
Self-Instructional
Material 181
Exception Handling
NOTES
which throws an object oe of OwnException type when the denominator of the
fraction is zero. The printStackTrace() method of the Throwable class is
overridden to display the message which contains all the information that lead to the
error, such as the name of the method which caused the error, the name of the caller of
the method which lead to the error, the line number in which that error has occurred, etc.
10.8 SUMMARY
In this unit, you have learned that:
The errors in a program are mainly classified into two types, namely, compile-
time errors and run-time errors.
The compile-time errors mostly occur due to syntactical errors, like missing
semicolons, missing brackets, miss spelt keywords, use of undeclared variables
and so on.
Run-time errors may occur due to problems in arithmetic calculations like divide
by zero, trying to access an out-of-bound array element, converting invalid string
to a number and so on. These run-time errors are usually referred to as exceptions.
The term exception is an abbreviation for the phrase exceptional event. It is an
unpredicted event that occurs while the program is executing and thus disrupts
the normal flow of the program or terminates the program abnormally.
Java exception handling mechanism not only guarantees the detection and handling
of run-time errors but also provides a way to separate the error-handling code
from the rest of the program.
Java exception classes are inherited by Throwable class.
Java exception handling is governed by the five keywords, namely, try, catch,
finally, throw and throws.
A set of statements that needs to be monitored for the exceptions is contained in
the try block.
Whenever an exception occurs within the try block, it is thrown. This passes
the control to the catch block associated with the try block.
In case multiple exceptions are thrown within a try block, Java allows using
multiple catch blocks for handling all these exceptions.
The try blocks can be nested, that is, one try-catch block can be placed
inside another try-catch block.
The code within the finally block will always be executed whether or not the
exception is thrown.
Java provides a mechanism to throw an exception explicitly by using the throw
keyword.
Sometimes a method may throw exceptions which it cannot handle, this must be
specified using throws keyword.
Java allows the programmer to create user-defined exceptions simply by defining
a subclass of Exception class and using the throw keyword.
Check Your Progress
11. What is the
difference between
throw and
throws
keywords?
12. A catch block
can throw an
exception caught
by itself. (True or
False)
13. What do you
understand by
user-defined
exceptions?
14. The descriptive
information about
the exception
occurred during
program execution
can be retrieved
using method of
the Throwable
class.
Self-Instructional
182 Material
Exception Handling
NOTES
10.9 KEY TERMS
Exception: It is an unpredicted event that occurs while the program is executing,
thereby disrupting the normal flow of the program or terminating the program
abnormally.
User-defined exceptions: They are exceptions added by the user in Java by
extending the Exception class and using the throw keyword.
10.10 ANSWERS TO CHECK YOUR PROGRESS
1. Compile-time errors, run-time errors
2. Run-time error
3. False
4. try, catch, finally, throw, throws
5. (b)
6. try
7. The catch block catches and handles the exception thrown by the statements
within the try block. The exceptions must belong to Exception or Error
class.
8. True
9. False
10. (c)
11. The throw keyword is used to explicitly throw an exception. The exception
thrown must be an instance of Throwable class or its subclass. The throws
keyword is used with the method signature and is followed by all the exceptions
which the method may throw, but the method does not have the appropriate code
to handle all those exceptions.
12. True
13. In addition to the exceptions already defined in Java, the user can also define his
own exceptions by extending Exception class and using throw keyword.
These are called user-defined exceptions.
14. printStackTrace()
10.11 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What is an exception? What happens when an exception is not handled in Java?
2. What is exception handling mechanism? List five keywords which rule Java
exception handling.
3. What is unreachable code problem? Give an example.
4. What is the significance of throws keyword in Java?
Self-Instructional
Material 183
Exception Handling
NOTES
Long-Answer Questions
1. Explain Java exception hierarchy. What is the difference between instances of
Exception class and Error class?
2. Describe, with an example, the significance of try-catch block in exception
handling.
3. Once the control transfers to the catch block, it does not return to the try
block to execute the remaining code. Justify with an example.
4. What is the output of the following code? Give reason to your answer.
class NestedTry
{
public static void main(String args[])
{
try
{
int a[] = {0,1};
System.out.println(a[1]);
try
{
int b[] = {0,5};
int d = b[1]/b[0];
System.out.println(Division of two number is : +d);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
}
}
catch(NullPointerException aibe)
{
System.out.println(aibe.getMessage());
}
}
}
5. Is it compulsory to include finally block? Justify your answer.
6. Check the output of the following program and find the error (if any).
class NestedFinally
{
public static void main(String args[])
{
try
{
int b[] = {0,5};
int d = b[1]/b[0];
Self-Instructional
184 Material
Exception Handling
NOTES
System.out.println(Division of two number is : +d);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
System.out.println(This is the first finally Block);
}
finally
{
System.out.println(This is the second finally Block);
}
}
}
7. What is the role of throw keyword? Explain.
8. Give an example of creating your own exception in Java.
Self-Instructional
Material 185
Event Handling
NOTES
UNIT 11 EVENT HANDLING
Structure
11.0 Introduction
11.1 Unit Objectives
11.2 Events
11.3 Event Handling Model
11.3.1 Java 1.0 Event Model
11.3.2 Delegation Event Model
11.4 Event Handling: Classes, Sources and Listner Interfaces
11.4.1 Event Classes
11.4.2 Event Sources
11.4.3 Event Listener Interfaces
11.5 Summary
11.6 Key Terms
11.7 Answers to Check Your Progress
11.8 Questions and Exercises
11.0 INTRODUCTION
Java applets are used to create graphical and user-interactive applications. Although the
applets designed earlier were graphical in nature, they did very little when it came to
demonstrating their user-interactive capability. User interaction means a specific action
is generated and an appropriate result is displayed to the user when he interacts with an
application say by clicking mouse or by entering a character with the help of the keyboard.
In Java, all the activities that occur between the user and the application are termed as
events. They play a significant role in applet programming as they facilitate inclusion
user-interactivity in applets.
11.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Understand what an event is
Learn about event handling model
Understand the various types of events supported by Java
11.2 EVENTS
In Java, an event is an object, which specifies the change of state in the source. It is
generated whenever an action takes place like a mouse button is clicked or text is
modified. Javas abstract window toolkit (AWT) is responsible for communicating these
actions between the program and the user. Java packages such as java.util,
java.awt and java.awt.event support event handling mechanism.
When an action takes place, an event is generated. The generated event and all
the information about it such as time of its occurrence, type of event, etc. are sent to the
appropriate event handling code provided within the program. This code determines
Self-Instructional
186 Material
Event Handling
NOTES
how the allocated event will be handled so that an appropriate response can be sent to
the user.
11.3 EVENT HANDLING MODEL
The working of an event-driven program is governed by its underlying event-handling
model. Till now two models have been introduced in Java for receiving and processing
events. The event handling mechanisms of these models differ a lot from each other.
11.3.1 Java 1.0 Event Model
The Java 1.0 Event model for event processing was based on the concept of containment.
In this approach, when a user-initiated event is generated it is first sent to the component
in which the event has occurred. However, in case the event is not handled at this
component, it is automatically propagated to the container of that component. This process
is continued until the event is processed or it reaches the root of the containment hierarchy.
For example, as shown in the Figure 11.1, button is contained in the panel, which
itself is contained within the frame. When the mouse is clicked on button, an event is
generated, which is first sent to the button. If it is not handled by it then this event is
forwarded to the panel and if it cannot handle the event, it is further sent to the frame.
Frame being the root of the given hierarchy processes this event. So, the event is forwarded
up the containment hierarchy until it is handled by a component.







Frame
Panel
Button
Event generated
at button
Unhandled event
propagated
Event handled at
frame
Figure 11.1 Java 1.0 Event Handling Mechanism
The major drawback in this approach is that events could be handled by the
component that generated it or by the container of that component. Another problem is
that events are frequently sent to those components that cannot process them, thus
wasting a lot of CPU cycles.
11.3.2 Delegation Event Model
The advanced versions of Java ruled out the limitations of Java 1.0 event model. This
model is referred to as the delegation event model, which defines a logical approach to
handle events. It is based on the concept of source and listener. A source generates an
event and sends it to one or more listeners. On receiving the event, listener processes
the event and returns it. The notable feature of this model is that the source has a
registered list of listeners, which will receive the events as they occur. Only the listeners
that have been registered actually receive the notification when a specific event is
generated.
Self-Instructional
Material 187
Event Handling
NOTES
For example, as shown in the Figure 11.2, when the mouse is clicked on button, an
event is generated. If the button has a registered listener to handle the event, this event
is sent to button, processed and the output is returned to the user. However, if it has no
registered listener the event will not be propagated upwards to panel or frame.
Frame
Panel
Button
Event generated
Event handler
Figure 11.2 Java 1.1 Event Handling Mechanism
Event Source
An event source is an object that generates a particular kind of event. An event is
generated when the internal state of the event source is changed. A source may generate
more than one type of event. Every source must register a list of listeners that are
interested to receive the notifications regarding the type of event. Event source provides
methods to add or remove listeners.
The general form of method to register (add) a listener is
public void addTypeListener(TypeListener eventlistener)
Similarly, the general form of method to unregister (remove) a listener is
public void removeTypeListener(TypeListener eventlistener)
where,
Type is the name of the event
eventlistener is a reference to the event listener
Event Listener
An event listener is an object, which receives notification when an event occurs. Only
registered listeners can receive notifications from sources about specific types of events.
The role of event listener is to receive these notifications and process them.
11.4 EVENT HANDLING: CLASSES, SOURCES AND
LISTNER INTERFACES
Java provides various classes and interfaces to handle the generated events.
11.4.1 Event Classes
Java 1.1 event classes encapsulate all types of events occurring in the system. A
successful handling of the events requires in-depth understanding of these classes. All
these classes have been arranged in a hierarchy having EventObject class as its
root element. This class acts as the superclass of all the event classes. EventObject
class belongs to java.util package. Some of the event classes are discussed as
follows:
Check Your Progress
1. How does the
delegation event
model handle
events?
2. How is an event
represented?
3. Which is the
highest class in
delegation event
model?
Self-Instructional
188 Material
Event Handling
NOTES
The ActionEvent Class
The ActionEvent class represents the event that is generated when a user selects a
menu item, presses button or double-clicks a list item.
The ActionEvent class defines the following constructors.
ActionEvent(Object source, int event_type, String
command_name)
ActionEvent(Object source, int event_type, String
command_name, int modifier_key)
ActionEvent(Object source, int event_type, String
command_name, long event_time, int modifier_key)
where,
source is a reference to the object that originated the event. The reference to the
object can be obtained by using getSource()method.
event_type specifies the type of the event. The getId()method returns
the type of the event.
command_name is the name of the command which invoked the ActionEvent
object which can be obtained by invoking the getActionCommand() method.
event_time represents the system time at which the event has occurred.
The getWhen() method returns the time of occurrence of the event.
modifier_key is the value of the modifier key(Alt, Ctrl, Meta, Shift), which
was pressed when the event was generated. The getModifiers() method returns
the value of the modifier key.
The AdjustmentEvent Class
An AdjustmentEvent represents an event that is generated when a change has
occurred in the scrollbar. The AdjustmentEvent class defines an integer constant,
ADJUSTMENT_VALUE_CHANGED signals that some change has occurred. In addition,
this class defines following integer constants to determine what kind of event is generated
by the scrollbar.
UNIT_INCREMENT: It indicates that the user has clicked the left arrow of the
horizontal or the top arrow of the vertical scrollbar to increase its value.
UNIT_DECREMENT: It indicates that the user has clicked the right arrow of
the horizontal or the bottom arrow of the vertical scrollbar to decrease its value.
BLOCK_INCREMENT: It indicates that the user has clicked inside the scrollbar
to increase its value.
BLOCK_DECREMENT: It indicates that the user has clicked inside the scrollbar
to decrease its value.
TRACK: It represents that the user has dragged the slider.
One of the constructors of the AdjustmentEvent class is as follows:
AdjustmentEvent(Adjustable source, int id, int event_type,
int data)
where,
source is a reference to the object that originated this event. The object that
generated the event can be obtained using getAdjustment()method.
Self-Instructional
Material 189
Event Handling
NOTES
id is the value equal to the ADJUSTMENT_VALUE_CHANGED
event_type specifies the type of the event. The type of the adjustment event
can be obtained using the getAdjustmentType()method.
data is the data associated with the event.
The ComponentEvent Class
The ComponentEvent class represents the event that is generated when the position,
size or visibility of a component alters.
The ComponentEvent class defines the following constructor:
Component(Component source, int event_type)
where,
source is a reference to the component that originated the event. The reference
to the component can be obtained by using getComponent()method.
event_type specifies the type of the event. The different types of component
events are represented by integer constantsCOMPONENT_MOVED,
COMPONENT_RESIZED, COMPONENT_HIDDEN, COMPONENT_SHOWN.
The ContainerEvent Class
The ContainerEvent class inherits ComponentEvent class. The container
event is generated when a component is added to or removed from a container.
The ContainerEvent class defines the following constructor:
ContainerEvent(Component source, int type, Component
component)
where,
source is a reference to the component that originated the event. The reference
to the component can be obtained by using getContainer()method.
event_type specifies the type of the event. The different types of events are
represented by integer constantsCOMPONENT_ADDED, COMPONENT_REMOVED.
component represents the component that has been added to or removed from
the container and can be obtained by using getChild() method
The FocusEvent Class
The FocusEventclass represents event that is generated when a component gains or
loses the focus of the input. The FocusEvent class is a subclass of ComponentEvent
class.
The FocusEventclass defines the following constructors:
FocusEvent(Component source, int event_type)
FocusEvent(Component source, int event_type, Boolean
tempflag)
FocusEvent(Component source, int event_type, Boolean
tempflag, Component opp_component)
where,
source is a reference to the component that originated the event.
event_type specifies the type of the event. The different types of events are
represented by integer constantsFOCUS_GAINED, FOCUS_LOST.
Self-Instructional
190 Material
Event Handling
NOTES
tempflag specifies whether the focus event is temporary. To determine if the
focus event is temporary isTemporaray() method is used.
opp_component represents another component that takes part in the focus
change. It means if the FOCUS_GAINED event takes place then the opp_component
is that component, which lost focus. On the other hand, if FOCUS_LOST event occurs
then the opp_component is that component which gains focus.
The ItemEvent Class
The ItemEvent class represents the event, which is generated when a menu item is
selected or deselected, checkbox item is clicked or a list item is selected.
The ItemEvent class defines the following constructor:
ItemEvent(ItemSelectable source, int event_type, Object
item, int item_state)
where,
source is a reference to the component that originated the event. The
getItemSelectable() method returns the reference to the component that
originated this event.
event_type specifies the type of the event. The different types of events are
represented by integer constantsITEM_SELECTED, ITEM_DESELECTED.
item is a reference to the item that originated the event which can be obtained
by using getItem()method.
item_state returns the current state of the item (selected or deselected),
which generated the item event. The getStateChange() method returns the current
state of the item.
The KeyEvent Class
The KeyEvent class represents the event that is generated when the user interacts
with the application through keys. Java supports key events through KeyEvent class.
The KeyEvent class defines the following constructor:
KeyEvent(Component source, int event_type, long
event_time, int modifier_key, int code, char character)
where,
source is a reference to the component that originated the event.
event_type specifies the type of the event. The different types of events are
represented by integer constantsKEY_PRESSED, KEY_RELEASED,
KEY_TYPED.
event_time represents the system time at which the event has occurred.
modifier_key is the value of the modifier key(Alt, Ctrl, Meta, Shift), which
was pressed when the event was generated.
code returns the value of virtual key codesVK_0 to VK_9, VK_A to
VK_Z, VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT etc. The getKeyCode()
method returns the value of the virtual key.
character specifies the character that has been entered and can be obtained
by using getKeyChar() method.
Self-Instructional
Material 191
Event Handling
NOTES
The MouseEvent Class
The MouseEvent class represents the event that is generated when the user interacts
with the application through the mouse. The MouseEvent class encapsulates mouse
events.
The MouseEventclass defines the following constructor:
MouseEvent(Component source, int item_type, long
event_time, int modifier_key, int a, int b, int
clicks_count, boolean popuptriggers)
where,
source is a reference to the component that originated the event.
event_type specifies the type of the event. The different types of events are
represented by integer constantsMOUSE_CLICKED, MOUSE_EXITED,
MOUSE_ENTERED, MOUSE_PRESSED, MOUSE_RELEASED,
MOUSE_DRAGGED, MOUSE_MOVED, MOUSE_WHEEL.
event_time represents the system time at which the event occurred
modifier_key is the value of the modifier key(ALT, CTRL, META, SHIFT)
which was pressed when the event was generated.
int a, int b represents the X, Y coordinates of the position of the mouse
within the component respectively. The getX() and getY() methods return the
X,Y coordinates respectively. Alternatively, getPoint()method can be used to obtain
both the coordinates
clicks_count represents the total number of mouse clicks took place for
this event. The getClickCount() method returns the total number of mouse clicks.
popuptriggers specifies whether the pop-up window will appear. To determine if
the pop-up window appears isPopupTrigger() method is used.
The TextEvent Class
The TextEvent class represents the event that is generated when the user enters or
changes text in text fields or text areas. The TextEvent encapsulates text events.
The TextEvent class defines the following constructor:
TextEvent(Object source, int event_type)
where,
source represents the object that originated the event.
event_type specifies the type of the event. The event is represented by
integer constantTEXT_VALUE_CHANGED.
The WindowEvent Class
The WindowEvent class represents the event that is generated when the state of the
window changes. The WindowEvent class is a subclass of ComponentEvent
class.
The WindowEvent class defines the following constructors:
WindowEvent(Window Source, int event_type)
WindowEvent(Window Source, int event_type, Window opposite)
WindowEvent(Window Source, int event_type, int from_State,
Self-Instructional
192 Material
Event Handling
NOTES
int to_State)
WindowEvent(Window Source, int event_type, Window another,
int from_State, int to_State)
where,
source is a reference to the component that originated the event. The reference
to the component is obtained by using getWindow() method.
event_type specifies the type of the event. The event is represented by
integer constantWINDOW_ACTIVATED, WINDOW_DEACTIVATED,
WINDOW_GAINED_FOCUS, WINDOW_LOST_FOCUS, WINDOW_OPENED,
WINDOW_CLOSED, WINDOW_CLOSING, WINDOW_ICONIFIED,
WINDOW_DEICONIFIED, WINDOW_STATE_CHANGED.
opposite represents the another window when the window focus or window
activation events took place and can be obtained by using getOppositeWindow()
method.
from_State specifies the old state of the window, that is, the state before the
state of the window changed. The getOldState() method returns the old state of
the window.
to_State specifies the new state of the window, that is, the state after the
state of the window changed. The getNewState() method returns the new state of
the window.
11.4.2 Event Sources
Event sources are the objects, which generate events. Some of the examples of event
sources are listed in the Table 11.1.
Table 11.1 Event Sources
Event source Description
Button generates action events when the button is pressed
Choice generates item events when choice changes
Window generates window events when the state of the
window changes
Text
components
generates text events when a text is entered in text
field or text area
Menu item generates action events when a menu item is selected,
generates item events when a checkable menu is
selected or deselected
Checkbox generates item events when a checkbox is selected or
deselected.
List generates action events when an item is double-
clicked, generates action events when an item is
selected or deselected
Scrollbar generates events when the scroll bar is manipulated
Self-Instructional
Material 193
Event Handling
NOTES
11.4.3 Event Listener Interfaces
Events generated by the event source are sent to event listeners, which handle them in
an appropriate manner. Event listeners implement various interfaces. Some of the
interfaces are discussed as follows:
The ActionListener Interface
When an action event occurs, the actionPerformed() method defined by the
ActionListener interface is invoked.
The general form of the actionPerformed()method is
void actionPerformed(ActionEvent e)
where,
e is the reference to an object of ActionEvent class
The AdjustmentListener Class
When an adjustment event occurs, the adjustmentValueChanged()method
defined by the AdjustmentListener interface is invoked.
The general form of the adjustmentValueChanged() method is
void adjustmentValueChanged(AdjustmentEvent e)
where,
e is the reference to an object of AdjustmentEvent class
The ComponentListener Interface
The methods provided by the ComponentListener interface are invoked when the
state of the component changes, that is, the component is resized, moved, shown or
hidden.
The general form of the methods defined in ComponentListener interface is
void componentShown(ComponentEvent com)
void componentHidden(ComponentEvent com)
void componentMoved(ComponentEvent com)
void componentResized(ComponentEvent com)
where,
com is the reference to an object of ComponentEvent class
The ContainerListener Interface
The methods defined by the ContainerListener interface are invoked when the
component is added to or removed from a container. The object of ContainerEvent
class is passed as method parameter.
The general form of the methods defined in ContainerListener interface is as
follows:
void componentAdded(ContainerEvent con)
void componentRemoved(ContainerEvent con)
Self-Instructional
194 Material
Event Handling
NOTES
The FocusListener Interface
The methods defined by the FocusListener interface are invoked when the focus
of the keyboard is lost or gained by the component. The object of FocusEvent class
is passed as method parameter.
The general form of the methods defined in FocusListener interface is as
follows:
void focusGained(FocusEvent foc)
void focusLost(FocusEvent foc)
The ItemListener Interface
The method itemStateChanged() defined by the ItemListener interface is
invoked when the state of an item is changed. The object of ItemEvent class is
passed as method parameter.
The general form of the method defined in ItemListener interface is void
itemStateChanged(ItemEvent item)
The KeyListener Interface
The methods defined by the KeyListener interface are invoked when any key is
pressed or released, or a character is entered. The object of KeyEvent class is passed
as method parameter.
The general form of the methods defined in KeyListener interface is
void keyPressed(KeyEvent key)
void keyReleased(KeyEvent key)
void keyTyped(KeyEvent key)
Note: If a key B is pressed and released, three events (key pressed, key typed and key released) are
generated.
The MouseListener Interface and MouseMotionListener Interface
The methods defined by the MouseListener interface are invoked when the mouse
is clicked, pressed, released, when the mouse enters or exits the component. Similarly,
the methods defined by the MouseMotionListener interface are invoked when
the mouse is dragged or moved from one position to another. The object of MouseEvent
class is passed as method parameter.
The general form of the methods defined in MouseListener interface is as
follows:
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
The general form of the methods defined in MouseMotionListener interface
is as follows:
void mouseMoved(MouseEvent me)
void mouseDragged(MouseEvent me)
Self-Instructional
Material 195
Event Handling
NOTES
The TextListener Interface
The method textValueChanged()defined by the TextListener interface is
invoked when the text inside the text area or text field alters. The object of TextEvent
class is passed as method parameter.
The general form of the method defined in TextListener interface is as
follows:
void textValueChanged(TextEvent te)
The WindowListener Interface
The methods defined by the WindowListener interface are invoked when the state
of the window changes. The object of WindowEvent class is passed as method
parameter.
The general form of the methods defined in WindowListener interface is
void windowOpened(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowActivated(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowIconified(WindowEvent we)
void windowDeiconified(WindowEvent we)
To understand the concept of event handling, consider Example 11.1. This program
demonstrates the generation of key events when the user presses or releases any keyboard
key. The methods of the KeyListener interface are invoked when the key is pressed
or released and output is displayed to the user in the status bar of the applet window.
Example 11.1: An applet to demonstrate the event handling mechanism using
KeyListener interface
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Applet implements
KeyListener
{
String pstr = This is your Key Listener Class;
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent e)
{
showStatus(You have pressed a key); /*displays the string
on the applet window*/
}
public void keyReleased(KeyEvent e)
{
showStatus(You have released a key);
Self-Instructional
196 Material
Event Handling
NOTES
}
public void keyTyped(KeyEvent e)
{
}
public void paint(Graphics g)
{
g.drawString(pstr, 10, 20);
}
}
The HTML code for KeyListenerExample is
<HTML>
<HEAD>
</HEAD>
<BODY>
<CENTER>
<APPLET
CODE= KeyListenerExample.class
WIDTH=600
HEIGHT=250>
</APPLET>
</CENTER>
</BODY>
</HTML>
The output of the HTML code is
In this example, the KeyListenerExample class extends Applet class
and implements KeyListener interface. In the init() method, the applet registers
itself as a listener for key events. It should be noted that here the applet itself is the
source and listener for these events. This applet implements all the methods defined by
the KeyListener interface.
Check Your Progress
4. What does the
ActionEvent
class represent?
5. How does the
ItemEvent class
define a
constructor?
6. What do you
understand by
event sources?
Self-Instructional
Material 197
Event Handling
NOTES
11.5 SUMMARY
In this unit, you have learned that:
In Java, all the activities that occur between the user and the application are
termed as events.
An event is an object which specifies the change of state in the source.
An event gets generated, whenever an action takes place like a mouse button is
clicked or text is modified.
Java packages such as java.util, java.awt and java.awt.event support event handling
mechanism.
The working of an event-driven program is governed by its underlying event-
handling model.
The Java 1.0 Event model of Java for event processing was based on the concept
of containment.
The delegation event model defines a logical approach to handle events. It is
based on the concept of source and listener.
A source generates an event and sends it to one or more listeners that can handle
the event.
Java provides various classes and interfaces to handle the generated events.
Some of the event classes are ActionEvent, AdjustmentEvent
ComponentEvent, ContainerEvent, FocusEvent,
ItemEvent, KeyEvent, WindowEvent, etc.
Some of the event listener interfaces are ActionListener,
AdjustmentEventListener, ComponentListener,
ConatinerListener, FocusListener, ItemListener,
KeyListener, WindowListener, etc.
11.6 KEY TERMS
Event: It is an object, which specifies the change of state in the source
Event source: It is an object that generates a particular kind of event.
Event listener: It is an object, which receives notification when an event occurs.
Abstract window toolkit: It is a set of application program interfaces used by
Java programmers to create graphical user interface.
11.7 ANSWERS TO CHECK YOUR PROGRESS
1. The delegation event model uses event listeners and handleEvent() to
handle events.
2. An event is represented by an object, which specifies the change of state in the
source.
3. EventObject is the highest class in the delegation event model.
Self-Instructional
198 Material
Event Handling
NOTES
4. The ActionEvent class represents the event that is generated when a user
selects a menu item, presses button or double-clicks a list item.
5. The ItemEvent class defines the constructor in the following manner:
ItemEvent(ItemSelectable source, int event_type, Object
item, int item_state).
6. Event sources are the objects which generate events.
11.8 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What is the usage of an event?
2. What is the difference between event source and event listener?
3. List the various event handling classes in Java.
Long-Answer Questions
1. Discuss the models proposed for event handling in Java.
2. Describe about the delegation event model in detail.
3. Describe the interfaces that support the event handling in Java.
Self-Instructional
Material 199
Network Programming
NOTES
UNIT 12 NETWORK PROGRAMMING
Structure
12.0 Introduction
12.1 Unit Objectives
12.2 Networking Fundamentals
12.2.1 TCP/IP Protocols
12.2.2 Internet Addressing
12.2.3 Ports
12.2.4 Sockets
12.3 The Networking Classes and Interfaces
12.4 The InetAddress Class
12.5 TCP/IP Socket Programming
12.5.1 Creating a TCP Server
12.5.2 Creating a TCP Client
12.6 UDP Socket Programming
12.6.1 Creating a UDP Server Program
12.6.2 Creating a UDP Client Program
12.7 Summary
12.8 Key Terms
12.9 Answers to Check Your Progress
12.10 Questions and Exercises
12.0 INTRODUCTION
At the core of the network programming is the concept of a socket. A socket is one
endpoint of a two-way communication link between two programs running on the network.
Java supports creation of sockets and exchange information using different protocols
through the classes defined in java.net package. To use these classes, one must
know the fundamentals of networking like working of TCP/IP protocols, Internet
Addressing and ports. You will learn about all these topics in this unit before learning
network programming.
12.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Understand the networking fundamentals, such as TCP/IP Protocols, UDP, etc.
Describe the networking classes and interfaces
Understand the significance of InetAddress class
Explain TCP/IP socket programming and UDP socket programming
12.2 NETWORKING FUNDAMENTALS
The network systems comprise a server, client and communication media (See Figure
12.1). A machine running a process that sends request for the services is known as
client. On the other hand, a machine running a process that responds to the clients
request by offering requested services is known as server. A server can handle many
Self-Instructional
200 Material
Network Programming
NOTES
clients at the same time. To make the clients and the server communicate, a connecting
medium is required. The communication medium may be wired or wireless network.










Network
Client Machine
Server Machine
Request
Respons
Figure 12.1 ClientServer Communication
A network can be small (having two computers) or as vast as Internet.
Communication over network requires some reliable delivery services that can carry
information between two machines. The delivery services must work regardless of the
hardware and software used on the network. The Internet provides delivery services
using a suite of protocols known as TCP/IP named after its two primary protocols,
namely, Transport Control Protocol and Internet Protocol. The TCP/IP consists of
four layers, namely, Application, Transport, Network, and Link layer. All the layers
along with their corresponding protocols are shown in Figure 12.2.
(http, telnet, ftp, )
(IP, )
(Device Driver, )
(TCP, UDP, )
Application Layer
Transport Layer
Network Layer
Link Layer
Figure 12.2 TCP/IP Model
12.2.1 TCP/IP Protocols
The three most commonly used protocols within the TCP/IP suite are IP, TCP and UDP.
To develop network application, one must have a clear understanding of these protocols.
TCP (Transmission Control Protocol)
The TCP (Transmission Control Protocol) is a reliable and connection-oriented protocol
that allows the data that originates from source machine to be delivered without error to
the destination. TCP sets up a connection between the source machine and the destination
machine by transmitting control information before initiating the communication. This
mechanism is known as handshake. Once the connection is established, data transfer
between the two machines begins. TCP fragments the data into discrete messages
(known as TCP segments) and passes them to the internet layer. At the destination,
the receiving TCP sends an acknowledgement that guarantees that the data has been
received. It then reassembles the segments to form the original message. In case the
segments are lost or corrupted, TCP is responsible for retransmitting the necessary
segments. When all the data has been exchanged between these machines, it closes the
connection.
Self-Instructional
Material 201
Network Programming
NOTES
IP (Internet Protocol)
IP (Internet Protocol) is an unreliable and connectionless protocol that manages the
address part of each packet (the basic unit of IP transmissions) so that the packet
reaches the right destination. Being a connectionless protocol, IP does not transmit control
information before initiating communication between the source and the destination. It
sends data from the source to the destination expecting that the data will be delivered at
the receiving end properly. It is unreliable as it does not retransmit lost or corrupted
packets, that is, it does not guarantee the safe delivery of packets.
UDP (User Datagram Protocol)
Unlike TCP based applications, some network applications do not require a host-to-host
and reliable channel of communication. Instead they require a mode of communication
which transmits independent, self-contained messages whose time of arrival, order of
arrival, content, etc. are not guaranteed. This mode of network communication is governed
by the UDP protocol. The UDP (User Datagram protocol) is an unreliable and
connectionless protocol which enables application to send independent, selfcontained
messages known as datagrams over the network. It has no mechanism for detecting
errors or retransmitting lost or corrupted information. It is used in the applications that
require prompt delivery instead of accurate delivery such as weather forecasting, clock
server, video, games, audio, etc.
12.2.2 Internet Addressing
Every machine on the Internet is identified by a numerical address known as IP address.
An IP address consists of 32-bit number, organized as four 8-bit values. It is represented
in a format known as dotted-decimal notation. In this representation, each group of
bit is represented by its decimal equivalent which is between 0 and 255. For example,
1.160.10.240 could be an IP address. This address type was specified by IPv4 (Internet
Protocol, version 4).
Since this representation is not user friendly, IP address is mapped to domain
name like www.google.com which is easier to remember. Special servers on the Internet
perform this mapping called Domain Name Servers. It allows users to work with
domain names, however, Internet operates on the IP addresses.
Note: New addressing scheme (known as IPv6) uses 128-bit value to represent an address.
12.2.3 Ports
A machine provides a variety of services including electronic mail, Telnet, FTP, etc.
Using IP address, a client can connect to the machine but cannot connect to the desired
service. To resolve this, with each service, a port number is associated. A port is a
logical number assigned to a particular service through which the service is requested.
Clearly, to avail a service of server, a client machine does not just connect to the
server, it connects to a port on that server. Each packet that is sent over a network
contains the IP address of the host machine and the port number to identify the particular
application running on that host machine. An IP address can be considered as the house
address where a letter is sent via post and port number is the name of the person to
whom letter is to be delivered.
Note: The port numbers below 1024 are known as well-known ports and are reserved for standard
services. For example, the port number used for Telnet is 23.
Self-Instructional
202 Material
Network Programming
NOTES
12.2.4 Sockets
The combination of IP address and port number is known as socket. A socket identifies
an endpoint of a two-way communication link between two programs running on the
network. When a client requests for a connection on a particular port, the server identifies
and keeps track of the socket that it will use to communicate with that client. A server
can communicate on the same port with many clients using sockets to determine the
destination and source of the communication.
Socket-based Communication
In socket-based communication, the server (program) running on a computer binds a
socket to a specific port. The server listens to this socket for any clients connection
request as shown in Figure 12.3(a). When a request is made, the server accepts the
request. Once the request is accepted, the server binds a new socket to a different port
[see Figure 12.3(b)]. The new socket is required so that the server can continue to listen
to the original socket for new connection requests and at the same time keep serving the
connected clients.
(a) Client requests for a connection with server











(b) Server obtains a new local port
2003
listen for
connections
Server
2003
Client
connection
request
2003
new local port
Server
2003
Client
Tells client to use
new local port
1099
Figure 12.3 Establishment of Path for Two-Way Communication
12.3 THE NETWORKING CLASSES AND
INTERFACES
Java facilitates creation of network applications through the classes and interfaces defined
in the java.net package. Some of the classes defined in this package are listed in
Table 12.1.
Check Your Progress
1. The Internet
provides delivery
services using a
suite of protocols
known as ______.
2. UDP (User
Datagram
protocol) is a
reliable and
connectionless
protocol which
enables application
to send
independent, self
contained messages
known as
datagrams. (True
or False)
3. Which of these
protocols
implements the
network layer?
(a) TCP (b) IP
(c) UDP
(d) Both (a) and (c)
4. The port numbers
below _____ are
known as _____
ports and are
reserved for
standard services.
5. How many bits
does IPv6 use to
represent an
address?
6. The combination
of IP address and
port number is
known
as_________.
Self-Instructional
Material 203
Network Programming
NOTES
Table 12.1 Some of the Classes of the java.net Package
Class Description
Authenticator represents an object that obtains authentication for a
network connection
ContentHandler an abstract classsuperclass of all the classes that
contains methods to read an object from a
URLConnection
DatagramPacket contains methods to implement a connectionless
packet delivery service
DatagramSocket represents a socket for sending and receiving
datagram packets
DatagramSocketImpl an abstract datagram and multicast socket
implementation superclass
HttpURLConnection
represents a URLConnection having support for
HTTP-specific features
InetAddress represents an IP address
ServerSocket implements server sockets
Socket implements client sockets
SocketImpl an abstract classsuperclass of all classes that
implements sockets
URL represents a Uniform Resource Locator, a pointer to a
resource on the WWW
URLConnection an abstract classsuperclass of all classes that
represent a communication link between the
application and a URL
URLStreamHandler an abstract classsuperclass of all stream protocol
handlers
Some of the interfaces defined in java.net package are listed in Table 12.2.
Table 12.2 Interfaces of java.net Package

Interface Description
ContentHandlerFactory defines factory for content handlers
CookiePolicy provides a mechanism to decide which
cookie should be accepted and which
should be rejected
CookieStore represents a storage for cookie
DatagramSocketImplFactory defines factory for the implementation of
datagram socket
FileNameMap provides a mechanism to map between a
file name and a MIME type string
SocketImplFactory defines factory for the implementation of
socket
SocketOptions defines methods to get or set socket
options
URLStreamHandlerFactory defines factory for URL stream protocol
handlers
Note: Factory methods are simply a convention by which the static methods in a class return an instance
of that class.
12.4 THE InetAddress CLASS
As stated earlier, users use the domain names, whereas, Internet operates on IP addresses.
In Java, the domain names can be resolved to their IP addresses and vice versa by using
the InetAddress class.
Self-Instructional
204 Material
Network Programming
NOTES
An InetAddress object can be created using one of the available factory methods.
Commonly used factory methods of InetAddress class are listed in Table 12.3.
Table 12.3 Methods of the InetAddress Class
Method Description
static InetAddress
getLocalHost()

returns the InetAddress object that
represents the local host
static InetAddress
getByName(String
hostname)
returns an InetAddress for a host
name passed to it
static InetAddress[]
getAllByName(String
hostname)
returns an array of InetAddress
that represents all of the addresses
resolved for a host name passed to it;
used in case a single name represents
several machines
All these methods throw an UnknownHostException. The methods
getLocalHost()and getByName(String hostname)throw this exception
if they are unable to resolve the host name. The method getAllByName() throws
this exception if it is unable to resolve the name to even a single address.
12.5 TCP/IP SOCKET PROGRAMMING
In Java, there are two types of TCP sockets; one is for servers and other is for clients.
These two sockets are implemented using two different classes of java.net package,
namely, ServerSocket class and Socket class.
The ServerSocket class is used to listen for incoming connections, that is, to
wait for clients to connect. The constructors defined in class ServerSocket are
listed in Table 12.4.
Table 12.4 Constructors of the ServerSocket Class
Constructor Description
ServerSocket() creates an unbound server socket
ServerSocket(int
portnumber)
creates a server socket and binds it to the
port number specified by portnumber
ServerSocket(int
portnumber, int
qlength)
creates a server socket, binds it to the
specified port number and creates a queue
of length specified by qlength for that
port. The queue length specifies the
number of client requests that can be kept
in the waiting list.
ServerSocket(int
portnumber, int
qlength, InetAddress
address)
creates a server socket, binds it to the
specified port number, creates a queue of
length specified by qlength and binds it
to the IP address specified by address.
The Socket class is used by the client to connect to the server sockets and
exchange data using input and output streams. When a Socket object is created, a
connection is established implicitly between the client and the server. Some of the
constructors defined in this class are listed in Table 12.5.
Self-Instructional
Material 205
Network Programming
NOTES
Table 12.5 Some of the Constructors of the Socket Class

Constructor Description
Socket() creates an unconnected socket
Socket(InetAddress
address, int
portnumber)
creates a socket and connects it to the
specified port number at the specified IP
address
Socket(String host,
int portnumber)
creates a socket and connects it to the
specified port number on the named host
The Socket class defines various methods; two of which are
getInputStream() and getOutputStream(). These methods return the
InputStream and OutputStream object respectively associated with a socket.
These streams are used in the same way as I/O streams to receive and send the data.
12.5.1 Creating a TCP Server
The following steps are involved in creating a server program:
1. Open the server socket: To open a socket, one of the constructors of class
ServerSocket given in Table 12.4 can be used.
2. Wait for the client request: The server socket waits until a connection request
is made by some client and then returns an actual Socket object representing
that connection. It is accomplished by the accept() method of the
ServerSocket class. The accept() method is a blocking call that waits
until a client tries to connect to it. When a connection is made, it returns the
Socket object.
3. Create I/O streams for communicating to the client: Once a dedicated
connection is established between client and server, obtain the InputStream
and OutputStream object associated with a socket using
getInputStream() and getOutputStream() methods respectively.
4. Communicate with the client: Data can be read from or written to the client
using the objects declared for input and output stream respectively.
5. Close the socket: Finally, the socket must be closed. To close the socket on the
server side, the close() method is used. Note that before closing the socket,
the input and output stream must be closed.
Example 12.1: A program to demonstrate a server program
import java.net.*;
import java.io.*;
public class ServerExample
{
public static void main(String args[])
{
int port = 2316;
try
{
//creates a socket on port 2316
ServerSocket ss = new ServerSocket(port);
//waits and accepts a connection
Self-Instructional
206 Material
Network Programming
NOTES
Socket socket = ss.accept();
//associates stream with the socket
OutputStream sout = socket.getOutputStream();
DataOutputStream out = new DataOutputStream(sout);
//sends output to the standard output device
System.out.println(Hello! this is your socket
programming );
// sends a string to the client
out.writeUTF(Server is Ready!);
//sends output to the standard output device
System.out.println(Waiting for the next
line...);
//Closes the connection except server socket
out.close();
sout.close();
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
12.5.2 Creating a TCP Client
The steps involved in creating a client program are:
1. Create a Socket object
2. Create I/O streams for communicating with the server
3. Communicate with the server
4. Close the socket when the communication ends
Example 12.2: A program to demonstrate a client program
import java.net.*;
import java.io.*;
public class ClientExample
{
public static void main(String args[])
{
int port = 2316;
try
{
//obtains the IP address for the localhost
InetAddress ipAddress =
Self-Instructional
Material 207
Network Programming
NOTES
InetAddress.getByName(localhost);
System.out.println(Address and the port no is:
+ ipAddress + and port + port + ?);
// opens connection to the server at port no 2316
Socket socket = new Socket(ipAddress, port);
System.out.println(I am the Client.);
// obtains an input file handle from the socket /
/and read the input
InputStream sin = socket.getInputStream();
DataInputStream in = new
DataInputStream(sin);
String pstr = new String(in.readUTF());
System.out.println(pstr);
// closes the connection
sin.close();
in.close();
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Note that in this program, at the time of creation of Socket, both the IP address
and port number where the client is trying to connect are provided.
12.6 UDP SOCKET PROGRAMMING
Java supports UDP by providing two classes, namely, DatagramPacket and
DatagramSocket.
DatagramSocket
The DatagramSocket class is used to send or receive the datagram packets. It
defines four constructors that are listed in Table 12.6.
Table 12.6 Constructors Defined in DatagramSocket Class
Constructor Description
DatagramSocket() creates a datagram socket
DatagramSocket(int
portnumber)
creates a datagram socket and binds it to
the port number specified by
portnumber
DatagramSocket(int
portnumber, InetAddress
ipAddress)
creates a datagram socket and binds it to
the port and the InetAddress specified
by portnumber and the ipAddress
respectively
DatagramSocket(SocketA
ddress address)
creates a datagram socket and binds it to
the SocketAddress specified by the
address
Self-Instructional
208 Material
Network Programming
NOTES
Note: While creating the datagram socket, if any error occurs, all these constructors throw a
SocketException.
The class DatagramSocket defines many methods. Two important methods
are listed in Table 12.7.
Table 12.7 Methods of the DatagramSocket Class
Method Description
void send(DatagramPacket
packet)
sends packet to the port
void receive(DatagramPacket
packet)
receives packet specified by
packet from the port
Note: Both the methods send() and receive() throw a IOException when an error occurs.
DatagramPacket
The DatagramPacket class is used to contain the data. It defines many constructors;
some of them are listed in Table 12.8.
Table 12.8 Constructors Defined in DatagramPacket Class

Constructor Description
DatagramPacket(byte
data[], int length)
creates a DatagramPacket for
receiving the packets of length length in
the buffer
DatagramPacket( byte
data[],int offset, int
length )
creates a DatagramPacket for
receiving the packets of length length,
specifying an offset into the buffer
DatagramPacket( byte
data[], int offset, int
length , InetAddress
ipAddress, int
portnumber)

creates a DatagramPacket for sending
packets of length length to the specified
port number on the specified host
Some of the commonly used methods defined in DatagramPacket class are
listed in Table 12.9.
Table 12.9 Methods of the DatagramPacket Class

Method Description
InetAddress getAddress() returns the address of the machine to
which the datagram is sent or from which
the datagram is received
byte[] getData() returns the data contained in the datagram
int getLength() returns the length of the valid data
contained in the byte array that is returned
from the getData() method
int getPort() returns the port number on the remote host
VoidsetAddress(InetAddress
ipAddress)
sets the address specified by ipAddress
to which a packet is to be sent
void setData(byte[] data)
sets the data to data
void setLength(int length)
sets the size of the packet to length
void setPort(int
portnumber)
sets the port number specified by
portnumber on the remote host
Self-Instructional
Material 209
Network Programming
NOTES
12.6.1 Creating a UDP Server Program
The following steps are involved in creating a UDP server program.
1. Open the Datagram Socket: To open a Datagram socket, one of the constructors
of class DatagramSocket can b used.
2. Obtain the IP address for the local host: To obtain the IP address for local
host, the statement InetAddress ipadd=InetAddress
.getLocalHost() is used.
3. Create the data input/output stream for communication with the client: A
string of data is created, then that string is converted in to datagram packets.
4. Perform communication with the client: Data can be read from or written to
the client using datagram packets.
5. Close the Datagram socket: Finally, the socket must be closed. To close the
socket on the server side, the close() method is used. Note that before closing
the socket, the input and output stream must be closed.
Example 12.3: A program to demonstrate a UDP server program
import java.net.*;
import java.io.*;
import java.util.*;
class UDPServerExample
{
public static void main(String args[]) throws Exception
{
int serverportno = 1139;
int clientportno = 1140;
try
{
//creates a socket and binds to port no 1139
DatagramSocket ds = new
DatagramSocket(serverportno);
//obtains the IP address for the localhost
InetAddress ipadd=InetAddress.getLocalHost();
String pstr = Hello this is your message;
byte buf[]=pstr.getBytes();
// creates a DatagramPacket for sending the packets
DatagramPacket send_packet = new
DatagramPacket(buf,buf.length,ipadd,clientportno);
ds.send(send_packet); //sends packets
ds.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
Self-Instructional
210 Material
Network Programming
NOTES
}
}
}
12.6.2 Creating a UDP Client Program
The steps involved in creating a UDP client program are as follows:
1. Create the Datagram Socket for communicating with server.
2. Create the data input/output stream for the communication with the server.
3. Communicate with the server.
4. Close the Datagram socket.
Example 12.4: A program to demonstrate a UDP client program
import java.net.*;
import java.io.*;
class UDPClientExample
{
public static void main(String args[]) throws Exception
{
int serverportno = 1139;
int clientportno = 1140;
try
{
//creates a socket and binds to port no 1140
DatagramSocket ds = new DatagramSocket(clientportno);
byte b[]=new byte[1024];
//creates a DatagramPacket for receiving the packets
DatagramPacket dp = new DatagramPacket(b,b.length);
ds.receive(dp); //receives packets
System.out.println(new String(dp.getData()));
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Note that both the server and client programs are running between two ports on
the local machine. The server and clients are running on port numbers, 1139 and 1140
respectively. So, run these programs on different command prompt windows.
Check Your Progress
7. For which purpose
is the InetAddress
class used?
8. TCP server and
client sockets are
implemented using
classes ____ and
____, respectively.
9. The
DatagramSocket
class is used to
send or receive the
datagram packets.
(True or False)
10. If any error occurs
while creating the
datagram socket,
which type of
exception is
thrown?
Self-Instructional
Material 211
Network Programming
NOTES
12.7 SUMMARY
In this unit, you have learned that:
The network systems comprise a server, client and communication media.
A network can be small (having two computers) or as vast as Internet.
Communication over network requires some reliable delivery services that can
carry information between two machines.
The delivery services must work regardless of the hardware and software used
on the network. The Internet provides delivery services using a suite of protocols
known as TCP/IP
The three most commonly used protocols within the TCP/IP suite are IP, TCP
and UDP
The TCP (Transmission Control Protocol) is a reliable and connection-oriented
protocol that allows the data that originates from source machine to be delivered
without error to the destination.
IP (Internet Protocol) is an unreliable and connectionless protocol that manages
the address part of each packet (the basic unit of IP transmissions) so that the
packet reaches the right destination.
The UDP (User Datagram Protocol) is an unreliable and connectionless protocol
which enables application to send independent, selfcontained messages known
as datagrams over the network.
Every machine on the Internet is identified by a numerical address known as IP
address. An IP address consists of 32-bit number, organized as four 8-bit values.
It is represented in a format known as dotted-decimal notation.
A port is a logical number assigned to a particular service through which the
service is requested.
The combination of IP address and port number is known as socket. A socket
identifies an endpoint of a two-way communication link between two programs
running on the network.
Java facilitates creation of network applications through the classes and interfaces
defined in the java.net package.
The domain names can be resolved to their IP addresses and vice versa by using
the InetAddress class.
In Java, there are two types of TCP sockets; one is for servers and other is for
clients. These two sockets are implemented using two different classes of
java.net package, namely, ServerSocket class and Socket class.
The ServerSocket class is used to listen for incoming connections, that is, to
wait for clients to connect.
The Socket class is used by the client to connect to the server sockets and
exchange data using input and output streams.
Java supports UDP by providing two classes, namely, DatagramPacket and
DatagramSocket.
Self-Instructional
212 Material
Network Programming
NOTES
12.8 KEY TERMS
Server: It refers to a machine running a process that responds to the clients
request by offering requested services.
TCP protocol: It is a reliable and connection-oriented protocol that allows the
data that originates from source machine to be delivered without error to the
destination.
IP address: It refers to the numerical address that identifies every machine on
the Internet.
Port: It is a logical number assigned to a particular service through which the
service is requested.
Socket: It is the combination of IP address and port number.
12.9 ANSWERS TO CHECK YOUR PROGRESS
1. TCP/IP
2. False
3. (b)
4. 1024, well-known
5. IPv6 uses 128-bit value to represent an address.
6. Socket
7. The InetAddress class is used to resolve the domain names to their IP
addresses and vice versa.
8. ServerSocket, Socket
9. True
10. If any error occurs while creating the datagram socket, SocketException is
thrown.
12.10 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What is the name of the IP address format?
2. State one function of socket.
3. What are the steps involved in creating a TCP client program?
4. Define User Datagram Protocol.
Long-Answer Questions
1. Explain the various interfaces defined in java.net package.
2. Discuss the role of IP (Internet Protocol) in the TCP/IP model.
3. Explain the constructors of the ServerSocket class.
4. Illustrate the steps involved in creating TCP Server/Client programs using socket.
Self-Instructional
Material 213
Java and Database
NOTES
UNIT 13 JAVA AND DATABASE
Structure
13.0 Introduction
13.1 Unit Objectives
13.2 Architecture of JDBC
13.3 JDBCODBC Bridge
13.4 The java.sql Package
13.4.1 The DriverManager Class
13.4.2 The Connection Interface
13.4.3 The Statement Interface
13.4.4 The ResultSet Interface
13.4.5 The PreparedStatement Interface
13.4.6 The ResultSetMetaData Interface
13.4.7 The SQLException Class
13.5 Summary
13.6 Key Terms
13.7 Answers to Check Your Progress
13.8 Questions and Exercises
13.0 INTRODUCTION
Accessing a database in Java requires Java Database Connectivity (JDBC). JDBC
provides a standard API that is used to access databases, through Java, regardless of
the DBMS. All the direct interactions with specific DBMSs are accomplished by DBMS
specific driver. It acts as wrapper that sends SQL requests to the server.
In this unit, you will learn how to deal with database in Java.
13.1 UNIT OBJECTIVES
After going through this unit, you will be able to:
Explain the architecture of JDBC
Explain JDBC ODBC bridge
Understand the classes and interfaces of java.sql
Discuss the SQLException class
13.2 ARCHITECTURE OF JDBC
The architecture of JDBC has four components, namely application, driver manager,
data source specific drivers and corresponding data sources.
An application establishes and terminates the connection with a data source. The
main goal of driver manager is to load JDBC drivers and pass JDBC function calls from
the application to the corresponding driver. The driver establishes the connection with
data source. The driver performs various basic functions like submitting requests and
returning results. In addition, the driver translates data, error formats and error codes
Self-Instructional
214 Material
Java and Database
NOTES
from a form that is specific to data source into the JDBC standard. The data source
processes commands from the driver and returns the results.
JDBC Drivers can be classified into four categories as follows:
JDBC-ODBC (open data base connectivity)-Bridge Driver: This type of
driver is used to access data through drivers using ODBC standard.
Native API partly-Java Driver: This driver is specific to every database and
converts the JDBC calls to database specific calls. For example, Oracle database
will have its own oracle native API, and Sybase will have its own native API.
Net protocol all-Java client Driver: This driver is server based driver that
uses network protocol and middleware for communicating with the server which
in turn translates it to the DBMS specific function calls.
Native protocol all-Java Driver: This driver is entirely written in Java, which
directly communicates with the database server without including any translation
steps.
13.3 JDBCODBC BRIDGE
Microsofts ODBC , short for open database connectivity is the most commonly used
driver to connect to the database as it can connect to almost all databases on most of the
platforms. However, ODBC uses the concept of pointers and other constructs that are
not supported by Java. Therefore, JDBCODBC bridge driver was developed which
translates the JDBC API to the ODBC API and vice versa. This bridge acts as interface
that enables all DBMS which support ODBC (Open Data Base Connectivity) to interact
with Java Applications. JDBC-ODBC bridge is implemented as a class file and a native
library. The name of the class file is JdbcOdbc.class. On windows platform, native
library called JDBCODBC.DLL is used.
Figure 13.1 shows the JDBC application architecture in which a front-end
application uses JDBC API for interacting with JDBC Driver Manager. Here, JDBC
Driver Manager is the backbone of JDBC architecture. It acts as interface that connects
a Java application to the driver specified in the Java program. Next, is the JDBC-ODBC
bridge which helps the JDBC to access ODBC data sources.

Java Application
JDBC API
JDBC Driver
JDBC-ODBC Bridge
Driver
ODBC Driver
Access
Driver
SQL
Driver
MS
Access
MS SQL
Database
Figure 13.1 JDBC Architecture with JDBCODBC Bridge
Self-Instructional
Material 215
Java and Database
NOTES
13.4 THE java.sql PACKAGE
To work with the database, Java provides java.sql package. It contains various
classes and interfaces that can be used for establishing connection with database and
retrieve data from it. This section discusses one of the important class DriverManager
and some of the important interfaces included in this package.
13.4.1 The DriverManager Class
The DriverManager class is responsible for loading the driver specific classes. The
drivers are registered with the DriverManager class either when an instance of
driver is created using registerDriver(Driver driver) method of the
DriverManager class or DriverManager class is initialized.
The static method forName() of the Class class can be used by
DriverManager class to locate and load the drivers listed in system variable
jdbc.drivers is as follows:
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver)
Here, the driver class specified in the string parameter is loaded dynamically at
the run time.
Some of the methods of the DriverManager are as follows:
Connection getConnection(String url): This method attempts
to establish a connection to a given database URLdoes not require password.
Connection getConnection(String url, String user,
String password): This method attempts to establish a connection to a
given database URL.
void registerDriver(Driver driver): This method is used to
register a driver specified by driver with the DriverManager.
void deregisterDriver(Driver driver): This method removes
the driver specified by driver from the DriverManagers list.
13.4.2 The Connection Interface
The Connection interface helps to establish a connection with the required database.
Other than establishing connection, it provides lot of functionality including transaction
management, maintaining database sessions and creating SQL statements.
Some of the commonly used methods of connection interface are as follows:
void close(): This method closes database connection associated with
Connections object and releases JDBC resources.
Statement createStatement(): This method creates a Statement
object which is used to send SQL statement to the database. It is usually used
when SQL statement without parameters is to be executed.
CallableStatement prepareCall(String sql): This method
creates an instance of CallableStatement which is used to handle database
stored procedures.
Self-Instructional
216 Material
Java and Database
NOTES
PreparedStatement prepareStatement(String sql): This
method creates PreparedStatement object which is used to create SQL
statement specified in string sql. It is usually used when parameterized SQL
statement is to be executed.
13.4.3 The Statement Interface
The statement interface provides methods that are used to execute static SQL
statements. The SQL statements are queries, insertions, updates and deletions etc.
Some of the methods of the Statement interface are as follows:
void close(): This method closes database connections associated with
Statements object and releases JDBC resources.
boolean execute(String sql): This method is used to execute an
SQL statement that might produce multiple result sets or multiple counts. It returns
true if multiple result sets are produced and returns false if multiple counts
are generated.
int executeUpdate(String sql): This method is used to execute an
SQL statement that gives information about number of affected rows. For example,
if we execute the statements like INSERT, DELETE, the result will only be a
number of rows affected.
ResultSet executeQuery(String sql): This method executes a
query and returns a ResultSet object. A result set is just like a table containing
the resultant data.
ResultSet getResultSet(): This method returns the first result set or
multiple count generated on the execution of execute(String sql) method.
If there is no result set, it returns null value.
int getUpdateCount(): After the execution of the execute(String
sql) method updates counts may be generated. This method returns the first
update count and clears it. More update counts can be retrieved by
getMoreResults(). Note that this method returns value -1 if there is no
update count or when only result sets are generated on execution of
execute(String sql) method.
boolean getMoreResults(): This method is used to retrieve the next
result set in multiple result set or to the next count in multiple update count generated
on execution of execute(String sql)method. It returns a true value if
multiple sets are available and returns a false value if multiple update counts
are available.
13.4.4 The ResultSet Interface
The execution of SQL statement results in table which consists of rows and columns
containing the resultant data. The data can be retrieved from the table by using methods
of the ResultSet interface. Some methods of the ResultSet interface are as
follows:
boolean next(): This method is used to move the ResultSet cursor to
the next row of the data. Initially, the ResultSet cursor is pointed before the
first row. It returns the false value if there are no more rows in the ResultSet
object.
Self-Instructional
Material 217
Java and Database
NOTES
String getString(int index): This method returns the string value
that is stored in the column indicated by the column number, index. For example,
if the value of index is 2 then it will return the value stored in second column
number.
String getString(String column): This method returns the string
value that is stored in the column indicated by the column name column.
Example 13.1: A program to establish connection and retrieve data from Student
database
import java.sql.*;
public class SimpleJDBCProgram
{
public static void main(String args[])
{
try
{
//loading the driver class
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
//defines the datasource for the driver
String url = jdbc:odbc:ITLESL;
//creating the connection through DriverManager
Connection con = DriverManager.getConnection (url, login,
password);
//creating the statement object
Statement st = con.createStatement();
//executing the query through Resultset object
ResultSet rs = st.executeQuery(Select Roll, Marks, Grade
FROM Student);
//output the resultset data
while (rs.next())
{
//retrieve columns
int roll = rs.getInt(Roll);
int marks = rs.getInt(Marks);
String grade = rs.getString(Grade);
//display values
System.out.println(Roll No :+ roll);
System.out.println(Marks :+ marks);
System.out.println(Grade :+ grade);
Self-Instructional
218 Material
Java and Database
NOTES
}
//cleaning up the environment
rs.close();
st.close();
con.close();
}
catch(Exception e)
{
System.out.println(Error +e);
}
}
}
In this program, following steps are followed to access the data from the database.
1. Appropriate drivers for the database are loaded by using Class.forName().
2. The getConnection() method of DriverManager class of JDBC is
used to create the Connection object. An application may have more than
one connection objects to connect with one or more databases.
3. The first parameter URL(jdbc:odbc:ITLESL) identifies the database.
This URL has three parts: protocol, subprotocol and DSN name. To connect to
the database username and password are also required which are specified by
the other two parameters of getConnection()method, login and
password.
4. The statement Statement st = con.createStatement()is used to
create Statement object, st for querying the database. It is created by calling
the createStatement() method using the Connection object, con.
5. In this example, st.executeQuery is used to execute the SELECT
statement of SQL. The try{..} catch {..} is used to catch any exceptions
that may arise as a result of executing this query statement. The result of this
query may consist of set of tuples, which is assigned to rs object of type
ResultSet. Initially, it places the cursor at the beginning of the first tuple. The
statement rs.next() moves the cursor to the next tuple
6. The next() method is used to fetch one tuple at a time from the result set rs.
The statement int roll = rs.getInt(Roll); is used to access
data from the database and System.out.println(Roll No :+
roll); is used to display data.
7. The connection must be closed after it is no more required at the end of the
procedure. The statement rs.close(), st.close(), con.close()
closes all the open connections.
Example 13.2: A program to establish connection and retrieve data from Employee
database
import java.io.*;
import java.sql.*;
Self-Instructional
Material 219
Java and Database
NOTES
public class ExampleSelectStatement
{
public static void main(String args[])
{
Connection con=null;
try
{
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
//loads driver
con=DriverManager.getConnection(jdbc:odbc:
Emp);
// establishes connection
Statement st = con.createStatement();
//creates Statement object
ResultSet rs = st.executeQuery(select * from
Employee);
// creates ResultSet object
System.out.println(
Employee Details);
System.out.println(\n);
System.out.print(Eno );
System.out.print(Name );
System.out.print(Department );
System.out.print(Designation );
System.out.println(Salary );
System.out.println(
);
// displays data till there are no more //
rows
while(rs.next())
{
System.out.print(rs.getString(ENumber));
System.out.print( );
System.out.print(rs.getString(EName));
System.out.print( );
System.out.print(rs.getString(
Department));
System.out.print( );
System.out.print(rs.getString(
Designation));
System.out.print( );
System.out.println(rs.getString(Salary));
Self-Instructional
220 Material
Java and Database
NOTES
}
// closes the connection
rs.close();
st.close();
con.close();
System.in.read();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
The output of the program is
Employee Details
Eno Name Department Designation Salary

1 Prem IT PL 30000
2 Samee IT SSE 29500
3 Preeti IT TL 29500
4 Mili IT SE 28000
5 Niti Math TL 28000
6 Surabhi IT SE 25000
7 Milendu IT SE 25000
13.4.5 The PreparedStatement Interface
PreparedStatement interface extends the Statement interface so it has access
to all the methods of Statement interface. It is used to execute precompiled
parameterized SQL statements. This helps statements to execute much faster thus
increases the efficiency of the program. It allows you to specify SQL query, in which
unknown values are replaced by ?. The user provides the unknown values later at the
run-time. The setString() and setInt() methods can be used to specify the
values for the parameters. To understand the concept of prepared statement, consider
the following statements.
PreparedStatement ps = con.prepareStatement(INSERT INTO
Student
VALUES(?,?,?));
ps.setString(1, A010);//assigns value to first attribute
ps.setInt(2, 90); //assigns value to second attribute
ps.setString(3, A); //assigns value to third attribute
ps.executeUpdate();
The values can be assigned to the corresponding attributes through variable name
also instead of using literal values representing index value. Like, setString() and
Self-Instructional
Material 221
Java and Database
NOTES
setInt() methods, there are various methods for setting value of other data type.
Some of these are setBoolean(), setFloat(), setByte(), setDate(),
etc. The method void clearParameters() can be used to clear all the values
held currently in the parameters.
Note: The methods execute(), executeQuery() and executeUpdate() have same functionality
as the methods of Statement interface, but with a difference that here no parameters are passed.
Example 13.3: A program to demonstrate implementation of PreparedStatement
interface
import java.io.*;
import java.sql.*;
public class ExamplePreparedStatement
{
public static void main(String args[])
{
Connection con=null;
int i = 0;
try
{
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
con=DriverManager.getConnection(jdbc:odbc:Emp);
Statement st = con.createStatement();
PreparedStatement ps =
con.prepareStatement(INSERT INTO Employee
VALUES(?,?,?,?,?));
ps.setInt(1,8);
ps.setString(2,Meenu);
ps.setString(3,IT);
ps.setString(4,SE);
ps.setInt(5,30000);
i = ps.executeUpdate();
System.out.println(Number of rows effected:
+i);
ResultSet rs = st.executeQuery(select * from
Employee);
System.out.print(Eno );
System.out.print(Name );
System.out.print(Depatment );
System.out.print(Designation );
System.out.println(Salary );
System.out.println(
);
while(rs.next())
Self-Instructional
222 Material
Java and Database
NOTES
{
System.out.print(rs.getString(ENumber));
System.out.print( );
System.out.print(rs.getString(EName));
System.out.print( );
System.out.print(rs.getString(
Department));
System.out.print( );
System.out.print(rs.getString(
Designation));
System.out.print( );
System.out.println(rs.getString(Salary));
}
rs.close();
System.in.read();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
The output of the program is
Number of rows effected: 1
Employee Details
Eno Name Department Designation Salary

1 Prem IT PL 30000
2 Samee IT SSE 29500
3 Preeti IT TL 29500
4 Mili IT SE 28000
5 Niti Math TL 28000
6 Surabhi IT SE 25000
7 Milendu IT SE 25000
8 Meenu IT SE 30000
13.4.6 The ResultSetMetaData Interface
The ResultSetMetaData interface provides methods that allow you to get metadata
for the resultset, that is, the number, types and properties of the columns in a ResultSet
object. This information is used to collect the data with same semantics but stored in
different databases in different formats.
Self-Instructional
Material 223
Java and Database
NOTES
To get this information of columns in the ResultSet object using methods of
the ResultSetMetaData interface, it is required to invoke the getMetaData()
method of the ResultSet object that returns a reference to an object of type
ResultSetMetaData.
Some of the methods of ResultSetMetaData interface are as follows:
int getColumnCount():This method returns the number of columns in
the resultset.
String getColumnName(int index):This method returns the name
of column specified by index value index in the resultset.
int getColumnType(int index):This method returns the type of
column specified by index value index in the resultset.
Example 13.4: A program to demonstrate implementation of ResultSetMetaData
and ResultSet interface
import java.sql.*;
class ExampleResultSetMetaData
{
public static void main(String args[])
{
Connection con;
Statement stmt;
ResultSet rs;
try
{
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
con = DriverManager.getConnection(jdbc:odbc:
Emp);
stmt = con.createStatement();
rs = stmt.executeQuery(Select * from Employee WHERE
Department=Math);
ResultSetMetaData rsmd = rs.getMetaData();
int col = rsmd.getColumnCount();
//returns number of columns
int row = 1;
while (rs.next())
{
System.out.println(Row + row + : );
for (int i = 1; i <= col; i++)
{
System.out.print( Column + i + : );
System.out.println(rs.getString(i));
}
System.out.println( );
row++;
Self-Instructional
224 Material
Java and Database
NOTES
}
stmt.close();
con.close();
}
catch(Exception e)
{
System.err.print(ClassNotFoundException: );
System.err.println(e.getMessage());
}
}
}
The output of the program is
Row 1:
Column 1: 5
Column 2: Niti
Column 3: Math
Column 4: TL
Column 5: 28000
13.4.7 The SQLException class
While accessing the database, the developer may encounter various types of errors. If
any JDBC object encounters an error, it throws the SQLException. The
SQLException class extends the java.lang.Exception class. Some of the
methods of the SQLException class are as follows:
SQLException getNextException(): This method is used to obtain
the next exception object in the chain of errors (if any exists).
String getSQLState(): This method provides the information about the
state of SQL, which helps in taking appropriate decisions.
int getErrorCode(): This method provides information about the vendor
specific errors whose meaning is defined by the driver vendor only.
Example 13.5: A program to demonstrate how exceptions related to JDBC are handled
import java.io.*;
import java.sql.*;
public class FinalExceptionExample
{
public static void main(String args[])
{
Connection con=null;
try
{
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
Self-Instructional
Material 225
Java and Database
NOTES
con=DriverManager.getConnection(jdbc:odbc:
Emp);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(select * from
EmployeeDB);
System.out.print(Employee Number );
System.out.print(Employee Name );
System.out.print(Department );
System.out.print(Designation );
System.out.println(Salary );
System.out.println(
);
while(rs.next())
{
System.out.print(rs.getString(ENumber));
System.out.print( );
System.out.print(rs.getString(EName));
System.out.print( );
System.out.print(rs.getString(
Department));
System.out.print( );
System.out.print(rs.getString(
Designation));
System.out.print( );
System.out.println(rs.getString(Salary));
}
rs.close();
}
catch(SQLException e)
{
while(e != null)
{
System.out.println(\nSQL Exception:);
System.out.println(e.getMessage());
System.out.println(SQL State: +
e.getSQLState());
System.out.println(Error Code: +
e.getErrorCode());
Self-Instructional
226 Material
Java and Database
NOTES
e = e.getNextException();
}
}
catch(ClassNotFoundException cnfe)
{
System.out.println(cnfe.getMessage());
}
}
}
The output of the program is
SQL Exception:
[Microsoft][SQL Server Native Client 10.0][SQL Server]Invalid
object name EmployeeDB.
SQL State: S0002
Error Code: 208
Note that if Class.forName() syntax is used for registering the driver, you
may encounter the ClassNotFoundException. This type of exception is
encountered if the class loader is unable to find the specified database driver.
13.5 SUMMARY
In this unit, you have learned that:
JDBC provides a standard API that is used to access databases, through Java,
regardless of the DBMS. All the direct interactions with specific DBMSs are
accomplished by DBMS specific driver.
The architecture of JDBC has four components, which are, application, driver
manager, data source specific drivers and corresponding data sources.
JDBC-ODBC acts as interface that enables all DBMS which support ODBC
(Open Data Base Connectivity) to interact with Java Applications.
To work with the database, Java provides java.sql package. It contains various
classes and interfaces that can be used for establishing connection with database
and retrieve data from it.
The DriverManager class is responsible for loading the driver specific classes.
The Connection interface helps to establish a connection with the required
database. Other than establishing connection, it provides lot of functionality including
transaction management, maintaining database sessions and creating SQL
statements.
The statement interface provides methods that are used to execute static
SQL statements. The SQL statements are queries, insertions, updates and deletions
etc.
The execution of SQL statement results in table which consists of rows and
columns containing the resultant data. The data can be retrieved from the table
by using methods of the ResultSet interface.
Check Your Progress
1. List the
components of
architecture of
JDBC.
2. List the different
categories of JDBC
drivers.
3. _________ driver
is used to access
data through
drivers using
ODBC standard.
4. The Driver class
is responsible for
loading the driver
specific classes.
(True or False)
5. _____allows you
to specify SQL
query, in which
unknown values
are replaced by ?.
6. ______method
provides
information about
the vendor specific
errors whose
meaning is defined
by the driver
vendor only.
7. What is SQL
Exception
class?
8. List the methods
available in SQL-
Exception class.
Self-Instructional
Material 227
Java and Database
NOTES
PreparedStatement interface extends the Statement interface so it has
access to all the methods of Statement interface. It is used to execute
precompiled parameterised SQL statements. Using this, the statements execute
much faster thus increases the efficiency of the program.
The ResultSetMetaData interface provides methods that allow you to get
metadata for the resultset, that is, the number, types and properties of the columns
in a ResultSet object.
While accessing the database, the developer may encounter various types of
errors. If any JDBC object encounters an error, it throws the SQLException.
13.6 KEY TERMS
Open database connectivity (ODBC): It is the most commonly used driver to
connect to the database as it can connect to almost all databases on most of the
platforms.
Connection interface: It is an interface that helps to establish a connection
with the required database.
boolean next(): It is a method that is used to move the ResultSet
cursor to the next row of the data.
ResultSetMetaData interface: It is an interface that provides methods
allowing to get metadata for the resultset, that is, the number, types and properties
of the columns in a ResultSet object.
13.7 ANSWERS TO CHECK YOUR PROGRESS
1. The architecture of JDBC has four components, namely application, driver
manager, data source specific drivers and corresponding data sources.
2. JDBC Drivers can be classified into the following four categories:
(i) JDBC-ODBC-Bridge Driver
(ii) Native API partly-Java Driver
(iii) Net protocol all-Java client Driver
(iv) Native protocol all-Java Driver
3. JDBC-ODBC Bridge
4. False
5. PreparedStatement
6. getErrorCode()
7. While accessing the database, the developer may encounter various types of
errors. If any JDBC object encounters an error, it throws the SQLException
which must be handled by the SQLException class. The SQLException
class extends the java.lang.Exception class.
8. Some of the methods of the SQLException class are as follows:
SQLException getNextException(): This method is used to obtain
the next exception object in the chain of errors (if any exists).
Self-Instructional
228 Material
Java and Database
NOTES
String getSQLState(): This method provides the information about
the state of SQL, which helps in taking appropriate decisions.
int getErrorCode(): This method provides information about the vendor
specific errors whose meaning is defined by the driver vendor only.
13.8 QUESTIONS AND EXERCISES
Short-Answer Questions
1. What is the role of the DriverManager class of java.sql package?
2. Write a code segment to show the usage of the next() method of class
ResultSet.
3. For which purpose is the getMetaData()method used?
4. Differentiate between the Statement interface and the
PreparedStatement interface.
Long-Answer Questions
1. Discuss the architecture of JDBC.
2. Describe JDBCODBC bridge with the help of a suitable diagram.
3. Write a program to demonstrate how exceptions related to JDBC are handled.

Das könnte Ihnen auch gefallen