0% found this document useful (0 votes)
1 views275 pages

BCA_JavaProgramming

This document provides an overview of Object-Oriented Programming (OOP), including its principles, benefits, and applications, as well as the evolution and features of the Java programming language. It covers key concepts such as classes, objects, encapsulation, inheritance, and polymorphism, while also discussing the advantages and limitations of OOP. Additionally, it highlights the history of Java, its versions, and its significance in programming, particularly in relation to user interface design.

Uploaded by

ajayviswam2014
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views275 pages

BCA_JavaProgramming

This document provides an overview of Object-Oriented Programming (OOP), including its principles, benefits, and applications, as well as the evolution and features of the Java programming language. It covers key concepts such as classes, objects, encapsulation, inheritance, and polymorphism, while also discussing the advantages and limitations of OOP. Additionally, it highlights the history of Java, its versions, and its significance in programming, particularly in relation to user interface design.

Uploaded by

ajayviswam2014
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 275

LESSON 1

OBJECT ORIENTED PROGRAMMING

CONTENTS
1.0 Aims and Objectives.
1.1 Introduction.
1.2 Object Oriented Programming Paradigm.
1.3 Principles of OOP.
1.4 Benefits of OOP.
1.5 Non-Benefits of OOP.
1.6 Applications of OOP.
1.7 Object Oriented Programming Languages.
1.8 Let us sum up.
1.9 Check Your Progress: Model Answers

1.0 AIM AND OBJECTIVES

In this lesson we will learn the Fundamentals of Object oriented


programming, basic concepts of OOP and the benefits of OOP. At the end of this
lesson the learner will be able to identify objects and distinguish the
characteristics of classes, objects and methods.

1.1 INTRODUCTION

Object-oriented programming forms the core of Java. Since the concepts


of OOP is so integral to Java, it is very essential to understand its basic
principles before starting to write some simple Java programs. This lesson
commences with theoretical discussions on OOP, followed by the benefits and
application of Object Oriented Programming (OOP).

1.2 OBJECT-ORIENTED PROGRAMMING PARADIGM

The need to program GUIs led to a distinct programming paradigm,


called object-oriented programming. An object-oriented programming system
(OOPS) consists of objects. An object comprises both data and algorithms. The
data describes the state of the object. Objects communicate by sending
messages to each other. When an object receives a message, it responds by
executing one of its algorithms. The algorithm may change the state of the
object, generate output, or send messages to other objects.

7
OOPS are well-suited to programming GUIs. Typically, each element of a
GUI is represented by one object. The object determines both the state and the
behavior of the corresponding element. For example, an object representing a
window would have data for its position, size and title. If the user closes the
window, the OOPS sends a message to the window object telling it to close
itself. The window then executes an algorithm that erases its image from the
screen.
All computer programs essentially consist of two elements: code and
data. A program can be conceptually organized around its code or data. The
first way, program organized around code is called the process-oriented model
and can be thought of as code acting on data. The second way of organizing
program around data (i.e., objects) is called Object-Oriented Programming, which
was created to manage the increasing complexity. An Object oriented program
is a collection of class definitions, each one wrapping up all the data and
functionality associated with a single concept or entity specified in the program
design.

1.3 PRINCIPLES OF OOP

All object oriented programming gives the basic mechanisms that help
you implement the object-oriented model.
Class Defines the abstract characteristics of a thing (object), including
the thing's characteristics (its attributes, fields or properties)
and the thing's behaviors (the things it can do, or methods,
operations or features). One might say that a class is a blueprint
or factory that describes the nature of something. Classes provide
modularity and structure in an object-oriented computer program.
A class should typically be recognizable to a non-programmer
familiar with the problem domain, meaning that the
characteristics of the class should make sense in context. Also,
the code for a class should be relatively self-contained (generally
using encapsulation). Collectively, the properties and methods
defined by a class are called members.
Object A particular object.
Instance One can have an instance of a class or a particular object. The
instance is the actual object created at runtime. The set of values
of the attributes of a particular object is called its state. The object
consists of state and the behavior that's defined in the object's
class.
Method An object's abilities. In language, methods are verbs
Message passing The process by which an object sends data to another
object or asks the other object to invoke a method.
Abstraction Abstraction is simplifying complex reality by modeling classes
appropriate to the problem, and working at the most appropriate
level of inheritance for a given aspect of the problem.

8
Abstraction is also achieved through Composition. For example, a
class Car would be made up of an Engine, Gearbox, Steering
objects, and many more components. To build the Car class, one
does not need to know how the different components work
internally, but only how to interface with them, i.e., send
messages to them, receive messages from them, and perhaps
make the different objects composing the class interact with each
other.
Encapsulation Encapsulation is the mechanism that binds together, the
data and code, it manipulates. It keeps both safe from outside
interference and misuse. Encapsulation may be thought of as a
protective wrapper that prevents the code and data from being
arbitrarily accessed by the other code defined outside the wrapper.
Access to the code and data inside the wrapper is tightly
controlled through a well-defined interface.
The power of an encapsulated code is that everyone knows it and
thus can use it regardless of the implementation details and
without fear of unexpected side effects.
In Java, the basis of encapsulation is the class. A class defines the
structure and behavior defined by the class. For this reason,
objects are sometimes referred to as instance of a class. Thus, a
class is a logical construct; an object has physical reality.
Since the purpose of a class is to encapsulate complexity, there is
mechanism for hiding the complexity of implementation inside the
class.
Each method or variable in a class may be marked private or
public. The public interface of a class represents everything that
may be known to the external users of that class. The private
methods and data can only be accessed by the code that is a
member of a class.
Inheritance Inheritance is the process by which one object acquires the
properties of another object. This is important because it supports
the concept of inheritance hierarchical classification. For Example,
Pomeranian is the part of the classification ‘dog’, which in turn is
part of the ‘mammal’ class, which is under the large class ‘animal’.
Without the use of hierarchies, each object would need only define
all of its characteristics explicitly. However, by use of inheritance,
an object need only define those qualities that make it unique
within its class. It can inherit its general attributes from its
parent.
It is the inheritance mechanism that makes it possible for one
object to be specific instance of a more general case. If you wish to
describe a more specific class of animals, such as mammals, they
would have more specific attributes, such as the type of teeth and

9
skeletal system. This is known as subclass of animals, where
animals are referred to as “superclass”.
Since mammals are simply more precisely specified animals, they
inherit all attributes from animals. A deeply inherited subclass
inherits all the attributes from each of its ancestors in the class
hierarchy.
Polymorphism Polymorphism is a feature that allows one interface to be
used for general class of action. The specific action is determined
by the exact nature of the situation. More generally, the concepts
of polymorphism are often expressed by the phrase ‘one interface,
multiple methods’. This means that it is possible to design a
generic interface to a group of related activities. It means it is
functions that do not care which variables types are passed to
them.
Check Your Progress: 1

List a few characteristics of Object oriented programming.

Notes: a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this
lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

1.4 BENEFITS OF OOP

In a broad sense, the greatest benefit of an object-oriented programming


system is that it imposes a powerful structure on computer programs. This
structure can make complex, intricate systems, such as GUIs, manageable.
Several features that contribute to this structure are:
(i) Modularity
The objects in an OOPS are self-contained, and have clearly defined interfaces
to other objects. This facilitates writing modular code, which reduces the
inherent complexity of a program.
(ii) Polymorphism
An OOPS can have many different kinds of objects, and new objects can inherit
properties of existing objects. For example, a GUI might have several kinds of
windows: document windows, dialog boxes, help screens, etc. An OOPS would
typically define a window object, and then define specialized sub-objects for

10
each particular kind of window. Again, this helps to manage the complexity of
the program.
(iii) Extensibility
If an OOPS provides for three kinds of windows, it can as easily provide
for four, or five. Adding a new feature is often simply a matter of defining an
object to implement it. Furthermore, new sub-objects can be defined without
having to modify, or even see, the original code.
In principle, the same programming can be done in a procedural
language. However, for technical reasons, it is more difficult, and it very often
corrupts the original design of the program, leading to unmanageable
complexity.
(iv) Reusability
One of the purported benefits of object-oriented programming is that
objects can be placed in libraries for all to use. This saves the world the effort of
continually rewriting the same code for every new program. Furthermore,
because objects are extensible, object libraries offer the programmer more
flexibility and functionality than subroutine libraries (their counterparts in
procedural languages).
Check Your Progress: 2

Enumerate a few benefits of Object oriented programming.

Notes: a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this
lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

1.5 NON-BENEFITS OF OOP

Object-oriented programming has real benefits. However, it is not a universal


remedy. Here are a few difficulties:
• An OOPS gives the tools to manage complexity; it doesn't give the
ability to do so. If a program isn't well designed to begin with, an
OOPS isn't going to help.
• Not everything is an object. Numerical integration and bank
statements are best left to procedural languages and database
systems, respectively.

11
1.6 APPLICATIONS OF OOP

Applications of OOP are beginning to gain importance in many areas. The


most popular application of object-oriented programming, up to now, has been
in the area of user interface design such as windows. Hundreds of windowing
systems have been developed, using the OOP techniques. Real-business
systems are often much more complex and contain many more objects with
complicated attributes and methods.
OOP is useful in these types of applications because it can simplify a
complex problem. The promising areas for application of OOP include:
• Real-time systems
• Simulation and modeling
• Object-oriented databases
• Hypertext, hypermedia and expertext
• AI and expert systems
• Neural networks and Parallel programming Decision support and office
automation systems
• CAM/CAD systems programming

1.7 OBJECT ORIENTED LANGUAGES

Object-oriented programming is not the right of any particular language.


Like structured Programming, OOP concepts can be implemented using
languages such as C and Pascal. However, programming becomes clumsy and
may generate confusion when the programs grow large. A language that is
specially designed to support the OOP concepts makes it easier to implement
them. The languages should support several of the OOP concepts to claim that
they are object oriented.
Depending upon the features they support, they can be classified into the
following two categories:
1. Object-based programming languages, and
2. Object-oriented programming languages.
Object-based programming is the style of programming that primarily
supports encapsulation and object identity. Major features that are required for
object-based programming are:
• Data encapsulation
• Data hiding and access mechanisms
• Automatic initialization and clear-up of objects
• Operator overloading

12
Languages that support programming with objects are said to be object-based
programming languages. They do not support inheritance and dynamic binding.
Ada is a typical object-based programming language.
Object-oriented programming incorporates all of object-based
programming features along with two additional features, namely, inheritance
and dynamic binding.
Object-oriented programming can therefore be characterized by the following
statement:
Object-based features + inheritance + dynamic binding
Languages that support these features include C++, Smalltalk, Object
Pascal, Simula, Visual Basic, Python, VB.NET and Java. There are a large
number of object-based and object-oriented programming languages.

1.8 LET US SUM UP

In this lesson we have discussed the basic features and benefits available in
Object oriented programming. The following points have been discussed in
this lesson :
• Java is an Object oriented language.
• The characteristics of OOP are Class, encapsulation, Objects,
Methods, Abstraction, Encapsulation
• Object-based programming is the style of programming that
primarily supports encapsulation and object identity.
• Object-oriented programming incorporates all of object-based
programming features along with two additional features, namely,
inheritance and dynamic binding.
• Object-oriented programming can be characterized by the statement:
Object-based features + inheritance + dynamic binding

1.9 CHECK YOUR PROGRESS : MODEL ANSWERS

1. Following are the characteristics of OOP. A few of them can be discussed.

Use of Class, encapsulation, Objects, Methods, Abstraction,


Encapsulation

2. The benefits of OOP are Modularity, Polymorphism, Extensibility and


Reusability

13
14
LESSON 2

EVOLUTION OF JAVA AND FEATURES OF JAVA

CONTENTS
2.0 Aims and Objectives
2.1 Introduction
2.2 Evolution of Java
2.3 Versions of Java
2.4 Java Version History
2.5 Java Platform
2.6 Features of Java
2.7 Let us sum up
2.8 Check Your Progress: Model Answers

2.0 AIMS AND OBJECTIVES

This lesson aims at providing the reader with information on the history
and evolution of Java language. This lesson also deals with the features
available in Java and also discusses the different versions and changes it has
undergone.
At the end of the lesson the learner will be able to understand the
features and highlight the different version of Java.

2.1 INTRODUCTION

The computer language innovation and development occurs for two


fundamental reasons:
• To adapt to changing environments.
• To implement refinements and improvements in the art of programming.
In the end of 1980s and the early 1990s, object-oriented programming
using C++ took hold. Indeed, for a brief moment it seemed as if programmers
had finally found the perfect language. Because C++ blended the high efficiency
and stylistic elements of C with the object-oriented paradigm, it was a language
that could be used to create a wide range of programs. Within few years, the
World Wide Web and the Internet reached critical mass, and the necessity for
architecture neutral language was felt, which resulted in the evolution of Java
language.

15
2.2 EVOLUTION OF JAVA

James Gosling and Patrick Naughton conceived Java. This language


was initially called “Oak” but was renamed “Java” in 1995. Surprisingly, the
original application area for Java was not the Internet. Instead, the primary
motivation was the requirement of a platform – independent language that
could be used to create software to be embedded in various consumer electronic
devices, such as microwave ovens and remote controls.
In addition to the surface similarities, Java shares some of the other
attributes that helped make C and C++ successful. First, Java was designed,
tested, and refined by real, working programmers. Second, Java is cohesive and
logically consistent. Third, except for those constraints imposed by the Internet
environment, Java enables the programmer, and has full control.

2.3 VERSIONS OF JAVA

Unlike other languages Java evolved at a fast rate due to its applications.
Soon after the release of Java 1.0, Java 1.1 was released. The features added by
Java 1.1 were more significant and substantial than the increase in the minor
revision number. Java 1.1 added many new library elements, redefined the way
events are handled by applets, and reconfigured many features of the 1.0
library. It also deprecated (rendered obsolete) several features originally defined
by Java 1.0.
The next major release of Java was Java 2. The first release of Java 2
carried the version number 1.2. It may seem odd that the first release of Java 2
used the 1.2 version number. The reason is that it originally referred to the
version of the Java libraries, but it was generalized to refer to the entire release,
itself. Java 2 added support for a number of new features, such as Swing and
the Collections framework, and it enhanced the Java Virtual Machine and
various programming tools. Java 2 also contained a few deprecations. The most
important affected the Thread class in which the methods suspend( ), resume( ),
and stop( ) were deprecated.
The next release of Java was Java 2, version 1.3. This version of Java
was the first major upgrade to the original Java 2 release. For the most part it
added to existing functionality and “tightened up” the development
environment. In general, programs written for version 1.2 and those written for
version 1.3 are source-code compatible. Although version 1.3 contained a
smaller set of changes than the preceding three major releases, it was
nevertheless important.
The current release of Java is Java 2, version 1.4. This release contains
several important upgrades, enhancements, and additions. For example, it adds
the new keyword assert, chained exceptions, and a channel-based I/O
subsystem. It also makes changes to the Collections Framework and the
networking classes. In addition, numerous small changes are made throughout.

16
Despite the significant number of new features, version 1.4 maintains nearly
100 percent source-code compatibility with prior versions.

2.4 JAVA VERSION HISTORY

The Java language has undergone several changes since JDK 1.0 as well
as numerous additions of classes and packages to the standard library. Since
J2SE 1.4, the evolution of the Java language has been governed by the Java
Community Process (JCP), which uses Java Specification Requests (JSRs) to
propose and specify additions and changes to the Java platform. The language
is specified by the Java Language Specification (JLS).
In addition to the language changes, much more dramatic changes have
been made to the Java class library over the years, which have grown from a
few hundred classes in JDK 1.0 to over three thousand in J2SE 5.0. Entire new
APIs, such as Swing and Java2D, have been introduced, and many of the
original JDK 1.0 classes and methods have been deprecated.

JDK 1.0 (January 23, 1996)


JDK 1.1 (February 19, 1997)
The following features were added in JDK 1.1
• an extensive retooling of the AWT event model
• inner classes added to the language
• JavaBeans
• JDBC
• RMI
J2SE 1.2 (December 8, 1998)
This and subsequent releases through J2SE 5.0 were rebranded and called
as Java 2 and the version name "J2SE" (Java 2 Platform, Standard Edition)
replaced JDK to distinguish the base platform from J2EE (Java 2 Platform,
Enterprise Edition) and J2ME (Java 2 Platform, Micro Edition). The following
features were included:
• the Swing graphical API was integrated into the core classes
• Sun's JVM was equipped with a JIT compiler for the first time
• Java Plug-in
• Java IDL, an IDL implementation for CORBA interoperability

J2SE 1.3 (May 8, 2000)

17
The most notable changes were:
• HotSpot JVM included (the HotSpot JVM was first released in April, 1999
for the J2SE 1.2 JVM)
• RMI was modified to support optional compatibility with CORBA
• JavaSound
• Java Naming and Directory Interface (JNDI) included in core libraries
(previously available as an extension)
• Java Platform Debugger Architecture (JPDA)
Section 1.02
Section 1.03 J2SE 1.4 (February 6, 2002)
This was the first release of the Java platform developed under the Java
Community Process. Major changes included :
• exception chaining allows an exception to encapsulate original lower-level
exception
• Internet Protocol version 6 (IPv6) support
• image I/O API for reading and writing images in formats like JPEG and
PNG
• integrated XML parser
• integrated security and cryptography extensions

J2SE 5.0 (September 30, 2004)


This version was originally numbered 1.5, which is still used as the internal
version number. This version added a number of significant new language
features such as :
• Generics: Provides compile-time (static) type safety for collections and
eliminates the need for most typecasts (type conversion).
• Meta data : Also called annotations, allows language constructs such as
classes and methods to be tagged with additional data, which can then
be processed by metadata-aware utilities.
• Autoboxing//unboxing: Automatic conversions between primitive types
(such as int) and primitive wrapper classes (such as Integer)
• Enumerations: The enum keyword creates a typesafe, ordered list of
values (such as Day.MONDAY, Day.TUESDAY, etc.). Previously this could
only be achieved by non-typesafe constant integers or manually
constructed classes (typesafe enum pattern).
• Swing: New look and feel, called synth.

18
• Varargs : The last parameter of a method can now be declared using a
type name followed by three dots (e.g. void drawtext(String... lines)). In the
calling code any number of parameters of that type can be used and they
are then placed in an array to be passed to the method, or alternatively
the calling code can pass an array of that type.
• Enhanced 'for loop': The for loop syntax is extended with special syntax
for iterating over each member of either an array or any Iterable such as
the standard collection classes.

Java SE 6 (December 11, 2006)


In this version, Sun replaced the name "J2SE" with Java SE and
dropped the ".0" from the version number. Internal numbering for developers
remains 1.6.0.
During the development phase, new builds including enhancements and bug
fixes were released approximately weekly. Beta versions were released in
February and June 2006, leading up to a final release that occurred on
December 11, 2006. The current revision is Update 6 which was released in
2008.
Major changes included in this version:
• Support for older Win9x versions dropped. The last version for Win98 is
1.5.0.13.
• Dramatic performance improvements for the core platform, and Swing.
• Improved Web Service support.
• JDBC 4.0 support
• Java Compiler API an API allowing a Java program to select and invoke a
Java Compiler programmatically.
• Many GUI improvements, such as integration of Swing Worker in the
API, table sorting and filtering, and true Swing double-buffering
(eliminating the gray-area effect).
Java SE 6 Update 10
Java SE 6 Update 10 (previously known as Java SE 6 Update N), while it
does not change any public API, is meant as a major enhancement in terms of
end-user usability.
Major changes for this update include:
• Java Deployment Toolkit, a set of JavaScript functions to ease the
deployment of applets and Java Web Start applications.
• Java Kernel, a small installer including only the most commonly used
JRE classes. Other packages are downloaded when needed.
• Java Quick Starter, to improve cold start-up time.

19
• Improved graphics performance on Windows using Direct3D.
• A new Swing look and feel called Nimbus and based on synth.
• Next-Generation Java Plug-In: applets now run in a separate process and
support many features of Web Start applications.
Java SE 7
This is in the early planning and development stages. This project is
codenamed as Dolphin Project. Started up in August 2006 and will tentatively
be released in January 2009.
New features that may be integrated in Java 7 comprise:
• JVM support for dynamic languages, following the prototyping work
currently done on the Multi Language Virtual Machine,
• A new library for parallel computing on Multi-core processors,
• Superpackages (JSR 294), which are a way to define explicitly in a library
or module which classes will be visible from outside of the library,
• Swing Application Framework, an infrastructure common to most
desktop applications, making Swing applications easier to create.
Check Your Progress : 1

Write a brief note on the different versions of Java.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this
lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

2.5 JAVA PLATFORM

The Java platform is the name for a bundle of related programs, or


platform, from Sun which allow for developing and running programs written in
the Java programming language. The platform is not specific to any one
processor or operating system, but rather an execution engine (called a virtual
machine) and a compiler with a set of standard libraries that are implemented
for various hardware and operating systems so that Java programs can run
identically on all of them.
Different "editions" of the platform are available, including:
• Java ME (Micro Edition): Specifies several different sets of libraries
(known as profiles) for devices which are sufficiently limited that

20
supplying the full set of Java libraries would take up unacceptably large
amounts of storage.
• Java SE (Standard Edition): For general purpose use on desktop PCs,
servers and similar devices.
• Java EE (Enterprise Edition): Java SE plus various APIs useful for
multi-tier client-server enterprise applications.
The Java Platform consists of several programs, each of which provides a
distinct portion of its overall capabilities. For example, the Java compiler,
which converts Java source code into Java bytecode (an intermediate language
for the Java Virtual Machine (JVM), is provided as part of the Java Development
Kit (JDK). The Java Runtime Environment (JRE), complementing the JVM
with a just-in-time (JIT) compiler, converts intermediate bytecode into native
machine code on the fly. Also supplied are extensive libraries (pre-compiled into
Java bytecode) containing reusable code, as well as numerous ways to deploy
Java applications, including embedding them in a web page as an applet.

2.6 FEATURES OF JAVA

Java is simple to use. Apart from the simplicity Java is Secure, Portable,
Object-Oriented, Robust, Multithreaded, Architecture-neutral, garbage
collected, multithreaded programming language with a strongly typed
exception-handling mechanism for writing distributed, and dynamically
extensible programs.
A few features of Java are :
Java is Simple to code and use
Java was designed to be easy for the professional programmer to learn
and use effectively. If you already understand the basic concepts of
object–oriented programming experience, learning Java will be even
easier.
Java is Object Oriented
Java was clean, usable, pragmatic approach to objects. The object
model in Java is simple and easy to extend, while simple types, such as
integers, are kept as high – performance no objects.
Safe and Robust
The ability to create robust programs was given a high priority in
the design of Java. To gain reliability, Java restricts in a few key areas, to
force to find mistakes early in program development. At the same time,
Java frees from having to worry about many of the most common causes
of programming errors. Because Java is a strictly typed language, it
checks the code at compile time. However, it also checks the code at run
time.
The C or C++ programmer can make use of features called “pointers”
which led to potential hazard in runtime. The use of Pointers are
disallowed in Java

21
Platform Independent
Platform independence is another way of saying that Java is
architecture neutral. To put it simply, Java programs don’t care what
system they’re running on. Platform independence is the ability of the
same program to work on different operating systems; Java is completely
platform independent.
Multithreaded
Java was designed to meet the real-world requirement of creating
interactive, networked programs. To accomplish this, Java supports
multithreaded programming, which allows writing programs that do
many things simultaneously. Threads represent a way for a computer
program to do more than one task at the same time.
Architecture-Neutral
A central issue for Java designers was that of code longevity and
portability. One of the main problems facing programmers is that no
guarantee exists that if you write a program today, it will run tomorrow -
even on the same machine. Designer goal was “Write Once, run
anywhere, any time, forever.”
Interpreted and High Performance
While it is true that Java was engineered for interpretation, the
Java bytecode was carefully designed so that it would be easy to
translate directly into native machine code for high performance by using
a just-in-time compiler. Java run-time systems that provide this feature
lose none of the benefits of the platform-independent code.
Distributed Computing
Java is designed for the distributed environment of the Internet, because
it handles TCP/IP protocols. In fact, accessing a resource using a URL is
not much different from accessing a file.
Automatic Garbage Collection
In C or C++, when a “pointer was used, the programmer head to “return”
it back to the OS. If this step was neglected, too much memory was used
up and this resulted in the slowing down of the program’s execution
speed. Java brought in a feature where unwanted memory was
automatically returned to the OS.
Exception Handling
Earlier programming languages did not support exceptions. In
those languages, when a program crashes at unexpected situation it will
not be possible to find the reason for the error. Java provides the
programmer a rich set of exception handlers that help in determining
why the program crashed and handle it an appropriate manner.
Check Your Progress : 2

22
List a few feature available in Java language.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this lesson.
……………………………………………………………………..

……………………………………………………………………..

2.7 LET US SUM UP

In this lesson we have learnt the evolution of Java. We have also


discussed a few features of the Java language. The following points were
discussed in this lesson :
• James Gosling and Patrick Naughton developed Java Language
• Java language was initially called “Oak” but was renamed “Java” in
1995.
• The different versions of Java includes JDK 1.0 (January 23, 1996), JDK
1.1 (February 19, 1997), J2SE 1.2 (December 8, 1998), J2SE 1.3 (May 8,
2000), J2SE 1.4 (February 6, 2002), J2SE 5.0 (September 30, 2004), Java
SE 6 (December 11, 2006),Java SE 6 Update 10, Java SE 7
• The different editions of Java are Java ME (Micro Edition), Java SE
(Standard Edition), Java EE (Enterprise Edition)

2.8 CHECK YOUR PROGRESS: MODEL ANSWERS

1. The different versions of Java includes


a. JDK 1.0 (January 23, 1996)
b. JDK 1.1 (February 19, 1997)
c. J2SE 1.2 (December 8, 1998)
d. J2SE 1.3 (May 8, 2000)
e. J2SE 1.4 (February 6, 2002)
f. J2SE 5.0 (September 30, 2004)
g. Java SE 6 (December 11, 2006)
h. Java SE 6 Update 10, Java SE 7
2. Few features of Java language are Java is Simple to code and use, Java
is Object Oriented, Safe and Robust, Platform Independent,
Multithreaded, Architecture-Neutral, Interpreted and High Performance,
Distributed Computing, Automatic Garbage Collection, Exception
Handling.

23
24
LESSON 3

COMPARISON OF C, C++, JAVA


JAVA AND THE WEB

CONTENTS
3.0 Aims and Objectives
3.1 Introduction
3.2 Comparison of C, C++ and Java
3.3 Java and the Web
3.3.1 Web surfing with Java enabled web browser
3.3.2 Third party Java tools
3.4 Let us sum up
3.5 Check Your Progress: Model Answers

3.0 AIMS AND OBJECTIVES

The objective of this lesson is to compare the high level programming


languages C, C++ and Java. The prime objective is that the reader will be able
to compare the features available in each of these languages and learn Java in a
easier manner. The second part of this lesson focuses on the applications of
Java in the internet and Web.

25
At the end of this lesson the learner will be able to identify the enhanced
features of Java and use them in an efficient manner.

3.1 INTRODUCTION

Java is more powerful and can do much more than C/C++. The Internet
is the place where the little dynamo called Java was first set free. Now
thousands of programmers, Internet developers, Web publishers, and software
houses around the world are racing to learn everything they can about this tool
for revolutionizing the Internet and the way programming is done. After all, C++
was supposed to revolutionize the software industry too, yet as you will soon
learn, the major difference between C++ and Java is that Java delivers on all its
promises.

3.2 COMPARISON OF C, C++ and Java

Java is harder because ...


• C doesn't have a graphical user interface (GUI), and C doesn't have any
way to do object-oriented programming (OOP). It's possible to write in
Java in a C style, avoiding the new powerful features of Java. But that is
foolish.
• Java either checks for errors, or makes you check for errors. C lets
you do many things that would cause errors (for example, convert strings
to integers, or do I/O), but doesn't make you write code to handle the
errors. Java makes you write try..catch statements around things that
might cause problems.
Java is easier because ...
• Java checks for errors. For example, Java checks subscripts to make
sure they are in the correct range.
• Java does things automatically. There are a huge number of things
that Java can automatically write for the user. For example, expandable
arrays, many data structures, etc. In C it would take a very long time to
write and debug these things by yourself.
• Java doesn't have the most dangerous things. The things in C which
cause the most program errors are pointers, pointer arithmetic, and
memory management. Java has replaced these with much, much safer
things: references, subscription, and garbage collection.
The Java language is based mostly on C and C++. A lot of the basic language
elements, for example, the primitive types, operators, and statements of Java
are taken directly from C.
Primitive Java types are similar to C
Java includes types which are similar to those in C/C++ (char, short,
int, long, float, and double). Unlike C/C++, Java defines exactly how
these types are implemented. For example, the length of an int in C
might be 16 bits on a PC, 32 bits on a workstation, and 60 bits on an old

26
supercomputer. Java defines exactly how ints are represented (32 bits,
two's complement, big-endian). All Java types are completely defined, in
contrast to C where NO types are well specified.
Portability and types
Because of the lack of complete type definitions, moving a C/C++
program from one machine to another can be a giant headache, or even
impossible. For example, to preserve the range of an integer variable it is
required to change shorts to ints, but then it is also necessary to change
the corresponding format specifiers, union declarations, bit field
declarations, shift operators, etc. This is only one example of the
tremendous number of portability problems in C/C++.
Additional primitive types
Java has two additional primitive types: boolean and byte. The boolean
type is a nice addition that is like Pascal boolean; it can have only the
values true and false. The byte type is used for 8-bit integers because
char is a Unicode character, which requires 16 bits.
Summary of the Java primitive types
Java integer types are two's complement: byte (signed 8 bits), char
(unsigned 16 bits), short (signed 16 bits), int (signed 32 bits), and long
(signed 64 bits). The real surprise here is that char is 16 bits. This is
because the Unicode character set is used so that characters in all major
human languages can be represented. C doesn't specify the character set
for char.
Java and C Arrays
Java arrays are very similar to C arrays although they must always be
dynamically allocated. However, Java arrays are not just pointers into
memory, but separate objects. One of the good benefits of this is that
array subscript bounds are checked, which makes finding bugs much
easier.
Java Strings are not Arrays of char
In Java there are two special object types, String and StringBuffer that
are used to store strings of characters. C uses arrays of char, but this
causes many problems. Of course, you can use an array of characters in
Java if you need to, but it is usually easier to use String or StringBuffer
Java Operators are similar to C
Most of the Java operators are the same as in C/C++, however Java
specifies the exact order of evaluation in an expression, which C does
not.
Rather than list all of the 40+ operators that are the same, it's easier to
list the differences.
There is an additional right shift operator, >>>, to add zero bits on the
left regardless of the sign of the left operand. The C comma operator is

27
limited to the first and third parts of the for loop, which is just about
the only place it is normally used in C programs anyway.
There are no pointer operators (&, *, ->) because Java uses references
instead of pointers. References are really pointers to objects, but are
simpler, and safer, than pointers that are present in Java.
Java statements are similar to C
The usual statement keywords used in C are with the same meanings: if,
else, switch, case, break, default, for, do, while, continue, and return.
A few statements have been added to handle exceptions and threads.
Java exceptions are basically errors, and there are statements to help
detect and handle these errors. Java also allows more than one part of a
program to run simultaneously using threads.
Object Oriented Programming - OOP
Classes form the basis for Object Oriented Programming (OOP). Java
classes are like C++ class, which are something like a C struct that
includes both data fields and functions. Objects are created when
memory is allocated for one of these class "struct".

28
Java supports large programming projects
For small programming projects it's sufficient to use functions,
sometimes in separate source files. Large programming projects need
more control over the structure and visibility of the program elements.
Java provides this control in the form of classes, packages, and
interfaces, along with a number of ways to control who can see what.
Class libraries
Sometimes someone says that Java is a small language, smaller than
C++, and perhaps smaller than C. This may be true if you ignore one of
the most important things: the class libraries. There are a huge number
of methods (the special OOP word for function) in the thousands of
classes that are grouped in packages. Packages and OOP are the reasons
that it's possible to have such large libraries.
Check Your Progress : 1

Compare a few features that are available in Java with that of C and C++.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this
lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

3.3 JAVA AND THE WEB

The Web is a powerful interface to everything the Internet has to offer. A


few years ago, the Intenet was equated with the monotony of low-level protocols
like FTP and Telnet. Today, Internet refers to a variety of features, which uses
the dynamic environment that enables to search through and access complex
"webs" of text, graphics, sound, and video. In short, today’s internet is equated
with the Web and that's because the Web has swallowed the Net.
To look through hypertext documents, a browser is required. A browser
is a software application that enables to access the World Wide Web. When a
hypertext document is loaded in the browser, a link is activated by moving the
mouse pointer to the area of the link and clicking the left mouse button.
In fact, Java is intimately associated with the Internet and the World-
Wide Web. Special Java programs called applets are meant to be transmitted
over the Internet and displayed on Web pages. A Web server transmits a Java
applet just as it would transmit any other type of information. A Web browser
that understands Java - that is, that includes an interpreter for the Java virtual

29
machine - can then run the applet right on the Web page. Since applets are
programs, they can do almost anything, including complex interaction with the
user. With Java, a Web page becomes more than just a passive display of
information. It becomes anything that programmers can imagine and
implement.
But applets are only one aspect of Java's relationship with the Internet,
and not the major one. In fact, as both Java and the Internet have matured,
applets have become less important. At the same time, however, Java has
increasingly been used to write complex, stand-alone applications that do not
depend on a web browser. Many of these programs are network-related. For
example many of the largest and most complex web sites use web server
software that is written in Java. Java includes excellent support for network
protocols, and its platform independence makes it possible to write network
programs that work on many different types of computer.
3.3.1 Web Surfing with Java-Enhanced Browsers
Browsers are available for use on almost any computer operating system,
including Amiga, Macintosh, OS/2, Windows 3.1, Windows 95/NT, and UNIX. A
browser can be thought of as a window to the Web; if the browser is changed, a
whole new view is got. Text-only browsers are the original browsers for the Web.
Although it might be hard to believe, several text-only browsers are still being
developed.
Use ncSA Mosaic, and your window to the Web has text and graphics.
Browsers that allow to view Web documents containing text and graphics are
the second generation of browsers, which are largely responsible for the
phenomenal success of the Web.
HotJava enables the browser window with text, graphics, and live
animation. Browsers that allow you to view Web documents containing text,
graphics, and inline multimedia and live applications are the third generation of
browsers that are driving the Web's transition to an extremely visual medium
that rivals television for information content and entertainment value.
HotJava
The HotJava browser, developed by Sun Microsystems, Inc., is written
entirely in Java. As the first browser to support Java applets, HotJava is
extremely popular. Although the Alpha version of HotJava supports only Java
Alpha, more recent versions of the browser support the 1.0 API. Versions of the
browser are available for Macintosh, Windows 95/NT, and Sun Solaris.
Although HotJava is popular, it is not feature rich like some of the other
Java-enhanced browsers; it has a rather plain interface and limited extras. Still,
HotJava is currently in the testing stages and may yet evolve into a full-featured
browser.
Netscape Navigator
The Netscape Navigator is the most widely used Web browser; versions of
it are available for Macintosh, Windows, and UNIX X Window systems. Driven

30
by Netscape's rise as a commercial corporation worth hundreds of millions of
dollars, all of Netscape’s products is shifting to a commercial model.
Not only does Navigator support Java, but it is undoubtedly the most
feature-rich browser available today. It supports HTML 3.0, plug-ins,
JavaScript, and unique Netscape extensions to HTML, such as frames. With
HTML 3.0, you get support for tables, figures, and all the advanced features of
HTML. Plug-ins allows you to add modules for inline video, sound, and
multimedia. JavaScript, a scripting language modeled after Java, enables you to
do client-side scripting.
Oracle PowerBrowser
PowerBrowser is everything you would expect in a browser created by the
database giant Oracle. The PowerBrowser software package includes a local
database called Blaze, which enables you store and manage large amounts of
data efficiently. The browser also supports HTML 3.0 and extensions to the
HTML standard including backgrounds, tables, embedded objects, and Java.
Internet Explorer
One of the most powerful browsers currently available is the Internet
Explorer from Microsoft. This full-featured browser took the Web by storm in
1995 and quickly moved to the number-two position in popularity. Versions of
Internet Explorer are available for Macintosh, Windows 95, and Windows NT.
Internet Explorer supports HTML 3; all Netscape extensions; and
powerful multimedia extensions including background sounds, scrolling
marquees, and inline video movies. Versions 3.0 and later also feature support
for Java, ActiveX controls, and VBScript. With the release of the Internet
Explorer VR extension that enables full VRML capability, Internet Explorer is
definitely the browser to watch. Microsoft is also developing an enhanced
version of VRML called ActiveVRML, with which animated VRML worlds that
take advantage of Java can be created.
3.3.2 Third-Party Java Tools
Lots of third-party development tools are available for Java. This section
focuses on the best of these tools. The speed with which industry giants,
like Borland and Symantec, introduced Java development tools speaks
volumes about Java's popularity and potential.
Borland C++ for Java Developers
Borland C++ for Java developers is a cutting-edge development
environment for C/C++ and Java. To ease the transition for current
C/C++ and Java programmers, Borland integrated its award-winning
C++ development environment with Sun's Java Developer's Kit. The
result is a graphical development environment that allows to develop,
test, and debug the applications without ever having to use command-
line tools.

31
Symantec Café
Symantec Café is an integrated development environment for Java
developers who use Windows 95/NT or the Power Mac. Like Borland C++,
Symantec Café uses the tools in Sun's Java Developer's Kit as the basis
for its graphical development environment. In fact, Café includes the
entire release version of the JDK, which provides the Java class library
source code and samples.
The integrated environment within which the program operates is called
the Café Desktop. The desktop is a customizable interface to all the tools
in Symantec Café. Because Café Desktop supports virtual desktop
environments, it is possible to access multiple viewing areas at the press
of a button.
Symantec Espresso and Symantec Caffeine
Symantec Caffeine is a scaled-down version of Symantec Café for Java
developers who use a Power Macintosh. As the first development
environment for the Macintosh, Symantec Caffeine has a lot going for it.
It provides a full-featured project-management system and powerful
editing tools that boost productivity.
Symantec Espresso is a scaled-down version of Symantec Café for Java
developers who use Windows 95/NT. It also provides a fully featured
project-management system and powerful editing tools that will boost the
software productivity.
SunSoft's Java Workshop
Java Workshop is the kind of quality product you would expect SunSoft
to produce. With the entire graphical development environment placed
within a Webified desktop, Java Workshop is as easy to use as your
favorite Web browser and, like the Web browser, all the most-used
features are accessible by clicking on an icon.

3.4 LET US SUM UP

In this lesson we have discussed the following points:


• Java has two additional primitive types: boolean and byte.
• There are no pointers and pointer operators (&, *, ->) in Java
• With Java, a Web page becomes more than just a passive display of
information.
• The HotJava browser, developed by Sun Microsystems, Inc., is written
entirely in Java.
• With Java, a Web page becomes more than just a passive display of
information.
• Some of the third party tools available for Java are Symantec Café,
Symantec Espresso

32
3.5 CHECK YOUR PROGRESS: MODEL ANSWERS

1. Following are the key areas that can be used to compare C, C++ and Java
• Primitive Java types are similar to C
• Portability and types
• Additional primitive types
• Java and C Arrays
• Java Strings are not Arrays of char
• Java Operators are similar to C
• Java statements are similar to C
• Object Oriented Programming features
• Java support for large programming projects.

33
LESSON 4

ARCHITECTURE AND STRUCTURE OF


JAVA PROGRAM

CONTENTS
4.0 Aims and Objectives
4.1 Introduction
4.2 Java’s Architecture
4.3 Structure of a Java program
4.4 First Java Program
4.5 Software required for developing a Java program
4.6 Edit, Compile, Debug and Run
4.7 Environment Variables
4.8 Let us Sum up
4.9 Check Your Progress: Model Answers

4.0 AIMS AND OBJECTIVES

In this lesson the reader will learn the basic architecture and the
structure of a Java Program. At the end of this lesson the learner will be able to
understand the way in which Java program is coded.
The learner will be able to understand the steps involved in coding and
executing a Java program.

4.1 INTRODUCTION

Every programming language will have a different Integrated


Development Environment(IDE) which will help the software developer to
develop and execute a program. The Java programming language does not have
a standard IDE to facilitate the user to develop the program. However there are
several third party software which acts as IDE.
Hence it is necessary for a developer to understand the basic concepts
involved in coding and executing a Java program.

4.2 JAVA’S ARCHITECTURE

It is easy to think of Java as merely the programming language with


which you develop your applications writing source files and compiling them
into bytecode.

34
The complete Java architecture is actually the combination of four components.
• The Java Programming language.
• The Java class file format.
• The Java Application Programming Interface (APIs).
• The Java Virtual Machine.

Your Application

Java Programming Language

Java Class Files

Java Runtime Environment

Java API

Java Virtual Machine

Operating System (Windows, Unix, etc.)

Fig 4.1 Java’s Architecture

The key that allows Java to solve both the security and the
portability problems just described is that the output of a Java compiler is not
executable code. Rather, it is bytecode. Bytecode is a highly optimized set of
instructions designed to be executed by the Java run – time system, which is
called the Java Virtual Machine (JVM). That is, in its standard form, the JVM is
an interpreter for bytecode.
Translating a Java program into bytecode helps makes it much
easier to run a program in a wide variety of environments. Sun has just
completed its Just In Time (JIT) compiler for bytecode, which is the part of the
JVM; it compiles bytecode into executable code all at once, because Java
performs various run-time checks that can be done only at run time. Instead,

35
the JIT compiles code, as it is needed, during execution. However, the just-in –
time approach still yields a significant performance boost.

4.3 STRUCTURE OF A JAVA PROGRAM

The structure of a programming language depicts the coding rules and


conventions to be followed while developing a program. The general structure of
a Java program is given below :

Documentation Section
Suggested

Package statements Suggested /Optional

Import Statements Optional

Interface statements Optional

Class definitions Essential

Main method
{ Essential
Main method definition
}
a) Documentation Section : The documentation section comprises a set of
comment lines giving the name of the program, the author and the other
details, which the programmer would like to refer to at the later stage.
Java also uses a style of comment /*………..*/ known as documentation
comment.
b) Package statement : The first statement allowed in Java file is a
package statement. This statement declares a package name and
informs the compiler that the classes defined here belong to this
package.
c) Import statement : Java includes the import statement to bring certain
classes or entire packages into visibility. Once imported, a class can be
referred directly, using only its name. The import statement is a
convenience to the programmer and is not technically needed to write a
complete Java program.
The import statement instructs the interpreter to load the test
class contained in the package. Using import statements user can have
access to classes that are part of other named packages.

36
d) Class Definition : A Java program may contain multiple class
definitions. Classes are the primary and essential elements of a Java
Program.
e) Main Method class : Since every Java stand alone program requires a
main method as the starting point, this class is the essential part of a
Java program. The main method creates objects of various classes and
establishes communication between them. On reaching the end of main
the program terminates and the control passes back to the operating
system.
Comments and Whitespaces:
Whitespace consists of spaces, tabs, and linefeeds. There are three types of
comments defined by Java. These are Single-line, Multi-line and Documentation
Comment.

Type Usage

/*Comment */ All characters between /* and*/ are ignored.

All characters after the // up to the end of the line


// Comment
are ignored.

Same as /* . */, except that are comment can be


/** comment */ used with the Javadoc tool to create automatic
documentation.

Check Your Progress


List the different sections present in a Java Program.
Notes : a) Write your answer in the space given below.
b) Check your answer with the one given at the end of this unit.

……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..

4.4 THE FIRST JAVA PROGRAM

Class MyFirstJavaProgram
{
public static void main(String args[])
{

37
System.out.println(“Welcome to Bharathiar University”);
}
}
A closer look at the first Java program
Class MyFirstJavaProgram
This line uses the keyword class to create a new class definition.
MyFirstJavaProgram is the class name. The body of a class should be contained
within curly brackets. According to Java convention, all class names begin with
an upper case alphabet. Classes may start with a lower case alphabet, but as
mentioned earlier, the convention of all classes starting with an upper case
alphabet will be followed hereafter.
public static void main (String args[])
The execution of a Java program starts at the main() function. The
keywords public static defines the scope of the function. Access specifier are
used to specify the scope of functions. The public keyword is an access
specifier, which allows the programmer to control the visibility of class
members. When a class member is preceded by public, then that member may
be accessed by code outside the class in which it is declared. (The opposite of
public is private, which prevents a member from being used by code defined
outside of its class.) In this case, main () must be declared as public, since it
must be called by code outside of its class when the program is started.
The keyword static allows main() to be called without having to
instantiate a particular instance of the class. This is necessary since main() is
called by the Java interpreter before any objects are made. The keyword void
simply tells the compiler that main () does not return a value. Keep in mind
that Java is case-sensitive.
Every Java program can have one(only one) main() function. String args [
] declares parameter named args, which is an array of instances of the class..
System.out.println (“Welcome to Bharathiar University”) ;
This statement displays the message “Welcome to Bharathiar University” on the
monitor. Each and every executable line has to end with a semicolon.

4.5 SOFTWARE REQUIRED FOR DEVELOPING A JAVA APPLICATION

One of the coolest features of Java is its cross-platform binary


portability. This means that the very same program you run on your Macintosh
or your Sun SPARC machine will also run under Windows or OS/2.
To write, test, and run Java programs, it is necessary to have three pieces of
software. Fortunately, each of these items is both widely available and
(generally) free.
A text editor - A text editor is used to code the Java programs. A text editor is
like a word processor, except that the files it creates do not contain any
formatting codes. If you are using Windows 95 or NT, you can use the Notepad

38
program or MS-DOS Edit. In the Macintosh world, you will want to use a
program like SimpleText. For all UNIX users, vi or emacs will be the tool of
choice. It is also possible to use a word-processing program like Microsoft Word,
Lotus WordPro, or WordPerfect, but it will be necessary to save the files without
any extra formatting—as plain text or ASCII.
Development tools—These are the programs used to convert the Java
programs into executable code, and to test and debug the applets and
applications. Usually these tools will be packaged as either a kit of individual
tools, or as an application program that combines the various tools into one
integrated program (called an IDE, short for “integrated development
environment”). The Java Development Kit (JDK) from JavaSoft can be
downloaded, the latest version will be available from http://www.javasoft.com.
The JDK contains separate versions of the development kit for Windows 95/NT,
Sun Solaris, and Macintosh.
A Java-enabled web browser—This is used to run and test the applets in their
native environment. Netscape’s Navigator and Microsoft’s Internet Explorer have
captured most of the market, but there are other browsers you might want to
try, such as Sun’s HotJava, which is written entirely in Java itself. Strictly
speaking, a Web browser is not absolutely necessary to develop Java programs,
because the JDK includes appletviewer, a program for viewing applets; neither
is an Internet connection mandatory. A text editor and the JDK are the bare
minimum you need to get started, but a Web browser and an Internet account
will make your work more useful.

4.6 EDIT, COMPILE, DEBUG, RUN

After setting the programming environment and installed the JDK, SDK, or the
IDE you will be using, you’re ready to start writing Java programs. The
following steps gives a bird’s-eye view of the process that has to be undergone
in developing the Java applications.
Step 1 : Coding the program
The first step in creating a Java application or applet is to use the text editor to
create a text file. Java programs use two types of files, one called source code
and the other called object code or machine code. The first type of file contains
the Java language programs that is written with the text editor. The filenames
must end with the file extension Java. (A file extension is added as a suffix to
the end of a filename, separated from the rest of the file by a period or dot).
Every source code file contains the definition for a single class that is publicly
visible, and, unlike many programming languages, in Java, the name of the file
and the name of the class must be identical. Each source file may also contain
other “helper” classes, but each file can contain only one public class, which is
visible to the rest of your program.

Step 2 : Compile The Program


Once the source code is written, the second step is to translate the
source code into the object code instructions that can be read by the Java

39
runtime environment (called the Java Virtual Machine or VM). In Java, this
object code is called byte code. The process of translating your source code into
machine code is called compiling, and is the job of a tool called a compiler. In
the JDK, the compiler is a program called javac, which is shorthand for java
compiler.
If you have used your text editor to create a class definition for a class called
Robotz, (saved in a text file named Robotz.java), you can compile the source
code by typing
javac MyFirstJavaProgram.java
and the javac compiler will turn the source code definition into object code,
storing it in a file named MyFirstJavaProgram.class Be sure to use uppercase
and lowercase letters exactly as shown in the line above. Even if you’re using a
Windows 95 or Windows NT command window, neither of which is case
sensitive, the Java compiler and other programs are case sensitive. They will
not properly process the command if the wrong case is used.
The above command invokes the Java compiler that sets about compiling the
Java source code and generates a .class file if nothing has been botched up, or
reports the errors that are encountered.
Step 3 : Debugging the program
The third step in developing a Java program is called debugging. Debugging is
a euphemism for finding and fixing the mistakes that were made when writing
the program. There are three basic types of mistakes: syntax errors, semantic
errors, and runtime errors.
Syntax errors occurs when the grammatical rules of the Java language are not
followed. You may have misspelled a word, or punctuated a line of code
incorrectly. When you have a syntax error in your program, the Java compiler
refuses to create the machine code from the source code, and prints out a
message telling what the compiler thinks the problem is. When such an error
occurs, it must be examined carefully, correct the offending code using the text
editor, and then try recompiling the entire application. This cycle is continued
until the compiler stops giving error messages.
Semantic errors are more difficult to detect than syntax errors, which the Java
compiler flags for you. A semantic error is an error in the meaning of a
computer statement: if you subtracted the sales tax in your program when you
should have added it, for example, you’ve created a semantic error. The usual
way to find semantic errors is by testing the program with predefined inputs
and outputs. This is, an extremely hard process, but it can mean the difference
between a successful product and a real disaster.
A runtime error is an error that occurs because of some unexpected
environmental condition. Trying to open a file that doesn’t exist or to read from
a closed socket are examples of runtime errors. Runtime errors have some
characteristics of both syntax errors and semantic errors. Like a syntax error,
Java creates an error message when a runtime error occurs. With syntax errors,
the Java compiler announces the mistake; with runtime errors, the Java VM
does the honors. Like semantic errors, however, runtime errors are discovered

40
when the program is executed and not when it is compiled. Because a program
may run correctly one time (when the server was working correctly for example)
and create a runtime error the next, runtime errors are fixed not by correcting
the source code, but by writing code to deal with the exceptional environmental
conditions that cause them. Such conditions are called exceptions, and the code
used to write is called an exception handler.
After the program is completed and bug free, it’s time to deploy the
application. Java provides two different ways to deliver and run the programs:
as an application or as an applet.
Step 4 : Execute The Program
Now the program can be executed by giving the following command at the OS
prompt.
java MyFirstJavaProgram
The above command invokes the Java interpreter, which executes
MyFirstJavaProgram.class.

Check Your Progress : 2


Li
List the different types of the error to be corrected in a Java program
Notes : a) Write your answer in the space given below.
b) Check your answer with the one given at the end of this unit.

……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..

4.7 ENVIRONMENT VARIABLES

While working with Java, two OS environmental variables, PATH


and CLASSPATH should be necessarily understood.
PATH specifies where the operating system should search for Java classes. Java
classes can either be user defined or a set of classes offered by JDK.
CLASSPATH specifies where the operating system should search for Java
classes. Java classes can either be user defined or a set of classes offered by
JDK.

41
The Java compiler, javac and the interpreter Java are available in jdk1.2.2\bin
folder. So the PATH variable should be set to that folder. Note that a semi-colon
separates every entry in PATH.
set path=%path%;c:\jdk1.2.2\bin;
Here, %path%; refers to the existing PATH and c:\jdk1.2.2\bin is appended to
it.

4.8 LET US SUM UP

In this lesson we have learnt the following :


• Integrated Development Environment (IDE) facilitates coding compilation
and development of a program.
• The Java architecture is the combination of four components. Java
Programming language, The Java class file format, The Java Application
Programming Interface, Java Virtual Machine.
• A Java program consists of the following sections : Documentation
Section, Package statements, Import Statements, Interface statements,
Class definitions, Main method, Main method.

4.9 CHECK YOUR PROGRESS : MODEL ANSWERS

1. A Java program consists of the following sections : Documentation


Section, Package statements, Import Statements, Interface statements,
Class definitions, Main method, Main method.
2. The types of errors are syntax errors, semantic errors and runtime
errors.

42
43
LESSON 5

JAVA TOKENS, JAVA STATEMENT,


JAVA VIRTUAL MACHINE

CONTENTS
5.0 Aims and Objectives
5.1 Introduction
5.2 Java character set
5.3 Java Tokens
5.4 Java programming statements
5.5 Java Virtual machine
5.6 Let us sum up
5.7 Check Your Progress: Model Answers

5.0 AIMS AND OBJECTIVES

This lesson aims at introducing the basic building blocks of Java namely
tokens and statements. Next we concentrate on the concept of JVM which is
used for achieving platform independence. We also discuss the use of bytecode
which is used in Java Virtual machine.

5.1 INTRODUCTION

In any programming language, the basic entity is the character set.


Character set of a high level language is much similar to the alphabets in a
normal language. Using a sequence of characters the basic building block
tokens are formed. Tokens are further combined to form statements and a
group of statement forms functions/classes.

5.2 JAVA CHARACTER SET

The full Java character set includes all the Unicode characters; there are
216 = 65,536 unicode characters. Since this character set is very large and its
structure very complex, only the subset of unicode characters that includes all
the ASCII (pronounced "Ask E") characters are listed. There are 28 = 256 ASCII
characters, of which only a small subset containing alphabetic, numeric, and
some special characters are described in this lesson.
The structure of this character set described with the alternatives in the right
hand sides are listed below :
lower-case <= a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z

44
upper-case <=
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z
alphabetic <= lower-case|upper-case
numeric <= 0|1|2|3|4|5|6|7|8|9
alphanumeric <= alphabetic|numeric
special <= !|%|^|&|*|(|)|-
|+|=|{|}|||~|[|]|\|;|'|:|"|<|>|?|,|.|/|#|@|`|_
graphic <= alphanumeric | special
White space consists of spaces (from the space bar), horizontal and
vertical tabs, line terminators (newlines and formfeeds): all are non-printing
characters, so we must describe them in English. White space and tokens are
closely related: we can use white space to force the end of one token and the
start of another token (i.e., white space is used to separate tokens). For example
XY is considered to be a single token, while X Y is considered to be two tokens.
Adding extra white space (e.g., blank lines, spaces in a line -often for
indenting) to a program changes its appearance but not its meaning to Java: it
still comprises exactly the same tokens in the same order. Programmers mostly
use white space for purely stylistic purposes: to isolate/emphasize parts of
programs and to make them easier to read and understand.

5.3 JAVA TOKENS

In a Java program, all characters are grouped into symbols called


tokens. Larger language features are built from the first five categories of
tokens (the sixth kind of token is recognized, but is then discarded by the Java
compiler from further processing). We must learn how to identify all six kind of
tokens that can appear in Java programs. One simple rule that captures Java
token structure is:
token <= identifier | keyword | separator | operator | literal | comment
The tokens available in Java and their meaning are given below :
1. Identifiers: names the programmer chooses
2. Keywords: names already in the programming language
3. Separators (also known as punctuators): punctuation characters and
paired-delimiters
4. Operators: symbols that operate on arguments and produce results
5. Literals (specified by their type)
o Numeric: int and double
o Logical: boolean
o Textual: char and String
o Reference: null

45
6. Comments
o Line
o Block
Check Your Progress : 1

List the different types of tokens available in Java.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this
lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

5.4 JAVA PROGRAMMING STATEMENTS

In Java programming, instructions are referred to as statements. A clear


indicator that a line of code is a statement is its termination with an ending
semicolon (;). For instance, consider the following statement.
int i = 9; // a single statement
If one were to write multiple statements, it is recommended that each statement
be entered on a separate line and should end with a semicolon (;).
int a = 10; // a statement
int b = 20; // another statement
int result = a + b; // yet another statement
However, the following way of writing code is also correct.
int a = 10; int b = 20; int result = a + b;
Java is an Object Oriented language; as such it is built on the structural
programming paradigm, where code consists of:
• Sequences
• Branches
• Loops(Iterations)

Program Control Flow

46
Statements are evaluated in the order as they occur. The execution of
flow begins at the top most statement and proceeds downwards till the last
statement is encountered. A statement can be substituted by a statement block.
There are special statements that can redirect the execution flow based on a
condition, those statements are called branching statements.

5.4.1 Statement Blocks


A bunch of statements can be placed in braces to be executed as a single
block. Such a block of statement can be named or be provided a condition for
execution. Below is how a series of statements are placed in a block.
{
int a = 10;
int b = 20;
int result = a + b;
}

5.4.2 Branching Statements


Program flow can be affected using function/method calls, loops and iterations.
Of various types of branching constructs, we can easily pick out two generic
branching methods.
• Unconditional Branching
• Conditional Branching
Unconditional Branching Statements
An unconditional branch is created either by invoking the method
or by calling break, continue, return or throw.
Conditional Branching Statements
Conditional branching is attained with the help of the if...else and switch
statements. A conditional branch occurs only if a certain condition
expression evaluates to true. The conditional branching statements
available in Java are
• if
• if..else
• switch
5.4.3 Iteration Statements

47
Iteration Statements are statements that used to iterate a block of
statements. Such statements are often referred to as loops. Java offers four
kinds of iterative statements.
• The while loop
• The do...while loop
• The for loop
• The foreach loop

Check Your Progress : 2

List the different types of statements available in Java..

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this
lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

5.5 JAVA VIRTUAL MACHINE

A Java Virtual Machine (JVM) is a set of computer software programs


and data structures which use a virtual machine model for the execution of
other computer programs and scripts. The model used by a JVM accepts a form
of computer intermediate language commonly referred to as Java bytecode. This
language conceptually represents the instruction set of a stack-oriented,
capability architecture.
Java Virtual Machines operate on Java bytecode, which is normally (but
not necessarily) generated from Java source code; a JVM can also be used to
implement programming languages other than Java. For example, C source
code can be compiled to Java bytecode, which may then be executed by a JVM.
The JVM is a crucial component of the Java Platform. Because JVMs are
available for many hardware and software platforms, Java can be both
middleware and a platform in its own right — hence the expression "write once,
run anywhere." The use of the same bytecode for all platforms allows Java to be
described as "compile once, run anywhere", as opposed to "write once, compile
anywhere", which describes cross-platform compiled languages. The JVM also
enables such unique features as Automated Exception Handling which provides

48
'root-cause' debugging information for every software error (exception)
independent of the source code.
The JVM is distributed along with a set of standard class libraries which
implement the Java API (Application Programming Interface). The virtual
machine and API have to be consistent with each other and are therefore
bundled together as the Java Runtime Environment.

JVM Machine Windows


for Windows Code OS

Byte Code

Java Java JVM Machine


Unix OS
Source Code Compiler for Unix Code

Byte Code

JVM Machine
Mac OS
for MAC Code

Execution environment
Programs intended to run on a JVM must be compiled into a
standardized portable binary format, which typically comes in the form of .class
files. A program may consist of many classes in different files. For easier
distribution of large programs, multiple class files may be packaged together in
a .jar file (short for Java archive).
The JVM runtime executes .class or .jar files, emulating the JVM
instruction set by interpreting it, or using a just-in-time compiler (JIT) such as
Sun's HotSpot. JIT compiling, not interpreting, is used in most JVMs today to
achieve greater speed. Ahead-of-time compilers that enable the developer to
precompile class files into native code for a particular platform also exist.
Like most virtual machines, the Java Virtual Machine has a stack-based
architecture.
Bytecode verifier
A basic philosophy of Java is that it is inherently "safe" from the
standpoint that no user program can "crash" the host machine or otherwise
interfere inappropriately with other operations on the host machine, and that it
is possible to protect certain functions and data structures belonging to
"trusted" code from access or corruption by "untrusted" code executing within
the same JVM. Furthermore, common programmer errors that often lead to
data corruption or unpredictable behavior such as accessing off the end of an
array or using an uninitialized pointer are not allowed to occur. Several features

49
of Java combine to provide this safety, including the class model, the garbage-
collected heap, and the verifier.
The JVM verifies all bytecode before it is executed. This verification consists
primarily of three types of checks:
• Branches are always to valid locations
• Data is always initialized and references are always type-safe
• Access to "private" or "package private" data and methods is rigidly
controlled.
The first two of these checks take place primarily during the "verification"
step which occurs when a class is loaded and made eligible for use. The third is
primarily performed dynamically, when data items or methods of a class are
first accessed by another class.
The verifier permits only some bytecode sequences in valid programs, e.g. a
jump (branch) instruction can only target an instruction within the same
function or method. Because of this, the fact that JVM is a stack architecture
does not imply a speed penalty for emulation on register-based architectures
when using a JIT compiler. In the face of the code-verified JVM architecture, it
makes no difference to a JIT compiler whether it gets named imaginary registers
or imaginary stack positions that need to be allocated to the target
architecture's registers. In fact, code verification makes the JVM different from
a classic stack architecture whose efficient emulation with a JIT compiler is
more complicated and typically carried out by a slower interpreter.
Bytecode instructions
The JVM has instructions for the following groups of tasks:
• Load and store
• Arithmetic
• Type conversion
• Object creation and manipulation
• Operand stack management (push / pop)
• Control transfer (branching)
• Method invocation and return
• Throwing exceptions
• Monitor-based concurrency
The aim is binary compatibility. Each particular host operating system needs its
own implementation of the JVM and runtime. These JVMs interpret the byte
code semantically the same way, but the actual implementation may be
different. More complicated than just the emulation of bytecode is compatible
and efficient implementation of the Java core API which has to be mapped to
each host operating system.

50
Secure execution of remote code
A virtual machine architecture allows very fine-grained control over the
actions that code within the machine is permitted to take. This is designed to
allow safe execution of untrusted code from remote sources, a model used by
Java applets. Applets run within a VM incorporated into a user's browser,
executing code downloaded from a remote HTTP server. The remote code runs
in a restricted "sandbox", which is designed to protect the user from
misbehaving or malicious code. Publishers can purchase a certificate with
which to digitally sign applets as "safe", giving them permission to ask the user
to break out of the sandbox and access the local file system and network...
C to bytecode compilers
From the point of view of a compiler Java bytecode is just another
processor with an instruction set for which code can be generated. The JVM
was originally designed to execute programs written in the Java language.
However, the JVM provides an execution environment in the form of a bytecode
instruction set and a runtime system that is general enough that it can be used
as the target for compilers of other languages.
Because of its close association with Java the JVM performs the runtime
checks mandated by the Java specification. This can make it technically
difficult to translate C code to the JVM and expect it to run without issuing any
warnings.

5.6 LET US SUM UP

In this lesson we have discussed the following points


• The full Java character set includes all the Unicode characters
• In a Java program, all characters are grouped into symbols called
tokens.
• The tokens available in Java are Identifiers, Keywords, Separators,
Operators, Literals, and Comments.
• The statements available in Java are Sequences (assignment etc.),
Branches (if, if..else, switch) and iteration statements (while loop,
do...while loop, for loop, foreach loop)
• A Java Virtual Machine (JVM) is a set of computer software programs
and data structures which use a virtual machine model for the execution
of other computer programs and scripts
• Java Virtual Machines operate on Java bytecode
• The JVM runtime executes .class or .jar files, emulating the JVM
instruction set by interpreting it, or using a just-in-time compiler (JIT)
such as Sun's HotSpot.

5.7 CHECK YOUR PROGRESS : MODEL ANSWERS

51
1. The tokens available in Java are Identifiers, Keywords, Separators,
Operators, Literals, and Comments.
2. The statements available in Java are Sequences (assignment etc.),
Branches (if, if..else, switch) and iteration statements (while loop,
do...while loop, for loop, foreach loop).

52
LESSON 6

CONSTANTS, VARIABLES, DATATYPES,


KEYWORDS

CONTENTS
6.0 Aims and Objectives
6.1 Introduction
6.2 Literals
6.3 Java Identifiers
6.4 Variables
6.5 Variables and Initialisation
6.6 Data Types
6.7 Java Keywords:
6.8 Let Us Sum Up
6.9 Check Your Progress: Model Answers

6.0 AIMS AND OBJECTIVES

In this lesson we will learn the basic building blocks of Java programs
namely the variables, constants and Keywords. For any programming language
these three forms the core for a program.
At the end of this lesson the reader will be able to declare variables,
initialize values to the variable and also distinguish between variables and
keywords.

6.1 INTRODUCTION

Unlike C or C++, Java is more strictly typed than any other. Java’s safety
and robustness is achieved due to types available in Java. Variables present in
Java has a type and all expressions has a type, and every type is strictly
defined. Second, all assignments, whether explicit or via parameter passing in
method calls, are checked for type compatibility. Java compiler checks all
expressions and parameters to ensure that the types are compatible. Any type
mismatches are errors that must be corrected before the compiler will finish
compiling the class.
In C/C++ it is possible to assign a floating-point value to an integer,
whereas in Java it is forbidden. In C type-checking between a parameter and an

53
argument is not strongly done, whereas in Java it is strongly checked and if a
mismatch occurs an error is generated.

6.2 LITERALS

A constant value in Java is created by using a literal representation. Following


is a list of literals:
98.3 100 ‘X’ “Java Programming”
In the above example, considering from left to right, the first literal specifies a
floating-point value, the next is an integer, the third is a character constant,
and the last is a string. A literal can be used anywhere a value of its type is
allowed.

Integer Literals
A whole number value without fraction is an integer literal. Integers are
commonly used in programs. Examples are 1, 2, 3, and 42. These are all
decimal values, meaning they are describing a base 10 number.
There are two other bases which can be used in integer literals, octal
(base eight) and hexadecimal (base 16). Octal values are denoted in Java by a
leading zero. It should be noted that normal decimal numbers cannot have a
leading zero. A hexadecimal constant is represented with a leading zero-x, (0x
or 0X). The range of a hexadecimal digit is 0 to 15, so A through F (or a through
f ) are substituted for 10 through 15.
Integer literals create an int value, which in Java is a 32-bit integer
value. When a literal value is assigned to a byte or short variable, no error is
generated if the literal value is within the range of the target type. Also, an
integer literal can always be assigned to a long variable. However, to specify a
long literal, it is necessary to explicitly specify the compiler that the literal value
is of type long. This is done by appending an upper- or lowercase L to the
literal.
For example, 0x7ffffffffffffffL or 9223372036854775807L is the largest long.

Floating-Point Literals
Floating-point numbers are used to represent decimal values with a
fractional component. They can be expressed in either standard or scientific
notation.
Standard notation consists of a whole number component followed by a
decimal point followed by a fractional component. For example, 2.0, 3.14159,
and 0.6667 represent valid standard-notation floating-point numbers. Scientific
notation uses a standard-notation, floating-point number plus a suffix that
specifies a power of 10 by which the number is to be multiplied. The exponent

54
is indicated by an E or e followed by a decimal number, which can be positive
or negative.
Examples include 6.022E23, 314159E–05, and 2e+100.
Floating-point literals in Java are double precision by default. To specify
a float literal, an F or f is to be added as suffix to the constant. It is also
possible to explicitly specify a double literal by appending a D or d. Double type
consumes 64 bits of storage, while the less-accurate float type requires only 32
bits.
Boolean Literals
Boolean literal can hold any of two logical values true and false. The values of
true and false do not convert into any numerical representation. As like other
languages such as C and C++ the true literal in Java does not equal 1, nor does
the false literal equal 0. In Java, they can only be assigned to variables declared
as boolean, or used in expressions with Boolean operators.
Character Literals
In Java characters are represented in Unicode characters, which are 16-bit
values that can be converted into integers and manipulated with the integer
operators, such as the addition and subtraction.
A literal character is represented inside a pair of single quotes. All of the visible
ASCII characters can be directly entered inside the quotes, such as ‘a’, ‘z’, and
‘@’. For characters that are impossible to enter directly, there are several escape
sequences, which allows to enter the required characters.
The following table shows the character escape sequences.

Escape Description
Sequence

\ddd Octal character (ddd)

\uxxxx Hexadecimal UNICODE character


(xxxx)
\’ Single quote

\” Double quote

\\ Backslash

\r Carriage return

\n New line (also known as line feed)

\f Form feed

55
\t Tab

\b Backspace

String Literals
String literals are specified by enclosing a sequence of characters between a
pair of double quotes.
Examples of string literals are
“Welcome to Bharathiar University”
“This text is in two\nlines”
“\”This is in quotes\””
In Java it is must that strings should begin and end on the same line. There is
no line-continuation escape sequence as in other languages.

Check Your Progress: 1


List the different types of literals available in Java
Notes : a) Write your answer in the space given below.
b) Check your answer with the one given at the end of this unit.

……………………………………………………………………..
……………………………………………………………………..

6.3 JAVA IDENTIFIERS

Identifiers are used for class names, method names, and variable names.
All Java identifiers are case-sensitive and must begin with a letter, an
underscore(_), or a dollar sign ($). Letters include both lowercase and uppercase
letters. Subsequent identifier characters can include the numbers 0 to 9. The
following table contains a list of valid and invalid identifier names.
Valid And Invalid Java Identifiers.

Valid Invalid Reason for invalidity

HelloRosh Hello Rosh Using a space.

Using a space and punctuation


Hello_Mom Hello Mom!
mark.

56
HeyCount2 2HeyCount Begins with Numbers.

Supreme Super This is Java keyword.

Poundage #age Does not begin with letter

High_Spirit High-Spirit (-) Sign can not be used

6.4 VARIABLES
The variable is the basic unit of storage in a Java program. A variable is
defined by the combination of an identifier, a type, and an optional initializer. In
addition, all variables have a scope, which defines their visibility, and a lifetime.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form
of a variable declaration is :
type identifier [ = value][, identifier [= value] ...] ;
The type is one of Java’s atomic types, or the name of a class or interface. The
identifier is the name of the variable. It is possible to initialize the variable by
specifying an equal sign and a value.
GE
Examples of variable declaration are :
int x, y, z; // declares three ints, a, b, and c.
byte a = 36; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.

Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid at
the time the variable is declared.
For example, here is a short program that computes the area of a rectangle
given the length and breadth of the triangle:

57
// Program for Demonstrating dynamic initialization of variables.
class DynInit {
public static void main(String args[])
{
double l = 3.0, b = 4.0;
// area is dynamically initialized
double area = l * b;
System.out.println("Area = " + area);
}
}

Here, two local variables— land b are declared and initialized by constants.
However, the variable area is initialized dynamically to the area of the rectangle.

Check Your Progress : 2


List a few valid variable names. Give Justification for each.
Notes : a) Write your answer in the space given below.
b) Check your answer with the one given at the end of this unit.
……………………………………………………………………..
……………………………………………………………………..

The Scope and Lifetime of Variables


Java allows variables to be declared within any block. A block in Java is begun
with an opening curly brace and ended by a closing curly brace. A block defines
a scope. Thus, each time a new block is started, a new scope is created. A
scope determines what objects are visible to other parts of the program. It also
determines the lifetime of those objects.
Most other computer languages define two general categories of scopes:
global and local. In Java, the two major scopes are those defined by a class
and those defined by a method. However, since the class scope has several
unique properties and attributes that do not apply to the scope defined by a
method, this distinction makes some sense. The scope defined by a method
begins with its opening curly brace. However, if that method has parameters,
they too are included within the method’s scope.
As a general rule, variables declared inside a scope are not visible (that
is, accessible) to code that is defined outside that scope. Thus, when a variable
is declared within a scope, the variable is localized and it is protected from
unauthorized access and/or modification.

58
6.5 VARIABLES AND INITIALIZATION

When a variable is declared a value is automatically initialized by the


Java compiler. The variables and their initial values are discussed in the
following table :

Initial
Element Type
Value

Byte 0

Int 0

short 0

long 0L

float 0.0f

double 0.0d

Char ‘\u0000’

boolean False

object
Null
reference

6.6 DATA TYPES

A variable is something that changes, or varies. In Java, a variable stores


data. Data types define the kind of data that can be stored in a variable and the
limits of the data. There are two major data types in Java: reference types and
primitive types.
Data types can be stored in variables, passed as arguments, returned as
values, and operated on.

6.6.1 PRIMITIVE DATA TYPES

Primitive data types can have only one value at a time. They do not
reference other data or indicate sequence in a group of data. They are primitive
in that they are the simplest built-in forms of data in Java. All other data types
are made up of combinations of primitive data types

59
The primitive data type keywords are boolean, char, byte, short, int, long,
float, double.
Every variable declared should have a name, a type and a value. Java
provides different data types that include character, double, float, integer,
string, boolean etc. These are primitive types as the are built into the Java
language and are not actual objects thus making it easier to use them. These
can be put in four groups:
Integers: This group includes byte, short, int, and long, which are for
whole-valued signed numbers.
Floating-Point Numbers: This group includes float and double, which
represent numbers with fractional precision.
Characters: This group includes char, which represents symbols in a
character set, like letters and numbers.
Boolean: Boolean is used for storing logical values. This group includes
boolean, which is a special type for representing true/false values. This
is the type returned by all relational operators, such as a < b. boolean is
also the type required by the conditional expressions that govern the
control statements such as if and for.
Integer Integers are used for storing integer values. There are four kinds
of integer types in Java. Each of these can hold a different range of values. The
values can either be positive or negative. Depending on the range of values that
it should hold, the type of integer is chosen. If the value becomes too large, it
will be truncated. The table for the range of values is given below :

Type Size Range

byte 8 bits -128 to +127

short 16 bits -32, 768 to +32, 767

int 32 bits -2, 147, 483, 648 to +2,147, 483, 647

long 64 bits -9223372036854775808 to


+9223372036854775807

Float: Float is used to store numbers with decimal part. There are two floating
point data types in Java namely, the float (32 bits, single precision) and the
double (64 bits, double precision).
Character It is used for storing individual characters. The char type has 16
bits of precision and it is unsigned.

60
Boolean Boolean data types hold either a true or a false value. These are
not stored as numeric values and cannot be used as such.

6.6.2 REFERENCE DATA TYPES

There are situations in which variables must be logically grouped


together for manipulation, possibly because they are going to be accessed in
sequence or identifiers must point to dynamically allocated objects. These are
called reference data types.

6.7 JAVA KEYWORDS

There are 49 reserved keywords defined in the Java language. These


keywords, combined with the syntax of the operators and separators, are used
for writing a Java program. In addition to the following keywords, Java reserves
true, false, and null. It is to be noted that these keywords cannot be used as
names for a variable, class, or method.

abstract Const Final int protected while

boolean Continue Finally interface public throw

break Default Float long return throws

byte Do For native short transient

case Double Goto new super true

catch Else If null switch try

char Extends implements package synchronized void

instance
class False Import private this
of

6.8 LET US SUM UP

• Literals :A constant value in Java is created by using a literal


representation. The literals available in Java are Integer Literals,
Floating-Point Literals, Boolean Literals, Character Literals, String
Literals
• Identifiers : Identifiers are used for class names, method names, and
variable names.

61
• A variable is defined by the combination of an identifier, a type, and an
optional initializer.
• In Java, the two major scopes are those defined by a class and those
defined by a method
• Data Types available in Java are Integer, Floating-Point Number,
Character and Boolean.
• 49 reserved keywords defined in the Java language

6.9 CHECK YOUR PROGRESS : MODEL ANSWERS

1. The literals available in Java are Integer Literals, Floating-Point Literals,


Boolean Literals, Character Literals, String Literals
2. Some valid variable names are
average
area
sum_2_numbers

62
63
LESSON 7

OPERATORS
CONTENTS
7.0 Aims and Objectives
7.1 Introduction
7.2 Expressions
7.3 Assignment Operator
7.4 Arithmetic Operators
7.5 Arithmetic assignment operators
7.6 Boolean logical operator
7.7 Relational operators
7.8 Bitwise operators
7.9 Ternary Operator
7.10 Operator precedence
7.11 Let us sum up
7.12 Check Your Progress: Model Answers

7.0 AIMS AND OBJECTIVES

This lesson aims at introducing the different types of Operators used in


expressions and their hierarchy of evaluation. At the end of this lesson the
learner will be able to write different expression and will be able identify the
evaluation procedure used in expressions.

7.1 INTRODUCTION

Java provides a rich set of operators. The operators present in Java can
be classified into the following four groups: arithmetic, bitwise, relational, and
logical. The operators are used to combine operands. The operands can be
variables or constants. When only one operand is required the operator is called
as unary operator and when there are more than one operand, then the
operator is called is called as binary operator.

7.2 EXPRESSIONS

An expression is a series of variables, operators, and method calls


(constructed according to the syntax of the language) that evaluates to a single
value.

64
Expressions perform the work of a Java program. Among other things,
expressions are used to compute and assign values to variables and to help
control the execution flow of a program. The job of an expression is two-fold:
perform the computation indicated by the elements of the expression and
return some value which is the result of the computation.
For example, the statement
count++;
is an expression. This particular expression evaluates the value of count
before the operation occurs.
The data type of the value returned by an expression depends on the
elements used in the expression.
Java allows to construct compound expressions and statements from
various smaller expressions as long as the data types required by one part of
the expression matches the data types of the other.
Take for example this compound expression:
k=x * y * z;
In this particular example, the values of x, y and z are multiplied and the result
of the multiplication is stored in the variable k.

7.3 ASSIGNMENT OPERATOR

The assignment operator is the single equal sign, =. The general form of the
assignment
operator is :
var = expression;
Here, the type of var must be compatible with the type of expression.

Consider the following Java code


int x=12,y;
y=x/2;
The above assignment statement first evaluates the expression x/2 and then
assigns the result to y. Hence the value of y after execution will be 6.
The assignment operator can also be used to create a chain of assignments. For
example, consider this fragment:A LANGUAGE
int a, b, c;
a = b = c= 96; // set a, b, and c to 96
This fragment sets the variables a, b, and c to 96 using a single statement. This
works because the = is an operator that yields the value of the right-hand
expression. Thus, the value of c = 96 is 96, which is then assigned to b, which

65
in turn is assigned to a. Using a “chain of assignment” is an easy way to set a
group of variables to a common value.

7.4 ARITHMETIC OPERATORS

Arithmetic operators are used for performing Arithmetic operations. Java


has five basic arithmetic operators. Each of these operators takes two operands,
one on either side of the operator.
The list of arithmetic operator is given below:

1) Operator Article II. Results Article III. Meaning

+ Addition Addition

- Subtraction Subtraction

* Multiplication Multiplication

/ Division Division

Remainder of a
division
% Modulus
(can also be applied to
floating point values)

Increment and Decrement Operator


The ++ and the – – are Java’s increment and decrement operators. The
increment and decrement operator can be used to increment or decrement the
value by 1.

1) Operator Article IV. Results Article V. Meaning

++ Self Increment Increment a value by


1

-- Self Decrement Decrement a value by


1

Example : 1
The Java statement:
x = x + 1;
can be rewritten by using the increment operator as

66
x++;

Similarly, the Java statement:


x = x - 1;
is equivalent to
x--;
These operators are unique in that they can appear both in postfix form,
where they follow the operand as just shown, and prefix form, where they
precede the operand. In the prefix form, the operand is incremented or
decremented before the value is obtained for use in the expression. In postfix
form, the previous value is obtained for use in the expression, and then the
operand is modified.
Example:2
x = 42;
y = ++x;
In this case, y is set to 43, because the increment occurs before x is assigned to
y. Thus, the line y = ++x; is the equivalent of these two statements:
x = x + 1;
y = x;
However, when the statement is written using postfix ,
x = 42;
y = x++;
the value of x is obtained before the increment operator is executed, so the
value of y is 42, and then x is incremented to 43.

Check Your Progress : 1

List the different type of Arithmetic operators available in Java.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this unit.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

67
7.5 ARITHMETIC ASSIGNMENT OPERATORS

Java provides special operators that can be used to combine an


arithmetic operation with an assignment These operators are used to perform
a) arithmetic operation and
b) assign the result to the variable present in the left of assignment
operator =

Operator Meaning

+= Addition assignment

-= Subtraction assignment

*= Multiplication
assignment

/= Division assignment

%= Modulus assignment

There are assignment operators for all the arithmetic, binary operators. Thus,
any statement of the form
var = var op expression;
can be rewritten as
var op= expression;

Example : 1
The Java statement
x = x + 5;
can be rewritten as :E JAVA LANGUAGE
x += 5;
This version uses the += assignment operator. Both statements perform the
same action: they increase the value of x by 6.

Example : 2
The Java statement

68
a = a % 3;
can be expressed as
a %= 3;
In this case, the %= obtains the remainder of a/2 and stores the result back
into a. If the value of a was 7 initially, after the execution of the statement, the
value of a will be 1.

7.6 BOOLEAN LOGICAL OPERATORS

When more than one relation are to be checked the logical operators are
used. Logical operators available are AND, OR, XOR, and NOT. The following
table shows the result of the Boolean operations for the inputs A and B.

OR AND XOR NOT

A B A|B A&B A^B !A

0 0 0 0 0 1

1 0 1 0 1 0

0 1 1 0 1 1

1 1 1 1 0 0

7.7 RELATIONAL OPERATORS

The relational operators are used to compare two values. The following tables
give a list of Relational operators.

Article VI. Operator Article VII. Meaning

== Equal to

!= Not Equal to

> Greater Than

< Less than

>= Greater than or Equal to

69
<= Less than or Equal to

In order to distinguish assignment operator = and conditional checking =, the


operator == (double equal to symbol) is provided for conditional checking.

7.8 BITWISE OPERATORS

Bitwise operators act upon the individual bits of their operands. Java defines
several bitwise operators which can be applied to the integer types, long, int,
short, char, and byte. They are summarized in the following table:

Operator Meaning

& Bitwise AND

~ Bitwise unary NOT

| Bitwise OR

^ Bitwise exclusive OR

>> Shift right

>>> Shift right zero fill

<< Shift left

&= Bitwise AND assignment

>>= Shift right assignment

|= Bitwise OR assignment

^= Bitwise exclusive OR assignment

<<= Shift left assignment

>>>= Shift right zero fill assignment

The Bitwise NOT


Also called the bitwise complement, the unary NOT operator, ~, inverts all of the
bits of its operand.

70
For example, the number 42, which has the following bit pattern:
00101010
becomes
11010101
after the NOT operator is applied.

The Bitwise AND


The AND operator, &, produces a 1 bit if both the operands are 1. A zero is
produced in all other cases. Here is an example:
00101010 42
& 00001111 15
--------------
00001010 10

The Bitwise OR
The OR operator, |, combines bits such that if either of the bits in the operands
is a 1, then the resultant bit is a 1. For example if there is a Java statement
int a=42,b=15,c;
c = a | b;
will have the effect as
00101010 42
| 00001111 15
--------------
00101111 47
The value of c after executing the above statement will be 47.
The Bitwise XOR
The XOR operator, ^, combines bits such that if exactly one operand is 1, then
the result is 1. Otherwise, the result is zero. The following example shows the
effect of the ^. This example also demonstrates a useful attribute of the XOR
operation.

00101010 42
^ 00001111 15
-------------

71
00100101 37

The Left Shift


The left shift operator, <<, shifts all of the bits in a value to the left a specified
number of times.
It has the general form:
value << num
Here, num specifies the number of positions to left-shift the value in value. That
is, the << moves all of the bits in the specified value to the left by the number of
bit positions specified by num. For each shift left, the high-order bit is shifted
out (and lost), and a zero is brought in on the right.
The following Java program fragment demonstrates this concept: LANGUAGE
byte a = 64, b;
int i;
i = a << 2;
b = (byte) (a << 2);
After executing the above statements i and b values will be 256 and 0
respectively.

The Right Shift


The right shift operator, >>, shifts all of the bits in a value to the right a
specified number of times. The general form of right shift operator is :
value >> num
Here, num specifies the number of positions to right-shift the value in value.
That is, the >> moves all of the bits in the specified value to the right the
number of bit positions specified by num.
The following code fragment shifts the value 32 to the right by two positions,
resulting in a being set to 8:
int a = 32;
a = a >> 2; // a now contains 8

7.9 TERNARY OPERATOR

? operator is also called as ternary (three-way) operator that can be used as an


alternative for if-then-else statements.
The ? operator has this general form:

72
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean value. If
expression1 is true, then expression2 is evaluated; otherwise, expression3 is
evaluated. The result of the ? operation is that of the expression evaluated.
Both expression2 and expression3 are required to return the same type, which
can’t be void.

Here is an example of the way that the ? is used:


ratio = (denom == 0) ? 0 : num / denom;
When Java evaluates this assignment expression, it first looks at the expression
to the left of the question mark. If denom equals zero, then the expression
between the question mark and the colon is evaluated and used as the value of
the entire ? expression. If denom does not equal zero, then the expression after
the colon is evaluated and used for the value of the entire ? expression. The
result produced by the ? operator is then assigned to ratio.

7.10 OPERATOR PRECEDENCE

Operator precedence determines which part of the expression to be


evaluated first when an expression is evaluated. The following table shows the
order of precedence for Java operators, from highest to lowest :

Priority No. Operator

Priority 1 ()[].
Highest
2 ++ – – ~ !

3 */%

4 +–

5 >> >>> <<

6 > >= < <=

7 == !=

8 &

9 ^

10 |

73
Lowest
11 &&

12 ||

13 ?:

14 = op=

Using Parentheses
Parentheses raise the precedence of the operations that are inside them. This is
often necessary to obtain the desired result. Parentheses are used to alter the
precedence of an operation.
For example, consider the following expression.
a = 4 * 5 + 3;
The above expression first evaluates * and then addition. Hence a value would
be 23. In a situation where the addition is to be performed first, the expression
could be rewritten as :
a = 4 * (5 + 3);
Hence the value of a would be 32.s

Separators:
In Java, there are a few characters that are used as separators. The most
commonly used separator in Java is the semicolon. The separators are shown
in the following table.

Separators supported by Java

{ } ; , :

7.11 LET US SUM UP

In this lesson we have discussed the different operators available in Java. We


has discussed the following key points:
• The operators present in Java can be classified into the following four
groups: arithmetic, bitwise, relational, and logical.

74
• The operators available in Java are Assignment Operator, Arithmetic
Operators, Arithmetic assignment operator, Boolean logical operator,
Relational operators, Bitwise operators, Ternary Operator.

7.12 CHECK YOUR PROGRESS : MODEL ANSWERS

The arithmetic operators available in Java are + (addition), - (subtraction),


*(multiplication), / (division) and % (modulus).

75
LESSON 8

DECISION MAKING AND BRANCHING STATEMENTS

CONTENTS
8.0 Aims and Objectives
8.1 Introduction
8.2 if statement
8.3 if-else-if ladder
8.4 switch statement
8.5 goto statement
8.6 Let us sum up
8.7 Check Your Progress: Model Answers
8.8 Programming Exercises

8.0 AIMS AND OBJECTIVES

In this lesson we will learn the different control structures available in


Java. The control structures if and switch is discussed in this lesson. At the
end of this lesson the learner will be able to understand the control structures
and write Java programs using the control structures.

76
8.1 INTRODUCTION

Control statements are used to alter the flow of control. In a normal


sequence the Java compiler executes the statements in the order of appearance
of the statements. In real time situation it might be required to alter the flow of
control based upon decisions/conditions, in such situations the control
statements play a vital role.
Java supports two selection statement if and switch. These statements
allow you to control the flow of the program’s execution based upon conditions
known only during run time.
CONTROL STATEMENTS
A programming language uses control statements to cause the flow of
execution to advance and branch based on changes to the state of a program.
Java’s program control statements can be put into the following categories:
selection, iteration, and jump.
Selection statements allow the program to choose different paths of
execution based upon the outcome of an expression or the state of a variable.
Iteration statements enable program execution to repeat one or more
statements (that is, iteration statements form loops).
Jump statements allows the program to execute in a nonlinear fashion

8.2 if STATEMENT

The if statement can be used to route program execution through


two different paths. The general form of the if statement:
if(condition)
statement1;
else
statement2;
The if works like this: if the condition is true, then statement1 is
executed. Otherwise, statement2 (if exists) is executed. In case if more than one
statement is to be executed in the true part or the else part, the statements are
embedded as a block using { and } braces. The general format for multiple
statements in true/false part would be
if(condition)
{
statement;
statement;
…..
….

77
}.
else
{
statement;
statement;
…..
…..
}
The flow of control for an if..else statement can be shown as :

true false
condition

Statement Statement
Statement Statement
…………. ………….

Figure 8.1 showing the flow of control in an if…else statement

Sample Program for if..else statement


class ifdemo
{
public static void main(String a[])
{
String name = a[0];
int marks=Integer.parseInt(a[1]);
if(marks>49)
{
System.out.println(name+" You Passed");
}
else

78
{
System.out.println(name+" You did not pass");
}
}
}
Explanation
 The above program accepts the user’s name and the percentage from
commandline. In the command prompt execute the program as
C:\jdk1.5.0_14\bin>java ifdemo raja 78

 The input is read from the command line as a String (in the variable a).
 This String is converted into the integer by using the Integer.parseInt()
method.
 Now the value of the percentage is checked and depending on the value of
the percentage an appropriate message is displayed on the screen.
Nested ifs
A nested if is an if statement that is the target of another if or else.
Nested ifs are very common in programming. When if statements are nested,
the main thing to remember is that an else statement always refers to the
nearest if statement that is within the same block as the else and that is not
already associated with an else.
The following Java program segment depicts the use of nested if statement :
if(i == 10)
{
if(j < 20) a = b;
if(k > 100)
c = d; // this if is
else
a = c; // associated with this else
}
else
a = d; // this else refers to if(i == 10)
As the comments indicate, the final else is not associated with if(j<20), because
it is not in the same block (even though it is the nearest if without an else).
Rather, the final else is associated with if(i==10). The inner else refers to
if(k>100), because it is the closest if within the same block.

79
8.3 if-else-if LADDER

When multiple conditions are to be checked when the condition is false


then the if-else-if ladder is chosen. if-else-if ladder looks like this:

if(condition1)
statement;
else if (condition2)
statement;
else if(condition3)
statement;
.
.
.
else
When all the default statement part…;
conditions fail the
default part is executed.

8.4 switch STATEMENT

The switch statement is Java’s multiway branch statement. The


limitation of if statement is that it can be used to check only whether the
condition is true or false. In case where more than one condition is to be
checked the switch statement is used.
The general form of a switch statement.

switch (expression)
{
case value1:
//statement sequence
break;
case value2:
//statement sequence
break;
.
.
.
case valueN:
//statement sequence
break;
default:
//default statement sequence
}

The expression must be of type byte, short, int, or char. Each case value
must be unique. The switch statement works like this: The value of the
expression is compared with each of the literal values in the case statements. If

80
a match is found, the code sequence following that case statement executed. If
none of the constants matches the value of the expression, then the default
statement is executed. However, the default statement is optional. Break
statement terminates the route and transfers the control outside the switch
block..
#Program to demonstrate the use of switch statement
//example of switch
class switchdemo
{
public static void main(String args[])
{
for(int i=0; i<6; i++)
switch(i)
{
case 0:
System.out.println("i is Zero");
break;
case 1:
System.out.println("i is One");
break;
case 2:
System.out.println("i is Two");
break;
case 3:
System.out.println("i is Three");
break;
default:
System.out.println("i is greater than three");
}
}
}
The important features of switch statement include :
• The switch differs from the if in that switch can only test for equality,
whereas if can evaluate any type of Boolean expression. That is, the

81
switch looks only for a match between the value of the expression and
one of its case constants.
• No two case constants in the same switch can have identical values. Of
course, a switch statement enclosed by an outer switch can have case
constants in common.
• A switch statement is usually more efficient than a set of nested ifs.
Check Your Progress : 1

List the conditional control statements available in Java.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this unit.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

Nested switch Statements


It is possible to use a switch as part of the statement sequence of an
outer switch. This is called a nested switch. Since a switch statement defines
its own block, no conflicts arise between the case constants in the inner switch
and those in the outer switch.
For example, the following fragment is perfectly valid:
switch(count)
{
case 1:
switch(target)
{ // nested switch
case 0:
System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;

82
case 2: // ...

Here, the case 1: statement in the inner switch does not conflict with the case
1: statement in the outer switch. The count variable is only compared with the
list of cases at the outer level. If count is 1, then target is compared with the
inner list cases.

8.5 goto STATEMENT

goto is a reserved word in Java, but the goto statement is not currently
part of the language. Labelled break and labeled continue statements
(discussed in section 9.6) replace some important and legitimate uses of goto,
and the try/catch/finally statement (which are used in exception handling)
replaces the others.

83
8.6 LET US SUM UP

In this lesson we have discussed branching and decision making statements.


The following points have been discussed in this lesson :
• Control statements are used to alter the flow of control.
• Java supports two selection statement if and switch.
• Selection statements allow the program to choose different paths of
execution based upon the outcome of an expression or the state of a
variable.
• Iteration statements enable program execution to repeat one or more
statements (that is, iteration statements form loops).
• Jump statements allows the program to execute in a nonlinear fashion
• switch statement is Java’s multiway branch statement

8.7 CHECK YOUR PROGRESS : MODEL ANSWERS.

1. The conditional control statements available in Java are if, if..else, switch
statements.

8.8 PROGRAMMING EXERCISES

1. Write a program to check whether the number is even number or odd


number. (Use command line arguments as used in example programs
available in if and switch statements)
2. Write a Java program to read three numbers from command line and
find the largest of three numbers.
3. Write a Java program to read the age of a person in command line and
determine whether he is eligible to vote (Note : A person is eligible to vote
if his age is above 18 years).

84
LESSON 9

LOOP STRUCTURES
CONTENTS
9.0 Aims and Objectives
9.1 Introduction
9.2 while loop
9.3 do..while loop
9.4 for loop
9.5 Java’s Jumping statement
9.5.1 break statement
9.5.2 continue statement
9.5.3 return statement
9.6 Labelled loops
9.7 Let us sum up
9.8 Check Your Progress: Model Answers
9.9 Programming Exercises

9.0 AIMS AND OBJECTIVES

In this lesson we learn the different looping constructs available in Java.


The looping constructs while, do..while and for are discussed in this chapter. At
the end of this lesson the learner will be able to write programs making use of
loop structures.

9.1 INTRODUCTION

Loop structures are used to repeatedly execute a set of statements till a


condition is satisfied or for a specified number of times.
Java’s Iteration statements are for, while, and do-while. These
statement creates loops which is repeatedly executes the same set of
instructions until a termination condition is met.

9.2 while LOOP STRUCTURE

The while loop is a looping construct available in Java. While Loop


continues till the evaluating control expression becomes false. The evaluating
control expression has to be a logical expression.

85
The general form of while loop is :
while (condition)
{
// body of loop
……….
………
}
Program for demonstrating the use of while loop structure
The following examples shows how a while loop can be used to print the
factorial of 5.
//Program for finding factorial of a number
class whiledemo
{
public static void main(String args[])
{
int i, fact;
fact=1;
i=1;
while(i<=5)
{ fact=fact*i;
i=i+1;
}
System.out.println("The factorial of 5 is" +fact);
}
}
Explanation
The above program declares two variables i and fact. The variable fact has an
initial value of 1. In this loop, the value of the variable fact is assigned to fact*i.
The value of fact in each of the five iterations will be as under.
fact=fact*i=1*1=1
fact=fact*i=1*2=2
.

86
.
so on.

9.3 do-while STATEMENT

If the conditional expression controlling a while loop is initially false,


then the body of the loop will not be executed at all. However sometimes it may
be required to execute the body of the loop at least once, even if the conditional
expression is false to begin with. The do-while loop always executes its body at
least once, because its conditional expression is at the bottom of the loop.
The general form of do..while statement is,
do
{
//Statement
//Statement
//Statement
} while (LoopCondition);
Program for demonstrating the use of do..while statement
class dowhiledemo
{
public static void main(String args[])
{ int i, fact;
fact=1;
i=1;
do
{
fact=fact*i;
i=i+1;
}while(i<=5);
System.out.println("The Factorial of 5 is "+ fact);
}
}

9.4 for LOOP STRUCTURE

The most compact and often used loop is the for construct - is similar to the
while or do... while loop.

87
The general usage is
for (initialization; condition; increment/decrement)
{
//Statement
//Statement
}
The for loop repeats the Statement the number of times that is determined by
the InitializationExpression, the LoopCondition, and StepExpression. The
InitializationExpression is used to initialize a loop control variable. The
LoopCondition compares the loop control variable to a limit value. Finally, the
StepExpression specifies how the loop control variable should be modified
before the next iteration of the loop.
Program for demonstrating the use of for() loop structure
class fordemo
{ public static void main(String args[])
{ int i,fact;
fact=1;
for (i=1; i<=5; i++)
{
fact=fact*i;
}
System.out.println(“The Factorial Of 5 is ” + fact);
}
}
Nested Loops
A loop within another loop is called as nested loop. Nesting of loops is
allowed in Java. When loops are nested, the inner most loop is given first
priority for execution and once the inner most loops finishes execution, the
control is transferred to the outer loop.
Example program for nested loops :
// Loops may be nested.
class Nested
{
public static void main(String args[])
{ int i, j;

88
for(i=0; i<10; i++)
{
for(j=i; j<10; j++)
System.out.print("*");
System.out.println();
}
}
}

The output produced by this program is shown here:


**********
*********
********
*******
******
*****
****
***
**
*

9.5 JAVA’S JUMPING STATEMENT

Java supports three jump statements break, continue and return. These
statement transfer control to a specific part of the program.
9.5.1 Break statement
The break statement is useful in dealing with termination of loop
structures. The break statement is used to jump out of a loop and effectively
bypass the loop condition. The break statement can also be used along with
switch statement to come out of the switch statement.
When a break statement is encountered inside a loop, the loop is terminated
and program control resumes at the next statement following the loop. When a
break statement used in nested loops, break will transfer contol out of the inner
most loop.
Program for demonstrating the use of break statement
class breakdemo{

89
public static void main(String args[])
{ int num,ctr,i;
ctr=i=0;
while(true)
{
num=Integer.parseInt(args[i++]);
if(num==0)
{
break;
}
if(num%7==0)
{ ctr=ctr+1;
num=num/7;
if(num<7)
num=0;
}
}
System.out.println("Number of 7's are "+ctr);
}
}
The above program is to accept the numbers through command line
arguments and count the number that are divisible by 7. If a 0 is entered, the
loop terminates by using the break statement. The modulo operator is used to
check if the remainder of a division evaluates to 0. The statement while(1)
creates the infinite loop, to jump out of this infinite loop, the break statement is
used.
To compile the program
C:\Java\jdk1.5.0_14\bin>javac breakdemo.java
To execute the program
C:\Java\jdk1.5.0_14\bin>java breakdemo 14 5 8 21 0
Number of 7's are 2

9.5.2 Continue STATEMENT

90
Another useful statement that works similarly to the break statement is
the continue statement. Unlike break, the continue statement is useful only
when working with loops; it has no real application in switch branch. The
continue statement works like a break statement in that jumps out of the
current iteration of a loop. The differences with continue is that program
execution is restored to the beginning of the loop. Break is used to jump out
and terminate the loop, continues is used to skip the remaining statements of
the body of the loop and takes the control to the next iteration of the loop.

9.5.3 return STATEMENT


The return statement is used to explicitly return from a method. That is,
it causes program control to transfer back to the caller of the method. As such,
it is categorized as a jump statement.
At any time in a method the return statement can be used to cause
execution to branch back to the caller of the method. Thus, the return
statement immediately terminates the method in which it is executed.
Check Your Progress : 1

List the different loop structures available in Java

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this unit.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

Sample Java programs which uses Loop and Control structures


1. Write a program generate a prime numbers from 1 to 100. (Note :Prime
Numbers are numbers that are divisible by 1 or by the number itself)

class PrimeNumberDemo
{ public static void main(String a[])
{ int num, i, j, ctr;
boolean prime;
for(i=1; i<100;i=i+1)
{
prime=true;
ctr=0;
for(j=2;j<=i-1;j=j+1)

91
{ if(i%j==0)
prime =false;
break;
}
if(prime)
{
System.out.println("Prime Number between 1 to 100 are "+
i);
}
}
}
}

The outer for loop, controlled by the variable I, generates odd numbers from
the initial value of 3.
• There is an inner for loop which is controlled the variable j. Such loops
are called nested loops.
• The variable j gets initialized to the value 1. i is divided by j. If there is a
perfect division with no remainder and the Boolean variable prime
remains true.
• If the number is not a prime, then the value of the prime will be made to
be false. In such case, control jumps out of the loop with the help of
break statement. The variable prime is assigned the value false.
• If the variable prime contains the value true, then i is a prime number
and gets printed out.

92
2. Write a program for reading a number from the keyboard and print it in
the reverse order.

Class ReverseDemo
{
public static void main(String a[])
{ String s=””;
int rev=Integer.parseInt(a[0]);
int des, rem;
while(rev>=10)
{
rem=rev%10;
s=s.trim()+rem;
rev=rev/10;
}
s=s+String.valueOf(rev);
des=Integer.parseInt(s);
System.out.println(des);
}
}

• Whatever the value is entered by user, which is, checked by the while
loop for greater than an equal to 10.
• If the value is greater than 10 then by using the modulo operator, we
calculate the remainder of the number which is nothing but the last
digit of the particular number.
• We concatenate this rem with string and rev is divided by 10 for taking
the next number.
• Atlast rev contains the first digit of the number, which is entered by the
user but in the result, which is last digit.
• Value of the s generates the reverse of the number, which is string, and
convert into the Integer.

9.6 LABELLED LOOPS

Both break and continue statements can have an optional label that tells
Java where to break to. Without a label, break jumps outside the nearest

93
loop (to an enclosing loop or to the next statement outside the loop), and
continue restarts the enclosing loop.
Using labeled breaks and continues enables to break outside nested loops or
to continue a loop outside the current loop.
To use a labeled loop, add the label before the initial part of the loop, with a
colon between them. Then, when break or continue is used, add the name of
the label after the keyword itself:
out:
for (int i = 0; i <10; i++)
{
while (x < 50)
{
if (i * x == 400)
break out;
...
}
...
}
In this snippet of code, the label out labels the outer for loop. Then, inside both
the for and the while loop, if a particular condition is met inside both loops, a
break causes the execution to come out of both loops and restart back at the
label (out).

Note : Labeled breaks/continues are an alternative to the goto statement(goto


statement is not supported by the Java language).

9.7 LET US SUM UP

In this lesson we have learnt the following


• Loop structures are used to repeatedly execute a set of statements till
a condition is satisfied or for a specified number of times.
• The loop structures available in Java are
 for loop
 while loop
 do..while loop
• The jumping statements available in Java are break, continue and
return statements.
• A loop within another loop is called as nested loop structure.

94
• The return statement is used to explicitly return from a method

9.8 CHECK YOUR PROGRESS : MODEL ANSWERS

1. The loop structures available in Java are for loop, while loop, do..while
loop.

9.9 PROGRAMMING EXERCISES

1. Write a program to generate a Fibonacci series .


Note: that Fibonacci series like this 0 1 1 2 3 5 8 13….
2. Write a program to display a triangle as shown below.
*
**
***
****
3. Write a Java program to display a triangle as under.
1
12
123
1234
4. Write a program to generate prime numbers between 1 and 100.
5. Write a program to generate first n numbers.
6. Write a Java program to generate multiplication table as shown below :
1x2=2
2x2=4
…..
…..
16 x 2 = 32

7. Write a program to print a PASCAL’s triangle as shown below :


1
1 2 1
1 2 3 2 1

95
1 2 3 5 3 2 1

96
LESSON 10

CLASSES, OBJECTS AND METHODS

CONTENTS
10.0 Aims and Objectives
10.1 Introduction
10.2 Classes

97
10.3 Objects
10.4 Methods
10.5 Abstraction and Encapsulation
10.6 Let us sum up
10.7 Check Your Progress: Model Answers

10.0 AIMS AND OBJECTIVES

This lesson aims at introducing the concepts of class, objects and


methods which are the basic building blocks in object oriented programming.
The different components of methods such as constructors are also discussed.
At the end of the lesson the learner will be able to define and build a class and
access it through its instances.

10.1 INTRODUCTION

The class is the core of Java. It is the logical construct upon which the
entire Java language is built because it defines the shape and nature of an
object. A class is a template for an object, and an object is an instance of a
class.

10.2 CLASSES

Java offers the programmer the keyword class that enables the
programmer to create abstract data type. Creation and manipulation of ADT
(Abstract Data Type) is the essence of object-oriented programming. Class
contains member data or variables; and methods, which provide the interface to
act on these member data.
Every class member has a scope. The scope determines the context of the
variable. To put it simply, the scope defines how and where a variable can be
accessed. In Java, a variable is normally hidden from the user to prevent
accidental manipulation. Keywords that determine the scope of member data
are private, protected and public. These keywords are called access modifiers.
They enable a programmer to declare variables and methods as private, public
or protected.
The general form of class is :
class classname
{
type instance-variable1;
type instance-variable2;
type methodname1(parameter-list)
{

98
//body of the method
}

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

10.2.1 Variables in a Class Definition


The data, or variables, defined with a class are called instance variable.
The code is contained with in the methods. Collectively, the methods and
variables defined within a class are called members of that class. In short, it is
the methods that determine how a class data can be used.
10.2.2 Instance variables
Variables defined within the class are called instance variable because
each instance of the class contains its own copy of these variables. Thus, data
from one object is separate and unique from the data of another object.
10.2.3 Class variables
A given class will have only one copy of each of its class variables and
will be shared among all objects of that class. All class variables exist even if no
object of the class have been created, they belong to the class, but they are
included as a part of every object of the class. If the value of the class variables
is changed, the new value is available to all objects of that class. This is
different as compared to instance variables where changing a value for one
object does not affect the value of other objects. A class variable must be
declared using the static keyword preceding the type name.
Examples:
Here is the class called box that defines two instance variables: length and
width.

box.java

class box
{

99
double length;
double width;
}

To create the box object, you have to give a statement as given below.
box b=new box();
After this statement is executed, b will be an instance of box. Each time
an instance of a class is created an object is created, and the object contains its
own copies of instance variables namely length, width. To access these
variables you will use the dot(.) operator, the dot operator links the name of the
object with the name of an instance variable. For example to assign the value to
the width variable, it is necessary to use the following statement:
b.width=150;
The following example depicts the use of instance variables.

rectangle.java

class rectangle
{
public static void main(String a[])
{
box b=new box();
double area;

b.length=100;
b.width=150;
area=b.length*b.width;
System.out.println(“Area of the rectangle is”+ area);
}
}
Output: Area of the rectangle is 15000.0

Check Your Progress : 1

Explain how a class is defined in Java.

Notes : a) Write your answer in the space given below.

100
b) Check your answer with the one given at the end of this unit.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

10.3 OBJECTS

Declaring Objects
Obtaining objects of a class is a two-step process.
• A variable of class type must be declared. This variable does not define
an object. Instead, it is simply a variable that can refer to an object.
• You must acquire actual, physical copy of the object and assign it to that
variable. This can be done using the new operator. The new operator
dynamically allocates memory for an object and returns a reference to it.
This reference is, more or less, the address of the memory of the object
allocated new. This reference is stored in the variable. You should note
that all class objects in Java must be dynamically allocated.
10.4 Methods
Classes usually consist of two things: instance variables and methods.
Methods defines the process to e carried over
The general form of a method is stated below.
[<Accessibility modifier>] [Storage or lifetime modifier>] <return type>
<function name> (<parameter list>)
{
//body of method;
}
Access and storage modifier are discussed later. Return type is the type
of data that is going to be returned by this function. If the function is not
returning a value, the return type should be specified as void. A function can
return only one value. It can take any number of parameters. While declaring
the function, the data type of the parameters should be specified. A function
can be invoked only if it has been defined.

Example : Adding a method to the class

101
box1.java

class box1
{ double length;
double width;
void area()
{ System.out.println("Area is");
System.out.println(length*width);
}
}

trialbox1.java
class trialbox1
{
public static void main(String a[])
{
box1 b1=new box1();
box1 b2=new box1();
b1.length=60;
b1.width=80;

b2.length=15;
b2.width=25;
b1.area();
b2.area();
}
}

Output is:
Area is 4800.0
Area is 375.0

102
Example: Adding a method that returns a value and take a
parameter
In the previous program, the class box1 consists of a method to calculate the
area, using this method area of the box is computed and the result displayed.
10.4.1 Constructors
Constructors have the same name as that of the class and they can be
overloaded. They cannot return any value. The constructor is a function that
will be automatically invoked by the runtime system whenever an instance is
created.
Example for constructor :

class box3
{
double length;
double width;
box3()
{
length=25;
width=25;
}
box3(double l,double w)
{
length=l;
width=w;
}
double area()
{
return length*width;
}
}

trialbox3.java

103
class trialbox2
{
public static void main(String a[])
{
box3 b1=new box3();
box3 b2=new box3(30,80);
double rectarea;
rectarea=b1.area();
System.out.println("Area is "+ rectarea);
rectarea=b2.area();
System.out.println("Area is "+ rectarea);
}
}

When an instance of this class is created, automatically the data


members get initialized to some default values. In this case, the default
constructor gets invoked. So the data member length and width are initialized
to a value of 25. Note the other constructor that has been added to the class:
box3(double l, double w)
{
length=l;
width=w;
}
When an instance is created, which constructor will be called? That depends on
the number of parameters passed and the type of parameters passed while
creating the instance.
10.4.2 ‘this’ keyword
The this keyword in Java is used in situations where a method is
required to refer to the object that invoked it. This can be used inside any
method to refer to the current object.
Example:

Bank.java

class Bank

104
{ int account_no;
String name;
int balance;
Bank()
{
account_no=0;
name=" ";
balance=0;
}
Bank(int account_no,String name,int balance)
{ this.account_no=account_no;
this.name=name;
this.balance=balance;
}
void display()
{
System.out.println("Account no is:" +account_no);
System.out.println("Name is :"+name);
System.out.println("Balance is :"+balance);
}
}

Transaction.java
class Transaction
{
int tran_no;
int acc_no;
String tr_type;
int tran_amt;
Transaction()
{
tran_no=0;

105
acc_no=0;
tr_type=" ";
tran_amt=0;
}
Transaction(int tran_no,int acc_no, String tr_type,int tran_amt)
{
this.tran_no=tran_no;
this.acc_no=acc_no;
this.tr_type=tr_type;
this.tran_amt=tran_amt;
}
void display()
{
System.out.println("Transaction no is :");
System.out.println("Account no is :"+acc_no);
System.out.println("Transaction Type is :"+tr_type);
System.out.println("Transaction Amount :"+tran_amt);
}

public static void main(String a[])


{
Bank b=new Bank(Integer.parseInt(a[0]),a[1],Integer.parseInt(a[2]));
Transaction t=new
Transaction(Integer.parseInt(a[3]),Integer.parseInt(a[0]),a[4],
Integer.parseInt(a[5]));
if(t.tr_type.equals("w"))
{
b.balance=b.balance-t.tran_amt;
}
else
{
b.balance=b.balance+t.tran_amt;

106
}
b.display();
t.display();
}
}

10.4.3 Method Overloading


Java allows to define two or more methods within the same class that
share the same name, as long as their parameter declarations are different. In
such situations, methods are said to be overloaded, the process referred to as
method overloading in case of methods that are overloaded, when Java
encounters a call to an overloaded method, it simply executes the version of the
method whose, parameters match the arguments used in the call.
10.4.4 Method Overriding
When the method in the subclass has the same name and type as a
method in its superclass, then the method in the subclass is said to override
the method in the superclass. When an overridden method is from within the
subclass, it will always refer to the version of that method defined by the
subclass. The version of the method defined by the superclass will be hidden.
Example:

overriding.java

class overriding
{ int len;
int x_coord;
int y_coord;
void setSquare(int xval,int yval,int l)
{
if(xval>0)
x_coord=xval;
else
x_coord=10;
if(yval>0)
y_coord=yval;
else

107
y_coord=10;
if(l>0)
len=l;
else
len=10;
}
void display()
{
System.out.println(x_coord +" "+y_coord+" "+len);
}
}

urectangle.java
class urectangle extends overriding
{ int width;
void display()
{ super.display();
System.out.println(width);
}
public static void main(String a[])
{
urectangle url=new urectangle();
url.setSquare(10,-20,0);
url.display();
}
}

The class urectangle uses the extends keyword for deriving data and
function members from the class overriding. Now the class urectangle has four
data members (x_coord, y_coord, len and width) and two function members
(display () and setSuare ()).
In the display function of urectangle class, the super keyword is used to
call the display function of base class.
10.4.5 Nested and Inner classes

108
It is possible to define a class within another class; Such classes are
known as nested classes. The scope of the nested classes is bounded by the
scope of its enclosing class. A nested class has access to the members,
including private members, of the class in which it is nested. However, the
enclosing class does not have access to the members of the nested class.
There are two types of nested classes:
Static class: A static nested class is the one which has the static
modifier applied. It must access the members of its enclosing class
through an object. Thus it cannot refer to members of its enclosing class
directly.

Non static class: Non static classes are known as inner class. It has
access to all variables and methos of its outer class and may refer to
them directly in the same way as other non-static members of the outer
class do. Thus an inner class is fully within the scope of its enclosing
class.

10.5 ABSTRACTION AND ENCAPSULATION

Normally, all objects present a great deal of complexity. To overcome this,


humans concentrate only on its essential details. For example a camera is an
object. The complex, inner working of the camera is hidden from the user. In
other words, the functioning of the camera is encapsulated. The user is
provided with some interfaces so that the camera can be used. Only the
essential details are revealed to him. This is known as abstraction. These
interfaces- the flash, the button etc are all a user needs to know use the
camera. A user need not know about how the motor winds the film.
Abstraction is the process where only the essential details are focuses upon
and all the non-essential details are ignored.
The programmer decides which parts of the class will be obscured from
the user and which parts of the program will be offered to the user as an
interface to the class. This feature Encapsulation is the process of hiding all
the details of an object that does not contribute to its essential characteristics.

10.6 LET US SUM UP

In this lesson we have dealt with the concepts of classes, object and
methods. We have also discussed the following points:
• A class is a template for an object, and an object is an instance of a
class.
• Classes usually consist of two things: instance variables and methods.
• Constructors have the same name as that of the class and they can be
overloaded.
• Abstraction is the process where only the essential details are focuses
upon and all the non-essential details are ignored

109
• Encapsulation is the process of hiding all the details of an object that
does not contribute to its essential characteristics

10.7 CHECK YOUR PROGRESS : MODEL ANSWERS

1. A class is defined using the following syntax :


class classname
{
type instance-variable1;
type instance-variable2;

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

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

110
111
LESSON 11

ARRAYS, STRINGS AND VECTORS

CONTENTS
11.0 Aims and Objectives
11.1 Introduction
11.2 Arrays
11.3 Strings
11.4 Vector class
11.5 Let us sum up
11.6 Check Your Progress: Model Answers
11.7 Programming Exercises

11.0 AIMS AND OBJECTIVES

In this lesson we will how to use arrays, characters and strings. We will
discuss 1D and 2D arrays. Next we discuss how to group characters using
strings. This lesson describes the different methods used for handling strings.
Finally vectors are presented in this lesson.
At the end of this lesson the reader will be able to write Java programs
based on arrays, strings and vectors.

11.1 INTRODUCTION

In a normal programming language it might be required to group


similar/different type of values under a single name. Arrays, strings and
vectors provides facilities for storing multiple values in a single name.

11.2 ARRAYS

An array is a group of variables referred to by a common name. The type


of data stored in array could be primitive like int or it could be an object type
like String. An element of an array is accessed by its index.
11.2.1 One Dimensional Array
The general form of one Dimensional array declaration is:
type variable-name[ ];
for example.
int[ ] numarray;

112
String[ ] stringarray;
The above declarations do not allocate memory for the array elements. That
has to be done using the new operator as follows:
numarray=new int[3];
After this statement executes, numarray will refers to an array of 3 integers. All
element in the array defined initialized to zero.
numarray[0]=30;
numarray[1]=40;
numarray[2]=50;
The following statement demonstrates how to retrieve the value of arrays and
display it.
System.out.println(numarray[0] +“,”+numarray[1]+”,”+numarray[2]);
It prints out the all the three values 30, 40 and 50.
Similarly, the other array stringarray can be initialized as:
stringarray=new String[4];
stringarray[0]=”Chennai”;
stringarray[1]=”Bombay”;
stringarray[2]=”Calcutta”;
stringarray[3]=”Delhi”;
The code
System.out.println(stringarray[1]);
can be used to print the value “Bombay”.
The length of the array can be determined using the property length. All arrays
in the Java have this property that can be used to determine the length or the
size of the array.
11.2.2 Multi-Dimensional Arrays
A multidimensional array is an array of arrays. In other terms the
multidimensional array is an array with multiple dimensions. For example, a
two dimensional array can be declared and initialized as:
int [] [] numarray=new int [3] [3]; or
int [] [] numarray={{1,2},{7,8,9}};
The first element of the above array has an array that contains two
elements. The second element contains an array that contains three elements.
Elements of two-dimensional arrays can be referred to using both row
subscript and column subscript for example.

113
System.out.println(numarray[1][0]);
The above statement will print the first element of the second row, which are 7.
Arrays can be effectively made use of with the control structure.
For example, the following declares a two-dimensional array variable called
twoD.
int twoD[][] = new int[4][5];
This allocates a 4 by 5 array and assigns it to twoD. Internally this
matrix is implemented as an array of arrays of int. Conceptually, this array will
look like the one shown in the following Figure 11.1

Figure 11.1Memory Allocation for a 2D array.

11.3 STRINGS

11.3.1 The String Class:


A combination of characters is a string. Strings are instances of the class
String. They are real objects, and hence, enable combination, testing and
modification. When a String literal is used in the program, Java automatically
creates instances of the String class. String are unusual in this respect. String
class represents constant(immutable) strings and the StringBuffer class
represents variable(mutable) strings.
The Constructors for the String class are:
• String()
• String(String s1)
• String(StringBuffer s2)
11.3.2 String Methods

114
The string class provides a number of methods to compare and search
strings. Some important methods in this class are listed in the table given
below:

115
Methods Description

(a) int length( ) Number of characters in


String

(b) char charAt(int index ) The char at a location in the


String.

(c) char[] toCharArray( ) Convert all the characters in


a string object into
character array.

(d) boolean equals(Object anobject ), An equality check on the


contents of the two Strings
(e) boolean equalsIgnoreCase(String
anotherstring )

(f) int CompareTo(String str) Result is negative, zero or


positive depending on the
lexicographical ordering of
the String and the
argument. Upper case and
lowercase are not equal.

(g) substring(int beginindex, int endindex) Returns a new String object


containing the specified
characterset.

(h) String concat(String str) Returns a new String object


containing the original
String's characters followed
by the characters in the
argument.

(i) String toLowerCase( ), Returns a new String object


with the case of all letters
(j) String toUpperCase( )
changed. Uses the old
String if no changes need to
be made.

(k) String trim( ) Returns a new String object


with the whitespace
removed from each end.
Uses the old String if no
changes need to be made.

116
(l) String valueOf(int i ) Returns a String containing
a character representation
(m) String valueOf(double d )
of the argument.
(n) String valueOf(float f)
(o) String valueOf(long l)
(p) String valueOf(Object obj)
String valueOf(char[] c)

Example for demonstrating the use of String :

stringdemo.java

public class stringdemo


{
public static void main(String args[])
{
String s1="Hello Jerald";
System.out.println("length of the String is:"+s1.length());
System.out.println("Display Character by character");
for(int i=0;i<s1.length();i++)
{
System.out.println(s1.charAt(i));
}
System.out.println("Substring is :"+s1.substring(5,9));
System.out.println("Uppercase :"+s1.toUpperCase());
System.out.println("Lowercase :"+s1.toLowerCase());
String s=" Hello Jerald ";
System.out.println("Before trimming the String" +s);
System.out.println("After trimming the string is :"+s.trim());
String s2="hello jerald";
System.out.println("Equal case");
if(s1.equals(s2))
{

117
System.out.println("They are equal");
}
else
{
System.out.println("They are not equal");
}
System.out.println("Equal Ignore Case");
if(s1.equalsIgnoreCase(s2))
{
System.out.println("They are equal");
}
else
{
System.out.println("They are not equal");
}
}
}

Explanation:
The above program creates string and prints the length of the string by
using the method length(). Then each and every character from the string is
taken and printed. substring() methods extracts string from the main methods
and prints the characters between 5 and 9. toUpperCase() and toLowerCase()
method converts all the string from lowercase to uppercase and vice versa.
trim() method trims the whitespace before and after the string. The string
objects s1 and s2 have the same content but the case is different. The equals()
method expects the hashcodes of these two objects are different. Therefore
equals() method returns the false. The other function equalsIgnoreCase()
method checks whether the character contents of the two strings are same,
ignoring case. So it returns true in this case.
The StringBuffer Class:
i) StringBuffer is a peer class of String. While String creates strings
of fixed length. StringBuffer creates flexible strings that can be
modified in terms of length and content. We can insert characters
and substrings in the middle of a string or append another string to
the end.
ii) StringBuffer defines the three constructors:

118
StringBuffer()
StringBuffer(int size)
StringBuffer(String str)
The default constructor reserves room for 16 characters without
reallocation. The second constructor accepts an Integer argument that explicitly
sets the size of the buffer. The third constructors accepts a string argument
that sets the initial contents of the StringBuffer object and reserve rooms for 16
additional character.
Methods:

• int length() It gives the Length of the StringBuffer


• int capacity() and Capacity of the StringBuffer.

• StringBuffer append(String str) The append() method concatenates the


string representation of any other type
• StringBuffer append(int i)
of data to the end of the invoking
• StringBuffer append(Object ob) StringBuffer object.

• StringBuffer insert(int index,String This insert() method inserts one string


str) into another.

This method reverses the object on


• StringBuffer reverse()
which it was called.

Example: stringBufferDemo

stringbufferdemo.java

public class stringbufferdemo


{ public static void main(String args[])
{ StringBuffer sb=new StringBuffer("Hello world");
System.out.println("Length :"+sb.length());
System.out.println("Capacity :"+sb.capacity());
System.out.println("Before Appending :"+sb);
System.out.println("Append :"+sb.append("!"));
System.out.println("Insert :"+sb.insert(0,"hi"));
System.out.println("Reverse :"+sb.reverse());

119
}
}
Output:
Length :11
Capacity :27
Before Appending :Hello world
Append :Hello world!
Insert :hiHello world!
Reverse :!dlrow olleHih

Check Your Progress : 1

List a few methods available for handling Strings.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

11.4 VECTOR CLASS

The Java Programming language does not include dynamically linked


list, queue, or other data structures. This is because Java does not support
pointers. Since it is very essential for a programming language to support
storage of objects in a dynamic array the Vector class has been designed. The
Vector class implements a dynamically allocated list of objects. The size of the
Vector can be increased or decreased according to the number of objects to be
stored.
11.4.1 Constructors present in the Vector class:

Vector() – Constructs an empty vector so that its internal data


array has size 10 and its standard capacity increment is zero.

Vector(int initialCapacity) – Constructs an empty vector with the


specified initial capacity and with its capacity increment equal to
zero.

120
Vector(int initialCapacity, int capacityIncrement) – Constructs an
empty vector with the specified initial capacity and capacity
increment.

All vectors start with an initial capacity. After the initial capacity is reached, the
next time that you attempt to store an object in the Vector, the Vector
automatically allocates space for that object plus extra room for additional
objects.
11.4.2 Methods of the Vector class are:
void addElement(Object element) – This method is used to add the specified
elemenet into the Vector.
Enumeration elements() – Returns the Enumeration of Elements in the Vector.
int size() – Returns the number of the elements present in the Vector.
Object firstElement() – Returns first Element in the Vector
Object lastElement() – Returns the last element in the Vector.
void removeAllElements() – Remove all elements of the Vector and sets its size to
zero.
void removeElementAt(int index) – Removes the element form the Vector
specified in the index.

Advantages :
• It is convenient to use vectors to store object.
• A vector can be used to store a list of objects that may vary in size.
• We can add and delete objects from the list as and when required.

Disadvantages:
Only objects can be stored in the vector. Simply data type cannot be
stored. Primitive data type converts into object by using wrapper classes.

Example: Vector Demo

vectordemo.java

import java.util.*;
public class vectordemo

121
{ public static void main(String args[])throws Exception
{ Vector v=new Vector();
v.addElement("Clinton");
v.addElement(new Integer(1));
v.addElement(new Double(6.89));
v.addElement(new Float(9.4));
System.out.println("Size of the vector is:"+ v.size());
System.out.println("First Element of the vector is
:"+v.firstElement());
System.out.println("Last Element of the Vector is:"+
v.lastElement());
Enumeration e=v.elements();
while(e.hasMoreElements())
{
System.out.println("lement os the vector is"
+e.nextElement());
}
}
}

11.5 LET US SUM UP

In this lesson we have discussed the following key points.


• An array is a group of variables referred to by a common name.
• A combination of characters is a string. Strings are instances of the class
String
• The Constructors for the String class are:
o String()
o String(String s1)
o String(StringBuffer s2)
• The Vector class implements a dynamically allocated list of objects.
• The constructors present in Vector class are ;
o Vector()
o Vector(int initialCapacity)
o Vector(int initialCapacity, int capacityIncrement)

122
11.6 CHECK YOUR PROGRESS : MODEL ANSWERS

1. Some of the methods available for handling strings are :


(q) int length( ), char charAt(int index ), char[] toCharArray( ),
(r) boolean equals(Object anobject ), boolean equalsIgnoreCase(String
anotherstring ), int CompareTo(String str),
(s) substring(int beginindex, int endindex), String concat(String str),
(t) String toLowerCase( ), String toUpperCase( ),
(u) String trim( )

11.7 PROGRAMMING EXERCISES

1. Write a Java Program to Define an array of 10 elements and find


the largest and second largest of them.
2. Write a Java program to read a string and check whether it is a
palindrome.
3. Write a Java program to sort a set of numbers in ascending order.

123
124
125
LESSON 12

INTERFACES

CONTENTS
12.0 Aims and Objectives
12.1 Introduction
12.2 Characteristics of an Interface
12.3 Defining an interface
12.4 Implementing Interfaces
12.5 Accessing Implementations through Interface References
12.6 Tagging Interfaces
12.7 Let us sum up
12.8 Check Your Progress: Model Answers

12.0 AIMS AND OBJECTIVES

The objective of this lesson is to make the learner understand the


concept of Interfaces. Since interface helps effective utilization of prewritten
code during run time, it will be helpful for the Java programmer to develop
efficient Java Programs.
At the end of this lesson the reader will be able to define and implement
his own interfaces.

12.1 INTRODUCTION

An interface is a list of methods that must be defined by any class which


implements that interface. It may also define constants (public static final).
Interfaces are designed to support dynamic method resolution at run
time. Normally, in order for a method to be called from one class to another,
both classes need to be present at compile time so the Java complier can check
to ensure that the method signatures are compatible. This requirement by itself
makes for a static and nonextensible classing environment.
Inevitably in a system like this, functionality gets pushed up higher and
higher in the class hierarchy so that the mechanisms will be available to more
and more subclasses. Interfaces are designed to avoid this problem. They
disconnect the definition of a method or set of methods from the inheritance
hierarchy. Since interfaces are in a different hierarchy from classes, it is
possible for classes that are unrelated in terms of the class hierarchy to

126
implement the same interface. This is where the real power of interfaces is
realized.
Using the keyword interface, it is possible to fully abstract a class
interface from its implementation. That is, using interface, it is possible to
specify what a class must do, but not how it does it. Interfaces are syntactically
similar to classes, but they lack instance variables, and their methods are
declared without any body. In practice, this means that it is possible to define
interfaces, which don’t make assumptions about how they are implemented.
Once it is defined, any number of classes can implement an interface. Also, one
class can implement any number of interfaces.

12.2 CHARACTERISTICS OF AN INTERFACE

Similar to abstract class. An interface is similar to a class without


instance and static variables (static final constants are allowed), and without
method bodies. This is essentially what a completely abstract class does, but
abstract classes do allow static method definitions, and interfaces don't.
When a class specifies that it implements an interface, it must define all
methods of that interface. A class can implement many different interfaces. If a
class doesn't define all methods of the interfaces it agreed to define (by the
implements clause), the compiler gives an error message, which typically says
something like "This class must be declared abstract". An abstract class is one
that doesn't implement all methods it said it would. The solution to this is
almost always to implement the missing methods of the interface.
A very common use of interfaces is for listeners. A listener is an object
from a class that implements the required methods for that interface. You can
create anonymous inner listeners, or implement the required interface in any
class.
Interfaces are also used extensively in the data structures (Java
Collections) package.
To implement an interface, a class must create the complete set of
methods defined by the interface. However, each class is free to determine the
details of its own implementation. By providing the interface keyword, Java
allows to fully utilize the “ one interface, multiple methods” aspect of
polymorphism.
Classes versus Interfaces
Classes are used to represent something that has attributes (variables,
fields) and capabilities/responsibilities (methods, functions). Interfaces are only
about capabilities. For example, you are a human because you have the
attributes of a human (class). You are a teacher because you have the ability of
a teacher (interface). You can also be an programmer (interface). You can
implement many interfaces, but be only one class.
Interfaces replace multiple inheritance
Simpler. A C++ class can have more than one parent class. This is called
multiple inheritance. Managing instance variable definitions in multiple

127
inheritance can be really messy, and leads to more problems than solutions.
For this reason Java designers chose to allow only one parent class, but allow
multiple interfaces. This provides most of the useful functionality of multiple
inheritance, but without the difficulties.

12.3 DEFINING AN INTERFACE

An interface is defined much like a class.


The general form of an interface is :
interface interfacename
{
variable declaration;
method declaration;
}
Here, access is either public or not used. When no access specifier is
included, then default access results, and the interface is only available to other
members of the package in which it is declared. When it is declared as public,
the interface and can be used by any other code. ‘Name’ is the name of the
interface; any can be any valid identifier. Notice that the methods, which are
declared, have no bodies. They end with a semicolon after the parameter list.
They are, essentially, abstract methods; there can be no default implementation
of any method specified within an interface. Each class that includes an
interface must implement all of the methods.

12.4 IMPLEMENTING INTERFACES

Once an interface has been defined, one or more classes can implement
that interface. To implement an interface, include the implements clause in a
class definition, and then create the methods defined by the interface.
The general form of a class that includes the implements clause looks like this:
access class classname [extends superclass] [implements interface
[,interface...]]
{
// class-body
}
Here, access is either public or not used. If a class implements more
than one interface, the interfaces are separated with a comma. If a class
implements two interfaces that declare the same method, then the same
method will be used by clients of either interface. The methods that implement
an interface must be declared public. Also, the type signature of the
implementing method must match exactly the type signature specified in the
interface definition.

128
Example for implementing the interface :

Umydisplay.java
public interface Umydisplay
{
public void display();
}

uclass1.java
public class uclass1 implements Umydisplay
{
int a;
public uclass1()
{
a=10;
}
public void diplay()
{
System.out.println(a);
}
public static void main(String args[])
{
uclass1 u=new uclass1();
u.display();
}
}

uclass2.java
public class uclass2 implements Umydisplay

129
{
String s;
public uclass2()
{
s=new String(“Some String”);
}
public void display()
{
System.out.println(s);
}
public static void main(String args[])
{
uclass1 u=new uclass1();
u.display();
}
}
Note: A class implementing an interface has to override all the methods
in that interface. A class can implement any number of interfaces.

In the above example uclass1 has an int data member, which gets
initialized in the constructor. And in the uclass2 also implements the same
interface. But public function display, in this class, is used for displaying a
string.

Check Your Progress : 1

What is the general format for defining and implementing an interface.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

130
12.5 ACCESSING IMPLEMENTATIONS THROUGH INTERFACE REFERENCES

It is possible to declare variables as object references that use an


interface rather than a class type. Any instance of any class that implements
the declared interface can be referred to by such a variable. When a method is
called through one of these references, the correct version will be called based
on the actual instance of the interface being referred to. This is one of the key
features of interfaces.
The method to be executed is looked up dynamically at run time,
allowing classes to be created later than the code which calls methods on them.
The calling code can dispatch through an interface without having to know
anything about the “callee.” This process is similar to using a superclass
reference to access a subclass object as defined in inheritance

12.6 TAGGING INTERFACES

Java defines a few interfaces that are just used as a boolean property of a
class, but don't actually require the implementation of any methods. These are
called tagging interfaces.
Tagging interfaces are an abuse of the interface principle, but Java
makes use of object-oriented features to solve all problems if possible, rather
than invent a more appropriate feature.
Common tagging interfaces that are available in Java are:
Cloneable Implementing this interface indicates that the class has
overridden Object's clone() method. But there is no check that this is
true, and because subclasses inherit interfaces, it will look like all
subclasses have defined clone() although that is not necessarily true. .
Serializable This tagging interface indicates that a class can serialized -
that an object of this class can be written out and read back.. This can
be useful for short-term storage of objects, but should not be used for
long-term storage because any change to the class definition makes that
persistent copy unreadable.

12.7 LET US SUM UP

In this lesson we have learnt the following concepts which are related with
interfaces :
• An interface is a list of methods that must be defined by any class which
implements that interface.
• Using interface, it is possible to specify what a class must do, but not
how it does it.
• An interface is similar to a class without instance and static variables
(static final constants are allowed), and without method bodies
• A very common use of interfaces is for listeners.

131
• Interfaces are also used extensively in the data structures (Java
Collections) package.
• Common tagging interfaces that are available in Java are Cloneable,
and Serializable

12.8 CHECK YOUR PROGRESS : MODEL ANSWERS

1. The general form for defining an interface is :


interface interfacename
{
variable declaration;
method declaration;
}

The general form of a class that includes the implements clause is:
access class classname [extends superclass] [implements interface
[,interface...]]
{
// class-body
}

132
133
LESSON 13

INHERITANCE
CONTENTS
13.0 Aims and Objectives
13.1 Introduction
13.2 Types of inheritance
13.3 Advantages of Inheritance
13.4 Abstract Class
13.5 Let us sum up
13.6 Check Your Progress: Model Answers
13.7 Programming Exercises

13.0 AIMS AND OBJECTIVES

The aim of this lesson is to introduce the concept of inheritance. The two
types of inheritance are discussed with suitable examples in this lesson. At the
end of this lesson the learner will be able to understand the concepts of
inheritance and apply it while developing Java programs.

13.1 INTRODUCTION

Inheritance is one of the cornerstones of object-oriented programming. It


allows the creation of hierarchical classifications. Using inheritance, it is
possible to create a general class that defines traits common to a set of related
items.
In Java terminology, a class that is inherited is called a super class and
the class that does the inheriting is called a subclass. It inherits all of the
instance variables and methods defined by the super class and add its own
unique elements.

13.2 TYPES OF INHERITANCE

Single inheritance: If a subclass is derived from a single super class, single


inheritance is said to take place.
Multiple inheritance: If a subclass is derived from more than one super class,
multiple inheritance is said to take place. It is important to note that Java does
not support multiple inheritance.

13.3 ADVANTAGES OF INHERITANCE

One of the major advantages of inheritance is the reusability of code. i.e.,


once a class is defined and debugged, it can be used to create new subclasses.

134
In addition to saving time, a lot of manual work involved in retyping the code
gets reduced.
Data and methods of the super class are physically available to all its
subclasses. However if a variable is declared private, it is not possible to access
them in the derived classes.
Example:

Person.java

class Person
{
String name;
int age;
Person(String name,int age)
{
this.name=name;
this.age=age;
}
public void validateAge()
{
if(age<0||age>100)
{
System.out.println("Not a valid age");
}
}
public void display()
{
System.out.println("Name is :"+name);
System.out.println("Age is :"+age);
}
}

emp.java

135
class emp extends Person
{
int eno;
int sal;
emp(String n, int a, int eno, int sal)
{
super(n,a);
eno=eno;
sal=sal;
}
public void display()
{
super.display();
System.out.println("Emp no is :"+eno);
System.out.println("Emp sal is :"+sal);
}
public static void main(String a[])
{
emp e=new
emp(a[0],Integer.parseInt(a[1]),Integer.parseInt(a[2]),Integer.parseInt(a[3]));
int age1=Integer.parseInt(a[1]);
if(age1<0||age1>100)
{
e.validateAge();
}
else
{
e.display();
}
}
}

136
Check Your Progress : 1

List the different types of inheritance.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this unit.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

Multiple Hierarchy:
All the preceding discussions are concerned with one level of hierarchy.
i.e. a derived class extended from a superclass. However, based on
requirements, we can build hierarchies that contain as many layers of
inheritance. It is perfectly acceptable to use a subclass as a superclass for
another.
Example: Multilevel Hierarchy

circle.java

class circle
{
int r;
double p=3.14;
double a;
void area ()
{
a=p*r*r;
System.out.println("The area of the circle is :"+a);
}

137
}

cylinder.java
class cylinder extends circle
{
int r,h;
double v,ar;
public cylinder(int r1,int h1)
{
super.r=r1;
h=h1;
r=r1;
}
void area()
{
ar=2*p*r*(r+h);
System.out.println(" the area of the cylinder is :"+ar);
}
void vol()
{
v=(4*p*r*r*h)/3;
System.out.println("The volume of the cylinder is :"+v);
}
}

somecylinder.java
class somecylinder extends cylinder
{
int r,h;
double v;
public somecylinder(int r1,int h1)

138
{
super(r1,h1);
h=r1;
r=r1;
}
void volume()
{
v=4*(p*r*r*h)/3;
System.out.println("The volume of the some cylinder is :"+v);
}
}

simple.java
public class simple
{
public static void main(String a[])
{
somecylinder sph=new somecylinder(5,6);
sph.volume();
sph.vol();
sph.area();
}
}

13.4 ABSTRACT CLASS

An abstract class declares only the structure without providing a


complete implementation of every method. It provides a class declaration that
cannot be instantiated. In general, abstract classes are used as building blocks
for declaring subclasses.
Abstract classes are specified using the abstract keyword. Abstract
classes are incomplete and hence their instances are impossible. The compiler
ensures the purity of the abstract class by throwing an error whenever an
abstract class is instantiated.

139
An abstract method is incomplete; it has only a declaration and no
method body. A class having at least one abstract method can be declared as
abstract.
abstract void x();
Even if the class contains no abstract method, it can be declared as abstract.

Example for use of abstract class:

shape.java

abstract class shape


{
int r,h;
double p=3.14;
double v,ar;
public shape(int r1,int h1)
{
h=h1;
r=r1;
}
void area()
{
ar=(r*h)/2;
System.out.println(“ the area is “+ar +” sqm”);
}
abstract void volume();
}

cylinder.java
class cylinder extends shape

140
{
int r,h;
double v,s;
public cylinder(int r1,int h1)
{
super(r1,h1);
h=h1;
r=r1;
}
void volume()
{
v=4*(p*r*r*h)/3;
System.out.println(“The volume of the cylinder is : “+v+ “ cubic
meters”);
}
void surface()
{
s=2*p*r*(r+h)/3;
System.out.println(“The surface area of cylinder sphere is :”+s+”
square meters”);
}
}

simple.java
public class simple
{
public static void main(String a[])
{
cylinder1 sph=new cylinder1(5,4);
sph.area();
sph.volume();
sph.surface();

141
}
}

142
Garbage Collection:
Since the objects are dynamically allocated by using the new operator, it
is necessary to know how objects are destroyed and their memory released for
later reallocation. In some languages, such as C++, dynamically allocated
objects must be manually released by use of a delete operator. Java takes a
different approach; it handles deallocation automatically. The technique that
accomplishes this is called garbage collection. It works like this: when no
references to an object exist, that object is assumed to be no longer needed, and
the memory occupied by the object can be reclaimed. There is no explicit need
to destroy objects as in C++. Garbage collection only occurs sporadically (if at
all) during the execution of your program. It will not occur simply because one
or more objects exist that are no longer used. Furthermore, different Java run-
time implementations will take varying approaches to garbage collection.

The finalize () Method


There are a few situations in which a class needs to clean itself up before
garbage collection. Finalizers are called just before a class is garbage collected.
They are normally used for closing open files and database connection.
Sometimes an object will need to perform some action when it is
destroyed. For example, if an object is holding some non-Java resource such as
a file handle or window character font, then you might want to make sure these
resources are freed before an object is destroyed. To handle such situations,
Java provides a mechanism called finalization. By using finalization, you can
define specific actions that will occur when an object is just about to be
reclaimed by the garbage collector. To add a finalizer to a class, simply define
the finalize ( ) method. The Java run time calls that method whenever it is
about to recycle an object of that class. Inside the finalize() method you will
specify those actions that must be performed before an object is destroyed. The
garbage collector runs periodically, checking for objects that are no longer
referenced by any running state or indirectly through other referenced objects.
Right before an asset is freed, the Java run time calls the finalize( ) method on
the object.
The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize() by
code defined outside its class.
It is important to understand that finalize() is only called just prior to garbage
collection. It is not called when an object goes out-of-scope, for example. This
means that you cannot know when-or even if - finalize( ) will be executed.

143
Therefore the program should provide other means of releasing system
resources, etc., used by the object. It must not rely on finalize( ) for normal
program operation.

13.5 LET US SUM UP

In this lesson we have discussed the concept of inheritance and the


various methods of implementations. We have also discussed the following
points :
• Using inheritance, it is possible to create a general class that defines
traits common to a set of related items.
• The main advantage of inheritance is the reusability of code
• In Java terminology, a class that is inherited is called a super class and
the class that does the inheriting is called a subclass
• Single inheritance: If a subclass is derived from a single super class,
single inheritance is said to take place.
• Multiple inheritance: If a subclass is derived from more than one
super class, multiple inheritance is said to take place. It is important to
note that Java does not support multiple inheritance.
• An abstract class declares only the structure without providing a
complete implementation of every method. It provides a class declaration
that cannot be instantiated.

13.6 CHECK YOUR PROGRESS : MODEL ANSWERS

1. The types of inheritance are


a. Single inheritance
b. Multiple inheritance (not available in Java).

13.7 PROGRAMMING EXERCISES

1. A student walks into a college for registration. When he gets registered, he


will get a registration number. The college has three departments-science,
commerce and arts. The student has to choose a specific department. He gets a
department id at the time of selecting the department id. Every department has
two sections. The student also gets a section id.

Create a class hierarchy for the above case.

144
{
public static void main(String a[])
{
Protection p1=new Protection();
derived d1=new derived();
nonderived d2=new nonderived();
}
}

package p2;
import p1.*;
class derived2 extends Protection
{
public derived2()
{
System.out.println("Derived class execution");
System.out.println("public x =:"+pub_x);
System.out.println("protected x= "+pro_x);
}
}

package p2;
import p1.Protection;
class nonderived2
{
public nonderived2()
{
System.out.println("NonDerived class execution");
Protection p=new Protection();
System.out.println("public x =:"+p.pub_x);
}
}

145
package p2;
public class demo5
{
public static void main(String a[])
{
derived2 d1=new derived2();
nonderived2 d2=new nonderived2();
}
}

14.4 LET US SUM UP

In this lesson we have learnt the following:


• Packages are containers for classes that are used to keep the class name
space compartmentalized.
• The modifiers available in Java are Abstract, Static, Public, Protected,
Private, Synchronized, Native, Transient, Final.
• Packages are stored in a hierarchical manner and are explicitly imported
into new class definitions.
• The sub packages available in Java are Java.lang, Java.awt, Java.io,
Java.net, Java.applet, Java.util, Java.rmi, Java.sql

14.5 CHECK YOUR PROGRESS: MODEL ANSWERS

1. The modifiers available in Java are Abstract, Static, Public, Protected,


Private, Synchronized, Native, Transient, Final.
2. Following are the steps involved in creating a package :
a. Declare the package at the beginning of a file using the form :
package <packagename>
b. Define the class that is to be put in the package and declare it
public.
c. Create the subdirectory under the directory where the main
source files are stored.
d. Store the listing as the class name java file in the subdirectory
created.
e. Compile the file. This creates the class file in the sub-directory.

146
14.6 PROGRAMMING EXERCISES

1. Create a package called institute. Create two classes called teacher and
student. The teacher class must have variable for storing the values of
salary, allowances and income tax.
The student class should have variables for storing the values name,
marks in three subjects, tuition fees, lab fees etc. Create a class called
profit that uses the classes of this package to calculate the average
marks secured by a student and to the total salary paid by the
organization.
2. Create an abstract class for employee and interface for clubmember. The
employee class should contain signature for methods to accept employee
details and print them. The interface member contains methods to accept
membership detail. The abstract class and interface should be contain
in package. Create the class, which accepts the details for the employee,
and ask if he/she is a member. If yes then accept the membership
details.
The employee details could include employee number, name,
department, designation, and salary.
The membership details could include membership number, joining
date, sport interested in.

147
LESSON 15

MULTITHREADED PROGRAMMING
CONTENTS
15.0 Aims and Objectives
15.1 Introduction
15.2 The Thread life cycle
15.3 The thread control methods
15.4 Creating a thread
15.5 Thread Class
15.6 Runnable Interface
15.7 Scheduling and priority
15.8 Thread group
15.9 Thread Daemon
15.10 Let us sum up
15.11 Check Your Progress: Model Answers

15.0 AIMS AND OBJECTIVES

In this lesson we introduce the concept of threads which is used for


multitasking. We also learn the life cycle of the thread and the way in which it
is implement. We will also learn the different methods that are used for
multitasking.
At the end of this lesson the learner will be able to write multithreaded
program in Java.

15.1 INTRODUCTION

A thread is a single sequence of execution within a program. When a


language supports multithreading, it means that the language allows creating
multiple threads and controlling execution of the same. One of the
characteristics that make Java a powerful programming language is its support
of multithreaded programming as an integral part of the language.
Multitasking refers to a computer’s ability to perform multiple jobs
concurrently. Modern desktop operating system like Windows 95, OS/2, Unix
has the ability to run two or more programs at the same time.
Multiprocessing refers the ability of the machine to run more than one
process in more than processor.
There are two ways of employing multitasking. One is process based
multitasking and the other is Thread based multitasking. In the former the

148
priority and scheduling is given to the process. The process becomes the
smallest unit of executable code. In a Thread based multitasking the single
process is further broken down in to smaller units of executable codes called
threads. In one perspective, thread can be considered as one more process,
which is waiting to be scheduled by the OS scheduler. The only difference is
that all the threads pertaining to a particular process runs in the same memory
space. The priority can be modified to a smaller extent within a program.
Main thread
All programs follow a line of execution, which is called a thread. Though
a new thread is created or not a default thread will always be created. This
default thread is the main thread. All the other user-defined threads will be
spawned from this thread. Care should be taken that all the child threads
spawned by the main thread should complete its execution before the main
thread finishes its execution. If the main thread completes its execution before
its child thread the program goes for an infinite loop.

15.2 THE THREAD LIFE CYCLE

Every thread, after creation and before destruction, will always be in one
of four states: newly created, runnable, blocked, or dead. These states are
illustrated in the following figure 15.1 and described in the following section.

Suspend(), wait(),
sleep(), I/O blocking
start() c) N
a) N b) R o
e u

resume(),notify(),
sleep(),I/O Finished.

Dead
stop() stop() stop()

(i) Figure15.1 Life cycle of a thread

15.3 THE THREAD-CONTROL METHODS

There are many methods defined in the Thread class to control the
running of a thread. Here are some of the commonly used methods :

149
start() Used to start the execution of the thread body defined in the run()
method. Program control will be immediately returned to the caller, and a
new thread will be scheduled to execute the run() method concurrently
with the caller’s thread.
stop() Used to stop execution of the thread no matter what the thread is doing.
The thread is then considered dead, the internal states of the thread are
cleared, and the resource allocated is reclaimed.
suspend() Used to temporarily stop the execution of the thread. All the states
and resources of the thread are retained. The thread can later be
restarted by another thread calling the resume() method.
resume() Used to resume the execution of a suspended thread. The
suspended thread will be scheduled to run. If it has a higher
priority than the running thread, the running thread will be
preempted; otherwise, the just-resumed thread will wait in the
queue for its turn to run.
The above two methods are deprecated because they are deadlock-prone. When
the desired state is suspend, the thread waits using Object.wait. When the
thread is resumed, the target thread is notified using Object.notify.
sleep(long sleep_time_in_milliseconds) A class method that causes the
Java runtime to put the caller thread to sleep for a specified time period.
The exception, InterruptedExecution, may be thrown while a thread is
sleeping. Either a try-catch-finally statement needs to be defined to
handle this exception or the enclosing method needs to have this
exception in the throws clause.
join() Used for the caller’s thread to wait for this thread to die-for example, be
coming to the end of the run() method.
yield() A class method that temporarily stops the caller’s thread and put it at
the end of the queue to wait for another turn to be executed. It is used to
make sure other threads of the same priority have the chance to run.
Example : Following is the program, which creates a thread subclassing
from the Thread class.

UserThread.java
public class UserThread extends Thread
{
public void run()
{
for(int i=0; i<100; i++)
{
System.out.print("i = " + i + " ");

150
}
}
public static void main(String args[])
{
UserThread u1 = new UserThread();
u1.start();
}
}

15.4 CREATING A THREAD

The process of creating new threads involves two steps: writing the code
that is executed in thread and writing the code that starts the thread.
When a main() function is written, that method is executed in a single
thread. Although the Java virtual machine provides a multithreaded
environment, it starts user applications by calling main() in a single thread. An
application’s main() method provides the central login for the mail thread of the
application. Writing the code for a thread is similar to writing main().
The main thread spawns a new thread. All threads start with a method,
which has the following prototype:
public void run();
Notice that the run() method is not a static method, the main() method is
static because an application starts with only one main(). But an application
may have many threads, so the main logic for a thread is associated with an
object – the Thread object. Implementation for the run() method can be provided
in two ways.
Java supports the run() method which is subclasses of Thread class.
Java also supports run() through the Runnable interface. Both methods for
providing a run() method implementation are described in the following sections.
In Java whenever a class is instantiated a separate memory space is
allocated for the object. The methods are invoked and executed from that
memory space. This execution of the methods of that particular class can be
done concurrently with the methods of other objects. So if an object has the
ability to run its methods concurrently or in parallel with the methods of other
objects then it means that the object runs in a separate thread. To enable an
object to rub as thread the class should be either extended from the Thread
class or it should have implemented Runnable interface.
Check Your Progress : 1

List a few methods available for implementing threads in Java.

Notes : a) Write your answer in the space given below.

151
b) Check your answer with the one given at the end of this unit.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

15.5 THREAD CLASS

A new thread can be created by subclassing java.lang.Thread. The


Thread class is the objectification of a Java sequence of control. When a
subclass of the Thread class is created, the subclass will override the run()
method of the Thread class. The complete task of the thread is coded in the
run() method. In other way it can be said that run() will be the first method to be
called in a thread object. The run() method gets executed when the call to the
start() method is made using the thread object.
Constructors
The Thread class has seven different constructors:
public Thread();
public Thread(Runnable target);
public Thread(Runnable target, String name);
public Thread(String name);
public Thread(ThreadGroup group, Runnable target);
public Thread(ThreadGroup group, Runnable target, String name);
public Thread(ThreadGroup group, String name);
These constructors represent most of the combinations of three different
parameters; thread name, thread group, and a Runnable target object. To
understand the three constructors, one must understand the parameters:
• Name is the (string) name to be assigned to the thread. If name is not
specified, the system generates a unique name of the form Thread-N,
where N is a unique integer.
• Target is the Runnable instance whose run() method is executed as the
main method of the thread.
• Group is the ThreadGroup to which this thread will be adder. (The
ThreadGroup class is discussed in detail later in the chapter.)
Constructing a new thread does not begin the execution of that thread. To
launch the Thread object, the start() method has to be invoked.
Example: Simple Thread Demo

152
SimpleThreadDemo.java

import java.io.*;
public class SimpleThread extends Thread
{
public SimpleThread(String s)
{
super(s);
}
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(i + " " + getName());
try
{
sleep((int)(Math.random() * 1000));
}catch(InterruptedException ex) { }
}
System.out.println("DONE! " +getName());
}
public static void main(String args[]) throws Exception
{
String s1,s2,s3;
byte b[]=new byte[20];
System.out.println("Enter three places where you want to
visit :");
System.out.print("1st option : ");
System.in.read(b);
s1=new String(b);
System.out.print("2nd option : ");
System.in.read(b);

153
s2=new String(b);
System.out.print("3rd option : ");
System.in.read(b);
s3=new String(b);
new SimpleThread(s1).start();
new SimpleThread(s2).start();
new SimpleThread(s3).start();
}
}

Explanation:
 This example helps you in deciding where to go for vacation. It asks the
user the destinations by using the concepts of threads, then it picks up
one location randomly.
 The first method in the SimpleThread class is a constructor that takes a
string as its only argument. This constructor is implemented by calling a
super class constructor and it sets the thread’s name, which used later
in the program.
 The next method in the SimpleThread class is the run method. The run
method is the heart of any Thread and where the action of the Thread
takes place. The run method of the SampleThread class contains a for
loop that iterates ten times. In each iteration the method displays the
iteration number and the name of the thread, then sleeps for a random
interval of up 1 second. After the loop has finished, the run method
prints DONE! Along with the name of the thread.

15.6 RUNNABLE INTERFACE

The runnable interface requires only one method to be implemented – the


run() method. You first create an instance of this class with a new statement,
followed by the creation of the Thread instance with another new statement,
and finally a call to this thread instance’s start() method defined within it must
be passed in as an argument to creating the thread instance so that when the
start() method of this Thread instance is called, Java runtime knows which run()
method to execute.
The alternative way of creating a thread comes in handy when the class
defining the run() methods of the superclass, and the Thread instance just
created can be used for thread control.
class newclass implements Runnable
Then an instance of the class is created and passed to a newly created Thread
instance, followed by a call to the start() method to start the execution of the
run() method as follows:

154
newclass p=new newclass();
Thread t=new Thread(p);
t.start();
Example: Stop, Start, Resume and Suspend method of the Thread

ThreadAWT.java

import java.awt.*;
import java.awt.event.*;
public class ThreadAWT extends Frame implements
Runnable,ActionListener
{ int cnt=0;
Panel p1;
TextField tf1;
Button btnsuspend;
Button btnresume;
Button btnstart;
Button btnstop;
Thread tg;
public ThreadAWT()
{ tg=new Thread(this);
p1=new Panel();
tf1=new TextField(10);
btnsuspend=new Button("Suspend");
btnresume=new Button("Resume");
btnstart=new Button("Start");
btnstop=new Button("Stop");
p1.add(tf1);
p1.add(btnsuspend);
p1.add(btnresume);
p1.add(btnstart);
p1.add(btnstop);
add(p1);

155
btnsuspend.addActionListener(this);
btnresume.addActionListener(this);
btnstart.addActionListener(this);
btnstop.addActionListener(this);
pack();
setVisible(true);
}
public void run()
{ while(true)
{
cnt++;
tf1.setText(Integer.toString(cnt));
}
}
public void actionPerformed(ActionEvent ae)
{ if(ae.getSource()==btnsuspend)
tg.suspend();

if(ae.getSource()==btnresume)
tg.resume();

if(ae.getSource()==btnstart)
tg.start();

if(ae.getSource()==btnstop)
tg.stop();
}
public static void main(String args[])
{
ThreadAWT ta=new ThreadAWT();
}
}

156
Output:

Explanation:
The above program shows the implementation of the thread control
mechanism. The applet has a textfield, which displays a count of
numbers. The starting, stopping, suspending and the resumption of the
thread are executed as the button click event of the various button.

15.7 SCHEDULING AND PRIORITY

Priorities are used to ensure that important and time critical threads are
executed frequently and immediately. Scheduling is the process of enforcing the
priorities. The main activity is to determine the execution order and the time
slice of each thread in a multithreaded environment.
Thread Priority
Most computer configuration have a single CPU, so threads actually run
one at a time in such a way as to provide an illusion of concurrency. Execution
of multiple threads on a single CPU, in some order, is called scheduling. The
Java runtime supports a very simple, deterministic scheduling algorithm known
as fixed priority scheduling. This algorithm schedules threads based on their
priority relative to other Runnable threads.
When a Java thread is created, it inherits its priority from the thread that
created it. You can also modify a thread’s priority at anytime after its creation
using the setPriority method. Thread priorities are integers ranging between
MIN_PRIORITY and MAX_PRIORITY (constants defined in the Thread class).
The higher the integer, the higher the priority. At any given time, when multiple
threads are ready to be executed, the runtime system chooses the Runnable
thread with the highest priority for execution. Only when that thread stops,
yields or becomes not Runnable for some reason will a lower priority thread
start executing. If two threads of the same priority are waiting for the CPU, the
scheduler chooses one of them to run in a round-robin fashion. The chosen
thread will run until one of the following conditions is true.
 A higher priority thread becomes Runnable.
 It yields, or its run method exits.
 On systems that support time-slicing, its time allotment has expired.
Then the second thread is given a chance to run, and so on, until the
interpreter exits.
The Java runtime system’s thread scheduling algorithm is also
preemptive. If at any time a thread with a higher priority than all other
Runnable threads becomes Runnable, the runtime system chooses the new

157
higher priority thread for execution. The new higher priority thread is said to
preempt the other threads.
Java permits us to set the priority of a thread using the setPriority () method:
ThreadName.setPriority (intNumber);
The intNumber is an integer value to which the thread’s priority is set. The
Thread class defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY =5
MAX_PRIORITY = 10
The intNumber may assume one of these constants or any value between 1 and
10.The default setting is NORM_PRIORITY.
Thread Schedule
Thread scheduling is the mechanism used to determine how RUNNABLE
threads are allocated CPU time ( that is, when the actually get to execute for a
period of time on the computer’s CPU), in general, scheduling is a complex
subject that uses terms such as preemptive, round robin scheduling, priority-
based scheduling, time-sliced, and so on.
Scheduling can be broadly classified as
 Preemptive Scheduling
 Non-preemptive Scheduling
In Preemptive Scheduling, the thread scheduler preempts (pause) a
running thread to allow different threads to execute. A Non-preemptive
scheduler never interrupts a running thread; instead, the non-preemptive
scheduler relies on the running thread to yield control, which goes to the CPU
so that other threads may execute. Under non-preemptive scheduling, other
threads may starve(never get CPU time) if the running thread fails to yield.

15.8 THREAD GROUP

Every Java thread is a member of a thread group. Thread groups provide


a mechanism for collecting multiple threads into a single object and
manipulating those threads all at once, rather than individually. For example, it
is possible to start or suspend all the threads within a group with a single
method call. Java thread groups the implemented by the ThreadGroup class in
the java.lang package.
The runtime system puts a thread into a thread group during thread
construction. When you create a thread, you can either allow the runtime
system to put the new thread in some reasonable default group or you can
explicitly set the new thread’s group. The thread is a permanent member of
whatever thread group it joins upon its creation—you cannot move a thread to
a new group after the thread has been created.

158
15.9 THREAD DAEMON

Daemon Threads are the service threads intended to provide services to


other threads. Normally the Daemon threads run as endless loop waiting for
other threads requests. These threads run in background and wake up in
regular intervals to provide service to other requesting threads. When only
daemon threads remain alive, and all the other threads exit the Java virtual
machine process also exists.
boolean isDaemon();
void setDaemon(boolean on);
A classic example of the daemon thread is the garbage collection thread
provided by the JVM. This thread runs in the background whenever JVM
executes any Java code. The basic operation of this thread is to destroy any
objects whenever the objects usage is over. This exists when no other thread is
running or the main thread exits.
The setDaemon() method sets the daemon status of this thread. . The
information whether the thread is daemon or not is found by isDaemon()
method.The isDaemon() method returns true if this thread is a daemon thread;
it returns false otherwise.

15.10 LET US SUM UP

In this lesson we have discussed the following points:


 A thread is a single sequence of execution within a program.
 Multitasking refers to a computer’s ability to perform multiple jobs
concurrently
 Multiprocessing refers the ability of the machine to run more than one
process in more than processor.
 Every thread, after creation and before destruction, will always be in one
of four states: newly created, runnable, blocked, or dead.
 The methods available in thread class are start(), stop(), suspend(),
resume(), sleep(), join(), yield().
 Thread groups provide a mechanism for collecting multiple threads into a
single object and manipulating those threads all at once, rather than
individually.
 Daemon Threads are the service threads intended to provide services to
other threads

15.11 CHECK YOUR PROGRESS: MODEL ANSWERS

1. The methods available for implementing thread class are start(), stop(),
suspend(), resume(), sleep(), join(), yield().

159
LESSON 16

MANAGING ERRORS AND EXCEPTIONS

CONTENTS
16.0 Aims and Objectives
16.1 Introduction
16.2 Exception
16.3 Exception handling construct
16.4 throw clause
16.5 finally clause
16.6 User defined exception
16.7 Exception class hierarchy
16.8 Let us sum up
16.9 Check Your Progress: Model Answers

16.0 AIMS AND OBJECTIVES

Aim of this lesson is to teach the learner, the concept of handling errors.
Methods and procedures involved in handling errors in Java are discussed. At
the end of this lesson the programmer will be able to code programs which
automatically catch and handle the error during run time.

16.1 INTRODUCTION

An exception is an abnormal condition that arises in a code sequence at


run time. In other words, an exception is a run-time error. An exception
condition is a problem that prevents the continuation of the method or scope
that is currently executing. When an exceptional condition occurs, enough
information to handle the problem is not available in the current context.
Therefore processing cannot be continued.
When a program does not function the way it is expected to and crashes
without giving sufficient clues as to why it crashed, it leaves the programmer
frantically wondering what could have gone wrong. If the programming
language provides adequate support to determine what caused the crash, then
it is indulging in an activity called exception handling.

16.2 EXCEPTION

Exceptions are a subset of errors that can be handled by the


programmer. When an error occurs in the JVM, it is uncoverable and it causes
the interpreter to display the message and abruptly terminate the program,

160
whereas an exception is an abnormal condition that can be handled to prevent
the program from terminating.
A simple example is a divide by zero. It is better to check the
denominator before proceeding with the division, as a program will crash if
there is a division by zero. But if this happens unintentionally and
unexpectedly, an exception must be thrown rather than continuing along that
path.
Some instances of abnormal conditions could be:
• The class file to be loaded is missing.
• The other end of the network connection is nonexistent.
• The network connection got disrupted due to some mysterious reasons.
• An array element index exceeding the array size is given.
Importance of Error Handling:
Exception handling provides the Java programmer with three distinct
advantages over traditional error-handling techniques:
• It provides a means to separate error-handling code from the functional
part of the program.
• It provides a mechanism for propagating errors up the method call stack,
meaning that methods higher up the call chain can be allowed to handle
problems originating from lower down the chain.
• It provides a way to organize and differentiate between different types of
abnormal conditions.
What happens when exception is thrown?
• The exception object is created on heap with the new operator.
• The current path of execution is stopped and the handle for the
exception object is ejected from the current context.
• The exception-handling mechanism takes over and begins to look for an
appropriate place in the exception handler, whose job is to recover from
the problem so that the program can either try to execute another track
or simply continue.

16.3 EXCEPTION HANDLING CONSTRUCT

The general form of an exception handling construct is:


try
{
//Body of Program
}

161
catch (Exceptionclassname1 variablename1)
{
exception_handle_program_body_1
}
catch(Exceptionclassname2 variablename2)
{
exception_handle_program_body_1
}
finally
{
exit_program_body
}
Java provides the try block to trap exceptions. To guard against and
handle a run-time error, simply enclose the code that you want to monitor
inside a try block. Immediately after the try block, include a catch clause that
specifies the exception type that you wish to catch.
The following program includes a try block and a catch clause, which
processes the ArithmeticException generated by the division-by-zero error. Any
statement or set of statements that are likely to throw an exception are enclosed
inside a try block.
Example:

Test1.java

class test1
{
public static void main(String ar[])
{
int a=20;
int b=0;
int c;
try
{
c=a/b;

162
System.out.println("c ="+c);
}
catch(Exception e)
{
System.out.println("Exception was caught and is :");
System.out.println("e.printStackTrace() ");e.printStackTrace();
System.out.println("e.getMessage() "+e.getMessage());
System.out.println("e.toString() "+e.toString());
}
}
}

Multiple Catch Clauses:


In certain cases more than one exception could be raised by a single
piece of code. To handle such situations, you can specify two or more catch
clauses, each catching a different type of exception. When an exception is
thrown, each catch statement is inspected in order, and the first one whose type
matches that of exception is executed. After the execution of one catch
statement, the others are bypassed, and the execution continues after the
try/catch block.

multicatch.java

class multicatch
{
public static void main(String args[])
{
try
{
int x=args.length;
System.out.println("x= "+x);
int b=42/x;
int c[]={1};
c[42]=99;
}

163
catch(ArithmeticException e)
{
System.out.println("Divide by zero "+e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index oob :"+ e);
}
System.out.println("After try/catch block");
}
}

c:\>java multicatch
x=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try / catch blocks
C:\>java multicatch 3 4
x=2
Array index oob : java.lang.ArrayIndexOutOfBoundsException: 42
After try / catch blocks

This program will cause a division-by-zero exception if it is started with


no command line parameters, since it will be equal to zero. If you provide a
command line argument-setting x is larger than zero. But it will cause an
ArrayIndexOutOfBoundsEception, since array c has a length of 1.
When you use multiple catch statements, it is important to remember
that exception subclasses must come before any of their superclasses. This is
because a catch statement that uses a superclass will catch that exception type
plus any of its subclasses. Thus subclass will never be reached if it occurs after
its superclass

16.4‘throw’ CLAUSE:

The previous sections have been catching exceptions that are thrown by
the Java run-time system. However, it is possible for the program to throw an
exception explicitly, using the throw statement. The general form of throw is
throw ThrowableInstance

164
The keyword throw executes the new operator to create an object that is
not there normal program execution the constructor is called for that object.
There are two constructors in all standard exceptions, the first is the default
constructor, and the second takes a string argument so that pertinent
information can be placed in the exception.
throw new NullPointerException(“t = null”);

16.4.1 Methods of the Throwable class:


All exception classes are subclasses of throwable class. All methods
available in this class are available to all the exception classes. Some of the
important methods are.
getMessage() To obtain the error message associated with the exception.
PrintStackTrace() To print a stack trace showing where the exception
occurs:
toString() To show the exception name along with the message returned by
getMessage()

16.4.2 ‘throws’ clause:


A method that throws an exception must catch the exception. Otherwise
it should include the throws clause so that the exception can be caught by a
higher level function or by the JVM. The throws clause can be made use of as
shown below:
public void fxyz() throws IOException
{
//statement
}
public void fxyz() throws IOException,NullPointerException
{
//statements
}
In the first case, IOException is being thrown fxyz(). In the second case,
the function is capable of throwing IOException and NullPointerException.
There is an alternative usage for the throws clause. In Java, the client
programmer, who calls a method, should be informed throws clause. In Java,
the client programmer, who calls a method, should be informed of the
exceptions that might be thrown from the method. This is civilized because the
caller can know exactly what code to write to catch all potential exceptions. Of
course, if source code is available, the client programmer could hunt through
and look for throw statements, but often a library does not come with sources.

165
To prevent this, the throws clause can be used. With the throws clause, by
looking at the function, the client programmer will know as to what are the
possible exceptions.

Nested try statements:


The try can be nested. That is, a try statement can be inside the block of
another try. Each time a try statement is entered, the context of that exception
is pushed on the stack. If an inner try statement does not have a catch handler
for a particular exception, the stack is unwound and the next try statement’s
catch handlers are inspected for a match. This continues until all of the nested
try statements are exhausted. If no catch statement matches, then the Java
run-time system will handle the exception.
Example: nested try

unestedtry.java

class unestedtry
{
public static void main(String args[])
{
try
{
int a=args.length;
int b=34/a;
System.out.println("a= "+a);
try
{
if(a==1)
{
b=b/(a-a);
}
System.out.println("Check");

166
if(a==2)
{
int count[]={1};
count[42]=99;
}
System.out.println("Indispensible check again");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out of bounds ="+e);
}
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0 "+e);
}
}
}

c:\>java unestedtry
Divide by 0: java.lang.ArithmeticException: by Zero

c:\>java unestedtry a
a=1
Divide by 0: java.lang.ArithmeticException: by Zero

c:\>java unestedtry a b
a=2
Array index out of bound = java.lang.ArrayIndexOutOfBoundsException:
42

The program has nested try statements. It works as follows. It first


counts the number of command-line arguments entered. If it is zero then a
divide-by-zero exception is thrown by the first try block. If it is one then the first

167
try block throws a divide-by-zero exception. If it is two then an array boundary
exception is generated.

16.5 ‘finally’ CLAUSE

finally creates a block of code that will be executed after the completion
of the try/catch block and before the code following the try/catch block. The
finally block will execute whether or not an exception is thrown. If an exception
is thrown, the finally block will execute even if no catch statement matches the
exception.
Finally is important since it ensures the release of memory regardless of
what happens in the try block. The finally block is executed irrespective of the
catch blocks and in situations where break and continue statements are
involved. Along with the labeled break and labeled continue, finally eliminates
the need for a goto statement in Java. The following illustrates how finally
works.
If a finally block is placed after a try and its associated catch blocks,
then the code in that finally block will definitely be executed whatever the
circumstances - well, nearly definitely. If an exception arises with a matching
catch block, then the finally block is executed after the catch block. If no
exception arises, the finally block is executed after the try block. If an exception
arises for which there is no appropriate catch block, then the finally block is
executed after the try block.
Example: finally block

finallydemo.java
class finallydemo
{
static int count=0;
public static void main(String args[])
{
while(true)
{ try
{
if(count++==0)
throw new Exception();
System.out.println("No Exception");
}
catch(Exception e)
{

168
System.out.println("Exception thrown");
}
finally
{ System.out.println("Exception thrown");
if(count==2) break;
}
}
}
}

Check Your Progress : 1

What are the different blocks available for exception handling in Java.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this unit.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

16.6 USER-DEFINED EXCEPTION

There is no need for a programmer to stick only to Java exceptions. This


is important because there may be a need to create user-defined exceptions to
denote a special error that a custom library is capable of creating, but which
was not forseen when the Java hierarchy was created.

To create a user defined exception class, an existing type of exception


has to be subclassed.
Example: UserDefined Exception

myException.java
class myException extends ArithmeticException
{ myException()
{
super();

169
}
myException(String s)
{
super(s);
}
}
userDefined.java
class userDefined
{ public void sum(int a, int b)
{
int x,y,z;
z=0;
try
{ x=a;
y=b;
if(y==0)
{
throw new myException("Y should not be zero");
}
else
z=x/y;
}
catch(myException ex)
{
System.out.println(ex.getMessage());
}
finally
{
System.out.println("z= "+z);
}
}
public static void main(String args[])

170
{ userDefined ud=new userDefined();

ud.sum(Integer.parseInt(args[0]),Integer.parseInt(args[1]));
}
}

In the above program, the exception class is subclasses. This user-defined


exception class, myException has two constructors. In the other class
userDefined, a user-defined exception is thrown. The myException class will
get the methods like toString(), printStackTrace() and getMessage() from its
superclass. It can also override those methods to give its custom output.

16.7 EXCEPTION CLASS HIERARCHY

All exception types are subclasses of the built-in class Throwable.


Immediately below Throwable are two subclasses that partition exceptions into
two distinct branches. One branch is headed by Exception. This class is used
for exceptional conditions that user programs should catch. This is also the
class that you will subclass to create your own custom exception types. There is
an important subclass of Exception, called RuntimeException. Exceptions of
this type are automatically defined for the programs that is written and include
things such as division by zero and invalid array indexing.

a. Throwable

b. Exception

c. Runtime

d. ArithmeticExcep
tion
e. NullPointerExce
ption
f. IndexOutOfBou
ndsException
g. ArrayIndexOutOfBou
ndsException
h. StringIndexOutOfBo
undsException
i. IOException

j.171 EOFException

k. FileNotFoundExcepti
Figure 16.1 Exception class hierarchy

172
16.8 LET US SUM UP

In this lesson we have discussed the following points on exception


handling.
• An exception is an abnormal condition that arises in a code sequence
at run time.
• Java provides the try block to trap exceptions. To guard against and
handle a run-time error, simply enclose the code that you want to
monitor inside a try block. Immediately after the try block, include a
catch clause that specifies the exception type that you wish to catch.
• It is possible for the program to throw an exception explicitly, using
the throw statement.
• A try statement can be inside the block of another try. (i.e nested)
• finally creates a block of code that will be executed after the
completion of the try/catch block and before the code following the
try/catch block.

16.9 CHECK YOUR PROGRESS : MODEL ANSWERS

1. The different blocks available for exception handling in Java are try,
throw, catch, finally

173
174
LESSON 17

ABSTRACT WINDOWING TOOLKIT (AWT)

CONTENTS
17.0 Aims and Objectives
17.1 Introduction
17.2 Components and Containers
17.3 Types of Components
17.4 Types of Containers
17.5 Component Layout
17.6 Event Handling
17.7 The ItemListener Interface
17.8 Let us sum up
17.9 Check your progress:Model Answers

17.0 AIMS AND OBJECTIVES

This lesson aims at providing an introduction about AWT(Abstract


Window Tool Kit) which is used for writing Java programs with GUI capability.
At the end of the lesson the learner will be able to understand the
components and containers available in AWT and write programs using it.

17.1 INTRODUCTION

Abstract windowing toolkit (AWT) provides the capability to create


platform independent GUI-based programs. This API(Application Program
Interface) allows powerful Graphical User Interfaces to be developed quickly and
easily.
The Java programming language class library provides a user interface
toolkit called the Abstract Windowing Toolkit, or the AWT. The AWT is both
powerful and flexible.
AWT features include:
• a rich set of user interface components
• a robust event-handling model

175
• graphics and imaging tools, including shape, color, and font classes
• layout managers, for flexible window layouts that don't depend on a
particular window size or screen resolution
• data transfer classes, for cut-and-paste through the native platform
clipboard.

Because the Java programming language is platform-independent, the AWT


is also platform-independent. The AWT was designed to provide a common set
of tools for graphical user interface design that work on a variety of platforms.
The disadvantage of such an approach is the fact that a graphical user interface
designed on one platform may look different when displayed on another
platform.

17.2 COMPONENTS AND CONTAINERS

A graphical user interface is built of graphical elements called


components. Typical components include such items as buttons, scrollbars,
and text fields. Components allow the user to interact with the program and
provide the user with visual feedback about the state of the program. In the
AWT, all user interface components are instances of class Component or one of
its subtypes.
Components do not stand alone, but rather are enclosed within
containers. Containers contain and control the layout of components.
Containers are themselves components, and can thus be placed inside other
containers.

17.3 TYPES OF COMPONENTS

The following figure shows the inheritance relationship between the user
interface component classes provided by the AWT. Class Component defines the
interface to which all components must adhere.
The AWT provides nine basic non-container component classes from
which a user interface may be constructed. These nine classes are class Button,
Canvas, Checkbox, Choice, Label, List, Scrollbar, TextArea, and TextField.

176
Figure 17.1 Inheritance relationships

17.3.1 Class Button


The button provides the simplest user interface component that
triggers action in the interface when they are pressed. For example : OK
and Cancel buttons in the dialog box.
To create a button, use one of the following constructors:

Button() – Constructs a Button with no label.

Button(String label) - Constructs a Button with the specified label.

For Example:
Button b1=new Button(“First”);
Add(b1);
Methods:
void addActionListener(ActionListener l) – Adds the specified action
listener to receive action events from this button.
String getLabel() - Gets the label of this button.
void setLabel(String label) - Sets the button's label to be the
specified string.
String getActionCommand() - Returns the Label of the button.

17.3.2 Class Label

177
A Label object is a component for placing text in a container. A label
displays a single line of read-only text. The text can be changed by the
application, but a user cannot edit it directly.
To create a label, use one of the following constructors:

Label() – Constructs an empty label.

Label(String text) – Constructs a new label with the specified string of


text, left justified.

Label(String text, int alignment) – Constructs a new label that presents


the specified string of text with the specified alignment.

The available alignments are stored in class variables in Label, making


them easier to remember: Label.RIGHT, Label.LEFT, and Label.CENTER
For Example:
add(new Label(“My Label with Left aligned”));
add(new Label(“My Label with center aligned”,Label.CENTER));
add(new Label(“My Label with Left aligned”,Label.RIGHT));

Methods:
String getText() – Returns a string containing this label’s text.
void SetText(String str) – Changes the text of the label.
int getAlignment() – Returns an integer representing the alignment of this
label:
0 is Label.LEFT, 1 is Label.CENTER, 2 is Label.RIGHT.
void setAlignment(int i1) – Changes the alignment of this label to the given
integer.

17.3.3 Class Checkbox


Checkboxes are user interface components that have two states: On and
Off (or checked and unchecked. (Selected, true and false and so on).
Unlike buttons, checkboxes usually don’t trigger direct action, instead,
are used to indicate optional features of some action.
Checkbox can be used in two ways:
• Nonexclusive, meaning that given a series of checkboxes, any of them
can be selected.

178
• Exclusive. Meaning that within one series, only one checkbox can be
selected at a time.
Checkbox can be created by using one of the following constructors:

CheckBox() – Creates a check box with no label.

Checkbox(String label) – Creates a check box with the specified


label.

Checkbox(String label, boolean state) – Creates a check box with


the specified label and sets the specified state. (ON or OFF)

Checkbox(String label, boolean state, CheckboxGroup group) -


Creates a check box with the specified label, in the specified check
box group, and set to the specified state.

Checkbox(String label, CheckboxGroup group, boolean state) –


Constructs a Checkbox with the specified label, set to the specified
state, and in the specified check box group.

ForExample: add(new Checkbox(“Visual Basic”));


add(new Checkbox(“Java”));
add(new Checkbox(“EJB”));
Methods:
String getLabel() – Returns a String containing checkbox’s label
void setLabel(String str) – Changes the text of the checkbox’s label.
boolean getState() – Returns true or false, based on whether the
checkbox is selected or not.
void setState(boolean state) – Changes the checkbox’s state to
selected (true) or unselected(false).
addItemListener(ItemListener l) – Adds the given item listener to
receive item events from this checkbox.
17.3.4 CheckboxGroup
This allows creating a set of mutually exclusive checkboxes in which only
one item can be selected at a particular point of time. This is the
functionality required by the radio buttons. The getSelectedCheckbox()
method returns a Checkbox object, which represents the check box that
is been selected, and the other functionality is possible through the
setSelectedCheckbox() method.

179
Note: The Checkbox, Choice and Lists require the ItemListener to trap
the events that happens on these components.
For Example:
CheckboxGroup cbg=new CheckboxGroup();
add(new Checkbox(“Male”,cbg, true));
add(new Checkbox(“Female”, cbg, false));
17.3.5 Class Choice
The Choice class can be used to create popup list of items, which can control
many items to choose. The choice list displays various items which are added
programmatically using the add() or the addItem() method both taking a string
parameter. When the user clicks on the choice object, it pops up on the screen
and the user can select the item.
You can create the Choice by using the following constructor:
Choice() – Creates a new choice menu.
For Example:
Choice c=new Choice();
c.addItem(“Delhi”);
c.addItem(“Chennai”);
c.addItem(“Bangalore”);
Methods:
void add(String item) – Adds an item to the control.
int getItemCount() – Gets number of items in the control.
String getItem() – Gets String at specified index in Choice control.
int getSelectedIndex() – Gets index of the currently selected item.
String getSelectedItem() – gets string representation of Choice control.
void select(int item) – Selects item at given position.
void addItemListener(ItemListener l) – Adds the given item listener to
receive item events from this choice.
void insert(String str,int index) – Inserts the item into this choice at the
specified position.
17.3.6 Class list
The List component presents the user with a scrolling list of text items.
The list can be set up so that the user can choose either one item or
multiple items.
You can create the List by using one of the following constructors:

180
List() – Creates a new scrolling list.

List(int rows) – Creates a new scrolling list initialized with the


specified number of visible lines.

List(int rows, boolean multipleMode) – Creates a new scrolling list


initialized to display the specified number of rows.

For Example:
List list1=new List(3,true);
list1.addItem(“Choice 1”);
list1.addItem(“Choice 2”);
list1.addItem(“Choice 3”);
add(list1);
Methods:
void add(String item) – Adds the specified item to the end of scrolling list.
void add(String item, int index) – Adds the specified item to the scrolling
list at the position indicated by the index.
void addActionListener(ActionListener l) – Adds the specified action
listener to receive action events from this list.
String getItem(int index) – Gets the item associated with the specified
index.
int getItemCount() – Gets the number of items in the list.
int getSelectedIndex() – Gets the index of the selected item on the list.
String getSelectedItem() – Get the selected item on this scrolling list.
String[] getSelectedItems() – Get the selected items on this scrolling list.
void remove(int position) - Remove the item at the specified position from
the scrolling list.
void remove(String item) - Removes the first occurrence of an item from
the list.

17.3.7 Class Scrollbar


When the GUI users enter numerical values that can range contiguously
from a minimum value to a maximum value, it is necessary to provide
with slider controls for simple entry. Java’s support for slider controls
comes in the form of class Scrollbar.

181
Scrollbars are used most often when only part of an entity (document,
list, picture, and so on) can be displayed by the application. The value
the scrollbar depicts becomes the starting point for a scrollable “window”
on the data set.
You can create the List by using one of the following constructors:

Scrollbar() – Constructs a new vertical scroll bar.

Scrollbar(int orientation) – Constructs a new scroll bar with the specified


orientation.

Scrollbar(int orientation, int value, int visible, int minimum, int maximum) –
Constructs a new scroll bar with the specified orientation, initial value, page
size, and minimum and maximum values.

Orientation Scrollbar.HORIZONTAL for horizontal scrollbar or


Scrollbar.VERTICAL for vertical scrollbar. These constants are built into
the Scrollbar class.
Value The scrollbar’s initial value. That is the location of the little scroll
box called the thumb in the scroll bar.
Visible The size of the scroll thumb in pixels.
Minimum and maximum The minimum and maximum values
the scrollbar can represent.

ForExample:
Scrollbar leftright=new Scrollbar(Scrollbar.HORIZONTAL, 1, 10, 1, 100);
Add(leftright);

Methods:
int getMaximum() – Gets maximum setting of Scrollbars.
int getMinimum() – Gets Minimum setting for Scrollbars.
int getOrientation() – Get Orientation of Scrollbars.
int getValue() – Gets Current value of Scrollbars.
void setValue(int value) – Sets value of Scrollbar to given value.
addAdjustmentListener(AdjustmentListener l) – Adds new
adjustment listener to get adjustment events from this scrollbar.

17.3.8 Class TextField

182
The TextField enables the user to enter information into a textfield.
TextField components can be created as empty or with an initial string.
Textfield components can be defined to have an initial number of
columns.
If Initial number of columns is not defined, then the layout manger uses
TextField component’s initial text value to determine the TextField
component’s appropriate length. The TextField class inherits most of its
functionality from TextComponent.
To create a Textfield, use one of the following constructors:

TextField() – Constructs a new text field.

TextField(int columns) – Constructs a new empty text field with the


specified number of columns.

TextField(String text) – Constructs a new text field initialized with the


specified text.

TextField(String text, int columns) – Constructs a new text field


initialized with the specified text to be displayed, and wide enough to
hold the specified number of columns.

For Example:
TextField txtnm=new TextField(30);
TextField txtnm=new TextField(“Hello world”,30);
Txtnm.setEchoChar(‘*’);

Methods:
void addActionListener(ActionListener l) – Adds the specified action
listener to receive action events from this text field.
char getEchoChar() – Gets the character that is to be used for echoing.
int getColumns() – Gets the number of columns in this text field.
void setEchoChar(char c) - Sets the echo character for this text field.
void setText(String t) – Sets the text that is presented by this text
component to be the specified text.

183
String getText() – Gets the text that is presented by this TextField.

17.3.9 Class TextArea


The TextArea component can contain multiple lines of text. Like the
TextField component. TextArea components can also be created either
empty or with an initial string. TextArea component can be defined with
an initial number of rows and columns. The TextArea component inherits
most of its functionality from TextComponent.

To create a TextArea, use one of the following constructors:

TextArea() – Constructs a new text area.

TextArea(int rows, int columns) – Constructs a new empty text area with
the specified number of rows and columns.

TextArea(String text) – Constructs a new text area with the specified text.

TextArea(String text, int rows, int columns) – Constructs a new text area
with the specified text, and with the specified number of rows and
columns.

TextArea(String text, int rows, int columns, int scrollbars) – Constructs a


new text area with the specified text, and with the rows, columns, and
scroll bar visibility as specified.

Methods:
Both the TextArea and TextField classes inherit from the TextComponent
class and hence it supports the getText(), setText(), getSelectedText()
methods. Besides these methods TextArea has the following important
methods:

void append(String str) – Appends the given text to the text area's
current text.
int getColumns() – Returns the number of columns in the TextArea.
int getRows() – returns the number of rows in the TextArea.
void insert(String text, int index) – Inserts the specified text at the
specified position within the Text area’s existing text.

184
Check Your Progress : 1

List the components available in Java.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this
lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

17.4 TYPES OF CONTAINERS

The AWT provides four container classes. They are class Window and its
two subtypes - class Frame and class Dialog - as well as the Panel class. In
addition to the containers provided by the AWT, the Applet class is a container -
it is a subtype of the Panel class and can therefore hold components. Brief
descriptions of each container class provided by the AWT are provided below.
Window A top-level display surface (a window). An instance of the window
class is not attached to nor embedded within another container.
An instance of the Window class has no border and no title.
Frame A top-level display surface (a window) with a border and title. An
instance of the Frame class may have a menu bar. It is otherwise
very much like an instance of the Window class.
Dialog A top-level display surface (a window) with a border and title. An
instance of the Dialog class cannot exist without an associated
instance of the Frame class.
Panel A generic container for holding components. An instance of the
Panel class provides a container to which to add components.
17.4.1 Creating a container
Before adding the components that make up a user interface, the
programmer must create a container. When building an application, the
programmer must first create an instance of class Window or class Frame.
17.4.2 Adding components to a container
To be useful, a user interface must consist of more than one container.
Components are added to containers via a container's add() method. There are
three basic forms of the add() method. The method to use depends on the
container's layout manager

17.5 COMPONENT LAYOUT

185
Layout is controlled not by the container, but by a layout manager
associated with the container. The layout manager makes all of the component
placement decisions. In the AWT, all layout manager classes implement the
LayoutManager interface. The AWT provides five layout managers. They are
FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout. The
important three layouts are discussed below :
The FlowLayout class places components in a container from left to
right. When the space in one row is exhausted, another row is started. The
single-argument version of a container's add() method is used to add
components.
The Border Layout class has five zones as depicted in the following
Figure. The zones are named ``Named”, “East”, “West”, and “Center”. A single
component can be placed in each of these five zones. When the enclosing
container is resized, each border zone is resized just enough to hold the
component placed within. Any excess space is given to the center zone. The
two-argument version of a container’s add() method is used to add components.
The first argument is a String object that names the zone in which to place the
component.

Figure 17.2 Figure showing border layout zones


The GridLayout class is used to lay out the components of a container
object in a grid in which all components are the same size. The GridLayout
constructor is used to specify the number of rows and columns of the grid.
Each container class has a default layout manager. The default layout
manager for the Frame class and Dialog class is the BorderLayout manager.
The default layout manager for the Panel class (and the Applet class) is the
FlowLayout manager.

17.6 EVENT HANDLING

It is very important that a user interface take action as a result of user


input. The action() method responds to the action events that are generated, for
example, by the selection of an item from a pop-up list. The action() method
requires that two parameters be supplied, an Event instance and an Object
instance. The Event instance contains information about the event, including
the target of the event, the x and y coordinates of the event, and the time when

186
the event occurred. The Object instance holds an event-specific piece of data.
For Button objects it contains the text in the button label.
Event Sources:
A source is an object that generates an event. This occurs when the
internal state of that object changes in some way. Sources may generate more
than one type of event
A source must register listeners in order for the listeners to receive
notification about a specific type of event. Each type of event has its own
registration method. Here is the general form:
public void addTypeListeners (TypeListeners el)

Event Listeners
A listener is an object that is notified when an event occurs. It has two
major requirements. First, it must have been registered with one or more
sources to receive notifications about specific types of events. Second, it must
implement methods to receive and process these notifications.
Java defines a new class hierarchy called java.awt.event, which contains a set
of interfaces and methods for dealing with events. These events classes are as
follows:

Control Register Received Event


interest

Button AddActionListener actionPerformed(ActionEvent ae)


List
MenuItem
TextField

Checkbox AddItemListener itemStateCharged(ItemEvent ie)


Choice
List
Checkbox
MenuItem

DialogFrame addWindowListener windowClosing(WindowEvent we)


windowOpened(WindowEvent we)
windowIconified(WindowEvent we)
windowDeiconified(WindowEvent we)

187
windowClosed(WindowEvent we)
windowActivated(WindowEvent we)
windowDeactivated(WindowEvent we)

Scrollbar AddAdjustmentListener AdjustmentValueCharged(Adjustment


Event e)

Canvas AddMouseListener mousePressed(MouseEvent me)


Dialog mouseReleased(MouseEvent me)
Frame mouseEntered(MouseEvent me)
Panel mouseExited(MouseEvent me)
window mouseClicked(MouseEvent me)

Canvas addMouseMotionListen mouseDragged(MouseEvent me)


er
Dialog mouseMoved(MouseEvent me)
Frame
Panel
window

Component addKeyListener keyPressed(KeyEvent ke)


keyReleased(KeyEvent ke)
keyTyped(KeyEvent ke)

Component AddFocusListener FocusGained(FocusEvent fe)


focusLost(FocusEvent fe)

TextCompone addTextListener textValueChanged(TextEvent te)


nt

Example: Button, Label with DefaultLayout by using ActionListener Demo

ActionDemo.java

import java.awt.*;
import java.awt.event.*;
public class ActionDemo extends Frame implements
ActionListener
{ Button b1,b2,b3,b4;

188
Label lb;
public ActionDemo()
{ super("My First Frame Demo by Default Layout");
b1=new Button("First");
b2=new Button("Second");
b3=new Button("Third");
b4=new Button("Four");
lb=new Label("Label Demo",Label.CENTER);
add(b1,"North");
add(b2,"South");
add(b3,"East");
add(b4,"West");
add(lb,"Center");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
lb.setText("First Button Clicked");
else if(ae.getSource()==b2)
lb.setText("Second Button Clicked");
else if(ae.getSource()==b3)
lb.setText("Third Button Clicked");
else if(ae.getSource()==b4)
lb.setText("Fourth Button Clicked");
}
public static void main(String args[])
{ ActionDemo ad=new ActionDemo();
ad.setSize(400,400);

189
ad.setVisible(true);
}
}

Explanation:
• This program creates a GUI screen, which displays a label and four
buttons with default layout.
• The default layout of the Frame is Border Layout. Each Button is set on
each corner and label on the center of the Frame.
• In the main() method object of the ActionDemo class is instantiated. And
the constructor of this class is calling the super() method, which pass the
string and set the Title of the Frame.
• The setSize(400,400) method is used to setting the size of the Frame and
setVisible(true) method is used to make the frame visible on the screen.

17.7 THE ItemListener INTERFACE

The ItemListener interface is responsible for trapping item changes on a


component like radio buttons, check boxes, combo boxes, check box menu
items, etc. ActionListener is of no use in these types of components because,
they can trap only the click event but to check which item from the group is
triggered, the ItemListener interface is used (i.e.) they are needed to trap the on
and off states of a component.
This interface provides only one abstract method itemStateChanged (),
which is necessarily over-ridden if implemented. This method takes the
ItemEvent object through which the events occurring on the components could
be trapped. The ItemEvent class provides the getItem () method, which returns
an object to the Object class denoting the item that has affected because of an
event. The component should have been registered through the
addItemListener() method to trap the event.
For example, the following Code snippet simulates the ItemListener interface.
class UswingApp extends Frame ActionListener,ItemListener
{
public void itemStateChanged(ItemEvent e)
{
/*this method should be over written because it is the only
abstract method of the ItemListener Interface*/
}
}

190
17.8 LET US SUM UP

In this lesson we have discussed the following points related with AWT:
• Abstract windowing toolkit (AWT) provides the capability to create
platform independent GUI-based programs.
• The AWT provides nine basic non-container component classes from
which a user interface may be constructed. These nine classes are class
Button, Canvas, Checkbox, Choice, Label, List, Scrollbar, TextArea, and
TextField.
• The AWT provides four container classes. They are class Window and its
two subtypes - class Frame and class Dialog - as well as the Panel class.
• The layout manager makes all of the component placement decisions.
The five layout managers provided by AWT are FlowLayout,
BorderLayout, CardLayout, GridLayout and GridBagLayout.
• The action() method responds to the action events that are generated
through user input.

17.9 CHECK YOUR PROGRESS : MODEL ANSWERS

1. These are nine classes of components in AWT. They are Button,


Canvas, Checkbox, Choice, Label, List, Scrollbar, TextArea, and
TextField.

LESSON 18

APPLET PROGRAMMING

CONTENTS

191
18.0 Aims and Objectives
18.1 Introduction
18.2 Applets and Internet
18.3 Application Vs Applets
18.4 Building Applet Code
18.5 Applet Execution
18.6 Applet Life Cycle
18.7 Passing parameters to applet
18.8 Placing applet on the web
18.9 Let us sum up
18.10 Check Your Progress: Model Answers

18.0 AIMS AND OBJECTIVES

This lesson aims to make the learner understand the concept of Applets
which is used in web pages for flash display. We discuss the life cycle of the
applet and also code samples are included in the lesson for the better
understanding of applets.
At the end of this lesson the reader will be able to develop applets and
deploy it in web pages.

18.1 INTRODUCTION

Java has revolutionized the way the Internet users retrieve and use
documents on the worldwide network. Java has enabled them to create and use
fully interactive web documents. A web page can now contain not only a simple
text or a static image but also a Java applet which when run can produce
graphics, sounds and animation. Java applets therefore have begun to make
significant impact on the World Wide Web.

18.2 APPLETS AND INTERNET

A Java applet is a Java program that is embedded inside of a Web


document. Applets are Java programs that are primarily used in Internet
computing. They can be transported over the Internet from one computer to
another and run using the AppletViewer or any Web browser that supports
Java.
Applets are created in the following situations:
• When something dynamic is to be included in the display of a Web page.
For example, an applet that displays daily sensitivity index would be
useful on a page that lists share prices of various companies or an applet
that displays a bar chart would add value to a page that contains data
tables.

192
• When it is required to have flashy/animated outputs. Applets that
produce sounds, animation or some special effects would be useful when
displaying certain pages.
Although both the applets and standalone application are Java programs,
there are significant differences between them. Applets are not full-featured
application programs. They are usually written to accomplish a small task or a
component of a task. Since they are usually designed for use on the Internet,
they impose certain limitation and restriction in their design.
• Applets do not use the main () method for initiating the execution of the
code. Applets, when loaded, automatically call certain methods of Applets
class to start and execute the applet code.
• Unlike stand-alone application, applets cannot run independently. They
run from inside a Web page using a special feature known as HTML tag.
• Applets cannot read from or write to the files in the local computer other
than the one from which it is downloaded.
• Applets cannot open a communication session with any host other than
the one from which it was downloaded.
• Applets cannot invoke other executables on the user’s workstation.
All these restrictions and limitations are placed in the interest of security of
systems. These restrictions ensure that an applet cannot do any damage to the
local computer.
Local and Remote Applets
We can embed applets into web pages in two ways. One, we can write our
own applets and embed into web pages. Second, we can download an applet
from a remote computer system and then embed it into web page. An applet
developed locally and stored in a local system is known as a local applet.
A Remote applet is that which is developed by someone else and stored
on a remote computer (web server) connected to the Internet. In order to locate
and load a remote applet. We must know the applet’s address on the web. This
address is known as Uniform Resource Locator (URL) and must be specified in
the applet’s HTML document as the value of the CODEBASE attribute.

18.3 APPLICATION VS. APPLETS

Some of the Java’s Functionality is not possible when programming


applets because of security concerns. The following safeguards are in place to
ensure security:
 Applets cannot read or write files on the Web user’s disk. If information
must be saved to disk during an applet’s execution the storage of
information must be done on the disk from which the Web page is
served.
 Applets cannot make a network connection to a computer other than the
one from which the web page is served.

193
 Pop-up windows opened by applets are identified clearly as Java
windows. A Java cup icon and text such as Untrusted Applet Window
appear in the window. These elements are added to prevent a window
opened by Java from pretending to be something else, such as a
Windows dialog box requesting a user’s name and password.
 Applets cannot use dynamic or shared libraries from any other
programming language. Java can make use of programs written in
languages such as Visual c++ by using a native statement from within
Java. However, applets cannot make use of this feature because there’s
no way to adequately verify the security of the non-Java code being
executed.
 Applets cannot run any programs on the Web Browser’s system.
Java applets are more limited in functionality than standalone Java
applications. The loss is a tradeoff for the security that must be in place for the
language to run remotely on user’s computers. Applets are programs offered on
the Web pages that require the use of Web browser to execute. Applications are
general-purpose programs run by executing the Java interpreter with the name
of the Java program as an argument. Applications do not have any of the
restrictions that are in place for applets.

18.4 BUILDING APPLET CODE

Most applets have a graphical user interface (GUI). This is a natural


consequence of the fact that each applet appears within a Web Browser
window.
An Applet is a Panel. Because Applet is a subclass of the AWT Panel,
applets can contain other Components just as any Panel can. Applets inherit
Panel’s default layout manager, which is the FlowLayout.
Every applet is implemented by creating a subclass of the Applet class.
Applets inherit the drawing and event handling methods of the AWT Component
class. Drawing refers to anything related to representing an applet on-screen
such as drawing images, presenting user interface components such as
buttons, or using graphics primitives. Applets inherit their paint() method from
the Applet class, which inherits them from the Component class.
The steps involved in developing and testing an applet are:
1.Building an applet code(.java file)
2.Creating a Web page using HTML tags
3.Preparing <APPLET> tag
4.Incorporating <APPLET>tag into the web page
5.Creating HTML file
6.Testing the applet code
It is essential that our applet code use the services of two classes, namely
Applet and Graphics from the Java class library. The Applet class, is contained

194
in the Java. Applet package provides life and behavior to the applet through its
methods such as init (), start () and paint (). When an applet is loaded, Java
automatically calls a series of Applet class methods for starting, running and
stopping the applet code.
The following figure shows the inheritance hierarchy of the Applet class

Java.lang.Object

Java.awt.Component

Java.awt.Container

Java.applet.Applet

Figure 18.1 Inheritance hierarchy of Applet Class

Check Your Progress : 1

What are the different steps in developing an applet.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this
lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

The complete syntax of the applet tag is

195
<APPLET
[CODEBASE=codebaseURL]
CODE=appletFILE
[ALT=alternate Text]
[NAME=appletInstanceName]
WIDTH=pixels
HEIGHT=pixels
[ALIGN=alignment]
[VSPACE=pixels]
[HSPACE=pixels]
[<PARAM NAME=appletParameter1 VALUE=value >]
[< PARAM NAME=appletParameter2 VALUE=value >]

[alternateHTML]
</APPLET>

CODEBASE=codebaseURL
This optional attribute specifies the base URL of the applet-the directory
or folder that contains the applet’s code. If the applet resides in the same
directory as the HTML file, then the CODEBASE attribute may be
omitted entirely.
CODE=appletFile
This required attribute gives the name of the file that should be displayed
if the browser understand the APPLET tag but can’t run Java applets.
Alt=alternate Text
This optional attribute specifies any text that should be displayed if the
browser understands the APPLET tag but can’t run Java applets.
NAME=appletInstanceName
This optional attribute specifies a name for the applet instance, which
makes it possible for applets on the same page to find (and communicate
with) each other.
WIDTH=pixels
HEIGHT=pixels
These required attributes give the initial width and height (in pixels) of
the applet display area.
ALIGN=alignment
This attribute specifies the alignment of the applet. The possible values
of this attribute are left, right, top, texttop, middle, absmiddle, baseline,
bottom, and absbottom.
VSPACE=pixels

196
HSPACE=pixels
These optional attributes specify the number of pixels above and below
the applet (VSPACE) and on each side of the applet (HSPACE). They’re
treated the same way as the IMG tag’s VSPACE and HSPACE attributes.
<PARAM NAME=appletParameter1 VALUE=value>
<PARAM>tags are the only way to specify applet-specific parameters.
Applets read user-specified values for parameters with the get Parameter
() method
alternate HTML
If the HTML page containing the <APPLET>tag is viewed by a browser
that doesn’t understand the <APPLET> tag, then the browser will ignore
the <APPLET> and <PARAM> tags, instead interpreting any other HTML
code between tag<APPLET> and </APPLET> tags. Java-compatible
browsers ignore this extra HTML code.

18.5 APPLET EXECUTION

public class Urfirstapplet extends Applet


{
// to do
}
In this sample, Urfirstapplet is the name of the applet program. An
Applet must be declared as a public class. Applets are subclasses of
java.applet.Applet, which is a subclass of the java.awt.Panel class.
The superclass of Applet class gives all applets a framework on which
user interface elements and mouse events can be built. These superclasses also
provide a structure for the applet that must be used when the program is
developed. Programming within an applet is so restrictive that it’s often referred
to as being “inside the sandbox”, which is the area taken by the applet
program inside the Html web page. The AWT can be used to build GUI
interfaces for regular applications as well as applets.
An applet can be executed as part of the HTML after testing the program
and can be tested through the appletviewer tool available with the JDK. The
applet tag of HTML can be made as part of the Java program by commenting
the entries and executed through the appletviewer. The following is an sample
for the same.
/*<applet code=Urfirstapplet.class codebase=”mydir” width=300
height=300>
</applet> */
And to test the program type the following command in the command prompt:
appletviewer Urfirstapplet.java

197
And the same could be part of the HTML file and executed through the web
browser or tested through the appletviewer itself.

18.6 APPLET LIFE CYCLE

Every Java applet has a set of default behaviors that are inherited from
the Applet class. As a result, when an applet is loaded, it undergoes a series of
changes in its state as shown in the following figure.
The applet states include:
• Born or initialization state
• Running state
• Idle state
• Dead or Destroyed state
Initialization state
Applet enters the initialization state when it is first loaded. This is
achieved by calling the init () method of the Applet class. The applet is born. At
this stage, we may do the following
• Create objects needed by the applet.
• Set up initial values
• Load images or fonts
• Set up colors
The initialization occurs only once in the applets life cycles. To provide any of
the behaviors mentioned above we must override the init () method.
Running State
Applet enters the running state when the system calls the start ()
method of the applet class. This occurs automatically after the applet is
initialized. Starting also occurs if the applet is already in “stopped”(idle) state.
For example, we may leave the Web page containing the applet temporarily to
another page and return back to the page. This again starts the applet running.
The start () method can be called more than once.
Idle or Stopped state
An applet becomes idle when it is stopped from running. Stopping occurs
automatically when we leave the page containing the currently running applet.
We can also do so by calling the stop() method explicitly. If we use a thread to
run the applet, then we must use stop() method to terminate the thread.
Dead state
An applet is said to be dead when it is removed from memory. This
occurs automatically by invoking the destroy() method when the browser is
quit. This also occurs once in the applet’s life cycle.

198
Display state
Applet moves to the Display State whenever it has to perform some
output operations on the screen. This happens immediately after the applet
enters into the running state. The paint() method is called to accomplish this
task. The paint() method is inherited from the Component class, a super class
of Applet.
The paint() method, must take an instance of the Graphics class as in
the following method definition:
public void paint(Graphics g)
{
g.drawString(“Welcome! to First Internet Program”,60,30)l
}

A graphics object is used to indicate where something should be drawn


and is part of the java.awt package. The Graphics object used as the parameter
to paint() is created automatically, and it represents the applet window. The
g.drawString() line uses this Graphics object to indicate where a string should
be drawn. Every time the repaint() method is called, the applet window must be
updated, the string “Welcome! To first Internet program” is drawn at the x, y
position.
The life cycle of applet can be diagrammatically shown as :

Init

Start
Leave Reload or resize browser
web page or return to web pages
Stop
Exit
Browser
Destroy

Figure 18.2 Applet life cycle


Example: Sample Applet Demo

SampleApplet.java
import java.awt.*;
import java.applet.*;

199
/*<applet code="SampleApplet" width=300 height=300></applet>*/

public class SampleApplet extends Applet


{
public void init()
{ setBackground(Color.cyan);
setForeground(Color.red);
}
public void paint(Graphics g)
{ g.drawString("This is a Frame window",30,60);
g.setColor(Color.green);
g.drawString("This is a Colored String",30,90);
showStatus("This is shown in the status window");
}
}

Explanation:
The class SampleApplet extends Applet to make an internet application
and init() method is executed first. It sets the background and Foreground color
of the applet by using setBackground() and setForeground() method.
Check Your Progress : 2

List the different states of the lifecycle of an applet.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this
lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

18.7 PASSING PARAMETERS TO APPLET

Parameters are to applets what command-line arguments are to


applications. They allow the user to customize the applet’s operation. By
defining parameters, you can increase your applet’s flexibility, making your
applet work in multiple situations without recoding and recompiling it. for

200
example, we can change the color of the text displayed to red by an applet by
using a <PARAM…> tag as follows:
<applet..>
<param name=”color” value=”red”>
</applet>
Parameters are passed to an applet when it is loaded. We can define the
init() method in the applet to get hold of the parameters defined in the<PARAM>
tag. This is done using the getParameter() method, which takes one string
argument representing the name of the parameter and returns a string
containing the value of that parameter.
Example: Passing parameter to applet.

PassApplet.java

import java.awt.*;
import java.applet.*;

/*<applet code="PassApplet" width=300 height=300>


<param name=fontname value=Tohma>
<param name=fontsize value=26>
</applet>*/
public class PassApplet extends Applet
{
Font f;
public void init()
{
String name=getParameter("fontname");
int size=Integer.parseInt(getParameter("fontsize"));
setBackground(Color.cyan);
setForeground(Color.red);
f=new Font(name,Font.BOLD,size);
}
public void paint(Graphics g)
{

201
g.setFont(f);
g.drawString("Hello! First Applet",30,90);
}
}

Output:

Figure 18.3 Output screen showing applet with parameters passed to the
applet
Explanation:
• The Name attribute of the Param tag indicates the name of a parameter
which should be given, and the VALUE attribute indicates the value to
associate with the parameter.
• The getParameter() method reads the parameter from the HTML and
passes it to the PassApplet class. It takes a String parameter and returns
a String which is specified as the Value attribute in the HTML <PARAM>
tag.

18.8 PLACING THE APPLET ON THE WEB:

Once the applet has been created and added into HTML pages, it can be
easily made available on the World Wide Web. Put all .class files required by the
applet on the Website, making sure to put the files in the same directory as the
CODEBASE attribute if it has been used if not, put the .class files in the same
directory as the Web page that includes the applet.
When a browser user visits an HTML page that contains an applet, this is what
will happen:

202
• The Browser finds the class file for the user-defined class that extends
the Applet class. The location of the class file, which contains Java
bytecodes is specified with the CODE and CODEBASE attributes of the
<APPLET> tag.
• It brings the bytecode over the network to the user’s computer.
• The browser then creates an instance of the user-defined class.
• It calls the applet’s init method. This method performs any one-time
initialization that is required.
The browser calls the applet’s start method and then the paint method.
Check Your Progress : 3

Explain the actions performed when a browser visits web page.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this
lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

18.9 LET US SUM UP

In this lesson we have discussed upon the following points :


• A Java applet is a Java program that is embedded inside of a Web
document.
• A Local applet is one, which we can write our own applets and embed
into web pages.
• A Remote applet is that which is developed by someone else and stored
on a remote computer (web server) connected to the Internet.
• An applet can be executed as part of the HTML after testing the program
and can be tested through the appletviewer tool available with the JDK.
• The applet tag of HTML can be made as part of the Java program by
commenting the entries and executed through the appletviewer. The
following is an sample for the same.
• The different states of the life cycle of an applet are :Born or initialization
state, Running state, Idle state, Dead or Destroyed state

18.10 CHECK YOUR PROGRESS : MODEL ANSWERS

203
1. The steps involved in developing and testing an applet are:
a) Building an applet code(.java file)
b) Creating a Web page using HTML tags
c) Preparing <APPLET> tag
d) Incorporating <APPLET>tag into the web page
e) Creating HTML file
f) Testing the applet code

2. The different states of the life cycle of an applet are :


a) Born or initialization state
b) Running state
c) Idle state
d) Dead or Destroyed state

3. The sequence of actions that are performed when a browser visits a web
page are :
o The Browser finds the class file for the user-defined class that
extends the Applet class. The location of the class file, which
contains Java bytecodes is specified with the CODE and
CODEBASE attributes of the <APPLET> tag.
o It brings the bytecode over the network to the user’s computer.
o The browser then creates an instance of the user-defined class.
o It calls the applet’s init method. This method performs any one-
time initialization that is required.

204
205
LESSON 19

GRAPHICS PROGRAMMING

CONTENTS
19.0 Aims and Objectives
19.1 Introduction
19.2 The Graphics Co-Ordinate systems
19.3 Colors
19.4 Drawing and filling
19.4.1 Lines
19.4.2 Rectangles
19.4.3 Polygons
19.4.4 Ovals
19.4.5 Arcs
19.4.6 Drawing text
19.5 Let us sum up
19.6 Check Your Progress: Model Answers

19.0 AIMS AND OBJECTIVES

In this lesson we learn how graphics are handled in Java. Graphics


generally include primitives, which can be further used to develop complex
figures, hence we also learn how the different graphic primitives such as line,
arc, circle and rectangles are drawn using Java
At the end of this lesson the programmer will be able to write graphic
related programs.

19.1 INTRODUCTION

With Java’s graphics capabilities it is possible to draw lines, shapes,


characters, and images on the screen. Most of the graphics operations in Java
are methods defined in the Graphics class. The user need not create an
instance of graphics in order to draw these objects in the applet or application.
In the applets paint method the user is provided with a Graphics object. By
using that object, it is possible to draw in the applet and the results appear on
screen.
The Graphics class is part of the java.awt package, so if the applet does
any painting, then it is necessary to import this class at the beginning of the
Java file as:

206
import java.awt.Graphics;

19.2 THE GRAPHICS CO-ORDINATE SYSTEM

To draw an object on the screen, it is necessary to call one of the drawing


methods available in the Graphics class. All the drawing methods have
arguments representing endpoints, corners, or starting locations of the object
as values in the applet’s co-ordinate System.
Java’s coordinate system has the origin (0,0) in the top left corner.
Positive x values are to the right =, and positive y values are down. All pixel
values are integers; there are no partial or fractional pixels. The following figure
shows to draw a simple square by using this coordinate system.
0,0 +X

20,20

60,60
a.

+Y
Figure 19.1 Simple square drawn in the Java co-ordinate system

19.3 COLORS

The Graphics class utilizes the current color for all its drawing methods.
The default current color is black; however, it can be changed by using the
setColor() method provided by the Graphics class. The setColor() method
accepts a Color object a parameter. The Color class provides static member
variables, which are also Color objects, for the most commonly used colors. The
following list contains these standard color member variables:
Color.black Color.blue
Color.cyan Color.darkGrey
Color.gray Color.green
Color.lightGray Color.magenta
Color.orange Color.pink

207
Color.red Color.white
Color.yellow
The static members in the preceding list can be passed to the setColor()
method to change the current color, as demonstrated by the following
example:
Graphics g=getGraphics();
g.setColor(Color.red);
The preceding code creates a Graphics object called g. Next g’s current
color is set to red by using setColor() method and a static member variable
provided by the color class. Any graphics or text can be subsequently drawn by
using g, displaying in red.
In addition to the standard colors, shown in the preceding list, new Color
objects can be constructed. The Color class’s constructor accepts three values
specifying the new color’s red, green, and blue components, or RGB values.
19.4 DRAWING AND FILLING
The Graphics class provides a set of simple built-in-graphics primitives
for drawing including lines, rectangles, polygons, ovals, and arcs.
19.4.1 Lines
To draw straight lines, use
void drawLine(int x1, int y1, int x2, int y2)
The above function draws a line, using the current color, between the
points (x1, y1) and (x2, y2) in this graphics context's coordinate system.
drawLine() takes four arguments: the x and y coordinates of the starting point
and the x and y coordinates of the ending point.

public void paint(Graphics g)


{
g.drawLine(25,25,75,75);
}

19.4.2 Rectangles
The Java graphics provide not just one, but three kinds of rectangles:
(ii) Plain rectangle
void drawRect (int x, int y, int width, int height)
void fillRect(int x, int y, int width, int height)
Both these functions take four arguments the x and y coordinates of the
top left corner of the rectangle, and the width and height of the rectangle to
draw.

208
209
For each of these rectangles, there are methods to choose from; one that
draws the rectangle in outline form, and one that draws the rectangle filled with
color.

public void paint(Grahics g)


{
g.drawRect(20,20,60,60);
g.fillRect(20,20,60,60);
}

Rounded rectangles, which are rectangles with rounded corners.


void drawRoundRect((int x, int y, int width, int height, in xdim, int ydim,)
void drawRoundRect((int x, int y, int width, int height, in xdim, int ydim,)
The Upper left corner of the rectangle is at x, y. The dimension of the
rectangle is specified by width and height. The diameter of the rounding arc
along the X-axis is specified by xdim. The diameter-rounding arc along the Y-
axis is specified by ydim.
5 20
5 5 20 20
20

Figure 19.2 Diagram showing different rounding rectangles


Here’s a paint () method that draws two rounded rectangles:

Public void paint(Graphics g)


{
g.drawRoundrect(20,20,60,60,10,10);
g.fillRoundRect(120,20,60,60,20,20);
}

Three-dimensional rectangles, which are drawn with a shaded border.


Finally, there are three-dimensional rectangles. These rectangles aren’t
really 3D; instead, they have a shadow effect that makes them appear either
raised or intended from the surface of the applet. Three-dimensional rectangle
has four arguments for the x and y of the first position and the width and the
height of the rectangles. The fifth argument is a Boolean indicating whether the
3D effect is to raise the rectangles (true) or indent it (false). As with the other

210
rectangles, there are also different methods for drawing and filling; draw3Drect()
and fill3DRect().
Here is a code to produce 3D rectangle :

public void paint(Graphics g)


{
g.draw3Drect(20,20,60,60,true);
g.draw3Drect(120,20,60,60,false);
} a.

19.4.3 Polygons
Polygons are shapes with an unlimited number of sides. To draw a
polygon, you need a set of x and y co-ordinates, and the drawing method then
starts at one, draws a line to the second, then a line to the third and so on.
As with rectangle, you can draw an outline or a filled polygon (the
drawPolygon() and fillPolygon() methods, respectively).You also have a choice of
how you want to indicate the list of coordinates-either as arrays of x and y
coordinates or as an instance of the Polygon class
drawPolygon(int[] xPoints, int[] yPoints, int nPoints) - Draws a closed
polygon defined by arrays of x and y coordinates.
fillPolygon(int[] xPoints, int[] yPoints, int nPoints) - Fills a closed polygon
defined by arrays of x and y coordinates.
The drawPolygon() and fillPolygon() takes three arguments:
An array of integers representing x coordinates
An array of integers representing y coordinates
An integer for the total number of points
The x and y arrays should, of course, have the same number of elements.
Following is an example of drawing a polygon’s outline by using this
method (the figure shows the result of the program).

public void paint(Graphics g)


{
int xpts[]={39,94,97,142,53,58,26};
int ypts[]={33,74,36,70,108,80,106};
int pts=xpts.length;
g.drawPolygon(xpts, ypts, pts);
}

211
Figure 19.3 Output screen showing polygon generated by the above
program

Java does not automatically close the polygon; if it is necessary want to


complete the shape, you have to include the starting point of the polygon at the
end of the array.
Drawing a filled polygon, however, joins the starting and ending points.
The second way of calling drawPolygon() and fillPolygon() is to use a
Polygon object. The polygon class is useful if you intend to add points to the
polygon or if you’re building the polygon on the fly. The Polygon class enables
you to treat the polygon as an object rather than dealing with individual arrays.
Polygon poly=new Polygon();
Or create a polygon from a set of points using integer arrays, as in the previous
example:

int xpts[]={39,94,97,142,53,58,26};
int ypts[]={33,74,36,70,108,80,106};
int pts=xpts.length;
Polygon poly=new Polygon(xpts,ypts,pts);

Once there are polygon objects, points can be appended to the polygon, as
needed
poly.addPoints(20,35);
Then to draw the polygon, just use polygon object as an arguments to
drawPolygon() or fillPolygon().Here’s the previous example, rewritten this tome
with a Polygon object
To fill this polygon, the following code can be used :
public void paint(Graphics g)
{
int xpts[]={39,94,97,142,53,58,26};
int ypts[]={33,74,36,70,108,80,106};
int pts=xpts.length;
Polygon poly=newPolygon(xpts,ypts,pts)
212
g.fillPolygon(poly);
}
19.4.4 Ovals
Ovals are circles that can be stretched either horizontally or
vertically. The drawOval() and fillOval() methods are;
void drawOval(int X, int Y, int width, int height)
void fillOval(int X,int Y,int width,int height)
These methods take the same parameters as drawRect(). With the
drawRect() method these parameters define the size of a rectangle. In the case
of the drawOval() and fillOval() methods, however, these parameters define the
size of the bounding rectangle within the oval is drawn.
The following code draws a regular oval by using drawOval() and a
solid red oval, which uses the fillOval() method;

Public void paint(Graphics g)


{
g.drawOval(10,10,75,100);
g.setColor(Color.red);
g.fillOval(150,10,100,75);
}

19.4.5 Arcs
Arcs can be best described as partial ovals. To draw an arc, you can
use the drawArc() or fillArc() methods;

void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle);
void fillArc(int X, int Y, int width, int height, int startAngle, int arcAngle)

Both methods take six parameters, the first four parameters are the
same as drawOval(). The fifth parameter specifies the starting angle of the arc
and the sixth specifies how far to draw around the oval. Both the fifth and sixth
parameter values are measured in degrees.
The following figure shows the orientation of the angles :
90

213
180 0

270
Figure 19.4 Figure showing different orientation of angles
The following code shows how a pie chart can be produced by drawing
two arcs.
In the following figure, both arcs are drawn within the same oval. Each
arc, however, is drawn by using different starting and ending angles. The first
arc, which is blue, is drawn starting from the top of oval-an angle of 90 degrees-
and ending at an angle of 0 degrees. Because a positive number(270) is used to
specify the ending angle’s distance from the starting angle. The arc is drawn in
a clockwise direction. In contrast, if the arc distance were specified as –270, the
blue arc would be drawn in a counterclockwise manner. Consequently, the blue
arc would be partially obscured by the red arc, which would have been drawn
over the blue arc.

public void paint(Graphics g)


{
g.setColor(Color.blue);
g.fillArc(10,10,100,100,90,270);
g.setColor(Color.red);
g.fillArc(10,10,100,100,0,90)
}

Here are the steps to construct arc in Java:


 Think of the arc as a slice of a complete oval.
 Construct the full oval with starting point and the width and the height.
 Determine the staring angle for the beginning of the arc.
 Determine how far to sweep the arc and in which direction
(counterclockwise indicates the positive values. Clockwise indicates
negative.)
Output:

214
Figure 19.5 Arc generated by the above program
19.4.6 Drawing Text
void drawString(String str, int x, int y)
The parameter for the drawString() method includes a String object (str)
and the x and y coordinates of the text’s position. The text is drawn from left to
right from the staring point. The x coordinate specifies the starting point and
the y coordinate is used as the baseline for the text.
The following code illustrates the drawString() method.

public void paint(Graphics g)


{
g.setColor(Color.gray);
g.drawLine(10,50,300,50);
g.setColor(Color.black);
g.drawString(“Programming with Java”, 50, 50);
}

Check Your Progress : 1

List the different methods used for handling graphics in Java.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

215
……………………………………………………………………..

19.5 LET US SUM UP

In this lesson, we have discussed the different methods related with graphics in
Java. We have discussed the following points.
• To use graphics it is necessary to use the following statement as the first
statement import java.awt.Graphics:
• To draw an object on the screen, it is necessary to call one of the drawing
methods available in the Graphics class.
• The Graphics class utilizes the current color for all its drawing methods.
The default current color is black; however, it can be changed by using
the setColor() method.

19.6 CHECK YOUR PROGRESS: MODEL ANSWERS

1. Following are the few methods used for handling graphics in Java:
drawLine(), drawRect(), drawPolygon, drawArc()… etc.

LESSON 20

PROGRAMS ON GRAPHICS/APPLETS

CONTENTS
20.0 Aims and Objectives
20.1 Introduction
20.2 Drawing lines
20.3 Drawing rectangles
20.4 Drawing ellipses and circles
20.5 Drawing Arcs
20.6 Drawing Polygons
20.7 Let us sum up
20.8 Check Your Progress: Model Answers
20.9 Programming Exercises

20.0 AIMS AND OBJECTIVES

The object of this lesson is to present a few working examples of Java


programs which demonstrates the use of graphics and applications. Several

216
programming examples with their output screen have been presented to make
the reader understand the use of applets and graphics.
At the end of this lesson the reader will be able to develop small Java
programs which make use of graphics methods.

20.1 INTRODUCTION

All graphics are drawn relative to a window. This can be the main
window of an applet, a child window of an applet, or a stand-alone application
window. The origin of each window is at the top-left corner and is 0, 0.
Coordinates are specified in pixels. All output to a window takes place through
a graphics context. A graphics context is encapsulated by the Graphics class
and is obtained in two ways:
 It is passed to an applet when one of its various methods, such as paint()
or update(), is called.
 It is returned by the getGraphics() method or Component.
The Graphics class defines a number of drawing functions. Each shape can
be drawn edge-only or filled. Objects are drawn and filled in the currently
selected graphics color, which is black by default.

217
20.2 DRAWING LINES

Lines are drawn by means of the drawLine() method, shown here:


void drawLine(int startX, int startY, int endX, int endY);
drawLine() displays a line in the current drawing color that begins at startX,
startY, and ends at endX, endY.

The following applet draws several lines in the applet viewer window:
// Draw lines
import java.awt.*;
import java.applet.*;
/*
<applet code = Lines width = 300 height = 200>
</applet>
*/
public class Lines extends Applet
{
public void paint(Graphics g)
{
g.drawLine(0, 0, 100, 100);
g.drawLine(40, 25, 250, 180);
g.drawLine(75, 90, 400, 400);
g.drawLine(40, 155, 400, 40);
}
}

The following screen shot shows the output displayed after executing the
previous Java program.

218
Figure 20.1 Screenshot showing Lines drawn using applets

20.3 DRAWING RECTANGLES

The drawRect() and fillRect() methods display an outlined and filled rectangle,
respectively. They are shown here:
void drawRect(int top, int left, int width, int height);
void fillRect(int top, int left, int width, int height);
To draw a rounded rectangle, use drawRoundRect() or fillRoundRect(), both
shown here
void drawRoundRect(int top, int left, int width, int height, int xDiam, int
yDiam)
void fillRoundRect(int top, int left, int width, int height, int xDiam, int
yDiam)
The following applet draws several rectangles:
// Draw rectangles
import java.awt.*;
import java.applet.*;
/*
<applet code = Rectangles width = 300 height = 400>
</applet>
*/
public class Rectangles extends Applet{
public void paint(Graphics g){
g.drawRect(10, 10, 70, 50);

219
g.fillRect(10, 100, 70, 50);
g.drawRoundRect(10, 190, 70, 50, 15, 15);
g.fillRoundRect(10, 280, 70, 50, 30, 40);
}
}

The following is the output screen, which displays four rectangles with different
characteristics such as rounded and filled etc.

Figure 20.2 Screenshot showing rectangles drawn using applets

Check Your Progress : 1

Write the general forms of the methods used for drawing ellipses and
rectangles.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this
lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

220
20.4 DRAWING ELLIPSES AND CIRCLES

To draw an ellipse, use drawOval(). To fill an ellipse, use fillOval(). These


methods are shown here:
void drawOval(int top, int left, int width, int height);
void fillOval(int top, int left, int width, int height);

To draw a circle, specify a square as the bounding rectangle. The following


program draws several ellipses:

// Draw Ellipses
import java.awt.*;
import java.applet.*;
/*
<applet code = “Ellipses” width = 300 height = 200>
</applet>
*/
public class Ellipses extends Applet{
public void paint(Graphics g){
g.drawOval(10, 10, 70, 70);
g.fillOval(100, 10, 70, 70);
g.drawOval(190, 10, 70, 50);
g.fillOval(100, 10, 70, 50);
}
}

The following screen shot shows the output displayed after executing the
previous Java program.

221
Figure 20.3 Screenshot showing circles drawn using applets

20.5 DRAWING ARCS

Arcs can be drawn with drawArc() and fillArc() methods. The general form of
the arc drawing methods are shown below :
void drawArc(int top, int left, int width, int height, int startAngle, int sweepAngle);
void fillArc(int top, int left, int width, int height, int startAngle, int sweepAngle);
The following applet draws four different arcs. Two arcs are filled and two arcs
are not filled.
// Draw Arcs
import java.awt.*;
import java.applet.*;
/*
<applet code = “Arcs” width = 300 height = 200>
</applet>
*/
public class Arcs extends Applet{
public void paint(Graphics g){
g.drawArc(10, 40, 70, 70, 0, 75);
g.fillArc(100, 40, 70, 70, 0, 75);
g.drawArc(10, 100, 70, 80, 0, 175);
g.fillArc(100, 100, 70, 90, 0, 270);
}
}
The following screenshot shows the result of execution of the previous program.
The screenshot shows four different arcs generated by the previous program.

222
Figure 20.4 Screenshot showing arcs drawn using applets

20.6 DRAWING POLYGONS

It is possible to draw arbitrarily shaped figures using drawPolygon() and


fillPolygon(), shown here:
void drawPolygon(int x[], int y[], int numPoints);
void fillPolygon(int x[], int y[], int numPoints);
The following applet draws an hourglass shape:
// Draw Polygon
import java.awt.*;
import java.applet.*;
/*
<applet code = “Polygons” width = 300 height = 200>
</applet>
*/
public class Polygones extends Applet{
public void paint(Graphics g)
{
int xpoints[] = {30, 200, 30, 200, 30};
int ypoints[] = {30, 30, 200, 200, 30};
int num = 5;
g.drawPolygon(xpoints, ypoints, num);
}
}

223
The following screenshot shows the result of execution of the previous program.
The screenshot shows a polygon which is in the shape of a hourglass. The
picture is drawn using the drawPolygon()method.

Figure 20.5 Screenshot showing Polygons drawn using applets

20.7 LET US SUM UP

In this lesson we have discussed a few programming examples which


demonstrates the use of graphic methods used in applets. We have
discussed the methods used for drawing lines, arcs, circles, ellipses and
polygons.

20.8 CHECK YOUR PROGRESS : MODEL ANSWERS

1. The methods used for drawing rectangles are


void drawRoundRect(int top, int left, int width, int height, int xDiam, int
yDiam)
void fillRoundRect(int top, int left, int width, int height, int xDiam, int
yDiam)

The methods used for drawing ellipses are :


void drawOval(int top, int left, int width, int height)
void fillOval(int top, int left, int width, int height)

20.9 PROGRAMMING EXERCISES

1. Write a Java applet program to draw an image using canvas.


2. Write a Java applet program for the following details

224
a) Create a scroll bar (horizontal or vertical), set the minimum and
maximum values.
b) Create a text field and implement event listener for scrollbar
that displays value showing the current position of scrollbar on a
text field.
3. Write a Java applet program that creates a scrolling list with several
choices and informs you of selections and deselections using a textfield
with the property set editable setting false.

225
226
LESSON 21

I/O CLASSES

CONTENTS
21.0 Aims and Objectives
21.1 Introduction
21.2 The file class
21.3 The FileInputStream Class
21.4 The OutputStream Class
21.5 The FilterOutputStream Class
21.6 The BufferedOutputStream Class
21.7 The DataOutputStream Class
21.8 The PrintStream Class
21.9 The FileOutputstream Class
21.10 I/O Exceptions
21.11 Let us sum up
21.12 Check Your Progress: Model Answers

21.0 AIMS AND OBJECTIVES

In this lesson we introduce the different classes used for handling


Input/Output in Java. At the end of this lesson the learner will be able to list
the different I/O classes and write programs using these classes.

21.1 INTRODUCTION

The java.io package contains interfaces, classes, and methods that


facilitate input and output of data to applets and applications. The Java input
and output package-java.io- is used to implement streams. The classes and
methods in the java.io package allow great flexibility in sending and receiving
data. Java also provides strong, flexible support for I/O as it relates to files and
networks. Java’s I/O system is cohesive and consistent.

21.2 THE FILE CLASS

The java.io.File class represents the name of a file or directory might exist
on the host Machine's file system. The simplest form of the constructor for this
class is
File (String pathname)

227
It is important to know that constructing an instance of File does not
create a file on local file system. Calling the constructor simply creates an
instance that encapsulates the specified string. Of course, if the instance is to
be any use, most likely it should encapsulate a string that represents an
existing file or directory, or one that will shortly be created. However, at
construction time no checks are made.
File (String subpath)
File (File dir, String subpath)
Both versions require you to provide a directory and a relative path (the
sub path argument) within that directory. In one version you use a string to
specify the directory; in the other, you use an instance of file.
1. File f1 = new file ("c:\a");
2. File f2 = new file (f1. "xyz.java");
After constructing an instance of File, you can make a number of method
calls on it. Some of these calls simply do string manipulation on the file's
pathname, while others access or modify the local file system. The methods that
support navigation are listed below:
• boolean exists( ): This returns true if the file or directory exists,
otherwise returns false.
• String getAbsolutepath ( ): This returns the absolute path (i.e., not
relative path of the file or directory.)
• String getCanonicalPath (): This returns the canonical path of the file or
directory. This is similar to
• String getName ( ): This returns the name of the directory. The name is
the last element of the path.
• String getParent ( ): This returns the name of the directory that contains
the File.
• boolean isDirectory ( ): Tests whether the file denoted by this abstract
pathname is a directory.
• boolean isFile ( ): Tests whether the file denoted by this abstract
pathname is a normal file.
• String [ ] list ( ): This returns an array containing the names of the files
and directories within the File. The File must describe a directory, not a
file.
This method listed above is not the entirety of the class methods. Some non-
navigation methods are:
• boolean canRead ( ): This returns true if the file or directory may be
read.
• boolean canWrite ( ): This returns true if the file or directory may be
modified.

228
• boolean delete ( ): This attempts to delete the file or directory.
• long length ( ): This returns the length of the file.
• boolean mkdir ( ): This attempts to create a directory whose path is
described by the File
• boolean renameTo (File new name): This renames the file or directory.
Returns true if the renaming succeeded, otherwise returns false.

21.3 THE FileInputStream CLASS

This class creates an Inputstream that can be used to read bytes from a file.
Its two constructors are:
FileInputStream(String filepath)
FileInputStream(File fileObj)
It overrides six of the methods in the abstract class InputStream.
Example: Display the contents of the Files

FileDemo1.java

import java.io.*;
public class FileDemo1
{
public static void main(String args[])throws Exception
{
String s;
File f=new File("test.txt");
DataInputStream dis=new DataInputStream(new
FileInputStream(f));
while((s=dis.readLine()).length()!=0)
{
System.out.println(s);
}
dis.close();
}
}

229
Example : Accept the Directory or File Name from The user and print the contents of it.

Filedemo3.java
import java.io.*;
public class FileDemo3
{
public static void main(String args[])throws Exception
{
DataInputStream dis=new DataInputStream(new
BufferedInputStream(System.in));
System.out.println("Enter The path of the File or Directory :");
String s=dis.readLine();
String s1=" ";
File f=new File(s);
if(f.isDirectory())
{
System.out.println("It is Directory");
String lst[]=f.list();
for(int i=0;i<lst.length;i++)
{
System.out.println(lst[i]);
}
}
if(f.isFile())
{
System.out.println("It is File and contents are:");
DataInputStream dis1=new DataInputStream(new FileInputStream(f));
while((s1=dis1.readLine()).length()!=0)
{
System.out.println(s1);
}
}

230
}
}

21.4 THE OutputStream CLASS

This abstract class is the superclass of all classes representing an output


stream of bytes. An output stream accepts output bytes and sends them to
some sink. Applications that need to define a subclass of OutputStream must
always provide at least a method that writes one byte of output.
void write(int) – Used to write a portion of an array characters.
void write(bytes[] array) – Used to write an array of bytes.
void write(bytes[] array, int off, int length) - Used to write the specified
length of bytes from the byte array starting at offset off to the output
stream.
void close() – used to close an output stream.
void flush() – used to clear the output stream.
Hierarchy of OutputStream Class:

Object

OutputStream Class

FileOutputStream class FilterOutputStream class

DataOutputStream Class PrintStream Class


BufferedOutputStream class

Figure 21.1 Hierarchy of Output stream class

21.5 THE FilterOutputStream CLASS

231
This class is the super class for all the classes that filter output streams.
This class overrides all the methods of the OutputStream class. The constructor
of this class is as follows:
FilterOutputStream(OutputStream out) – The constructor creates an
output stream filter object above underlying output stream.
The methods of this class are same as the ones defined above for the
OutputStream class. Like the FilterInputStream, this class also is not
instantiated but used by the derived classes. This class acts as a wrapper for
the output stream classes.

21.6 THE BufferedOutputStream CLASS

The class implements a buffered output stream. By setting up such an


output stream, an application can write bytes to the underlying output stream
without necessarily causing a call to the underlying system for each byte
written. The data is written into an internal buffer, and then written to the
underlying stream if the buffer reaches its capacity, the buffer output stream is
closed, or the buffer output stream is explicitly flushed. It contains the
following constructors:
BufferedOutputStream(OutputStream out)
Creates a new buffered output stream to write data to the specified
underlying output stream with a default 512-byte buffer size.
BufferedOutputStream(OutputStream out,int size)
Creates a new buffered output stream to write data to the specified
underlying output stream with the specified buffer size.
This class contains all the methods that have been mentioned for the
OutputStream class.
Example: BufferedOutputStream Demo

UbufDemo.java

import java.io.*;
public class UbufDemo
{
public static void main(String args[])throws Exception
{
byte[] str=new byte[30];
String s="Hello Benjamin!";
str=s.getBytes();
BufferedOutputStream bf=new

232
BufferedOutputStream(System.out);
bf.write(str,0,str.length);
bf.flush();
}
}

21.7 THE DataOutputStream CLASS

A data input stream lets an application write primitive Java data types to
an output stream in a portable way. An application can then use a data input
stream to read the data back in. The constructor is:
DataOutputStream(OutputStream out) – This is used to create a new data output
stream to write data to the specified underlying output stream.
The method of these class remain same as that of the OutputStream
class. Apart from those methods, the DataOutputStream class also contains
certain important methods that are:
void writeChars(String s) – This methods accepts a string and displays it
character by character.
void writeInt(int i) – This method is used to accept and display an integer.
void writeBytes(String s) – This method is used to display the entire
String.

233
Example: DataOutputStream Demo

UdosDemo.java

import java.io.*;
public class UdosDemo
{
public static void main(String args[])throws Exception
{
DataOutputStream dos=new
DataOutputStream(System.out);
dos.writeInt(20);
dos.writeChars("Character are:");
dos.writeBytes("Bytes are:");
dos.flush();
}
}

21.8 THE PrintStream CLASS

A PrintStream adds functionality to another output stream, namely the


ability to print representations of various data values conveniently. Two other
features are provided as well. Unlike other output streams, a PrintStream never
throws an IOException; instead, exceptional situations merely set an internal
flag that can be tested via the checkError method. Optionally, a PrintStream can
be created so as to flush automatically; this means that the flush method is
automatically invoked after a byte array is written, one of the println methods is
invoked, or a newline character or byte ('\n') is written.
All characters printed by a PrintStream are converted into bytes using the
platform's default character encoding. The PrintWriter class should be used in
situations that require writing characters rather than bytes.
The constructor of this class is:
PrintStream(OutputStream out) – Used to create a new PrintStream object
without the automatic buffer flushing feature. This object is created from
an existing OutputStream.
PrintStream(OutputStream ou, boolean autoflusht) – Used to create a new
PrintStream object with the automatic buffer flushing feature. This object
is created from an existing OutputStream.

234
Method Summary of PrintStream class

void print(boolean b) Print a boolean value.

void print(char c) Print a character.

void print(char[] s) Print an array of characters.

void print(double d) Print a double-precision floating-point number.

void print(float f) Print a floating-point number.

void print(int i) Print an integer.

void print(long l) Print a long integer.

void print(Object obj) Print an object.

void print(String s) Print a string.

void println() Terminate the current line by writing the line separator string.

void println(boolean x) Print a boolean and then terminate the line.

void println(char x) Print a character and then terminate the line.

void println(char[] x)Print an array of characters and then terminate the line.

void println(double x) Print a double and then terminate the line.

void println(float x) Print a float and then terminate the line.

void println(int x) Print an integer and then terminate the line.

void println(long x) Print a long and then terminate the line.

void println(Object x) Print an Object and then terminate the line.

235
void println(String x) Print a String and then terminate the line.

Example: PrintStream Demo

UpsDemo.java

import java.io.*;
public class UpsDemo
{
public static void main(String args[]) throws Exception
{
PrintStream dos=new PrintStream(System.out,
true);
dos.println("Integer is"+20);
dos.println("Character are:");
dos.println("Bytes are:");
}
}

In the above program, the second parameter passed to the Printstream


constructor specifies the default auto flush features to be activated. However, this
features works only along with the println() methods.

21.9 THE FileOutputstream CLASS

FileOutpuStream creates an OutputStream that can be used to write


bytes to a file. Its most commonly used constructors are shown below.
FileOutputStream(File file)
Creates a file output stream to write to the file represented by the
specified File object.
FileOutputStream(String name)
Creates an output file stream to write to the file with the specified name.
FileOutputStream(String name, boolean append)
Creates an output file stream to write to the file with the specified name.

236
21.10 I/O EXCEPTIONS

An IOException is used to signal an I/O error. The constructors available in


the I/O exception are :
IOException()
This constructor constructs an IOException with no detail message. A
detail message is a String that describes this particular exception.
IOException(String)
This constructor constructs an IOException with the specified detail
message.
Example :
public IOException(String s)
Constructs an IOException with the specified detail message. A detail
message is a String that describes this particular exception. Parameter s
represents the detail message

Check Your Progress : 1

Itemize a few I/O classes available in Java.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this lesson.
……………………………………………………………………..

……………………………………………………………………..
……………………………………………………………………..

Example: Adding Data to a file and Display the Data From the file.

FileDemo2.java

import java.io.*;
public class FileDemo2
{
String s;
File f=new File("test.txt");

237
DataInputStream dis=new DataInputStream(System.in);
public void menu()throws Exception
{
System.out.println("1. Add Data to a file");
System.out.println("2. Display a File");
System.out.println("3. Exit");
System.out.println("Enter Your Choice");
}
public void select()throws Exception
{ while(true)
{
menu();
s=dis.readLine();
String s1;
int i=Integer.parseInt(s);
if(i==1)
{
System.out.println("Enter Statement");
s=dis.readLine();
PrintStream o=new PrintStream(new FileOutputStream(f),true);
o.println(s);
}
if(i==2)
{
DataInputStream dis1=new DataInputStream(new FileInputStream(f));
while((s1=dis1.readLine()).length()!=0)
{
System.out.println(s1);
}
}
if(i==3)
{

238
System.exit(0);
}
}
}
public static void main(String args[])throws Exception
{ FileDemo2 fd=new FileDemo2();
fd.select();
}
}

When the first choice is selected, the data accepted from the user should
be added to the file. The second choice allows the user to view the contents of
the file. Third choice exists from the program.

21.11 LET US SUM UP

In this lesson we have discussed the different classes and methods used
for Input and Output handling in Java. The following points were discussed in
this lesson:
• The Java input and output package-java.io-is used to implement
streams.
• The FileInputStream Class creates an Inputstream that can be used to
read bytes from a file.
• The OutputStream Class and abstract class which is the superclass of
all classes representing an output stream of bytes.
• A data input stream lets an application write primitive Java data types to
an output stream in a portable way.
• A PrintStream adds functionality to another output stream, namely the
ability to print representations of various data values conveniently.
• All characters printed by a PrintStream are converted into bytes using
the platform's default character encoding.

21.12 CHECK YOUR PROGRESS : MODEL ANSWERS

1. Following are a few I/O streams available in java. A few of these could be
discussed :

239
The FileInputStream Class, The FileOutputstream Class. The OutputStream
Class, The FilterOutputStream Class, The BufferedOutputStream Class, The
DataOutputStream Class,The PrintStream Class.

240
LESSON 22

FILE HANDLING

CONTENTS
22.0 Aims and Objectives
22.1 Introduction
22.2 Reader Class
22.2.1 Hierarchy of the Reader class
22.2.2 Input Stream Reader
22.2.3 The BufferedReader
22.2.4 The FileReader class
22.3 Writer Class
22.3.1 Hierarchy of the Writer Class
22.3.2 The Filewriter Class
22.4 Let us sum up
22.5 Check Your Progress: Model Answers
22.6 Programming Exercises

22.0 AIMS AND OBJECTIVES

This lesson aims at introducing the concept of files, which are used for
permanent storage. The methods and classes defined for file handling are
discussed in this lesson.
By the end of this session, you would know how data files are created,
updated and processed by Java programs. Here, we shall consider both
sequential and random files and indicate the kinds of application for which they
are best suited.

22.1 INTRODUCTION

The data and programs in a computer's main memory survive only as


long as the power is on. For more permanent storage, computers use files,
which are collections of data stored on a hard disk, on a USB memory stick, on
a CD-ROM, or on some other type of storage device. Files are organized into
directories (sometimes called folders). A directory can hold other directories, as
well as files. Both directories and files have names that are used to identify
them.

241
Programs can read data from existing files. They can create new files and
can write data to files. In Java, such input and output can be done using
streams. Human-readable character data is read from a file using an object
belonging to the class FileReader, which is a subclass of Reader. Similarly, data
is written to a file in human-readable format through an object of type
FileWriter, a subclass of Writer. For files that store data in machine format, the
appropriate I/O classes are FileInputStream and FileOutputStream. In this
section, we discuss character-oriented file I/O using the FileReader and
FileWriter classes. However, FileInputStream and FileOutputStream are used in
an exactly parallel fashion. All these classes are defined in the java.io package.
A stream is a sequence of data of undetermined length. Data is fetched
into a program when a stream of information namely a file, memory or a socket
is opened and read serially. Similarly, a program can send information to an
external destination by opening a stream to a destination and writing the data
serially.
Package java.io provides system input and output through data streams,
serialization and the file system.

Class Summary

A BufferedInputStream adds functionality to


another input stream-namely, the ability to
BufferedInputStream
buffer the input and to support the mark and
reset methods.

BufferedOutputStream The class implements a buffered output stream.

Read text from a character-input stream,


BufferedReader buffering characters so as to provide for the
efficient reading of characters, arrays, and lines.

Write text to a character-output stream,


buffering characters so as to provide for the
BufferedWriter
efficient writing of single characters, arrays, and
strings.

A data input stream lets an application read


DataInputStream primitive Java data types from an underlying
input stream in a machine-independent way.

A data input stream lets an application write


DataOutputStream primitive Java data types to an output stream in
a portable way.

242
An abstract representation of file and directory
File
pathnames.

A FileInputStream obtains input bytes from a file


FileInputStream
in a file system.

A file output stream is an output stream for


FileOutputStream
writing data to a File or to a FileDescriptor.

FileReader Convenience class for reading character files.

FileWriter Convenience class for writing character files.

This abstract class is the superclass of all


InputStream
classes representing an input stream of bytes.

An InputStreamReader is a bridge from byte


streams to character streams: It reads bytes and
InputStreamReader
translates them into characters according to a
specified character encoding.

This abstract class is the superclass of all


OutputStream
classes representing an output stream of bytes.

Writes characters to an output stream,


OutputStreamWriter translating characters into bytes according to a
specified character encoding.

A PrintStream adds functionality to another


output stream, namely the ability to print
PrintStream
representations of various data values
conveniently.

Print formatted representations of objects to a


PrintWriter
text-output stream.

Instances of this class support both reading and


RandomAccessFile
writing to a random access file.

Reader Abstract class for reading character streams.

243
Writer Abstract class for writing to character streams.

22.2 THE READER CLASS

The Reader class is an abstract class used for reading character streams.
The only methods that a subclass must implement are read(char[ ], int, int) and
close(). Most subclasses, however, will override some of the methods defined
here in order to provide higher efficiency, additional functionality, or both.
public int read()throws IOException
Reads a single character. This method will block until a character is
available, or I/O error occurs, or the end of the stream is reached.

public int read(char[] cbuf) throws IOException


Read characters into an array. This method will block until some input is
available, an I/O error occurs, or the end of the stream is reached.

22.2.1 Hierarchy of the Reader class:

Object

Reader Class

BufferedReader Class

InpurStreamReader Class

FileReader Class

244
Figure 22.1 Hierarchy of Reader class

22.2.2 Input Stream Reader Class:


Reader is an abstract class. One of the concrete sublasses is
InputStreamReader, which converts bytes to characters. To obtain an
InputStreamReader object that is linked to System.in, uses the following
constructor:
InputStreamReader(InputStream inputstream)
InputStreamReader(System.in)
System.in Refers to an object of type InputStream
Reading character by using InputStreamReader. Each time read() is
called, it reads a character from the input stream and returns it as an
integer value.
Example 1: InputStreamReader Demo:
Accept the string from the user and print it.

uisrdemo.java
import java.io.*;
class uisrdemo
{
public static void main(String args[])throws Exception
{
String str=" ";char c1;
InputStreamReader id=new
InputStreamReader(System.in);
System.out.println("Enter Statement");
char c=(char)id.read();
System.out.println(c);
while(c!='\n')
{
str=str+c;

245
c=(char)id.read();
}
System.out.println(str);
}
}

22.2.3 The BufferedReader


The BufferedReader is used to read text from a character-input stream,
buffering characters so as to provide for the efficient reading of characters,
arrays, and lines. The buffer size may be specified, or the default size may be
used. The default is large enough for most purposes. It enhances the
performance of the input operation by making it faster than directly using the
InputStreamReader
BufferedReader(Reader in)
Create a buffering character-input stream that uses a default-sized input
buffer.
BufferedReader(Reader in,int sz)
Create a buffering character-input stream that uses an input buffer of the
specified size.
Example: BuferedReader Demo

ubuffdemo.java

import java.io.*;
public class ubuffdemo
{
public static void main(String args[])throws Exception
{
String str=" ";
BufferedReader id=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter Statement");
char c=(char)id.read();
System.out.println(c);
BufferedReader id1=new BufferedReader(new

246
InputStreamReader(System.in));
System.out.println ("Enter another Statement");
System.out.println("Enter 'stop' to exit");
do
{
str=id1.readLine();
System.out.println (str);
} while(!str.equals("stop"));
}
}

22.2.4 The FileReader class:


The FileReader class is a Convenient class used for reading character
files. The constructors of this class assume that the default character encoding
and the default byte-buffer size are appropriate
FileReader(Strung filename) – The name of the file to be opened for input can be
specified as parameter to this constructor.
FileReader(File fileobject) – An object of the file class is passed to this
constructor. The file specified in the file object is opened for input.
Example: Read file

ufiledemo.java

import java.io.*;
public class ufiledemo
{
public static void main(String args[])throws
Exception
{
File f1=new File("stringdemo.java");
FileReader fr=new FileReader(f1);

char str;
int x;
while((x=fr.read())!=-1)

247
{
str=(char)x;
System.out.println(str);
}
fr.close();
}
}

The above program is used to open a file called stringdemo.java for input.
The data stored in this file is read character by character and displayed on the
screen using the read() method.

22.3 WRITER CLASS

The writer class is an abstract class for writing to character streams.


The only methods that a subclass must implement are write(char[], int, int)
which write a portion of an array of characters, flush() which used to flush or
clear a stream, and close() which used to close stream object. Most subclasses,
however, will override some of the methods defined here in order to provide
higher efficiency, additional functionality, or both.

void write(int c)
Write a single character.

void write(String str)


Write a string.

void write(String str, int off, int len)


Write a portion of a string.

22.3.1 Hierarchy of the Writer Class:

Object

Writer Class

` OutputStreamwriter Class

BufferedWriter Class BufferedWriter Class


248

FileWriter Class
Figure 22.2 Hierarchy of Writer class

22.3.2 The FileWriter class:


The FileWriter class is used to write characters to a file. The most
commonly used constructors of this file are as follows:
FileWriter(File fileobject) – The File class object can be passed to
constructor.
FileWriter(String filename) – The name of the file is passed as a
parameter. The existing content of the file are lost in this case.
FileWriter(String filename, boolean append) – the name of the file is
paseed as the first parameter. The second parameter is to specify if the
file needs to be opened in an append mode.
The FileWriter supports all the write() methods present in the Writer class.
However for effective file output, the FileWriter class is used along with the
PrintWriter class.

Check Your Progress : 1

List the constructors available in the FileWriter and FileReader Class.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this
lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

249
Example: FileWriter Demo.
Accept the String from the user and display into the file.

ufiledemo1.java

import java.io.*;
public class ufiledemo1
{
public static void main(String args[])throws Exception
{
PrintWriter o=new PrintWriter(new
FileWriter("out.txt",true),true);
o.println("Welcome to File Demo");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the Statement");
String s=br.readLine();
o.println(s);
}
}

The above program demonstrates the use of FileWriter. When this


program is executed, it asks for a statement from the user, and once the user
enters a statement through the keyboard, the file is created. The details are
written into the file out.txt. The contents of the output file can be viewed using
any text editor or by using the command type out.txt in the command prompt.

22.4 LET US SUM UP

In this lesson we have learnt the different classes and methods related
with handling files. Following are the points that we have discussed in
this lesson:
• Files are organized into directories (sometimes called folders). A
directory can hold other directories, as well as files.
• A stream is a sequence of data of undetermined length.
• Package java.io provides system input and output through data
streams, serialization and the file system.

250
• The Reader class is an abstract class used for reading character
streams
• The BufferedReader is used to read text from a character-input
stream, buffering characters so as to provide for the efficient reading
of characters, arrays, and lines.
• The writer class is an abstract class for writing to character streams.

22.5 CHECK YOUR PROGRESS : MODEL ANSWERS

1. The constructors available in the FileReader class are FileReader(Strung


filename), FileReader(File fileobject)
The constructors available in the FileWriter class are FileWriter(File
fileobject), FileWriter(String filename), FileWriter(String filename, boolean
append)

22.6 PROGRAMMING EXERCISES

1. Write a program to accept 10 numbers from the user. Print the total,
average, product, largest and the smallest and the difference between the
largest and the smallest and write them into a file
2. Write a program to accept two files names from the user and check
whether it is directory or file. If both are file then the contents of one file
should be appended to the contents of the second file.
3. Write a Java Program to read the name and telephone number of 10
consumers and store them in a file.

251
252
LESSON 23

STREAMS AND STREAM CLASSES


CONTENTS
23.0 Aims and Objectives
23.1 Introduction
23.2 Predefined Streams
23.3 The InputStream Class
23.4 The BufferedInputStream Class
23.5 The DataInputStream class
23.6 Let us sum up
23.7 Check Your Progress: Model Answers

23.0 AIMS AND OBJECTIVES

In the previous lesson we have learnt the different file handling methods
present in Java. The lesson aims at making the learner familiar with the
streams and classes. At the end of this lesson the learner will be able to write
Java programs which makes use of streams.

23.1 INTRODUCTION

A stream is a sequence of data of undetermined length. Data is fetched


into a program when a stream on information namely a file, memory or a socket
is opened and read serially. Similarly, a program can send information to an
external destination by opening a stream to a destination and writing the data
serially.

23.2 PREDEFINED STREAMS

All Java programs automatically import the java.lang package. This


package defines a class called System, which encapsulates several aspects of
the run-time environment. For example, using some of its methods, you can
obtain the current time and the settings of various properties associated with
the system. System also contains three predefined stream variables, in, out,
and errs. These fields are declared as public and static within System. This
means that they can be used by any other part of your program and without
reference to a specific System object.
System.out refers to the standard output stream. By default, this is the
console. System.in refers to standard input, which is the keyboard by default.
System.err refers to the standard error stream, which also is the console by
default. However, these streams may be redirected to any compatible I/O
device.

253
System.in is an object of type InputStream; System.out and System.err are
objects of type PrintStream. These are byte streams, even though they typically
are used to read and write characters from and to the console.

23.3 THE InputStream CLASS

The InputStream class is the base class for the FilterInputStream class,
DataInputStream, FileInputStream class and the BufferedInputStream class. The
InputStream class contains the default constructor. This class also contains an
abstract method, which is defined in the following manner:

int available()
Returns the number of bytes that can be read (or skipped over)
from this input stream without blocking by the next caller of a
method for this input stream.

void close()
Closes this input stream and releases any system resources
associated with the stream.

abstract int read()


Reads the next byte of data from the input stream.

int read(byte[] b)
Reads some number of bytes from the input stream and stores
them into the buffer array b.

int read(byte[] b, int off, int len)


Reads up to len bytes of data from the input stream into an
array of bytes.

23.3.1 Hierarchy of the InputStream class:

Object

InputStream Class

BufferedInputStream class DataInputStream Class

254
FilterInputStream class
FileInputStream class

Figure 23.1 Hierarchy of Input Stream class

23.4 THE BufferedInputStream CLASS

A BufferedInputStream adds functionality to another input stream-


namely, the ability to buffer the input and to support the mark and reset
methods. When the BufferedInputStream is created, an internal buffer array is
created. As bytes from the stream are read or skipped, the internal buffer is
refilled as necessary from the contained input stream, many bytes at a time.
The mark operation remembers a point in the input stream and the reset
operation causes all the bytes read since the most recent mark operation to be
reread before new bytes are taken from the contained input stream.
This class contains the following constructors:

BufferedInputStream(InputStream in)
Creates a BufferedInputStream and saves its argument, the
input stream in, for later use.

BufferedInputStream(InputStream in, int size)


Creates a BufferedInputStream with the specified buffer size,
and saves its argument, the input stream in, for later use.

Example : BufferedInputStream Demo

ubuf.java

import java.io.*;
public class ubuf
{
public static void main(String args[])throws Exception
{
byte[] arr;
arr=new byte[30];
BufferedInputStream b=new BufferedInputStream(System.in);
b.read(arr,0,30);
String str=new String(arr);
System.out.println(str);

255
}
}

In this example, the read() method is used to accept an array of bytes


from the user and is stored in arr. These bytes are then converted and stored in
a string variable called str.
Check Your Progress : 1

What is a buffered stream? List the constructors available in the buffered


stream class.

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this
lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

23.5 THE DataInputStream CLASS

The DataInputStream class is used for more sophisticated read


operations. The constructor of this class is given below.
DataInputStream(InputStream in)
Creates a FilterInputStream and saves its argument, the input stream in.
It is used for input operation.
The methods available in DataInputStram Class are:
int read() – This method is used to read the next byte from the input
stream.
int read(byte[], int offset, int length) – This method is used to read bytes
from the InputStream into the specified byte array, starting at the given
offset. The number of bytes to be read is also specified.
String readLine() – the readLine() method is a sophisticated method that
can be used to read strings from the user.
Example: DataInputStreamDemo:

udisdemo.java

256
import java.io.*;
public class udisdemo
{
public static void main(String args[])throws Exception
{ String s=" ";
StringBuffer sb=new StringBuffer(s);
DataInputStream dis=new DataInputStream(new
BufferedInputStream(System.in));
System.out.println("Enter The paragraph");
while(((s=dis.readLine()).length())!=0)
{ sb=sb.append(s);
s=" ";
}
System.out.println("Paragraph was "+sb);
}
}

In the above program readLine() method is used for accepting the single
line and appending in the StringBuffer object.

23.6 LET US SUM UP

This lesson has focused on the methods and the facilities available in
Stream and the classes used in Stream handling. We have discussed the
following points :
• The java.lang package defines a class called System, which encapsulates
several aspects of the run-time environment.
• System.out refers to the standard output stream
• System.in is an object of type InputStream; System.out and System.err are
objects of type PrintStream.
• The InputStream class is the base class for the FilterInputStream class,
DataInputStream, FileInputStream class and the BufferedInputStream
class.
• A BufferedInputStream adds functionality to another input stream-
namely, the ability to buffer the input and to support the mark and reset
methods.

257
23.7 CHECK YOUR PROGRESS : MODEL ANSWERS

1. A BufferedInputStream adds functionality to another input stream-


namely, the ability to buffer the input and to support the mark and reset
methods. The constructors available in the BufferedInputStream class
are:
BufferedInputStream(InputStream in, int size)
BufferedInputStream(InputStream in)

258
LESSON 24

THE CHARACTER STREAMS

CONTENTS
24.0 Aims and Objectives
24.1 Introduction
24.2 Reader
24.3 Writer
24.4 FileReader Class
24.5 FileWriter Class
24.6 CharArrayReader
24.7 CharArrayWriter
24.8 BufferedReader
24.9 BufferedWriter
24.10 PushBackReader
24.11 PrintWriter
24.12 Let us sum up
24.13 Check Your Progress: Model Answers

24.0 AIMS AND OBJECTIVES

This lesson aims at introducing character streams. Different methods


that are available for handling character streams are discussed in this lesson.
At the end of this lesson, the reader will be able to understand character
streams and write simple programs, which makes use of character streams.

24.1 INTRODUCTION

While the byte stream classes provide sufficient functionality to handle


any type of I/O operation, they cannot work directly with Unicode characters.
Since one of the main purposes of Java is to support the “write once, run
anywhere” philosophy, it was necessary to include direct I/O support for
characters. In this section, several of the character I/O classes are discussed.
As explained earlier, at the top of the character stream hierarchies are the
Reader and Writer abstract classes.

24.2 Reader

Reader is an abstract class that defines Java’s model of streaming


character input. All of the methods in this class will throw an IOException on

259
error conditions. The following table provides a synopsis of the methods in
Reader.

Method Description

abstract void close( ) Closes the input source. Further read


attempts will generate an IOException.

void mark(int numChars) Places a mark at the current point in the


input stream that will remain valid until
characters are read.

boolean markSupported( Returns true if mark( )/reset( ) are


) supported on this stream.

int read( ) Returns an integer representation of the


next available character from the
invoking input stream.
–1 is returned when the endof the file is
encountered.

int read(char buffer[ ]) Attempts to read up to buffer.length


characters into buffer and returns the
actual number of characters that were
successfully read.
–1 is returned when the end of the file is
encountered.

abstract int read(char Attempts to read up to numChars


buffer[ ], int offset, int characters into buffer starting at
numChars) buffer[offset], returningthe number of
characters successfully read. –1 is
returned when the end of the file is
encountered.

boolean ready( ) Returns true if the next input request will


not wait. Otherwise, it returns false.

void reset( ) Resets the input pointer to the previously


set mark.

24.3 Writer

Writer is an abstract class that defines streaming character output. All


of the methods in this class return a void value and throw an IOException in
the case of errors. The following Table shows the various methods present in
Writer.

260
Method Description

abstract void close( ) Closes the output stream. Further write


attempts will generate an IOException.

abstract void flush( ) Finalizes the output state so that any


buffers are cleared. That is, it flushes
the output buffers.

void write(int ch) Writes a single character to the


invoking output stream.

void write(char buffer[ ]) Writes a complete array of characters to


the invoking output stream.

abstract void write(char buffer[ Writes a subrange of numChars


],int offset,int numChars) characters from the array buffer,
beginning at buffer[offset] to the
invoking output stream.

void write(String str) Writes str to the invoking output


stream.

void write(String str, int offset,int Writes a subrange of numChars


numChars) characters from the array str,

24.4 FileReader

The FileReader class creates a Reader that can be used to read the
contents of a file. Its two most commonly used constructors are shown here:
FileReader(String filePath)
FileReader(File fileObj)
Either can throw a FileNotFoundException. Here, filePath is the full path
name of a file,
and fileObj is a File object that describes the file.

24.5 FileWriter JAVA LIBRARY


FileWriter creates a Writer that is used to write to a file. Its most commonly
used constructors are shown here:
FileWriter(String filePath)

261
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)
FileWriter(File fileObj, boolean append)
They can throw an IOException. Here, filePath is the full path name of a
file, and fileObj is a File object that describes the file. If append is true, then
output is appended to the end of the file. The fourth constructor was added by
Java 2, version 1.4.
Creation of a FileWriter is not dependent on the file already existing.
FileWriter will create the file before opening it for output when you create the
object. In case if an attempt is to open a read-only file, an IOException will be
thrown.
The following example is a character stream version of an example shown
earlier when FileOutputStream was discussed. This version creates a sample
buffer of characters by first making a String and then using the getChars( )
method to extract the character array equivalent. It then creates three files. The
first, file1.txt, will contain every other character from the sample. The second,
file2.txt, will contain the entire set of characters. Finally, the third, file3.txt,
will contain only the last quarter.

// Demonstrate FileWriter.
import java.io.*;
class FileWriterDemo
{
public static void main(String args[]) throws Exception
{
String source = "Now is the time for all good men\n" + " to come to the
aid of their country\n" + " and pay their due taxes.";
char buffer[] = new char[source.length()];
source.getChars(0, source.length(), buffer, 0);
THE JAVA LIBRARY
FileWriter f0 = new FileWriter("file1.txt");
for (int i=0; i < buffer.length; i += 2)
{
f0.write(buffer[i]);
}
f0.close();
FileWriter f1 = new FileWriter("file2.txt");

262
f1.write(buffer);
f1.close();
FileWriter f2 = new FileWriter("file3.txt");
f2.write(buffer,buffer.length-buffer.length/4,buffer.length/4);
f2.close();
}
}

24.6 CharArrayReader

CharArrayReader is an implementation of an input stream that uses a


character array as the source. This class has two constructors, each of which
requires a character array to provide the data source:
CharArrayReader(char array[ ])
CharArrayReader(char array[ ], int start, int numChars)

Here, array is the input source. The second constructor creates a Reader from
a subset of your character array that begins with the character at the index
specified by start and is numChars long.

The following example uses a pair of CharArrayReaders:


// Demonstrate CharArrayReader.
import java.io.*;
public class CharArrayReaderDemo {
public static void main(String args[]) throws IOException {
String tmp = "abcdefghijklmnopqrstuvwxyz";
int length = tmp.length();
char c[] = new char[length];
THE JAVA LIBRARY
tmp.getChars(0, length, c, 0);
CharArrayReader input1 = new CharArrayReader(c);
CharArrayReader input2 = new CharArrayReader(c, 0, 5);
int i;
System.out.println("input1 is:");

263
while((i = input1.read()) != -1
{
System.out.print((char)i);
}
System.out.println();
System.out.println("input2 is:");
while((i = input2.read()) != -1)
{
System.out.print((char)i);
}
System.out.println();
}
}
The input1 object is constructed using the entire lowercase alphabet, while
input2 contains only the first five letters.
Here is the output:
input1 is:
abcdefghijklmnopqrstuvwxyz
input2 is:
abcde

24.7 CharArrayWriter

CharArrayWriter is an implementation of an output stream that uses an


array as the destination. CharArrayWriter has two constructors, shown here:
CharArrayWriter( )
CharArrayWriter(int numChars)
In the first form, a buffer with a default size is created. In the second, a
buffer is created with a size equal to that specified by numChars. The buffer is
held in the buf field of CharArrayWriter. The buffer size will be increased
automatically, if needed. The number of characters held by the buffer is
contained in the count field of CharArrayWriter. Both buf and count are
protected fields.
The following example demonstrates CharArrayWriter by reworking the
sample program shown earlier for ByteArrayOutputStream. It produces the
same output as the previous version.
// Demonstrate CharArrayWriter.

264
import java.io.*;
class CharArrayWriterDemo
{
public static void main(String args[]) throws IOException
{
CharArrayWriter f = new CharArrayWriter();
String s = "This should end up in the array";
char buf[] = new char[s.length()];
s.getChars(0, s.length(), buf, 0);
f.write(buf);
System.out.println("Buffer as a string");
System.out.println(f.toString());
System.out.println("Into array");
char c[] = f.toCharArray();
for (int i=0; i<c.length; i++)
{
System.out.print(c[i]);
}
System.out.println("\nTo a FileWriter()");
FileWriter f2 = new FileWriter("test.txt");
f.writeTo(f2);
f2.close();
System.out.println("Doing a reset");
f.reset();
for (int i=0; i<3; i++)
f.write('X');
System.out.println(f.toString());
}
}
Check Your Progress : 1

Enumerate a few classes and methods related with character handling.

Notes : a) Write your answer in the space given below.

265
b) Check your answer with the one given at the end of this lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

24.8 BufferedReader

BufferedReader improves performance by buffering input. It has two


constructors:
BufferedReader(Reader inputStream)
BufferedReader(Reader inputStream, int bufSize)
The first form creates a buffered character stream using a default buffer
size. In the second, the size of the buffer is passed in bufSize. As is the case
with the byte-oriented stream, buffering an input character stream also
provides the foundation required to support moving backward in the stream
within the available buffer. To support this, BufferedReader implements the
mark() and reset() methods, and BufferedReader.markSupported( ) returns
true.
The following example uses a BufferedReader character stream rather
than a buffered byte stream. It uses mark( ) and reset( ) methods to parse a
stream for the HTML entity reference for the copyright symbol. Such a reference
begins with an ampersand (&) and ends with a semicolon (;) without any
intervening whitespace.
The sample input has two ampersands, to show the case where the
reset( ) happens and where it does not. Output is the same as that shown
earlier.
// Use buffered input.
import java.io.*;
class BufferedReaderDemo
{
public static void main(String args[]) throws IOException
{
String s = "This is a &copy; copyright symbol " + "but this is &copy
not.\n";
char buf[] = new char[s.length()];
s.getChars(0, s.length(), buf, 0);

266
CharArrayReader in = new CharArrayReader(buf);
BufferedReader f = new BufferedReader(in);
int c;
boolean marked = false;
while ((c = f.read()) != -1)
{
switch(c)
{
case '&':
if (!marked)
{Yf.mark(32);
marked = true;
}
else
{ marked = false;
}
break;
case ';':
if (marked)
{
marked = false;
System.out.print("(c)");
}
else
System.out.print((char) c);
break;
case ' ':
if (marked)
{ marked = false;
f.reset();
System.out.print("&");
}

267
else
System.out.print((char) c);
break;
default:
if (!marked)
System.out.print((char) c);
break;
}
}
}
}

24.9 BufferedWriter

A BufferedWriter is a Writer that adds a flush( ) method that can be


used to ensure that data buffers are physically written to the actual output
stream. Using a BufferedWriter can increase performance by reducing the
number of times data is actually physically written to the output stream.
A BufferedWriter has these two constructors:
BufferedWriter(Writer outputStream)
BufferedWriter(Writer outputStream, int bufSize)
The first form creates a buffered stream using a buffer with a default size. In
the second, the size of the buffer is passed in bufSize.

24.10 PushbackReader

The PushbackReader class allows one or more characters to be returned


to the input stream. This allows you to look ahead in the input stream. Here are
its two constructors:
PushbackReader(Reader inputStream)
PushbackReader(Reader inputStream, int bufSize)
The first form creates a buffered stream that allows one character to be pushed
back. In the second, the size of the pushback buffer is passed in bufSize.
PushbackReader provides unread( ), which returns one or more characters to
the invoking input stream. It has the three forms shown here:
void unread(int ch)
void unread(char buffer[ ])
void unread(char buffer[ ], int offset, int numChars)

268
The first form pushes back the character passed in ch. This will be the next
character returned by a subsequent call to read( ). The second form returns the
characters in buffer. The third form pushes back numChars characters
beginning at offset from buffer. An IOException will be thrown if there is an
attempt to return a character when the pushback buffer is full.
The following program reworks the earlier PushBackInputStream example by
replacing PushBackInputStream with a PushbackReader. As before, it shows
how a programming language parser can use a pushback stream to deal with
the difference between the == operator for comparison and the = operator for
assignment.

// Demonstrate unread().
import java.io.*;
class PushbackReaderDemo
{
public static void main(String args[]) throws IOException
{
String s = "if (a == 4) a = 0;\n";
char buf[] = new char[s.length()];
s.getChars(0, s.length(), buf, 0);
CharArrayReader in = new CharArrayReader(buf);
PushbackReader f = new PushbackReader(in);
int c; JAVA LIBRARY
while ((c = f.read()) != -1)
{
switch(c)
{
case '=':
if ((c = f.read()) == '=')
System.out.print(".eq.");
else
{
System.out.print("<-");
f.unread(c);
}

269
break;
default:
System.out.print((char) c);
break;
}
}
}
}

24.11 PrintWriter

PrintWriter is essentially a character-oriented version of PrintStream. It


provides the formatted output methods print( ) and println( ). PrintWriter has
four constructors:
PrintWriter(OutputStream outputStream)
PrintWriter(OutputStream outputStream, boolean flushOnNewline)
PrintWriter(Writer outputStream)
PrintWriter(Writer outputStream, boolean flushOnNewline)
where flushOnNewline controls whether Java flushes the output stream every
time println( ) is called. If flushOnNewline is true, flushing automatically takes
place. If false, flushing is not automatic. The first and third constructors do not
automatically flush. Java’s PrintWriter objects support the print( ) and
println( ) methods for all types, including Object. If an argument is not a
simple type, the PrintWriter methods will call the object’s toString( ) method.

24.12 LET US SUM UP

In this lesson we have learnt the classes and methods available for
handling character streams in Java. We have discussed the following
points in this lesson :
• Reader is an abstract class that defines Java’s model of streaming
character input.
• Writer is an abstract class that defines streaming character output.
• BufferedReader(Reader inputStream) is a constructor present in
BufferedReader class that creates a buffered character stream using a
default buffer size.

270
• The PushbackReader class allows one or more characters to be
returned to the input stream.

24.13 CHECK YOUR PROGRESS : MODEL ANSWERS

1. The following are a few classes/methods used for handling character


streams:
CharArrayReader is an implementation of an input stream that
uses a character array as the source.
CharArrayWriter is an implementation of an output stream that
uses an array as the destination.
PrintWriter is essentially a character-oriented version of
PrintStream. It provides the formatted output methods print( )
and println( ).

LESSON 25

RANDOM ACCESS FILES AND BYTE STREAMS

CONTENTS
25.0 Aims and Objectives
25.1 Introduction
25.2 Random Access files
25.3 ByteArrayInputStream
25.4 ByteArrayOutputStream
25.5 Filtered Byte Streams
25.6 Buffered Byte Streams
25.7 Let us sum up
25.8 Check Your Progress: Model Answers

25.0 AIMS AND OBJECTIVES

In the previous lesson we have learnt the character stream and the
methods available in the character stream. This lesson aims at making the
learner understand the use of Random files. The functions required for creating
and accessing random files are discussed in this lesson.
At the end of this lesson the learner will be able to write Java programs
that can access files in a random manner.

271
25.1 INTRODUCTION

There are two methods to access a file. They are sequential and random
mode. Random mode files access the required data in a faster manner. Several
methods are available in Java for accessing files sequentially and in a random
manner.

25.2 RANDOM ACCESS FILE

RandomAccessFile encapsulates a random-access file. It is not derived


from InputStream or OutputStream. Instead, it implements the interfaces
DataInput and DataOutput, which define the basic I/O methods. It also
supports positioning requests—that is, it is possible to position the file pointer
within the file.
The constructors available are
RandomAccessFile(File fileObj, String access)throws FileNotFoundException
RandomAccessFile(String filename, String access) throws
FileNotFoundException

The first syntax, fileObj specifies the name of the file to open as a File object. In
the second form, the name of the file is passed in filename. In both cases,
access determines what type of file access is permitted. If it is “r”, then the file
can be read, but not written. If it is “rw”, then the file is opened in read-write
mode. If it is “rws”, the file is opened for read-write operations and every change
to the file’s data or metadata will be immediately written to the physical device.
If it is “rwd”, the file is opened for read-write operations and every change to the
file’s data will be immediately written to the physical device.
The method seek( ), shown here, is used to set the current position of the file
pointer within the file:
void seek(long newPos) throws IOException
Here, newPos specifies the new position, in bytes, of the file pointer from the
beginning of the file. After a call to seek( ), the next read or write operation will
occur at the new file position.
RandomAccessFile implements the standard input and output methods,
which you can be used to read and write to random access files. It also includes
some additional methods. One is setLength( ).
The setLength() is of the form:
void setLength(long len) throws IOException
This method sets the length of the invoking file to that specified by len. This
method can be used to lengthen or shorten a file. If the file is lengthened, the
added portion is undefined.
Java 2, version 1.4 added the getChannel( ) method to
RandomAccessFile. This method returns a channel connected to the

272
RandomAccessFile object. Channels are used by the new I/O classes contained
in java.nio.

25.3 ByteArrayInputStream

ByteArrayInputStream is an implementation of an input stream that


uses a byte array as the source. This class has two constructors, each of which
requires a byte array to provide the data source:
ByteArrayInputStream(byte array[ ])
ByteArrayInputStream(byte array[ ], int start, int numBytes)
Here, array is the input source. The second constructor creates an InputStream
from a subset of the byte array that begins with the character at the index
specified by start and is numBytes long.
The following example creates a pair of ByteArrayInputStreams,
initializing them with the byte representation of the alphabet:
// Demonstrate ByteArrayInputStream.
import java.io.*;
class ByteArrayInputStreamDemo {
public static void main(String args[]) throws IOException {
String tmp = "abcdefghijklmnopqrstuvwxyz";
byte b[ ] = tmp.getBytes();
ByteArrayInputStream input1 = new ByteArrayInputStream(b);
ByteArrayInputStream input2 = new ByteArrayInputStream(b, 0,3);
}
}
The input1 object contains the entire lowercase alphabet, while input2 contains
only the first three letters.
A ByteArrayInputStream implements both mark( ) and reset( ). However,
if mark() has not been called, then reset( ) sets the stream pointer to the start of
the stream—which in this case is the start of the byte array passed to the
constructor. The next example shows how to use the reset( ) method to read the
same input twice. In this case, we read and print the letters “abc” once in
lowercase and then again in uppercase.
import java.io.*;
class ByteArrayInputStreamReset {
public static void main(String args[]) throws IOException {
String tmp = "abc";
byte b[] = tmp.getBytes();

273
ByteArrayInputStream in = new ByteArrayInputStream(b);
for (int i=0; i<2; i++) {
int c;
while ((c = in.read()) != -1)
{
if (i == 0)
{
System.out.print((char) c);
}
else
{ System.out.print(Character.toUpperCase((char) c));
}
}
System.out.println();
in.reset();
}
}
}
This example first reads each character from the stream and prints it as
is, in lowercase. It then resets the stream and begins reading again, this time
converting each character to uppercase before printing.
The output for the above program would be
abc
ABC

25.4 ByteArrayOutputStream

ByteArrayOutputStream is an implementation of an output stream that


uses a byte array as the destination. ByteArrayOutputStream has two
constructors, as shown below :
ByteArrayOutputStream( )
ByteArrayOutputStream(int numBytes)
In the first form, a buffer of 32 bytes is created. In the second, a buffer is
created with a size equal to that specified by numBytes. The buffer is held in
the protected buf field of ByteArrayOutputStream. The buffer size will be
increased automatically, if needed.

274
The number of bytes held by the buffer is contained in the protected count field
of ByteArrayOutputStream.
The following example demonstrates ByteArrayOutputStream:
// Demonstrate ByteArrayOutputStream.
import java.io.*;
class ByteArrayOutputStreamDemo
{
public static void main(String args[]) throws IOException
{
ByteArrayOutputStream f = new ByteArrayOutputStream();
String s = "This should end up in the array";
byte buf[] = s.getBytes();
f.write(buf);
System.out.println("Buffer as a string");
System.out.println(f.toString());
System.out.println("Into array");
byte b[] = f.toByteArray();
for (int i=0; i<b.length; i++)
{
System.out.print((char) b[i]);
}
System.out.println("\nTo an OutputStream()");
OutputStream f2 = new FileOutputStream("test.txt");
f.writeTo(f2);
f2.close();
System.out.println("Doing a reset");
f.reset();
for (int i=0; i<3; i++)
f.write('X');
System.out.println(f.toString());
}
}

275
The following output is created when the program is executed.
Buffer as a string
This should end up in the array
Into array
This should end up in the array
To an OutputStream()
Doing a reset
XXX
This example uses the writeTo( ) convenience method to write the contents of f
to test.txt. Examining the contents of the test.txt file created in the preceding
example shows the result we expected:

25.5 Filtered Byte Streams

Filtered streams are simply wrappers around underlying input or output


streams that transparently provide some extended level of functionality. These
streams are typically accessed by methods that are expecting a generic stream,
which is a superclass of the filtered streams. Typical extensions are buffering,
character translation, and raw data translation. The filtered byte streams are
FilterInputStream and FilterOutputStream.
The constructors of Filtered Byte streams are :
FilterOutputStream(OutputStream os)
FilterInputStream(InputStream is)
The methods provided in these classes are identical to those in InputStream
and OutputStream.

Check Your Progress : 1

List the constructors available in ByteArrayInputStream and


ByteArrayOutputStream..

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this
lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

276
25.6 Buffered Byte Streams

For the byte-oriented streams, a buffered stream extends a filtered


stream class by attaching a memory buffer to the I/O streams. This buffer
allows Java to do I/O operations on more than a byte at a time, hence
increasing performance. Because the buffer is available, skipping, marking, and
resetting of the stream becomes possible. The buffered byte stream classes are
BufferedInputStream and BufferedOutputStream. PushbackInputStream also
implements a buffered stream.

25.6.1 BufferedInputStream

Buffering I/O is a very common performance optimization. Java’s


BufferedInputStream class allows you to “wrap” any InputStream into a
buffered stream and achieve this performance improvement.
BufferedInputStream has two constructors:
BufferedInputStream(InputStream inputStream)
BufferedInputStream(InputStream inputStream, int bufSize)

The first form creates a buffered stream using a default buffer size. In the
second, the size of the buffer is passed in bufSize. Use of sizes that are
multiples of memory page, disk block, and so on can have a significant positive
impact on performance. This is, however, implementation-dependent. An
optimal buffer size is generally dependent on the host operating system, the
amount of memory available, and how the machine is configured. To make good
use of buffering doesn’t necessarily require quite this degree of sophistication. A
good guess for a size is around 8,192 bytes, and attaching even a rather small
buffer to an I/O stream is always a good idea. That way, the low-level system
can read blocks of data from the disk or network and store the results in the
buffer. Thus, while reading the data a byte at a time out of the InputStream, it
will be manipulating fast memory over 99.9 percent of the time.
Buffering an input stream also provides the foundation required to
support moving backward in the stream of the available buffer. Beyond the
read( ) and skip( ) methods implemented in any InputStream,
BufferedInputStream also supports the mark( ) and reset( ) methods. This
support is reflected by BufferedInputStream.markSupported( ) returning true.
The following example shows a situation where we can use mark( ) to
remember where we are in an input stream and later use reset( ) to get back
there. This example is parsing a stream for the HTML entity reference for the
copyright symbol. Such a reference begins with an ampersand (&) and ends
with a semicolon (;) without any intervening whitespace. The sample input has
two ampersands to show the case where the reset( ) happens and where it does
not.
// Use buffered input.
import java.io.*;

277
class BufferedInputStreamDemo
{
public static void main(String args[]) throws IOException
{
String s = "This is a &copy; copyright symbol " + "but this is &copy
not.\n";
byte buf[] = s.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(buf);
BufferedInputStream f = new BufferedInputStream(in);
int c;
boolean marked = false;
while ((c = f.read()) != -1)
{
switch(c)
{
case '&':
if (!marked)
{ f.mark(32);
marked = true;
}
else
marked = false;
break;
case ';':
if (marked)
{
marked = false;
System.out.print("(c)");
}
else
System.out.print((char) c);
break;

278
case ' ':
if (marked)
{ marked = false;
f.reset();
System.out.print("&");
}
else
System.out.print((char) c);
break;
default:
if (!marked)
System.out.print((char) c);
break;
}
}
}
}
Notice that this example uses mark(32), which preserves the mark for the
next 32 bytes read (which is enough for all entity references).
The output produced by the above program is :
This is a (c) copyright symbol but this is &copy not.
Use of mark( ) is restricted to access within the buffer. This means that it is
possible to apply only specify parameter to mark( ) that is smaller than the
buffer size of the stream.
25.6.2 BufferedOutputStream
A BufferedOutputStream is similar to any OutputStream with the
exception of an added flush( ) method that is used to ensure that data buffers
are physically written to the actual output device. Since the point of a
BufferedOutputStream is to improve performance by reducing the number of
times the system actually writes data, you may need to call flush( ) to cause any
data that is in the buffer to get written.
Unlike buffered input, buffering output does not provide additional
functionality. Buffers for output in Java are there to increase performance. Here
are the two available constructors:
BufferedOutputStream(OutputStream outputStream)
BufferedOutputStream(OutputStream outputStream, int bufSize)

279
The first form creates a buffered stream using a buffer of 512 bytes. In the
second form, the size of the buffer is passed in bufSize.

Check Your Progress : 2

List the constructors available in BufferedInputStream and


BufferedOutputStream..

Notes : a) Write your answer in the space given below.


b) Check your answer with the one given at the end of this
lesson.
……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

……………………………………………………………………..

25.7 LET US SUM UP

In this lesson we have learnt the implementation of Random access files


in Java and the different byte streams available in Java. We have discussed the
following points in this lesson :
• RandomAccessFile is not derived from InputStream or OutputStream, it
implements the interfaces DataInput and DataOutput, which define the
basic I/O methods.
• RandomAccessFile implements the standard input and output methods,
which can be used to read and write to random access files
• ByteArrayInputStream is an implementation of an input stream that
uses a byte array as the source.
• In Java the buffered stream extends a filtered stream class by attaching
a memory buffer to the I/O streams.

25.8 CHECK YOUR PROGRESS : MODEL ANSWERS

1. The constructors available in the ByteArrayOutputStream() are


ByteArrayOutputStream( )
ByteArrayOutputStream(int numBytes)
The constructors available in the ByteArrayInputStream() are
ByteArrayInputStream(byte array[ ])
ByteArrayInputStream(byte array[ ], int start, int numBytes)

280
2. The constructors available in the BufferedInputStream() are
BufferedInputStream(InputStream inputStream)
BufferedInputStream(InputStream inputStream, int bufSize)
The constructors available in the BufferedOutputStream() are
BufferedOutputStream(OutputStream outputStream)
BufferedOutputStream(OutputStream outputStream, int bufSize)

281

You might also like