BCA_JavaProgramming
BCA_JavaProgramming
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.1 INTRODUCTION
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.
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
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
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
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
11
1.6 APPLICATIONS OF OOP
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.
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
13
14
LESSON 2
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
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
15
2.2 EVOLUTION 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.
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.
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
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.
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
……………………………………………………………………..
……………………………………………………………………..
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.
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.
……………………………………………………………………..
23
24
LESSON 3
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
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.
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++.
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
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.
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
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
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
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 API
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.
Documentation Section
Suggested
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
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
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.
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.
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.
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.
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
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.
42
43
LESSON 5
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
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
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.
45
6. Comments
o Line
o Block
Check Your Progress : 1
……………………………………………………………………..
……………………………………………………………………..
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.
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
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
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.
Byte 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.
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
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
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
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
\” Double quote
\\ Backslash
\r Carriage return
\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.
……………………………………………………………………..
……………………………………………………………………..
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.
56
HeyCount2 2HeyCount Begins with Numbers.
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.
58
6.5 VARIABLES AND INITIALIZATION
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
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 :
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.
instance
class False Import private this
of
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
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.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
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.
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.
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.
+ Addition Addition
- Subtraction Subtraction
* Multiplication Multiplication
/ Division Division
Remainder of a
division
% Modulus
(can also be applied to
floating point values)
Example : 1
The Java statement:
x = x + 1;
can be rewritten by using the increment operator as
66
x++;
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
67
7.5 ARITHMETIC ASSIGNMENT OPERATORS
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.
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.
0 0 0 0 0 1
1 0 1 0 1 0
0 1 1 0 1 1
1 1 1 1 0 0
The relational operators are used to compare two values. The following tables
give a list of Relational operators.
== Equal to
!= Not Equal to
69
<= Less than or Equal to
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 OR
^ Bitwise exclusive OR
|= Bitwise OR assignment
70
For example, the number 42, which has the following bit pattern:
00101010
becomes
11010101
after the NOT operator is applied.
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
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.
Priority 1 ()[].
Highest
2 ++ – – ~ !
3 */%
4 +–
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.
{ } ; , :
74
• The operators available in Java are Assignment Operator, Arithmetic
Operators, Arithmetic assignment operator, Boolean logical operator,
Relational operators, Bitwise operators, Ternary Operator.
75
LESSON 8
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
76
8.1 INTRODUCTION
8.2 if 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
…………. ………….
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
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.
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
……………………………………………………………………..
……………………………………………………………………..
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.
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
1. The conditional control statements available in Java are if, if..else, switch
statements.
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.1 INTRODUCTION
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.
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();
}
}
}
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
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.
……………………………………………………………………..
……………………………………………………………………..
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.
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).
94
• The return statement is used to explicitly return from a method
•
1. The loop structures available in Java are for loop, while loop, do..while
loop.
95
1 2 3 5 3 2 1
96
LESSON 10
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.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
}
}
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
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.
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);
}
}
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);
}
106
}
b.display();
t.display();
}
}
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.
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
type methodname1(parameter-list)
{
//body of the method
}
type methodname2(parameter-list)
{
//body of method
}
}
110
111
LESSON 11
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
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
11.2 ARRAYS
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
11.3 STRINGS
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
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)
stringdemo.java
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:
Example: stringBufferDemo
stringbufferdemo.java
119
}
}
Output:
Length :11
Capacity :27
Before Appending :Hello world
Append :Hello world!
Insert :hiHello world!
Reverse :!dlrow olleHih
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
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.
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());
}
}
}
122
11.6 CHECK YOUR PROGRESS : MODEL ANSWERS
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.1 INTRODUCTION
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.
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.
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.
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
130
12.5 ACCESSING IMPLEMENTATIONS THROUGH INTERFACE REFERENCES
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.
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
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
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
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
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
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();
}
}
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.
shape.java
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.
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.
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();
}
}
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.1 INTRODUCTION
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.
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()
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();
}
}
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
151
b) Check your answer with the one given at the end of this unit.
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
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.
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.
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.
158
15.9 THREAD DAEMON
1. The methods available for implementing thread class are start(), stop(),
suspend(), resume(), sleep(), join(), yield().
159
LESSON 16
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
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
16.2 EXCEPTION
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.
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());
}
}
}
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
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”);
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.
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
167
try block throws a divide-by-zero exception. If it is two then an array boundary
exception is generated.
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;
}
}
}
}
What are the different blocks available for exception handling in Java.
……………………………………………………………………..
……………………………………………………………………..
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]));
}
}
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
1. The different blocks available for exception handling in Java are try,
throw, catch, finally
173
174
LESSON 17
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.1 INTRODUCTION
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.
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
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.
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:
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.
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:
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.
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.
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(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.
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.
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:
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.
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.
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
……………………………………………………………………..
……………………………………………………………………..
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
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.
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:
187
windowClosed(WindowEvent we)
windowActivated(WindowEvent we)
windowDeactivated(WindowEvent we)
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.
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.
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
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.
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.
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.
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
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
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.
197
And the same could be part of the HTML file and executed through the web
browser or tested through the appletviewer itself.
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
}
Init
Start
Leave Reload or resize browser
web page or return to web pages
Stop
Exit
Browser
Destroy
SampleApplet.java
import java.awt.*;
import java.applet.*;
199
/*<applet code="SampleApplet" width=300 height=300></applet>*/
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
……………………………………………………………………..
……………………………………………………………………..
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.*;
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.
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
……………………………………………………………………..
……………………………………………………………………..
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
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.1 INTRODUCTION
206
import java.awt.Graphics;
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.
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.
210
rectangles, there are also different methods for drawing and filling; draw3Drect()
and fill3DRect().
Here is a code to produce 3D rectangle :
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).
211
Figure 19.3 Output screen showing polygon generated by the above
program
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;
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.
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.
……………………………………………………………………..
……………………………………………………………………..
215
……………………………………………………………………..
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.
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
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
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
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.
Write the general forms of the methods used for drawing ellipses and
rectangles.
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
220
20.4 DRAWING ELLIPSES AND CIRCLES
// 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
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
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.
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.1 INTRODUCTION
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.
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
}
}
Object
OutputStream 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.
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();
}
}
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();
}
}
234
Method Summary of PrintStream class
void println() Terminate the current line by writing the line separator string.
void println(char[] x)Print an array of characters and then terminate the line.
235
void println(String x) Print a String and then terminate the line.
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:");
}
}
236
21.10 I/O EXCEPTIONS
……………………………………………………………………..
……………………………………………………………………..
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.
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.
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
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
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
242
An abstract representation of file and directory
File
pathnames.
243
Writer Abstract class for writing to character streams.
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.
Object
Reader Class
BufferedReader Class
InpurStreamReader Class
FileReader Class
244
Figure 22.1 Hierarchy of Reader class
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);
}
}
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"));
}
}
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.
void write(int c)
Write a single character.
Object
Writer Class
` OutputStreamwriter Class
FileWriter Class
Figure 22.2 Hierarchy of Writer class
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
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);
}
}
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.
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
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
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.
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.
int read(byte[] b)
Reads some number of bytes from the input stream and stores
them into the buffer array b.
Object
InputStream Class
254
FilterInputStream class
FileInputStream class
BufferedInputStream(InputStream in)
Creates a BufferedInputStream and saves its argument, the
input stream in, for later use.
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
}
}
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
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.
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
258
LESSON 24
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.1 INTRODUCTION
24.2 Reader
259
error conditions. The following table provides a synopsis of the methods in
Reader.
Method Description
24.3 Writer
260
Method Description
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.
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
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.
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
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
265
b) Check your answer with the one given at the end of this lesson.
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
24.8 BufferedReader
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
24.10 PushbackReader
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
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.
LESSON 25
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
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.
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
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
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:
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
276
25.6 Buffered Byte Streams
25.6.1 BufferedInputStream
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 © copyright symbol " + "but this is ©
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 © 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.
……………………………………………………………………..
……………………………………………………………………..
……………………………………………………………………..
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