Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
168 views

Java

Uploaded by

Kavya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
168 views

Java

Uploaded by

Kavya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 381

Karnataka State Open University

Mukthagangotri, Mysore-570006

MSc Computer science


First Semester

Oops with JAVA

COURSE – MCSDSC-1.2 BLOCK – 1-4


CREDIT PAGE

Programme Name: MSc-Computer Science Year/Semester: I Semester Block No:1-4

Course Name: OOPs with Java Credit: 4 Unit No: 1-16

Course Design Expert Committee


Dr. Vidyashankar S. Chairman
Vice Chancellor,
Karnataka State Open University,
Mukthagangotri, Mysuru-570006.

Dr. Ashok Kamble Member


Dean (Academic),
Karnataka State Open University,
Mukthagangotri, Mysuru-570 006.

Editorial Committee
Dr. D M Mahesha MCA.,PhD Chairman
BOS Chairman,
Assistant Professor & Programme co-ordinator(PG)
DoS&R in Computer Science,
Karnataka State Open University, Mysuru-570 006.

Smt, Suneetha MSc.,(PhD) Member Convener


Dept Chairperson & Programme co-ordinator (UG)
DoS&R in Computer Science,
Karnataka State Open University, Mysuru-570 006.

Dr Bhavya D.N., MTech., PhD Member


Assistant Professor & Programme co-ordinator(UG)
DoS&R in Computer Science,
Karnataka State Open University, Mysuru-570 006.

Dr. Ashoka S B., MSc.PhD Member


External Subject Expert,
Assistant Professor,
DoS&R in Computer Science,
Maharani’s Cluster University, palace Road Bangalore-01
Name of Course Writer No of No Name of No
Blocks of Course Editor of
Units Units

Dr. Sumati Ramakrishna Dr. Bhavya D N


Gowda., Assistant Professor
BE (CS & E)., MSc(IT)., Block-1 1-2 1-2
DoS in Computer Science
MPhil(CS)., Ph.D.,
Assistant Professor Karnataka State Open
DoS&R in Computer Science, University
Karnataka State Open Mukthagangothri, Mysore-06
University, Mysuru-06

Dr. Natesh M Block-1-4 3-16 Dr. Poornima Y 3-16


Associate Professor Asst, Professor
VVCE Mysore-02 Dos in Computer Science
Maharaja’s College-
5700021

Copy Right
Registrar,
Karnataka State Open University,
Mukthagantoghri, Mysore 570 006.

Developed by the Department of Studies and Research in Computer science, under


the guidance of Dean (Academic), KSOU, Mysuru.
Karnataka State Open University, February-2022.
All rights reserved. No part of this work may be reproduced in any form or any other
means, without permission in writing from the Karnataka State Open University.
Further information on the Karnataka State Open University Programmes may be obtained
from the University’s Office at Mukthagangotri, Mysore – 570 006.

Printed and Published on behalf of Karnataka State Open University, Mysore-570 006 by
the Registrar (Administration)-2022
TABLE OF CONTENTS

BLOCK 1 PAGE NO.

UNIT- 1 Introduction to java 1-41

UNIT-2 Java methods 42-75

UNIT-3 Arrays 76-85

UNIT-4 Strings 86-100

BLOCK 1I

UNIT-5 Inheritance in java 101-114

UNIT-6 Overriding 115-128

UNIT-7 Dynamic binding 129-140

UNIT-8 Abstract class 141-170

BLOCK 1II

UNIT-9 Event and GUI Programming 171-185

UNIT-10 Panels 186-227

UNIT-11 Gui programming 228-253

UNIT-12 Applet and its life cycle 254-301

BLOCK 1V

UNIT-13 Text and binary i/o classes, object i/o, random access files 302-321

UNIT-14 Multithreading in java 322-333

UNIT-15 Thread synchronization 335-356

UNIT-16 Introduction to Java Beans 357-376


Preface
Think Java is an introduction to computer science and programming intended for readers with
little or no experience. We start with the most basic concepts and are careful to define all terms
when they are first used. The book presents each new idea in a logical progression. Larger
topics, like recursion and object-oriented programming, are divided into smaller examples and
introduced over the course of several chapters.

Object Oriented Programming with Java is introductory computer programming course that
uses Java as the language of instruction and OOP concepts enhances the simplicity and power
in handling. It is suitable for use in an introductory programming course and for people who
are trying to learn programming on their own. There are no prerequisites beyond a general
familiarity with the ideas of computers and programs. There is enough material for a full course
at this-level programming. The whole course is comprised of 4 Blocks of 16 units’ total.
UNIT 1: INTRODUCTION TO JAVA

Structure
1.0 Objectives
1.1 Introduction
1.2 Java and Its Salient Features
1.3 Fundamentals of Java Programming ,Data Types, Variables, Operators, Control
Structures, Including Selection Looping
1.4 Introduction to OOP’s
1.5 Summary
1.6 Key words
1.7 Questions for Self Study
1.8 Suggested readings

1.0 OBJECTIVES

At the end of this unit you will be able to

 Explain Java and its Features.


 Developing a Java Program
 Data types, Literals, Expressions and Operators
 Programming Constructs
 Describe OOP’s.

1
1.1 INTRODUCTION

This unit introduces us to Java and its salient features. It lists the newly added
features in Java 2. This unit lays a firm groundwork to Java, explaining in brief
the various data types, literals, operators and programming constructs available.
This unit also gives us a brief introduction to the Object-Oriented Programming
Structure (OOPS).

1.2 JAVA AND ITS SALIENT FEATURES

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


Microsystems in 1991. It is designed to be small, simple and portable across different
platforms as well as operating systems.

The popularity of Java is due to its unique technology that is designed on the basis of
three key elements. They are the usage of applets, powerful programming language
constructs and a rich set of significant object classes.

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


instructions that is specific to the processor. In the Java development environment
there are two parts: a Java compiler and a Java interpreter.

The compiler generates bytecode (a set of instructions that resemble machine code
but are not specific to any processor) instead of machine code and the interpreter
executes the Java program

The disadvantage of using bytecode is the execution speed. Since system specific
programs run directly on the hardware, they are faster than the Java bytecodes that is
processed by the interpreter. In order to write a Java program, an editor, a Java
compiler and a Java Runtime Environment are needed.

The editor can be a Notepad, WordPad, MS-DOS editor etc. The easiest way to get a
Java Compiler and Runtime Environment is to download Sun's Java Development Kit.

2
This provides system input and output capabilities and other utility functions in
addition to classes that support networking, common Internet protocols and user
interface toolkit functions.

Features of Java
Java was designed to meet all the real world requirements with its key features, which
are explained in the following paragraphs. The features of Java are also known as
Java buzzwords.

A list of the most important features of the Java language is given below.

1. Simple

2. Object-Oriented

3. Portable

4. Platform
independent

5. Secured

6. Robust

7. Architecture neutral

8. Interpreted

3
9. High Performance

10. Multithreaded

11. Distributed

12. Dynamic

Simple and powerful: Java is very easy to learn, and its syntax is simple,
clean and easy to understand. According to Sun Microsystem, Java language is
a simple programming language because:

o Java syntax is based on C++ (so easier for programmers to learn it after C++).

o Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.

o There is no need to remove unreferenced objects because there is an


Automatic Garbage Collection in Java.

No concept of Pointers, Explicit Memory Allocation, Structures, Operator


Overloading etc.
Java was designed to be easy for the professional programmer to learn and use
effectively. Java makes itself simple by not having surprising features. Since it
exposes the inner working of a machine, the programmer can perform his desired
actions without fear. Unlike other programming systems that provide dozens of
complicated ways to perform a simple task, Java provides a small number of clear
ways to achieve a given task.
Anyone can master Java with a little bit of programming experience. If the user
already understands the basic concepts of object-oriented programming, learning Java
will be much easier.
Object-oriented : Java is an object-oriented programming language. Everything in
Java is an object. Object-oriented means we organize our software as a combination
of different types of objects that incorporate both data and behavior.

4
Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules. Basic OOPs concepts such as
Object, Class, Inheritance, Polymorphism, Abstracton and Encapsulation.

Portable:
Java Program written in one environment can be executed in another
Environment. Run on any Environment

In Java, the same mechanism that gives security also helps in portability. Many types
of computers and operating systems are in use throughout the world and are
connected to the Internet. For downloading programs through different platforms
connected to the Internet, some portable, executable code is needed. Java’s answer to
these problems is its well- designed architecture.
Platform Independent:

Java is platform independent because it is different from other languages like C, C++,

etc. which are compiled into platform specific machines while Java is a write once,
run anywhere language. A platform is the hardware or software environment in which
a program runs.

There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.

The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on top of other hardware-based platforms. It has two
components:

1. Runtime Environment

2. API(Application Programming
Interface)

Java code can be executed on multiple


platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc. Java code is compiled
by the compiler and converted into bytecode.
This bytecode is a platform-independent code

5
because it can be run on multiple platforms, i.e., Write Once and Run Anywhere
(WORA).

Secure : Secured

Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:

o No explicit pointer

o Java Programs run inside a virtual machine sandbox

o Classloader: Classloader in Java is a part of the Java Runtime Environment


(JRE) which is used to load Java classes into the Java Virtual Machine
dynamically. It adds security by separating the package for the classes of the
local file system from those that are imported from network sources.

o Bytecode Verifier: It checks the code fragments for illegal code that can
violate access rights to objects.

o Security Manager: It determines what resources a class can access such as


reading and writing to the local disk.

Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS, Cryptography,

6
etc.

Secure for Internet applications, It will raise out of Boundary Exception in


Arrays. For Arrays size 10 after execution will thru exception if pgm contains
more than that. It is also a strong typed language.

Today everyone is worried about safety and security. People feel that conducting
commerce over the Internet is as safe as printing their credit card number on the first
page of a Newspaper. Threatening of viruses and system hackers also exists. To
overcome all these fears Java has safety and security as its key design principle.
Using Java Compatible Browser, anyone can safely download Java applets without
the fear of viral infection or malicious intent. Java achieves this protection by
confining a Java program to the Java execution environment and by making it
inaccessible to other parts of the computer. We can download applets with confidence
that no harm will be done and no security will breached.

Robust:
Early identification and Checking of errors. This can be achieved with the help
of Garbage Collection, Exception Handling.

Java is robust because:

o It uses strong memory management.

o There is a lack of pointers that avoids security problems.

o Java provides automatic garbage collection which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.

o There are exception handling and the type checking mechanism in Java. All
these points make Java robust.

Most programs in use today fail for one of the two reasons: memory management or
exceptional conditions. Thus, the ability to create robust programs was given a high
priority in the design of Java. Java forces the user to find mistakes in the early stages

7
of program development. At the same time, Java frees the user from having to worry
about many of the most common causes of programming errors Java checks code at
compilation time. However, It also checks the code at run time.

Java virtually rectifies the problem of memory management by managing memory


allocation and automatic memory deallocation by providing garbage collection for
unused objects. Java also handles exceptional conditions by providing object-oriented
exception handling. In a well-written Java program, all run-time errors can - and
should - be managed by the program itself.

Multithreaded : Concurrent execution of several parts of same programs at the


same time. This will improve CPU utilization.
A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-media, Web
applications, etc.

Java was designed to meet the real-world requirements of creating interactive,


networked programs. To achieve this, Java supports multithreaded programming,
which allows the user to write programs that perform many functions simultaneously.
The Java run-time system enables the user to construct smoothly running interactive
systems. Java's easy-to use approach to multithreading allows the user to think about
the specific behavior of his/her own program, not the multitasking subsystem.

Architecture-neutral:

Java is architecture neutral because there are no implementation dependent features,


for example, the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of
memory for both 32 and 64-bit architectures in Java.

Irrespective of architecture, the memory allocated to the varibles will not vary.

8
The Java designers worked hard in attaining their goal "write once; run anywhere,
anytime, forever" and as a result the Java Virtual Machine was developed. A main
issue for the Java designers was that of code longevity and portability. One of the
main problems is the execution speed of the program. Since Java is Architecture-
neutral it generates bytecode that resembles machine code, and are not specific to any
processor.

Interpreted and High performance


Java enables the creation of cross-platform programs by compiling the code into an
intermediate representation called Java byte code. This code can be interpreted on any
system that has a Java Virtual Machine. Most of the earlier cross-platform solutions
are run at the expense of performance. Other Interpreted systems, such as BASIC, Tel
and PERL, suffer from almost insoluble performance deficits. Java, however, was
designed to perform well on very low -power CPUs. Java byte code was carefully
designed so that it can be easily translated into native machine code for very high
performance by using a just-in-time compiler. " High-performance cross platform" is
no longer an oxymoron.

Distributed : It is a software that runs on multiple computers connected to a


network at the same time. For this Java requires 1. RMI (Remote Method
Invocation ) and 2. EJB (Enterprise Java Beans) .
So with the help of these two java can be implemented in distributed
environment.

Java is designed for the distributed environment for the Internet, because it handles
TCP/IP protocols. In fact, accessing a resource using a URL is not entirely different
from accessing a file. Original Version of Java (OAK) included features for intra-
address-space messaging. This allowed objects on two different computers to execute
procedures remotely. Java has recently revived these interfaces in a package called
Remote Method Invocation (RMI).

Dynamic:
Java is a dynamic language. It supports the dynamic loading of classes. It means

9
classes are loaded on demand. It also supports functions from its native languages,
i.e., C and C++.

Java programs carry with them extensive amounts of run-time information that is used
to verify and resolve accesses to objects at run time. Using this concept it is possible
to dynamically link code. Dynamic property of Java adds strength to the applet
environment, which small fragments of byte code may be dynamically updated on a
running system.

Newly Added Features in Java 2

1. Swing is a set of user interface components that is implemented entirely in


Java.The user can use a look and feel that is either specific to a particular
operating system or uniform across operating systems.
2. Collections are groups of objects. Java provides several types of collection, such
as linked lists, dynamic arrays, and hash tables, for our use. Collections offer a
new way to solve several common programming problems.
3. Various tools such as javac, java and javadoc have been enhanced. Debugger
and profiler interfaces for the JVM are available.
4. Performance improvements have been made in several areas. A Just-In-Time
(JIT) compiler is included in the JDK.
5. Policy files can define the permissions for code from various sources. These
determine if a particular file or directory may be accessed, or if a connection can
be established to a specific host and port.
6. Digital certificates provide a mechanism to establish the identity of a user, which
can be referred as electronic passports.
7. The Java 2D library provides advanced features for working with shapes, images
and text.
8. Various security tools are available that enable the user to create and store
cryptographic keys and digital certificates, sign Java Archive (JAR) files, and
check the signature of a JAR file.
9. The user can now play audio files such as MIDI, AU, WAY and RMF files using
Java programs.

10
1.3 Fundamentals of Java Programming, Data Types, Variables, Operators,
Control Structures, Including Selection Looping
Developing a Java Program
The Sun's Java Development Kit (JDK) provides all features to write programs. The
JDK is available for systems running Windows NT, Windows 95 and Solaris 2.3 or
higher. Java applications are general programs written in the Java language that do not
require a browser to run. The Java source file is created in a plain text editor and can
also be created in an editor that saves files in plain ASCII without any formatting
characters. To type in a program, in UNIX systems, the vi or pico editors are used
whereas in Windows, the Notepad or DOS editor is employed. A Java program has
two main parts - a class definition that encloses the entire program and a method
called main that contains the body. Once the program is typed in, it is saved as a file
with an extension of .java. Usually, Java files have the same name as their class
definition. This file is then compiled using javac. The javac program should be in the
execution path for compilation of the Java code. Once completed, a file by the same
name, but with the .class extension is created. This is the Java bytecode file. The
bytecode.is then run using the Java interpreter. In the JDK, the Java interpreter is
called java. To execute this, java followed by the file name without the .class
extension is typed at the DOS prompt. The above compilation and execution
procedure works only if Sun's Java compiler is used.

The following example depicts the writing of a Java program. Compile and execute
the program.

Example 2.1

• Open a new file in the editor and type the following script

1: Class First {
2: public static void main (String args[ ]) {
3: System.out.println(“WELCOME TO JAVA CLASS”);
4: }
5: }

11
 Save the file as First.java.
 Compile by typing javac First.java on the command line.
 On successful compilation execute the program by typing java First,
on the command line.
 The output of the program appears as follows:

Welcome to java class

In addition to compilation and execution, both Java compiler and the Java interpreter
check the Java source code and bytecode to make sure that the Java programmer has
not overrun buffers, stack frames etc.
Class declaration is done in line no. 1. Every Java application program has a
main( ) method. It is the first function run when the program is executed. The void
keyword preceding main( ) indicates that it does not return any values. public
indicates that the method is global, static denotes that main( ) is a class method
and can be called without creating an object. Line 3 gives the syntax for printing a
string onto the screen. The curly braces are used to enclose the class and main
function.

Note: The line numbers given are not part of the source code and should not be
typed so.

Data Types, Literals, Expressions and Operators

For effective and easy programming, any programming language offers the user data
types, expressions and operators. These features are present in Java and are
elucidated in the following paragraphs.

Data Types

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.

12
These are primitive types as they are built into the Java language and are not actual
objects thus making it easier to use them. The data types in Java are machine
independent. New types are declared by a class definition and objects of this class
can be created. There are times when the data types are required to be true objects.
Wrapper classes are provided for the primitive types for this purpose. The wrapper
classes for the primitive data types have the same name as the primitive type, but
with the first letter capitalized. The advantage of using wrappers is that when an
object is passed to a method, the method is able to work on the object itself.
Another advantage is that the user can derive his/her own classes from Java's built-
in wrapper classes

Integer

Integers are used for storing integer values. There are four kinds of integer types in
Java. Each of these can hold a different range of values. The values can either be
positive or negative. Depending on the range of values that it should hold, the type of
integer is chosen. If the value becomes too large, it will be truncated. The table for the
range of values is given below:

Type Size Range


byte 8 bits -128-127
short 16 bits -32,768 - 32,767
int 32 bits -2,147,483,648 - -2,147,483,647
long 64 bits -9223372036854775808 -
9223372036854775807

Table 2.1

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).

13
Character

It is used-for storing individual characters. The char type has 16 bits of precision and
it is unsigned.

Boolean

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

Variables

Variables are locations in the memory that can hold values. Before assigning any
value to a variable, it must be declared. Java has three kinds of variables namely,
 Instance variables
 Local variables
 Class variables

Local variables are used inside blocks as counters or in methods as temporary


variables. Once the block or the method is executed, the variable ceases to exist. The
local variables are used to store information needed by a single method.

Instance variables are used to define attributes or the state of a particular object. These
are used to store information needed by multiple methods in the objects.

Class varibles are explained in the next session.

All three kinds of varibles are declared in the same way,but class and instance
varibles are alone are acessed in a different manner.

Declaring Variables

Variables can be declared anywhere in the method definition and can be initialized

14
during their declaration. They are commonly declared before usage at the beginning
of the definition. Variables with the same data type can be declared together. Local
variables must be given a value before usage.

Variable Names

Variable names. in Java can start with a letter, an underscore ( _ ), or a dollar sign ($)
but cannot begin with a number. The second character onwards can include any letter
or number. Java is case sensitive and also uses the Unicode character set.

Variable Types

Variable types can be any data type that Java supports - the eight primitive types, the
name of a class or Interface and an array.

Assigning Values
Values are assigned to variables using the assignment operator "equal to" (=).
The following example demonstrates declaration, initiation and display of variables.

Example 2.2
1: class Second {
2: public static void main (String args[ ]) {
3: int x = 90;
4: short y = 4;
5: float z = 10.87f;
6: String name = "Aarti";
7: System.out.println("The integer value is " + x);
8: System.out.println("\nThe Short value is " + y);
9: System.out.println("\n The float value is " + z);
10: System.out.println(" \n The string value is " + name);
11: }

12: }
Note: The line numbers given are not part of the source code and should not be

15
typed so.

 Save this file as Second.java and compile using javac Second.java at DOS
prompt.
 On successful compilation, execute the program using java Second
 The output is displayed as shown below:

The integer value is 90


The short value is 4

The float value is 10.87

The string value is Aarti

The lines 3 - 6 depict the declaration, initialization and naming of-various data types.
The values of the declared variables are printed from lines 7 - 10. The + operator is
used here as a concatenation operator which is dealt later

Note: The line numbers given are not part of the source code and should not be
typed so.

Literals

A Literal represents a value of a certain type where the type describes the
behaviour of the value.

There are different types of literals. They are:

 Number literals
 Character literals
 Boolean literals
 String literals

Number

There are several integer literals such as int, long, octal, hexadecimal, etc. 4 is an

16
example of a decimal integer literal of type into If a decimal integer literal is larger
than the int, it is declared to be of type long. A number can be made long by
appending L or l to it.
Negative integers are preceded by the minus sign. These integers can also be
expressed as octal or hexadecimal. A leading 0 to the integer indicates that the
number is an octal integer. For example, 0987 is an octal integer. A leading Ox to the
integer indicates that the number is a hexadecimal integer, example, 0xaf94 is a
hexadecimal number.

Floating point literals have a decimal part and an integer part. Floating point literals
result in floating point numbers of type double. By appending f to a number, it can
be changed as type float. Exponents can be used in floating point literals by using
the letter E or e followed by the exponent.

Boolean

Boolean literals consist of the keywords true and false.

Character

Character literals are expressed by a single character enclosed within single quotes.
Characters are stored as Unicode characters. Table 2.2 lists the special codes that
represent non-printable characters and characters from Unicode character set.

Escape Meaning
\n Newline
\t Tab
\b Backspace
\r Carriage return
\f Form feed
\\ Backslash
\' Single quote
\" Double quote
\ddd Octal
\xdd Hexadecimal
\udddd Unicode
Table 2.2
character

17
The letter 'd' in the octal, hex and the Unicode escapes represent a number or a
hexadecimal digit . Java does not include character codes for the bell and the vertical
tab.

StrIng

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

When a string literal is declared Java automatically creates an instance of the class
String and initializes it with the value specified.

Expressions

Expressions are the simplest form of statements in Java. These statements return a
value that can be assigned to a variable. The following are examples for
expressions:

X+ 15
count/2
total-l
Operators

Operators are special symbols used in expressions. They include arithmetic


operators, assignment operators, increment and decrement operators, logical
operators, bitwise operators and comparison operators.

Arithmetic Operators

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

18
Operator Meaning Example
+ Addition 8 + 10
- Subtraction 10- 8
* Multiplication 20 * 84
/ Division 10 / 5
% Modulus 10%6

Table 2.3

The subtraction operator is also used to negate a single operand. Integer division
results in an integer. Any remainder due to integer division is ignored. Modulus
gives the remainder once the division has been completed. For integer types, the result
is an int regardless of the type of the operands. If anyone or both the operands is of
type long, then the result is also long. If one operand is an int and the other is float,
then the result is a float.

Example 2.3 illustrates the usage of various arithmetic operators.


Example 2.3
• Open a new file in the editor and type the following script.
1: class Three {
2: public static void main (String args[ ]) {
3: int x=10;
4: int y=20;
33335: float z=25.98f;

6: System.out.println("The value of x + y is " + (x+y));


7: System.out.println("The value of z - y is " + (z-y));
8: System.out.println("The value of x * y is " + (x *y));
9: System.out.println("The value of z/ y is " + (z/y));
10: System.out.println("The value of z % y is " + (z% y));
11: }
12: }

Note: The line numbers given are not part of the source code and should not be
typed so.

19
 Save this file as Three.java and compile using javac Three.java at DOS prompt.
 On successful compilation, execute the source code using: java Three
 The output appears as shown below:

The value of x + y is 30
The value of z - y is 5.9799995

The value of x *y is 200

The value of z / y is 1.299

The value of z % y is 5.9799995

Notice the usage of the various arithmetic operators from lines 6 - 10.

Assignment Operators

The assignment operators used in C and C++ are also used in Java. A selection of .
assignment operators is given.

Expression Meaning
x+=y x=x+y
x -= y x=x-y
x *= y x=x*y
x/=Y x = x/ y
x=y x=y
Table 2.4

Example 2.4 demonstrates the various operator assignments in action.

20
Example 2.4

• Open a new file in the editor and type the following script.

1: class assign{
2: public static void main(String args[ ]) {
3: int a=1;

.: int b=2;
5: int c=3;

6: a+=5;

7: b*=4;
8: c+=a*b;

9: c%=6;

10: System.out.println ("a=" +a);

11: System.out.println("b=" +b);

12: System.out.println("c=" +c);

13: }

14: }
Note: The line numbers given are not part of the source code and should not be
typed so.

 Save this file as assign.java and compile using javac assign.java at the
DOS prompt.
 On successful compilation, execute the source code using: java assign
 The output appears as shown below:
a=6
b=8

c=3

21
Incrementing and Decrementing

To increment or decrement a value by one, the ++ operator and -- operator are


used respectively. The increment and the decrement operators can be prefixed or
postfixed. The different increment and decrement operators can be used as given
below:

 ++a (Pre increment operator): Increment "a" by 1, then use the new value
of "a" in the expression in which "a" resides.
 a++ (Post increment operator): Use the current value of "a" in the
expression in which "a" resides and then increment "a" by 1.
 --b (Pre decrement operator): Decrement "b" by 1, then use the new value
of "b" in the expression in which "b" resides .
 .b- -(Post decrement operator): Use the current value of "b" in the
expression in which "b" resides and then decrement "b" by 1.

Example 2.5 demonstrates the usage of the increment and decrement operators.
Example 2.5
 Open a new file in the editor and type the following script.
1: class IncDec {
2: public static void main (String args[ ]) {
3: int a =1;
4: int b=2;
5: int c=++b;
6: int d=a++;
7: c++;
8: System.out.println(" a = " + a) ;
9: System.out.println(" b = " + b) ;
10: System.out.println(" c = " + c) ;
11: System.out.println(" d = " + d);
12: }
13: }

22
 Save this file as InDec.java and compile using javac InDec.java at the DOS
prompt. \
 On successful compilation, execute the source code using: java IncDec
 The output appears as given below:

a=2

b=3

c=4

d=1

Comparison Operators

There are several expressions for testing equality and magnitude. All these
expressions return a boolean value. Table 2.5 enlists the comparison operators.

Operator Meaning Example


== Equal u ==45
!= Not equal u !=75
< Less than u < 85
> Greater than u > 68
<= Less than or equal to u <=53
>= Greater than or equal u>=64
to
Table 2.5

Logical Operators

Logical operators available are AND, OR, XOR and NOT.

The AND operator (& or &&) returns true only if both sides in an expression are
true. If anyone side fails, the operator returns false. For example, consider the
following statement

gender ==1 && age >=65

23
This condition is true if and only if both the simple conditions are true. In the &&
operator, if the left side of the expression returns false, the whole expression returns
false and the right side is totally neglected. The & operator evaluates both sides
irrespective of outcome.

The | or | | is used for OR combination. This returns true if any of the expressions is
true. Only if all the conditions are false, the expression is false. Consider the
following statement

semesterAverage>=90 | | finalExam >=90

The above condition is true if either of the two conditions is true. The | | evaluates
the left expression first and if it returns true, never evaluates the right side
expression. A single | evaluates both the expressions regardless of the outcome.

The XOR operator indicated by ^, returns true only if its operands are different. If
both its operands are similar (true-true, false-false), it returns false.

The ! operator is used for NOT. The value of NOT is negation of the expression.

Bitwise Operators

The bitwise operators are inherited from C and C++. They are used to perform
operations on individual bits in integers. A list of the bitwise operators available is
given in Table 2.6.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
« Left Shift
» Right Shift
»» Zero fill right shift
~ Bitwise Complement
«= Left Shift assignment
»= Right Shift assignment
>>>= Zero fill right shift
assignment

24
x&=y AND assignment
x !=y OR assignment
x ^=v XOR assignment

Table 2.6

The following example demonstrates the usage of bitwise operators.

• Open a new file in the editor and type the


following script.

1: class Bitop {
2: public static void main (String args[ ]) {
3: int a=1;
4: int b=2;
5: int c=3;
6: a=a|4;
7: b>>=1;
8: c<<=1;
9: a=a^c;
10: System.out.println ("a=" +a);
11: System.out.println ("b=" +b);
12: System.out.println ("c=" +c);
13: }
14: }
Note: The line numbers given are not part of the source code and should not be
typed so.

 Save this file as BitOp.java and compile using javac BitOp.java at


the DOS prompt.
 On successful compilation, execute the source code using: java BitOp
 The output appears as shown below:

a=3

25
b=l

c=6

Operator Precedence

The order in which the expressions are evaluated and their overall value
is determined by Operator precedence.

The following table indicates specific precedence of the


various operators.

Operator Notes
[ ], ( ), . [ ] is used for arrays. ( ) group expressions. Dot is used
to access methods and variables within objects and
classes.
++, --, !, - , instance of Returns true or false based on whether the object is an
instance of the named class or any of that class's
superclass.

New (type) expression The new operator is used to create instances of classes
*, /, % Multiplication, division, modulus Modulus
+, - Addition, subtraction
<< , >> Bitwise left and right shift
<, >, <=, >= Relational comparison tests

== , != Equal to and not equal to

& AND •

^ XOR
| OR
&& Logical AND
|| Logical OR

?: Ternary operator
=, +=, - =, *=, /=, %=, Assignment
^=
Table 2.7

26
Programming Constructs

Programming constructs in Java are the if construct and ternary operator, switch
statement the while, do while and for loops.

The If Construct

The if else construct executes different bits of code based on successful completion
of a condition, that returns only boolean values. If the execution is unsuccessful, the
sets of instructions under else are executed.

if (condition)
body of loop;
else
body of loop;

The following example illustrates usage of the if else construct and logical operators.

Example2.7

 Open a new file in the editor and type the following script.

class Four {
public static void main (String args[]) { int month = 4;
String season;
if (month = =12 I I month ==1 II month ==2) {
season="Winter";
}
else if (month = =3 I I month ==4 II month ==5){
season="Springll;
}
else if (month = =6 I I month = =7 II month ==8){
season="Summer";
}

27
else if (month = =9 I I month ==10 I I month ==11) {
season="Autumn";
}
else{
season="Invalid month";
System.out.println ("April is in " + season + ".");
}
}

 Save this as Four.java and compile using javac Four.java at the DOS prompt.
 On successful compilation execute, using java Four.
 The output of the program is given below:

April is in Spring.
This example uses several if-else statements to determine which season a particular
month is in.

Conditional Operator

The conditional operator is otherwise known as the ternary operator and is


considered to be an alternative to the if else construct. It returns a value and the
syntax is:

<test> ? <pass> : <fail>

where, <test> is the condition to be tested. If the condition returns true then the
statement given in <pass> will be executed. Otherwise, the statement given in
<fail> will be executed.

The following example delineates the usage of the ternary operator.

Example 2.8

• Open a new file in the editor and enter the following code:

28
1: class Ternary

2: public static void main (String args[ ]) {


3: int i =10;
4 : int j =78;
5: int z=0;
6: z = i < j ? i : J
7: System.out.println ("The value assigned is " + z);
8: }
9: }
Note: The line numbers given are not part of the source code and should not be
typed so.

 Save this file as Five.java and compile using javac Five.java at the DOS prompt.
 On successful compilation execute using java Five.
 The output is given below:

The value assigned is 10

Note the usage of conditional operator at line number 6. If the value of the variable i
is than j, then z contains the value of i, else it contains the value of j.

The while loop

The while loop executes a set of code repeatedly until the condition returns false.
The
syntax for the while loop is given below:

while (<condition> ) {

<body of the loop>

where <condition> is the condition to be tested. If the condition returns true then
the statements inside the <body of the loop> are executed. Else, the loop is not

29
executed.

The do while loop is similar to the while loop except that the condition to be evaluated
is given at the end. Hence the loop is executed at least once even when the condition
is false. The syntax for the do while loop is as follows:

do{

<body of the loop>


} while (<condition>);

Example 2.9 depicts the usage of the while loop.

Example 2.9

• Open a new file in the editor and type the following script

1: class Fibo
2: public static void main (String args l l ) {
3: int max = 25;
4: int prev =0;
5: int next=1;

6: int sum;

7: while (next <= max)

8: {

9: System.out.println ("The Fibonacci series is " + next);


10: sum = prev + next;
11: prev = next;
121 next = sum;

13: }

14: }
15: }
Note: The line numbers given are not part of the source code and should not be
typed so.

30
 Save this file as Fibo.java and compile using javac Fibo.java at DOS prompt.
 On successful compilation, execute using java Fibo.
 The output appears as given below:

The Fibonacci series is 1


The Fibonacci series is 1
The Fibonacci series is 2
The Fibonacci series is 3
The Fibonacci series is 5
The Fibonacci series is 8
The Fibonacci series is 13
The Fibonacci series is 21

The while loop, shown from line 7 - 13, is executed as long as the value of the
variable next is less than or equal to 25. This program generates the Fibonacci series

The for loop

The for loop repeats a set of statements a certain number of times until a condition is
matched. It is commonly used for simple iteration. The for loop appears as shown.

for (initialization; test; expression) {


set of statements;
}

In the first part a variable is initialized to a value. The second part consists of a test
condition that returns only a boolean. The last part is an expression, evaluated every
time the loop is executed. The following example depicts the usage of the for loop.

Example 2.10
• Open a new file in the editor and type the following script.
class ForDemo {
public static void main (String args[ ])
{

31
int i;
for (i =0;i < 10;i=i+2)
{
if ((i%2) == 0)
System.out.println ("The number" + i +" is a even number");
}
}
}

Save this file as ForDemo.java and compile using javac ForDemo.java at


DOS prompt.
On successful compilation, execute using java ForDemo.
The output appears as given below:

The number 0 is an even number


The number 2 is an even number
The number 4 is an even number
The number 6 is an even number
The number 8 is an even number
This example generates even numbers that are less than 8. Notice the usage of the for
loop from line numbers 4 - 8.

Switch Statement
The switch statement dispatches control to the different parts of the code based on
the value of a single variable or expression. The value of expression is compared
with each of the literal values in the case statements. If they match, the following
code sequence is executed. Otherwise an optional default statement is executed. The
general syntax of the switch
statement is as follows:
switch (<test>) {
case <valueOne>:
<resultOne>;
break;

32
case <valueTwo>:
<resultTwo>;
break;
default :
<defaultResult>;
}

An illustration of the switch statement's usage is given below in Example


2.11.
Example 2.11

• Open a new file in the editor and type the following.

1: class season {

2: public static void main (String args[]) {

3: int v = 4;

4: switch(v) {

5: case 1:

6: case 2:

7: case 3:

8: System.out.println ("Spring is around the corner");

9: break;

10: case 4:
11: case 5:
12: case 6:

13: System.out.println ("Summer is scorching its way through");

14: break;
15: case 7:

16: case 8:

17: case 9:

33
18: System.out.println ("Autumn leaves are abundant");

19: break;
20: case 10:

21: case 11:


22: case 12:
23: System. out .println ("Winter is freezing");
24: break;
25: }
26: }
27: }

Note: The line numbers given are not part of the source code and should not be
typed so.

 Save this file as season.java and compile using javac season.java at DOS prompt.
 On successful compilation, execute using java season.
 The output appears as given below:

Summer is scorching its way through

Note the usage of the switch statement between lines 4 - 25.

Break and Continue

The break keyword halts the execution of the current loop and forces control out of
the loop. The term break refers to the act of breaking out of a block of code. It tells
the runtime to pick up execution past the end of the named block. In order to refer to
a block by name, Java has a label construct that assigns a name to every block. The
following example demonstrates the usage of break statement.

Example 2.12

• Open a new file in the editor and type the following script:

34
class breakdemo {
public static void main (String args[ ]) {
boolean t=true;
a: {
b: {
c: {
System.out.println("Before the break");
if (t)
break b;
System.out.println ("This will not execute");
}
System.out.println ("This will not execute");
}
System.out.println ("This is after b");
}
}
}

 Save this file as breakdemo.java and compile using javac breakdemo.java at


the DOS prompt.
 On successful compilation, execute using java break demo.
 The output appears as given below:

Before the break


This is after b

continue is similar to break, except that instead of halting the execution of the
loop, it starts the next iteration. The following example demonstrates the usage of
continue statement.
Example 2.13
class continuedemo {
public static void main (String args[ ]) {
for(int i=0; i<10; i++) {
System.out.print(+i+ " " );

35
if (i%2 == 0)
continue;
System.out.println (" ");
}
}
 }Save this file as continuedemojava and compile using javac continuedemo.java
at DOS prompt.
 On successful compilation, execute using java continuedemo.
 The output appears as given below:
o 1
2 3
4 5
6 7
8 9

1.4 INTRODUCTION TO OOP


Introduction to OOPS
The acronym OOPS stands for Object-Oriented Programming Structure. In order to
manage increasing complexity of the programs, the approach called object-oriented
programming, was introduced. Object-Oriented Programming develops a program
around its data and sets well-defined interfaces to that data. An object-oriented
program can be characterized as data controlling access to code.
The object-oriented model is based on three important concepts namely
Encapsulation, Inheritance and Polymorphism. Let us learn about each of these
concepts in detail.
Object-Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies software development and maintenance by
providing some concepts:

Object means a real-world entity such as a pen, chair, table, computer, watch, etc.
Properties and Task Performed.

36
Encapsulation

Encapsulation is the mechanism that binds together code and the data it
manipulates, and keeps both safe from outside interference and misuse
.
Encapsulation is a protective wall that prevents the code and data from being
randomly accessed by other code define outside the wall.

Access to the code and data inside the wall is tightly controlled through a well-
defined interface. To relate this to the real world, consider the functionality of a
television. It encapsulates hundreds of bits of information about the internal

37
architecture such as how the signals are converted, how the volume is controlled and
about the power supply. The user has only one method of affecting this complex
encapsulation: by opening the television box.

In Java the basis of encapsulation is the class. Since the purpose of a class is to
encapsulate complexity, there are mechanisms for hiding the complexity inside the
class. Each method or variable in a class may be marked private or public. The
public method can be accessed even by the members outside the class. The private
methods and data can only be accessed by a member of that particular class.
Therefore any other code that is not a member of the class cannot access a private
method or variable. Since the private members of a class can only be accessed
externally through the public methods, the user can ensure that no improper actions
take place. The concept of encapsulation is depicted in Fig 1.1.

Inheritance
Inheritance is the process by which one object acquires the properties of another
object. Inheritance stands for its concept of hierarchical classification. By
inheritance, information is made manageable by hierarchical (i.e. top-down)
classification
For example Labrador is part of the classification dog, which in turn is part of the
mammal class, which is under the larger class termed animal. Without the use of
hierarchies, each object would need to define all of its characteristics explicitly.
However, by use of inheritance, objects need to define only those qualities that make
it unique within its class. It can inherit its general attributes from its parent.

38
Animal class contains its own attributes such as size, intelligence and type of
skeletal system. When going deeper into more specific class of animals (sub-
class), such as mammals, they would have more specific attributes, such as teeth
and mammary glands. Since mammals are simply more precisely specified
animals, they inherit all the attributes from animals. This inheritance is depicted in
Fig. 1.2. Thus it is the inheritance mechanism that makes it possible for one object
to be a specific instance of a more general case.

Polymorphism
Polymorphism (from the Greek, meaning "many forms").is a feature that
allows one interface to be used for a general class of actions.
A stack can explain polymorphism easily. Consider a stack (which is a last-in- first-

39
out list). Let us consider a program that requires three types of stacks, one stack for
integer values, floating-point values, one for characters .The algorithm for
manipulating the numbers is the same for all the three stacks, only the data differs.
In Java, using polymorphism the user can specify a general set of stack that shares
the same name.
More generally, the concept of polymorphism is often expressed by the phrase "one
interface, multiple methods." This means that one common interface can be used for a
group of related methods. It is the compiler's job to select the suitable method
according to the situation. The programmer does not have to make this selection
manually. Extending the dogs' analogy, a dog's sense of smell is polymorphic. If the
dog smells a cat, it will bark and run after it. If it smells its food, it will salivate and
run to its bowl. The same sense of smell is at work in both situations. The difference
is what is being smelt, that is, the type of data/being operated upon by the dog's nose.
This same general concept can be implemented in Java as it applies to methods within
a Java program.

1.5 SUMMARY / TO SUM / LET’S SUM UP

In this unit, we have given a brief introduction to Java and its features. Java and Its
Salient Features, Fundamentals of Java Programming, Data Types, Variables,
Operators, Control Structures, Including Selection Looping and Introduction to
OOP’s

1.6 KEYWORDS / GLOSSARY

Data Types, Variables, ControlStructures


1.7 QUESTIONS FOR SELF STUDY
1. What are the Salient Features of Java. Explain each features.
2. What are the different data types in Java. Explain each with an example.
3. Explain OOP’s Concept.

1.8 SUGGESTED READINGS AND REFERENCE


1. David J. Eck Introduction to Programming Using Java.

40
2. Elliotte Rusty Harold Java I/O published by O'Reilly
3. Ken Arnold, James Gosling . The Java Programming Language

4. Patrick, Naughton The Java Handbook

5. Dwight Deugo More java gems

6. Sun Microsytems Java tutorial,

7. E Balaguruswamy Programming with java

8. Schum series publications Programming in java

9. Doug Lea . Concurrent Programming in Java: Design Principles and Patterns

10. Jose M. Garrido Object-Oriented Programming: From Problem Solving to


Java
11. Bill Venners Object-Oriented Design with Java
12. E. Balaguruswamy Programming with java

13. Internet.

41
UNIT 2: JAVA METHODS

Structure
2.0 Objectives
2.1 Introduction
2.2 Classes
2.3 Methods
2.4 Constructor and Finalizer
2.5 Garbage Collections
2.6 Summary/Let us Sum up
2.7 Keywords
2.8 Questions for Self Study
2.9 Suggested readings

2.0 OBJECTIVES

At the end of this unit you will be able to

 State Classes

 Describe Methods

 Analyze Constructor and Finalizer

 Define Garbage Collection

42
2.1 INTRODUCTION
This unit deals with classes and their creation. It demonstrates creation of methods,
instances and the usage of the keyword "new". It also describes access specifiers and the
variable scope. Constructors and finalizers and inner classes are also dealt with in detail.

2.2 CLASSES

Classes :
The basic element of object-oriented programming is a class.
A class defines the shape and behaviour of an object and is a template for multiple
objects with similar features. Any concept represented in a program is
encapsulated in a class. When an application is written, classes of objects are
defined. To create a class, a source file with the class keyword in it, followed by a
legal identifier and a pair of curly braces for the body is required.

class <classname> {
<body of the class>
}

A class called Book includes all its features serving as template for the concept. Each
property is treated as an attribute of that class. For example, the book's name, the
author's name, number of pages it contains are its attributes. The definition of the
Book class would be

class Book {
String name;
String authorName;
int nopages;
}

Apart from defining an object's structure, a class also defines its functional interface,
known as methods. For instance, the Book can have a method that displays the name

43
of the book.
class Book
String name;
String authorName;
int nopages;
String displayName() {
System.out.println("Name of the book is " + name);
}
}

Once a Book class is defined, instances of that class can be created and each
instance can have different attributes. When the program runs, instances of the
class are created and discarded as and when required.

An instance of a class can be used to access the variables and methods that form
part of the class. Each instance of the class has its own copy of instance variables
defined in the class and hence can hold different attributes. For instance, one object
of the Book class can contain the attributes of 'Gone with the wind' while another
may contain that of 'Learn Java'.
The methods in the class operate on individual instances of the class. For example,
the same display method can operate on both the instances of the Book class
described above.
Suppose we have two instances objl and obj2 of the Book class. Objl.display( )
displays the attribute of objl, while obj2 .display( ) displays that of obj2.

Note :The terms instance and object are used interchangeably.


The Java environment comes with a library of classes that implement a lot of the
basic behaviour. By creating classes that use the classes provided by Java, highly
maintainable programs can be constructed.
Example 3.1 explains the creation of a class.

 Open a new file in the editor and enter the following


code

44
class One{
public static void main (String args[ ])) {
int a = 1;
int b = 2;
int c = 3;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}

 Save the file as One.java


 Compile the file using javac One.java
 Run the file using java One

output appears as shown below:


a =1
b =2
c= 3

The class is declared in line 1. The main method, the entry point to all Java application
programs, is defined in line 2. In lines 3 - 5, three variables that are local to the main
are declared. These variables are displayed using println in lines 6 - 8.
Attributes
Aaributes are individual properties that differentiate one object from another and determine
apperance, state and other qualities. Each attribute has a corresponding instance variable.
Instance Varibles
Data is encapsulated in a class by declaring variables inside the class declaration. Variables
declared in this scope are known as instance variables. Instance variables are declared in
same way as local variables except that they are declared outside the scope of any
particular method, such as main. For example, a class named Point can be created with
two instance variables namely a and b. Every object of this class has its own copy of

45
the instance variable.

class Point {

int a,b;

Dot Operator

The dot notation is used to obtain the value of the instance variables. It has two
parts namely the object on the left side of the dot and the variable on the right
side of the dot. Dot expressions are evaluated from left to right. The general form
for accessing instance variables using the dot operator is given below:

<ObjectReference>.<variableName>

where <objectReference> is the name of the object and <variableName> is the


instance variable.

We can store values into instance variables using the dot operator as shown below:

p.x =10;

p.y= 20;

We can refer to values of instance variables using the dot operator as given below:

System.out.println ("x=" + p.x + "y=" + p.y) ;

The new Operator

The new operator creates a single instance of a named class and returns a reference
to the object. For example, an instance of the class point can be created as shown:

point p = new point( );

Here p is a reference to an instance of point. There is a critical distinction between

46
how simple types and objects are manipulated in Java. The variable p is a reference
to the object. It does not actually contain it.
Note :When an object is no longer referred to by any variable, Java automatically
reclaims memory used by that object. This is known as garbage collection.
When a new object is created a distinct set of instance variables are obtained. Each object
has its own copy of the instance variables of its class, so changes to the instance variables
of one object have no effect on the instance variables of another. Each object's instance
variables are separate and distinct from the others.

Example 3.2 depicts the usage of the new operator to create an instance of the class. It
also demonstrate the creation and usage of instance variables and the use of the dot
operator in variables.

 Open a new file in the editor and enter the following code:
class Insvar {
int a = 10;
int b = 20;
public static void main (String args[]){
Insvar insvar1 = new Insvar();
System.out.println("The value of a is = " + insvar1.a);
System.out.println("The value of b is = " + insvar1.b);
}
}
 Save the file as Insvar.java
 Compile the file using javac Insvar.java
 Run the file using java Insvar

The output appears as given below :


The value of a is 10
The value of b is 20

Two instace variables, a and b, are defined in the class Insvar. The main ( )
method creates an instance of the class using the new operator. When the object is

47
created, the instance varibles a and b, are initialized to 10 and 20 respectively. Lines 6
and 7 display these varibles, accessing them using the dot operator.

Muliple references of the same object can be created. In the illustration, a single object of
a class named Coord is created, with two variables, referencing it.

Coord p1 = new Coord () ;

Coord p2 = p1;
p1
Coord
p2
Object

Fig 3.1

Any changes to the object referenced by p2 will affect the same object to which p1
is referring. The assignment of p1 to p2 does not allocate memory. Subsequent
assignment to p1 will simply unhook p1 from the original object without affecting
the object itself.

Example 3.3 depicts the referencing of objects.

Exaample 3.3

• Open a new file in the editor and enter the following code:

class Coord {

int x,y;

public static void main(String args[]) {

Coord p1,p2;

p1 = new Coord();

p1.x = 50;

p1.y = 50;

48
p2= p1;

p1.x =100;

p1.y= 75;

System.out.println("Coordinates
of p1 are" + p1.x + "," + p1.y);

System.out.println("Coordinates
of p2 are" + p2.x + ","+ p2.y);

}
 Save the file as Coord •. java
 Cornpile the file using javac Coord.java
 Run the file using java Coord

The output appears on the screen as given below:

Coordinates of p1 are 100, 75·


Coordinates of p2 are 100, 75
Coord class has two public instance variables, x and y. In the main method, an
instance of Coord is created and the reference is stored in the variable pl.

The assignment statement in line 8 copies the reference p1 (not the object it is
referring to) to p2. The values of x and y of the object that p1is pointing to, are
modified. Lines 11 and 12 display the variables, x and y, of the objects that p1 a
nd p2 are pointing to. The output of program shows that though only p1 was
modified, changes are reflected both in p1 and p2 since they were pointing to
the same object.
Class Variables
Class variables are global to a class and to all the instances of the class. They are
useful for communicating between different objects of the same class or for
keeping track of global states. The keyword static is used to declare a class
variable. For class variables there is only one copy of the variable. Every instance
of the class has access to that variable. We have to use the dot notation to access

49
the class variable, and instead of using the object's name on the left hand side of
the dot operator, the class name can be used. Thus, class variables can be
accessed without creating an object of that class.

2.3 METHODS

Methods are functions that operate on instances of classes in which they are
defined. objects can communicate with each other using methods and can call
methods in other classes. Just as there are class and instance variables, there are
class and instance methods. Instance methods apply and operate on an instance
of the class while class methods operate on
the class.
Method in Java
In general, a method is a way to perform some task. Similarly, the method in Java is
a collection of instructions that performs a specific task. It provides the reusability of
code. We can also easily modify code using methods. In this section, we will
learn what is a method in Java, types of methods, method declaration, and how to
call a method in Java.
What is a method in Java?
A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation. It is used to achieve the reusability of
code. We write a method once and use it many times. We do not require to write code
again and again. It also provides the easy modification and readability of code, just
by adding or removing a chunk of code. The method is executed only when we call or
invoke it.
The most important method in Java is the main() method. If you want to read more
about the main() method, go through the link https://www.javatpoint.com/java-main-
method

Method Declaration
The method declaration provides information about method attributes, such as
visibility, return-type, name, and arguments. It has six components that are known
as method header, as we have shown in the following figure.

50
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the method. It
specifies the visibility of the method. Java provides four types of access specifier:

o Public: The method is accessible by all classes when we use public specifier
in our application.

o Private: When we use a private access specifier, the method is accessible only
in the classes in which it is defined.

o Protected: When we use protected access specifier, the method is accessible


within the same package or subclasses in a different package.

o Default: When we do not use any access specifier in the method declaration,
Java uses default access specifier by default. It is visible only from the same
package only.

Return Type: Return type is a data type that the method returns. It may have a
primitive data type, object, collection, void, etc. If the method does not return
anything, we use void keyword.

Method Name: It is a unique name that is used to define the name of a method. It
must be corresponding to the functionality of the method. Suppose, if we are creating
a method for subtraction of two numbers, the method name must be subtraction(). A

51
method is invoked by its name.

Parameter List: It is the list of parameters separated by a comma and enclosed in the
pair of parentheses. It contains the data type and variable name. If the method has no
parameter, left the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.

Naming a Method

While defining a method, remember that the method name must be a verb and start
with a lowercase letter. If the method name has more than two words, the first name
must be a verb followed by adjective or noun. In the multi-word method name, the
first letter of each word must be in uppercase except the first word. For example:

Single-word method name: sum(), area()

Defining Methods
Method definition has four parts. They are:

 Name of the method


 Type of object or primitive type that the method returns
 A list of parameters
 Body of the method

A method's signature is a combination of the first three parts mentioned above. Java
permits different methods to have the same name as long as the argument list is
different. This is called method overloading. A basic method definition resembles
the one given below:

<returntype> <methodname> (typel> <argl>, <type2> <arg2>,


…)

{
<set of statements>

52
The returntype is the primitive type or class of the value that this method returns.
It should be void if the method does not return a value at all.

The method's parameter list is a set of variable declarations. The list is separated by
commas within the parentheses. The parameters become local variables in the body
of the method whose values are passed when the method is called.

Inside the body of the method, statements, expressions and method calls can be
present. the method has a return type, then a value must be returned using the
keyword return.

Calling Methods

Calling a method is similar to calling or referring to an instance variable. The


methods are accessed using the dot notation. The object whose method is called is
on the left of the dot. while the name of the method and its arguments are on the
right.

Obj.methodname(paraml,param2);

Example 3.4 indicates the usage of methods.

Exampe 3.4

Open a new file in the editor and enter the following code

class Area {

int len = 10;


int bre = 10;
void calc ( ) {

int ara = len * bre;

53
System.out.println("The area is " + ara + " sq.cms");
}
public static void main (String args[]) {
Area a = new Area();
a.calc() ;
}
}

 Save the file as Area.java

 Compile the file using javac Area.java

 Run the file using java Area

The output appears on the screen as given below:


The area is 100 sq.cms
The class Area has two instance variables, len and bre, which are initialized
when an object is created. The calc method, which does not return any value,
is defined in line 4. This method calculates the area and displays it.
In the main method, an instance of the class, Area, is created. The calc
method of the class, calculates and displays the area, is called in line 10.

Class Methods
Class methods, like class variables, are available to instances of the class and can be
made avialable to other classes. Class methods can be used anywhere regardless of
whether an instance of the class exists or not. Methods that operate on a particular
object should be defined as instance methods. Methods that provide some general
utility but do not directly affect an instance of the class are declared as class
methods. Class method is defined as given below:

static <returntype> <methodname>(<type1> <arg1>, <type2> <arg2>, ... ) {


<set of statements>
The static keyword indicates that it is a class method and can be accessed without
creating an object. The class methods, unlike instance methods, are not allowed to use
instance variables, as these methods do not operate on an object.

54
Passing Argument to Methods

The objects that are passed to the body of the method are passed by reference and the
basic types are passed by value. This results in a change in original value of the object
if the value is modified in the method.
Example 3.5 depicts the passing of arguments to methods.

Example 3.5
• Open a new file in the editor and enter the following code:

class Marg {
void calc(int x) {
int square = x * x;
System.out.println ("The square of " + x + " is " + square + "sq.cms");
}
public static void main (String args[]) {
Marg a = new Marg();
a.calc(15);
}
}

 Save the file as Marg.java


 Compile the file using javac Marg.java
 Run the file using java Marg

The output appears as shown:


The area is 225 sq.cms
The calc method, which takes an integer as argument is defined in line 2. This
method calculates the square of the parameter passed and displays it. In the
main ( ) method an object of this class is created. Then, calc method is
invoked with an argument 15. The calc method calculates the square of the
argument passed and displays it.

55
The this keyword
A special reference value called this is included in Java. The this keyword is used
inside any insance method to refer to the current object. The value of this refers to
the object on which the current method has been called. The this keyword can be
used where a reference to an object of the current class type is required. Methods
declared with the keyword
static (class methods) cannot use this.

The follwing example illustrates the usage of the keyword


this.
Example3.6
 Open a new file in the editor and enter the following
code:

class point1{
int x,y;
void init (int x,int y)
{
this.x=x;
this.y=y;
}
void disp()
{
System.out.println("x=" +x);
System.out.println("y=" +y);
}
}
class point{
public static void main(String args[]) {
point1 pp =new point1 ();
pp.init (4,3);
pp.disp();

56
}
}

 Save the file as point1.java


 Compile the file using javac point1.java
 Run the file using java point!

The output appears as given below:

x=4

y=3

Overloading methods

To create an overloaded method, different method definitions each with the same
name but different parameter lists are created. Java allows method overloading as
long as the each parameter list is unique for the same method name. Java
differentiates overloaded methods with the same name, based on the number and type
of parameters to that method and not on the return type. When a method is called,
Java chooses the method definition to execute, depending on the method name and
number and type of arguments. If methods are chosen to have the same names and
parameter lists but different return types then the compiler returns an error. The
variable names in the parameter list do not matter. Only the number and the
type of the parameters matter.

Example 3.7 illustrates method overloading.

Example 3.7

• Open a new file in the editor and enter the following code:

1: class Load {
2: String fname;
3: String 1name;

57
4: int age;
5: String prof;
6: Load f1oad(String fname,String 1name,int age,String prof) {
7: this.fname fname;
8: this.1name 1name;
9: this.age = age;
10: this.prof = prof;
11: return this;
12: }
13: Load f1oad(String fn,String In)
14: fname = fn;
15: lname = In;
16: return this;
17: }
18: Load fload{String fnme, String lnme, String pr) {
19: fname fnme;
20: lname lnme;
21: prof = pr;
22: }
23: return this;
24: Load fload{String fna,String lna,int ag) {
25: fname fna;
26: lname lna;
27: age = ag;
28: return this;
29: }
30: void print ( )
31: System.out.println{fname + ", " + lname + " " + age + " " + prof);
32: System.out.println (" ");
33: }
34:public static void main (String args [1) {
35:Load loads = new Load ( ) ;
36:System.out.println ("The various values supplied are as follows:");
37:System.out.println{);

58
38:loads.fload{ "Aswath", "Narayanan", 24, "Engineer");
39:loads. print ( ) ;
40:loads. fload{ "Shankar", "Athreya");
41:loads. print ( ) ;
42:loads.fload{ "Gautham", "Bhaskaran", "Doctor");
43:loads. print ( );
44:loads. fload{ "Nakul", "Mahadevan" , 28) ;
45:loads. print ( ) ;
46: }
47:}

Note: The line numbers given are not part of the source code and should not be
typed so.

 Save the file as Load.java


 Compile the file using javac Load.java
 Run the file using java Load
The output appears as given below:
The various values supplied are as follows:
Aswath Narayanan 24 Engineer
Shankar Athreya 24 Engineer
Gautham Bhaskaran 24 Doctor
Nakul Mahadevan 28 Doctor

The above example depicts method overloading. It has a print () method that prints the
values of the various arguments supplied to the various methods.

More About Classes


This section delves into the additional concepts related to classes.
Access Specifiers
Access control is the process of controlling visibility of a variable or method .When a method is
visible to another class, its methods can reference the method or variable, There are four levels of
visibility that are used, Each level is more restrictive than the other and provides more protection

59
than the one preceding it.

Public
Any method or variable is visible to the class in which it is defined. If the method or variable
must be visible to all classes, then it must be declared as public. A variable or method with
public access has the widest possible visibility. Any class can use it.

Package
Package is indicated by the lack of any access modifier in a declaration, It has
an increased protection and narrowed visibility and is the default protection
when none has been specified.
Protected
This specifier is a relationship between a class and its present and future
subclasses. The subclasses are closer to the parent class than any other class.
This level gives more protection and narrows visibility.

Note : The package and protected access specifiers have been dealt with while
dealing with packages in the latter half of the book.

Private
It is narrowly visible and the highest level of protection that can possibly be
obtained. Private methods and variables cannot be seen by any class other than
the one in which they are defined. They are extremely restrictive but are most
commonly used. Any representation unique to the implementation is declared
private. An object’s primary job is to encapsulate its data and limit
manipulation. This is achieved by declaring data as private.

Example 3.8 depicts declaration of data as private.


Example 3.8
 Open a new file in the editor and enter the following code:
class Priv {
private int x = 10;
void var() {

60
System.out.println ("The private value is "+ x)?
)
public static void main(String args[{]) {
Priv pl = new Priv()7

pl.var();
}
}

 Save the file as Priv.java


 Compile the file using javac Priv.java
 Run the file using java Priv

The output appears as shown below :

The private value is 10


The class Priv has a private instance variable x. This variable can be accessed only
inside the Class. The method var displays this variable using the print1n method. The
main method of the class and invokes the var method. It is important to note that the
instance variable x of the Object cannot be accessed directly from the main sinceit is
declared private.The following code,when included in main,will result in a
compilation error.

System.out.println( “Value = “ + pl.x);

To determine the Class of an object


To find out the class to which the object belongs , the getclass() can be used. This
method is defined in the object class and is available to all objects. The object class
has a method getName (), which returns a string representing the name of the class.
The following code fragment retrieves the class name of an object.
String Sl= Obj.getClass().getName();
Alteratively, the instance of operator can be used. This operator has two operands
namely, the object on the left and the name of the class on the right. The expression

61
returns a boolean depending upon the object being an instance of the named class or
any one of its subclasses. For example, if a variable s1 is declared to be an instance of
the string class, then it can be checked if s1 is an instance of the string class as shown:

String s1 = new String();


if (s1 instanceof String) {
<set of statements>
}

Object References
Each new class created adds another type that can be used just like simple types, when
a new variable is declared; classname can be used as a type. Such variables refer to
instance or object of that class. These variables are known as object reference. An
instance is an individual copy of the class template with its own set of data called
instance variable.

When the type of variable is declared as a class, it has a default value of null - a
reference of type Object, and is thus type-compatible with all other classes. The null
object has no value

An object reference is a memory pointer. These pointers cannot be manipulated.


Object references point at an intermediate data structure which stores the type
information as well as the current address of the actual instance data.

Java Class Library


The Java class library provides a set of classes guaranteed as available in any
commercial Java environment. These classes are in the Java package. The Java
Developer’s Kit , comes with documentation for the entire Java class library which
has descriptions of each class’s instance variable, methods, constructors, and
interfaces. Exploring the Java class library and its methods is a good way to start
learning Java.

A list of the class packages that are part of the Java class library are:
Java.lang: Classes that apply to the language itself which includes the object class, the

62
String class and the system class. It also contains the special classes for the primitive
types
(Integer, Character, Float)

java.util: Utility classes such as Date as well as simple collection classes such as
vector and Hashtable

java.io: Input and output classes for writing to, and reading from streams and for
handling files

java.net: Classes for networking support, including Socket and URL.

java.awt : (the Abstract Window Toolkit) : Classes to implement a graphical user


interface, including classes for Window, Menu, Button, Font, CheckBox. This
package also includes classes for processing images.

java.applet: Classes to implement Java applets, including the Applet class itself as
well as the Audioclip interface.

The development environment may also include additional classes that provide other
utilities or functionality. Although these classes may be useful, they will not be
available to others, as they are not part of the standard Java library. This is
particularly important for applets are expected to run on any platforms. The classes
inside the Java package are guaranteed to be available in all Java environments.

Importing Class
Classes external to a program must be imported before they can be used. To import a
class, the import keyword should be used as given below:
import <classname>;

The classes in Java are arranged in hierarchical order. The Java library consists of a
number, of packages (as discussed earlier). These packages contain a set of related
classes. The whole path of the class must be specified to import a class from the Java
library, For instance, to import the Date class from the util package use the following

63
code.

import java.util.Date;

It is also possible to import all classes that belong to a package using the * symbol.

import java.awt.* ;

Note : All the classes in java.lang package are automatically imported when a
program is compiled.

The following program illustrates the usage of the import keyword.

Example 3.9
 Open a new file in the editor and enter the following code:
import java.awt.Point;
//The following program illustrates the usage of the import keyword.
// Open a new file in the editor and enter the following code:
import java.awt.Point;
class Lib {
public static void main(String args[]) {
Point pl = new Point (2,2);
pl.x = 12;
pl.y = 12;

System.out.println ("The value of pl.x is " + pl.x);

System.out.println ("The value of pl.y is" + pl.y);


}
}

 Save the file as Lib,java


 Compile the file using javac Lib.java

64
 Run the file using java Lib

The output appears on the screen as shown below:

The value of p1.x is 12


The value of pl.y is 12

The point class is imported in line 1 of the program. An instance of this class is
created inside the main method, The variables in the object are initialized in lines 7
and 8 and displayed using println method.

Command and Line Arguments


A generic Java program can be enabled to operate on different kinds of input by
passing command line arguments.

Arguments to Java programs can be passed by appending them to the command line
when the Java program is run. These arguments can be grouped by using double
quotes that are removed before the arguments are passed to the program.

The Java program stores the command line arguments in the array of strings which is
passed To the main() method in the program. Inside the main() method, the arguments
can be handled by iterating over the array of arguments. The arguments are passed to
the main() method as an array of strings and to treat them as non-strings, they are to
be converted to the specfic type.

Example 3.10 illustrates the passing of command line arguments to a program.

Example 3.10

 Open a new file in the editor and enter the following code:

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

65
System.out.println ("The first argument value is: “ + arge[0]);
}
}

 Save the file as Arg.java


 Compile the file using javac Arg.java
 Run the file using java Arg “This is my first argument”
 The output on the screen appears as given below :

The first argument value is: This is my first argument


In this example, the main method outputs the first command line argument.

Note: The example assumes that at least one argument is passed to the program. If the
program is executed without an argument, an error occurs. If more than one argument
is passed, it is ignored.

2.4 CONSTRUCTOR AND FINALIZER

The forthcoming paragraphs deal with an important concept in Java, namely the
Constructors and Finalizers. Constructors are called whenever an instance of a given
class is created. Finalizers are used to destroy the objects created using constructors.
Basic Constructors
A constructor method is a special kind of method that determines how an object
is initialized when created. They have the same name as the class and do not have any
return type.

When the keyword new is used to create an instance of a class, Java allocates memory
for the object, initializes the instance variables and calls the constructor methods.
Every class has a default constructor that does not take any argument and the body of
it does not have any statements. Constructors can also be overloaded.

Example 3.11 describes constructor definition, passing of arguments and changing of


values

66
Example 3.11

 Qpen a new file in the editor and enter the following code:

classCons {
int i;
int j;
Cons(int a,int b) {
i = a;
j = b;
}
void print() (
System,out.println ("The addition of " + i + " and " + j + " gives " + ( i + j ));
}
public static void main(String args[)) (
Cons c;
c = new Cons(10,10);
c.print ();
System.out.println (" ");
c = new Cons(50,50);
c.print ();
Sytem.out.printin (" "“);

 Save the file as Cons,java


 Compile the file using javac Cons.java
 Run the file using java Cons

The output appears as given below:

The addition of 10 and 10 gives 20


The addition of 50 and 50 gives 100

67
The constructor passes arguments as is declared in line 4. It also indicates the print
method used to display the values of the constructor arguments.

Calling Another Constructor


A constructor can be called from another constructor. When a constructor is written,
the functionalities of another defined constructor can be used. A call to the constructor
can be made current Class, use:
this (argl,arg2,arg3....)

The arguments to this are the arguments to the constructor. Example 3.12 illustrates
this concept.

Example 3.12
 Open a new file in the editor and enter the following code:
class point{
int x,y;
point(int x,int y){
this.x=x;
this.y=y;
}
point(){
this(-1,-1)
}
public static void main(String args[]){
point p=new point();
System.out.println("x ="+ p.x +", y=" + p.y);
p=new point(10,10);
System.out.println("x ="+ p.x +", y=" + p.y);
}
}

 Save the file as Arg.java


 Compile the file using javac Arg.java

68
 Run the file using java Arg

The output is appears shown below:


x = -l , y= -1

In the example given above, the second constructor calls the first constructor and
initializes the instane variables.

Finalizer
Finalizer method functions in contradiction to the constructor method. Finalizers are
called Just before the object is garbage collected and its memory is reclaimed. The
finalizer method is represented by finalize(). The Object class defines a default
finalizer method, which does nothing. To create a finalizer method for the classes, the
£inalize() method can be overridden as shown below:

protected void finalize(){


<set of statements>
}
Any cleaning required may be included inside the body of the finalize() method. This
method can be called at any point of time. Calling finalize( ) need not trigger an
object to be garbage collected. Removing references to an object will cause it to be
marked for deletion. Finalizer methods are best used for optimizing the removal of an
object.

Overloading constructors

Constructors can also take varying numbers and types of parameters. This enables
creation of objects with the properties required.

Example 3.13 illustrates overloaded constructors. The constructor takes a different


number of arguments each time and gives the same to the print method for display.

Example 3.13

69
 Open a new file in the editor and enter the following code:

Class Cload {
String pname;
int qty;
int price;
Cload(int prodgty, String prodname,int prodprice) {
pname = prodname;
qty = prodgty;
price = prodprice;
}
Cload(int q,String plname) (
pname = plname;
price = q;
qty = price/10;
}

Cload(String ppname,int pprice) {


pname = ppname;
price = (int)(pprice - (0.1));
)
void print() {
System.out.println("Product Name : " + pname) ;
System.out.println("Quantity " # qty);
System.out.println("Price " + price);
}

public static void main(String args[]) {

Cload prods;
prods = new Cload(10,"Apples",10);
prods.print();

70
prods = new Cload(10,"Oranges");
prods.print();
prods = new Cload("Grapes",25);
prods.print ();
}
}
 Save the file as Cloud.java
 Compile the file using javac Cloud.java
 Run the file using java cloud

The output is appears shown below:

Product Name: Apples


Quantity : 10
Price : 10
Product Name: Oranges
Quantity : 1
Price : 10
Product Name: Grapes
Quantity : 0
Price : 24

Inner Classes
It is possible to nest a class definition within another class and treat the nested class
like any other method of the class.Such a class is called nested class, As a member of
its enclosing class, a nested class has privileges to access all class has privileges to
access all the members of the class enclosing it. A nested class can either be static or
non-static. nested classes are called as inner classes. While static nested classes are
just called as static nested classes,non-static nested classes are called as nested
classes.
NewTerm : An inner class is a nested class whose instance exists within an instance
of its enclosing class and has direct access to the instance members of its enclosing
instance.

71
class <EnclosingClass> {
class <InnerClass> {
<set of statements>
}
}

The interesting feature about the relationship between these two classes is not that the
InnerClass is inside the EnclosingClass. Apart from this feature, the instance of the
InnerClass can exist only within an instance of the EnclosingClass and it has direct
access to instance variables and methods
of its enclosing instance.

Example 3.14
 Open a new file in the editor and enter the following code:
public class Parcel{
class Contents (
private int i=16;
public int value(){
return i;
}
}
Class Destination{
brivate String label;
Destination(String whereTo) {
label=whereTo;
}
String readLabel(){
return label;
}
}
public void ship(String dest) {
Contents c=new Contents();

72
Destination d=new Destination(dest) ;
System.out.println("Shipped "+c.value()+" item(s) to " + dest);
}
public static void main(String args[]){
Parcel p=new Parcel();
: p-ship("Congo");
}
}

 Save the file as Parcel.java


 Compile the file using javae Parcel.java
 Run the file using java Parcel

The output appears as shown below:

Shipped 16 item(s) to Congo

The above example explains the usage of inner class. There are two inner class
definitions, each with its own variables/methods namely Contents and Destination.
The enclosing class has a method ship (String dest) which creates instances of the
inner classes and this called by the main() method.

More usage of inner classes can be seen while dealing with event handling.

2.5 GARBAGE COLLECTION

Garbage Collection:
In Certain languages like C++, dynamically allocated objects must be manually
released by use of a delete operator. In Java deallocation happens automatically. The
technique that accomplishes this is called garbage collection.

Java has no malloc or free functions. Since every complex data structure is an object,
they are all allocated via the new operator, which allocates space for an object on the

73
heap of memory .

The memory available for objects is called a heap because the user doesn’t have to
think about
it. It is just a loosely collected heap of object instances. From new keyword, the user
actually gets a handle to an object and not the memory address.

The actual memory allocated for this object may move around, as the program runs,
but the User doesn’t have to worry about that'll that matters is that this memory will
be available for as long as the program cares for it. As soon as the user no longer have
any references of any kind to the object, the memory it is occupying will become
available for reuse by the rest of the system. The user’s doesn’t have to call free or
delete. This is known as garbage collection.

Garbage Collection only occurs sporadically during the execution of the program. It
will not occur simply because one or more objects exist that are no longer used.

Garbage Collection can also be known as litter recycling, because the user doesn’t
even have to drag the objects to the crub to have them collected. It’s just dropping and
forgetting them. The garbage collector runs whenever the system is idle, or when a
request allocation fails to find enough memory.

2.6 SUMMARY / LET US SUM UP


In This unit we have learnt Methods, More about Classes, Constructor and
Finalizers. Also about Garbage Collection.

2.7 KEYWORDS / GLOSSARY


Classes , Finalizer, Constructor
2.8 QUESTIONS FOR SELF STUDY

1. Explain about Methods in Java with an example.


2. Write a short note on Constructor and Finalizer.
3. Discuss about garbage collection.

74
2.9 SUGGESTED READINGS AND REFERENCE

1. David J. Eck Introduction to Programming Using Java.


2. Elliotte Rusty Harold Java I/O published by O'Reilly
3. Ken Arnold, James Gosling . The Java Programming Language

4. Patrick, Naughton The Java Handbook

5. Dwight Deugo More java gems

6. Sun Microsytems Java tutorial,

7. E Balaguruswamy Programming with java

8. Schum series publications Programming in java

9. Doug Lea . Concurrent Programming in Java: Design Principles and Patterns

10. Jose M. Garrido Object-Oriented Programming: From Problem Solving to


Java
11. Bill Venners Object-Oriented Design with Java
12. E. Balaguruswamy Programming with java

13. Internet.

75
UNIT 3: ARRAYS

Structure
3.0 Objectives
3.1 Introduction
3.2 Arrays
3,3 Summary
3.4 Keywords
3.5 Questions for Self Study
3.8 Suggested readings

3.0 OBJECTIVES

At the end of this unit you will be able to

 Explain the Arrays

76
3.1 INTRODUCTION

This unit deals with arrays and their declaration.

3.2 ARRAYS
Arrays
An array is an object that stores a list of items. Each slot in an array holds individual
elements. An array should be of a single type, comprising of integers, strings and so
on. To create an array, a variable to hold the array is declared, and a new object is
created and assigned to it.
Declaring Array Variables
Array declaration is akin to any other variable declaration. Array variable indicates
the type of object that the array holds. It also indicates the name of the array followed
by empty brackets. The brackets may be inserted after the specification of the type
instead of succeeding the variable.
int arr[];
Creating Array Object
After declaring an array, create and assign objects to it. Two methods can be used to
create the array- initialization of the array or usage of the new keyword, The new
keyword creates an instance of the array. The number of elements that the array will
hold must be specified. The two modes of creating an array are given below:
int iarr [ ] = new int [ 10 ];
char carr[ ] = {‘a’, ‘b’,’c’,’d’};

Example 4.1 depicts the creation and definition of an array.


Example 4.1 |
 Open a new file in the editor and enter the following code

1: class Array {
2: int I;
3: int da[] = (1,2, 3,4,5,6,7};
4: void disp() {
5 System.out.println(“Displaying Array Details”}
6: for (int i=0; I < 7; i++)
7: System.out.println(da[i] );

77
8: }
9: }
10: public static void main(Str ing args[]) {
11: Array d = new Array();
12: d.disp()
13: }
14: }
Note: The line numbers given are not part of the source code and should not be
typed so.
 Save the file as Array.java
 ¢Compile the file using javac Array.java
 Run the file using java Array

The output appears as given below:


Displaying Array Details:
1
2
3
4
5
6
7
Line 3 declares the array. The array is being initialized at the point of declaration and
hence, it is not necessary to specify the number of elements that the array would hold
or their size. Line 4 gives the method declaration. The method, disp, prints the array
elements. In the main method, an instance of the class is created and the disp method
is invoked.

Accessing Array Elements


The array subscript expression must be used to change and test the values of the array.
To access an element in the array, subscript expression is employed. Array subscripts
start with zero. All array subscripts are checked to ensure that they are within the
boundaries of the array. If the array subscript is calculated at runtime as part of a
looping control and it ends outside the boundaries of the array, then the interpreter

78
produces an error. To avoid overrunning the end of an array, its length can be tested
using the length instance variable. This variable is available for all array objects
irrespective of the type. The usage is,
int len = arr.length

Changing Array Elements


A value can be assigned to a slot in the array by inserting an assignment statement
after the array access expression. When a value is assigned to a slot, a reference to
that object is created. When values are reassigned, references are also reassigned.
Arrays of primitive type the values from one slot to another. Having references to
array objects means the multiple references to the same object is possible.
Example 4.2 represents assigning and changing of values in arrays.
Example 4.2
 Open a new file in the editor and enter the following code

class Number1 {
int I;
int arr({] = new int [10];
vpid add() {
int j = 100;
for (i = 0; 1 < arr.length; i++) {
arr[i] = j;
j++;
}
}
void show() {
for (i=0; i < arr.length; i++) {
System.out.printin (“The “ + i + “ array element is “ +
arr(i]));
}
}
public static void main(String args[]) {
Numberl n = new Numberl();

79
n.add();
n.show();
}
}
Note: The line numbers given are not part of the source code and should not be
typed so.
 Save the file as Numberl.java
 Compile the file using javac Number1.java
 Run the file using java Numberl

The output appears as given below: _


The 0 array element is 100
The 1 array element is 101
The 2 array element is 102
The 3 array element is 103
The 4 array element is 104
The 5 array element is 105
The 6 array element is 106
The 7 array element is 107
The 8 array element is 108
The 9 array element is 109
The array is declared in line 3. The add method, declared in line 4, assigns values to
the array. The show method displays elements of the array.
In the main method, a new instance of the class is created. The add method is invoked
to assign values that are displayed by calling the show method. |
Multidimensional Arrays
Java does not Support multidimensional arrays. However, an array of arrays can be
created .The following example typifies the creation of an array of arrays.
Example 4.3
 Open a new file in the editor and enter the following code

class coord {
int i=0;
int j=0;

80
int coor[][] = new int [3] [3];
yoia set() {
coor [0] [0] =1;
coor [0] [1]=0;
coor [0] [2]=0;
coor [1] [01=0;
coor [1] [1]=1;
coor [1] [2]=0;
coor [2] [0]=0;
coor [2] [1]=0;
coor [2] [2]=17
}
void show() {
for (i=0;1<3;i++) {
for (j=0;5<3;j++) {
System.out .print (coor [i] [J] + “ ”);
System.out.printin(" “);
}
}
public static void main(String args[])
Coord c = new coord();
c.set();
c.show();

 Save the file as Coord.java


 ‘Compile the file using javae Coord
 Run the file using java Coord

The output appears as shown below:


100
010
001
An integer array is declared at line 4. Values are set into the array using the set ()

81
method.
The array is displayed using the show () method.
Vector
A Vector is an array of object references. Internally, a Vector implements a strategy to
minimize reallocation and wasted space. Objects can be stored at the end of a Vector
by using the addElement method or inserted at a given index by the insertElementAt
method. An array of objects can be stored in a Vector using the copy Into method.
Example 4.4 demonstrates the usage of vector.
Example 4.4
 Open a new file in the editor and enter the following code

1: import java.util.*;
2: class Cat {
3: private int catNumber;
4: Cat(int i) {
5 :catNumber = i;
6: }
7: void print() {
8 System.out.println ("Cat #" + catNumber) ;
9 :}
10:}
ll:class Dog {
12: private int dogNumber;
13: Dog(int i) {
14: dogNumber = i;
15: }
16: void print() {
17: System.out.println ("Dog 4" 4 dogNumber ) ;
18: }
19:}
20:public class CatsAndDogs {
21: public static void main(String args[]) {
22: vector cats = new Vector();
23: for(int i =0; I < 7 ;i++)

82
24: cats.addElement (new Cat(i));
25: cats.addBlement (new Dog(7)); //Not a problem to add a dog to cats:
26:for(int i = 0; i < cats.size(); i++)
27: ((Cat)cate.elementat (1)).print()1// Dog is detected only at run-time
28: }
29:}
Note: The line numbers given are not part of the source code and should not be
typed so.

 Save the file as CatsAndDogs.java


 Compile the file using javac CatsAndDogs.java
 Run the file using java Cats AndDogs

The output appears as shown below:


Cat #0
Cat #1
Cat 2
Cat #3
Cat #4
Cat #5
Cat #6
Exception in thread “main” Java. lang.ClassCastException at CatsAndDogs
.main(Compiled code)

The classes Cat and Dog are distinct ~ they have nothing in common except that they
are Objects (if we don’t explicitly say what class we are inheriting from, we
automatically inherit from Object).The Vector class, which comes from java.util,
holds Objects, so not only can we place Cat objects into this collection using the
Vector method addElement (), but we can also add Dog objects without complaint at
either compile-time or run-time. When we go to fetch out what we think are Cat
objects using the Vector method elementAt (), we get back a handle to an Object that
we must cast to a Cat. Then we have to Surround the entire expression with
parentheses to force the evaluation of the cast before calling the print () method for
Cat, otherwise we will get Syntax error. Then, at run, when we try to cast the Dog

83
object to a Cat, we will get an exception:

3.3 SUMMARY
 An array stores a list of items. Each slot in an array holds individual elements.
An array should be of a single type.
 Array declaration is similar to any other variable declaration.
 To change and test the values of the array, use the array subscript expression.
 To assign a value to a slot, include an assignment statement after the array
access expression.
 Java does not support multidimensional arrays. However, an array of array can
be created.
 3.4 KEYWORDS

Arrays, Casting Objects

3.5 QUESTIONS FOR SELF STUDY

1. What are arrays? How can values be stored in them? Should the datatype of each
element in the array be the same?
2. Give the three different ways of creating a string object.
3. How do we declare and create array objects?
4. How do we change the values of the elements in an array? How can we test the
values that an array holds?
5. What are multi - dimensional arrays? Does Java support them?

3.6 SUGGESTED READINGS AND REFERENCE

1. David J. Eck Introduction to Programming Using Java.


2. Elliotte Rusty Harold Java I/O published by O'Reilly
3. Ken Arnold, James Gosling . The Java Programming Language

4. Patrick, Naughton The Java Handbook

5. Dwight Deugo More java gems

84
6. Sun Microsytems Java tutorial,

7. E Balaguruswamy Programming with java

8. Schum series publications Programming in java

9. Doug Lea . Concurrent Programming in Java: Design Principles and Patterns

10. Jose M. Garrido Object-Oriented Programming: From Problem Solving to


Java
11. Bill Venners Object-Oriented Design with Java
12. E. Balaguruswamy Programming with java

13. Internet.

85
UNIT4: STRINGS

Structure
1.0 Objectives
4.1 Introduction
4.2 Strings
4.3 Casting and Converting
4.4 Summary
4.5 Keywords
4.6 Questions for Self Study
4.7 Suggested readings

4.0 OBJECTIVES

At the end of this unit you will be able to:

 Define Strings

 Describe Casting and Converting

86
4.1 INTRODUCTION

This unit provides a detailed description of strings. The manipulations that can be
done with strings is also dealt with. Casting and converting of various operators as
also methods is also elucidated in this unit.

4.2 STRINGS

Strings
A combination of characters is a string. Strings are instances of the class string. They
are real objects, and hence, enable combination, testing and modification. When as
string literal is used in the program, Java automatically creates instances of the string
class. Strings are unusual in this respect.
Example 4.5 delineates declaration and access of strings.

 Open a new file in the editor and enter the following code

1: class Strings {
2: int i;
3: String names[ ] = ("Aswath", "Aswin", "Anand", "Aditya",
"Anirudh"};
4: void show() {
5: System.out.println ("My Favourite Names Are ");
6: for (i=0; i< 5; i++) {
7: System.out.println (names[i]);
8: }
9: }
10: public static void main(String args[]) {
11; Strings s = new Strings();
12: s.show();
13: }
14: }
Note: The line numbers given are not part of the source code and should not be

87
typed so.

 Save the file as Strings.java


 Compile the file using javac Strings.java
 Run the file using java Strings.

The output appears as given below:


My Favourite Names Are:
Aswath
Aswin
Anand
Aditya
Anirudh
Line 3 declares a string array and initializes it. The array is displayed using the or
loop.
String constructors
Calling the default constructor with no parameters as shown below can create an
empty string:
String s = new string ()
The above example will create an instance of String with no characters in it. In order
to create a String initialized with characters, we need to pass in an array of char to the
constructor. The following code fragment creates a String instance with three
characters from the char
array as the initial value of the string, s. The code will print the string “abc”
Char chars[ ]={'a’,’b’,’C'};
String s=new String (chars);
Sytem.out.println(s);
There is another constructor that allows the specification of the starting index and
number of characters that have to be used. The following code fragment illustrates
this constructor,
String (char chars[ ], int startIndex, int numchars)
The example given below will print “cde” because” was at index 2 and we specified a
count of 3 characters to be used to construct the String,
Char chars[ ]= {‘a', b, ‘c’,’d’, ‘e',’f’};

88
String S=new String(chars,2,3);
System.out.println(s);
Hash table
Often it is necessary to store Strings and other data types in a manner that allows the
information to be found quickly. One of the ways to store information for fast lookup
is a hash table. A hash table stores information using a special calculation on the
object to be stored. A hash code is produced as a result of the calculation. The hash
code is used to choose the location in which to store the object. When the information
needs to be retrieved, the same calculation is performed, the hash code is determined
and a look up of that location in the table results in the value that was stored there
previously. Every object has the ability to be stored in a hash table. Class Object
defines method hashCode to perform the hash code calculation. Method hashCode is
overridden by String to provide a good hash code distribution based on the contents of
the String.

Example 4.6 demonstrates the hashCode method for two Strings containing “hello”
and“Hello”.
Example 4.6
 Open a new file in the editor and enter the following code

1: class hash{
2:public static void main(String args[ ]){
3:String si="hello";
4:String s2="Hello";
5: System.out.println("The hash code for "+s1+ “is" + sl.hashCode(
6 System.out.println("The hash code for "+s2+ "is" + s2.hashCode( }
7:}
8 :}
Note: The line numbers given are not part of the source code and should not be
typed so.

 Save the file as hash.java


 Compile the file using javac hash.java
 Run the file using java hash

89
The output appears as shown below:
The hash code for hello is 99162322
The hash code for Hello is 69609650
The hash code for each of the Strings is different because the Strings themselves are
lexicographically different.

String Arithmetic
The ‘+’ sign does not mean “addition” when it is used with String objects, The Java
string class has something called “operator overloading.” In other words, the “+" sign
when used with String objects, behaves differently than it does with everything else.
For Strings, it means: “concatenate these two strings.” When used with strings and
other objects, the + operator creates a single string that contains the concatenation of
all its operands.
What happens when a numerical value is added to a String? The complier calls a
method that turns
numerical value (int, float, etc.) into a String, which can then be “added” with the plus
sign. Any object or type can be converted to a string if the method toString()
implemented, To create a string, add all the parts together and output it .The +=
operator will also work for string.
Example 4.7 outlines the concatenation of two strings.
Example 4.7
 Open anew file in the editor and enter the following code

class Arith {
string fname = "Aswath";
String lname = "Narayanan";void show()
{
system. out.printin ("The full name is " + fname + ” “ + lname);
}
public static void main(String args[]) {
Arith al = new Arith();
al.show();
 Save the file as Arith.java

90
 Compile the file using javae Arith,java
 Run the file using java Arith

The Output appears as given below:


The full name is Aswath Narayanan
Lines 2 and 3 declare string variables and initialize them. The concatenated string is
displayed within the show() method at line 4.
String Methods
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:
Method USE
length( ) Number of characters in String.
charAt() The char at a location in the String.

getChars(_ ), getBytes( ) Copy chars or bytes into an external array,


Produces a char[] containing the characters in the
toCharArray( ) String
equals( ), equalslgnoreCase( ) An equality check on the contents of the two Stimgs
Result is negative, zero or positive depending
compareTo( ) lexicographical ordering of the String and the
argument. Uppercase and lowercase are not equal
regionMatches() Boolean result indicates whether the region matches

Boolean result indicates if the String starts with the


starts With () argument.
ends With() Boolean result indicates if the argument is a suffix.
Returns -1 if the argument is not found within this
String, otherwise returns the index where the argument
indexOf(),lastIndexOf() starts. lastIndexOf( ) searches backwards from énd

Returns a new String object containing the specified


substring() character set.
Returns a new String object containing the original
String’s characters followed by the
concat() characters in the argument.

91
Returns a new String object with the replacemets
replace() made. Uses the old String if no match is found,
Returns a new String object with the case of all Ietters
changed. Uses the old String if no changes need to be
toLoweCase(),toUpperCase() made.
Returns a new String object with the whitespace
removed from each end. Uses a
trim() the old String if no changes need to be made.

Returns a String containing a character represertation


valueOf() of the argument.
Produces one and only one String handle for each
intern() unique character sequence
Table 4.1
It is seen that every String method returns a new String object when it is necessary to
change the contents. Also notice that if the contents do not require any change, the
method will just return a handle to the original String. This saves storage and
overhead.
Example 4.8 demonstrates comparison of two strings:
Example 4.8
 Open a new file in the editor and enter the following code

Class equaldemo {
public static void main (String args{ ] ){
string s1="Hello”;
String g2="Hello”;
String s3="Good bye”;
String g4="HELLO”;
system.out .print1n (s1 + “equals” +s2 + “is” +s1.equals(s2));
system.out .print1n (s1 + “equals” +s3 + “is” +s1.equals(s3));
system.out .print1n (s1 + “equals” +s4 + “is” +s1.equals(s4));

 Save the file as equaldemo,java


 Compile the file using javac equaldemo,java

92
 Run the file using java equaldemo

Output appears as shown below


Hello equals Hello is True
Hello equals Good bye is false
Hello equals HELLO is false
The following example demonstrates the usage of some of the methods of strings -
concat(), indexof(), lastIndex0f(), substring(),replace() and trim().
Example 4.9
 Open a new file in the editor and enter the following code

class st{
public static void main(String args[]){String s="Now is the time for all
good men" + " to come to the aid of their country”
+” and pay their t axes”;
String s1 = "Hello world";
String s2="Hello";
String s3="HELLO";
System.out.println(s);
System.out.println (index of t = " +s.indexOf('t'));
System.out.println("last index of t= "+s.lastindexOf('t'));
System.out.println("index of(t,10) =" +s.indexOf('t',10));
System.out.println("last index of (t,60)=" + s.lastIndexOf(‘t’,60));
System. out .println (s1l.substring(6));
System. out .println(s1.substring(3,8));
System.out .println(s2.concat ("World") );
System.out.println(s2.replace('1', 'w'));
System. out .println(s3.toLowerCase ());
System.out.println(s1.trim()) ;
}
}
 Save the file as st.java
 Compile the file using javac st.java
 Run the file using java st

93
Output appears as shown below

Now is the time for all good men to come to the aid of their country and pay their
taxes
index of t =7
last index of t =83
index of(t,10) = 11
last index of (t,60)=55
world
lo wo
HelloWorld
Hewwo
hello
Hello world

StringBuffer
StringBuffer is a peer class of String that provides much of the common use
functionality of strings. Strings represent fixed-length character sequences. String
Buffer represents varied length character sequences. StringBuffer may have characters
and substrings inserted in the middle, or appended at the end. The compiler
automatically creates a StringBuffer to evaluate certain expression, in particular when
the overloaded operators + and += are used with String object.
Example 4.10 demonstrates the usage of StringBuffer:
 Open a new file in the editor and enter the following code

public class buf {


public static void main (String args []){
String foo = " foo";
String s = "abc" + foo + "def" + Integer.toString (47);
system.out .println(s);
// The equivalent" using stringBuffer:
StringBuffer sb = new stringBuffer(“abc” ); // Creates string!
sb.append (foo);
sb.append ("def"); // Creates string!

94
sb.append (integer .tostring (47) );
system. out.println (sb);
 Save the file as buf.java
 Compile the file using javac buf.java
 Run the file using java buf

The output is given below:


abcfoodef 47
abcfoodef 47
In the creation of String s, the compiler is actually performing the rough equivalent of
the subsequent code that uses sb, A StringBuffer sb is created and append ( ) is used
to add new characters directly into the StringBuffer object (rather than making new
copies each time), While this is more efficient, it is worth noting that each time we
create a quoted character string like “abc” and “def”, the compiler actually turns those
into String objects. Thus, there may be more objects created than we expect, despite
the efficiency afforded through StringBuffer.

StringBuffer methods
Table 4.2 enlists the StringBuffer methods and their uses.

Method Use

toString( ) Creates a String from this StringBuffer.

length( ) Returns the number of characters in the StringBuffer.

capacity( ) Returns current number of spaces allocated

ensureCapacity( Makes the StringBuffer hold at least the desired number of spaces
)
setLength( ) Truncates or expands the previous character string. If expanding,
pads with nulls
charAt( ) Returns the char at that location in the buffer.

95
setCharAt( ) Modifies the value at that location.

getChars( ) Copy chars into an external array. There is no getBytes( ) as in


String
Append( ) The argument is converted to a string and appended to the end of
the current buffer, increasing the buffer if necessary
insert() The second argument is converted to a string and inserted into the
current buffer beginning at the offset. The size of the buffer is
increased, if necessary.
reverse( ) The order of the characters in the buffer is reversed.

Table 4.2
The most commonly-used method is append (), which is used by the compiler when
evaluating String expressions containing the ‘+’ and ‘+=* operators. The insert ()
method has a similar form, and both methods perform significant manipulations to the
buffer rather than creating new objects.

4.3 CASTING AND CONVERTING

Casting and Converting


Casting is used to convert the value of one type to another. Casting is the mechanism
of converting the value of an object or primitive type into another type. The result of
the cast is a new reference or value. Casting does not affect the original object or
value. The concept that is involved in casting is simple enough but for the fact that
Java has both primitive types and objects types. Casting is of three types namely,
casting between object types and converting primitive types objects and then
extracting primitive types to Objects and then extracting primitive values out of those
Objects.
Casting Primitive Types
Casting between primitive types allows conversion of one primitive type to another.
This occurs commonly between numeric types. Boolean values cannot be cast into
any other primitive type. If the casting is between types larger than the type of value
being converted, then an explicit cast need not be used. The larger type provides more

96
precision than the smaller type, and hence no information is lost when the value is
cast. The casting of integers into floating– point values or an int to a float may cause
must be used. Converting the value result in loss of precision. Precedence of casting is
higher than that of arithmetic operations .A typical cast from an higher value to a
lower value.
(int ) (d / t);
Example 4.11 explains casting between primitive types.

 Open a new file in the editor and enter the following code

Class Convert {
double x;
double y;
int z;
void prod(double a,double b) {
x= a;
y= b;
z= (int) ( a * b);
}
void print() {
System.out.println ("The value is " + z);
}
public static void main(String args[]) {
Convert con = new Convert ();
con.prod(10.94,94.30);
con.print();
}
}
 Save the file as Convert.java
 Compile the file using javac Convert.java
 Run the file using java Convert

The output appears as given below:


The value is 1031

97
This example accepts two double values, calculates its product using the method
prod().The resulting value is printed using the print() method ,as an integer by casting
the result value at line 8.

Casting Objects
Instance of class can be cast to instance of other classes. There is only one restriction,
the class of the Object being cast and the class that it is being casted to must be related
by inheritance. Some object may not be explicitly cast .An instance of a subclass can
be used anywhere a superclass is expected because a subclass contains all the
information that a superclass contains.Casting an object to an imstance of that objects
superclass loses the information the original subclass provided and requires a specific
cast.To cast an Object to another Object .
(classname) object;
The classname is the class we want to cast the object to. Object is a reference to the
object being cast. Casting creates a reference to the old object of the type classname
and the old object continues to exist.

Converting Primitive Types to Objects


Converting primitive types to objects cannot be done explicitly. Primitive types and
objects are two distinct things. Java.lang package includes several special classes that
correspond to each primitive type. For example, Integer for int, Float for float,
Boolean for Boolean etc. These classes can be used to create objects that encapsulate
the primitive types. To convert the values back into the primitive types values, we
have methods that can be utilized.

4.4 SUMMARY
 A combination of characters is known as a string. Strings are instances of the
class String. The addition operator (+) can be used to create and concatenate
strings.
 Casting is a mechanism of converting the value of an object or primitive type
into another type.
 Casting between primitive types allows conversion of one primitive type to
another.This occurs most commonly between numeric types.

98
 Instances of class can be cast to instances of other classes.
 Conversion of primitive types to objects cannot be done explicitly. Primitive
type and objects are two different things. java.lang package includes several
special classes that correspond to each primitive type.

4.5 KEYWORDS

Strings, Casting

4.6 QUESTIONS FOR SELF STUDY

1. Give the three different ways of creating a string object.

2. Are strings real objects? How can we combine, test and modify string?

3. What is the use of a hash table?

4. What is String Buffer? How does it differ from String?

5. What is casting? What are its uses? What are the objects on which casting can
be applied?

6. Why should we use conversion? What is the package that can be used for his
purpose?

4.7 SUGGESTED READINGS AND REFERENCE

1. David J. Eck Introduction to Programming Using Java.


2. Elliotte Rusty Harold Java I/O published by O'Reilly
3. Ken Arnold, James Gosling . The Java Programming Language

4. Patrick, Naughton The Java Handbook

5. Dwight Deugo More java gems

99
6. Sun Microsytems Java tutorial,

7. E Balaguruswamy Programming with java

8. Schum series publications Programming in java

9. Doug Lea . Concurrent Programming in Java: Design Principles and Patterns

10. Jose M. Garrido Object-Oriented Programming: From Problem Solving to


Java
11. Bill Venners Object-Oriented Design with Java
12. E. Balaguruswamy Programming with java

13. Internet.

100
UNIT-5: INHERITANCE IN JAVA
Structure
5.0 Objectives
5.1 Introduction
5.2 Inheritance in Java
5.3 Super Class and Sub Class
5.4 Summary
5.5 Keywords
5.6 Questions for Self Study
5.7 Suggested readings

5.0 Objectives
At the end of this unit you will be able to
 Define Inheritance in Java
 Describe Super Class and Sub Class

101
5.1 Introduction

This unit introduces the concept of inheritance used frequently in Java. Subsequently
it provides a Super Class and Sub Class. The term inheritance brings to mind - huge
piles of money, large estates and farmhouses left to us by our ancestors! It also
conjures visions of the inherent genetic features and characteristics provided by our
forefathers. Let us try defining its meaning in the Object-ted context.
5.2 Inheritance In Java

Definition and Advantages


In Object-oriented programming, inheritance refers to the properties of a class being
available to many other classes. A derived class / sub class is one that has been
created from an existing class. It incorporates all features of the existing class in
addition to its own. The original class is called as base class / super class. Inheritance
is the process of deriving a class from a super class or a base class. No changes are
made to the base class.
For example, a class called even number is derived from class called numerals. Class
every instance of the even numbers class, apart from being a numeral, has its own
features.
From a class called people, different classes based on gender, professional
qualifications, of the subclasses of ple, a class called even m ee of the even numbers
class,class called people, annual income, nationality, etc. can be derived. Figure 5.1
shows some of the subclasses of the numerals super class.
Numerals Class Hierarchy
Numerals

Even Numbers Odd numbers Prime numbers

Java Class Hierarchy


The Java class hierarchy begins with the class object as its super class. This is the
most common class in the hierarchy. Each subclass of the hierarchy apart from

102
inheriting the features of the object class has distinct features. Each of the subclasses
has been defined for a specific purpose. Thus the object class definition is found to be
abstract and further down the hierarchy, there are clear specifications to define an
object. If a class is defined without any superclass, the object class acts as its super
class. The Java class hierarchy is shown with some of its derived classes in Fig 5.2.
Java Class Hierarchy

Object
Boolean
Character
Compiler
Math
String
Number
Class
Runtime
Thread

Points to note while creating class hierarchy


 Super classes must be defined in such a way that its information can be used
time and again by its derived classes.
 Changing a class or inserting a class in the hierarchy reflects in all its derived
classes. As a result, the need to recompile all these classes is eliminated.
 When an object calls a method, Java compiler first checks for the method
definition in the same class in which the method is defined. If it is not found,
it checks its super classes one by one. If it is unable to locate the method
definition, then the complier issue an error message.

Advantages of Inheritance
The major advantage of inheritance is reusability of code, once a class is defined and
debugged, it can be used to create new subclasses. In addition to saving a lot of time
and effort, retyping the same code becomes unnecessary. The next benefit is that data
and method of a super class are physically available to its subclasses .In case data and
methods of the super class are declared private, the derived class cannot access them

103
.To deal with this situation, protected is used.
Types of Inheritance

There are various types of inheritance as demonstrated below.

A very important fact to remember is that Java does not support multiple inheritance.
This means that a class cannot extend more than one class. Therefore following is
illegal −

Example

public class extends Animal, Mammal{}

However, a class can implement one or more interfaces, which has helped Java get
rid of the impossibility of multiple inheritance.

104
Form of Inheritance
When a subclass is derived from a single super class, the inheritance is called single
inheritance and when It Is derived from more than one super class, it is called multiple
inheritances. Java supports single inheritance only.
Example 5.1 illustrates the concepts of super class and derived class. A super class
called WoodFurn and a derived class called woodTable are created.

Note:
 The line numbers are provided for code reference and easy explanation. They
do not form part of the code.
 The base class and the derived class are created and stored in separate files.
 The filename for any class is similar to the class name with .java extension.
 The files containing base class and derived class are compiled separately and
the derived class alone is run, since it contains the main() method.
 To run base class separately include the main() method and initialize an object
of the base class type

Example 5.1
Class Wood {
String type = “teak";
String finish = "coarse";
void showDet() {
System.out.println ( “instance of class “+this ,getclass.getName () );
System.out.println(“===========================”);
System.out .println ("type of wood –“ + type);
System.out.printin ("finish is - " + finish);
}
}

 Save the file as Wood,java and compile

Caution: Do not run this file

105
 Type the following code in another file
class WoodTable extends WoodFurn {
int legs=4;
void show( ) {
System.out.println("woodtype - " + type);
System.out.println("finish - " + finish);
System.out.println("legs - " + legs);
}
public static void main (String args[ ]) {
WoodTable t = new WoodTable( );
t.show( );
}
}

 Save the file as WoodTable.java


 Compile the file and run the class file using java

The output appears as shown below:


woodtype — teak
finish — coarse
legs - 4
Line number 1 of the WoodTable class has the subclass declaration. The word extends
indicates that it has been derived from the class WoodFurn. An attribute called legs
and a method called show () are defined in this subclass from line numbers 2 to 7.
Note that the attributes of the base class are also included in the show () method.
When this method is called at line number 10, it not only displays the details of its
attribute, but also of the base class.
Example 5.2 accepts an integer and returns its square value.
Note: A stream is a path of communication between the source of information and the
destination. Input stream are used to read bytes output streams are used to write bytes.
Readers/Writers are similar streams but they handle characters instead bytes. We will
deal about streams and Readers/Writers in detail in 7th session. Some of the example
of this chapter and the next chapter uses DataInputStream, InputStreamReader and

106
BufferedReader. These are used to accept input from the user.
Example 5.2
 Open anew file in the editor and enter the following code:

import java.io.*;
class Numeral {
public int x;
void getiInt() {
try {
BufferReader br = new BufferedReader(new Input StreamReader
(System.in));
System.out.println("enter a number to find its square”);
String s=br.readLine();
x=Integer.parseInt(s);
}
catch(IOException e){ }
}
}
 Save the file as Numberal.java and compile.

Caution: Do not run this file


The base class Numeral accepts an integer using the method getInt ().Note that the
variable x is declared as public .This is because it is accessed by the derived class.
Any error occurring in the try block is caught by catch ,which is an exception handler.
The try block is represented is represented from line 5 to line a 10. An integer is
accepted in the form of a string and converted to an integer using the method
parseInt(), which belongs to the Integer class.
import java.io.*;
Class Square extends Numeral {
int retSquare() {
int y=(x*x);
}
public static void main(String args[]) {
Square s = new Square();

107
s.getInt();
s.retSquare();
}
}
 Save the file as Square.java
 Compile the file and run the class file using java

If we input the number 2 the output appears as shown below:


square is 4
The derived class square calculates the square of the number accepted from the base
class and prints the value using the method retSquare().
Access specifier - protected
The previous chapters have dealt with two access specifiers namely private and
public.The attributes and methods defined inside a class can be used within the class
irrespective of them being declared as private or public. But outside the class, the
attributes and methods defined as private cannot be used. It is always better to declare
the attributes or methods that need to be accessed by its derived class, as protected.
Instances of the derived class can access all methods and attributes of the base class,
provided they are declared as public or protected. The attributes and methods declared
as protected in the base class can be accessed within the class and any of its derived
class.
Example 5.3 depicts the usage of a variable declared as protected. The base class Info
has two variables declared as protected. The derived class method disp1() is able to
access these variables because of their declaration. Try declaring the variables in the
base class as private and observe what happens.
Example 5.3
 Open a new file in the editor and enter the following code:

Class info {
protected string name = “ezhil”;
protected string add = “9 lal mohammed street”;
}
 Save this file as Info.java and compile

108
Caution: Do not run this file
The derived class Info1 has a method disp( ),which displays the value of the attributes
in both base class and the derived class.
class Infol extends Info {
private int age =22;
public void disp() {
System.out.println(“name : ”” + name);
System.out.println(“name : ”” + name);
System.out.println(“name : ”” + name);
}
public static void main(string args[]) {
Infol i=new Info1;
i.displ();
}
}
 Save the file as Info1.java
 Compile the file and run the class file using java

The output appears as shown below:


name: ezhil
address: 9 lal mohalmmed
age is: +22
Methods can also be declared as protected.
In Java when variables are declared without accessibility specification, it implies that
it can be accessed by the class of its declaration, its sub classes and non-sub classes,
which form part of the same package. Sub classes or non-sub classes of different
packages cannot access it .Table 5.1 lists accessibility of some of the access specifier
used in Java.
An interface is a collection of abstract behaviour specifications that individual classes
can implement. Packages in Java are a way of grouping together related classes and
interfaces.

109
5.3 Super Class and Sub Class

The super keyword is similar to this keyword. Following are the scenarios where the
super keyword is used.

 It is used to differentiate the members of superclass from the members of


subclass, if they have same names.

 It is used to invoke the superclass constructor from subclass.

Subclass A subclass is a class that derives from another class. A subclass inherits
state and behavior from all of its ancestors. The term superclass refers to a class's
direct ancestor as well as all of its ascendant classes.

Creating Subclasses
To create a subclass of another class use the extends clause in your class declaration.
As a subclass, your class inherits member variables and methods from its superclass.
Your class can choose to hide variables or override methods inherited from its
superclass.
Usage of super
Usage of the keyword super before the methods getDet () and showDet() in the
derived classes, enables accepting and displaying of details for all three classes. The
method getDet () will have an extra line before the try block in both the Books class
and Category class as follows
super .getDet ();
The showDet () method also has an extra line before displaying the details of its own
class, to display the details of its base classes, as follows
super. showDet ();
This concept is explored using another example. In Example 5.5, the name of a
country is accepted. A list of countries belonging to SAARC is provided. The name of
the country that is entered is compared with the list to ascertain if it belongs to
SAARC.

Example 5.5
 Open a new file in the editor and enter the following code:

110
import java.io.*;
class Nations {
protected String name;
protected void get() {
try {
BufferedReader br = new BufferedReader (new InputStreamReader (System.
in)); System.out.println("enter name of a country ");
system.out.println("you can check if the country name you have entered is a
member of SAARC");
name=br.readLine();
} catch(IOException e) { }
}
void show() {
System.out.println(“Executing base class's show function from the derived
class ..."); System.out.println(“This is possible due to use of super");
System.out.println(“==============================");
System.out.println(“Your country name : “+name");
}
}
 Save the file as Nation.java
 Compile the file using javac Nations.java

Caution : Do not run this file


The base class Nations has two methods get () and show() which accept the name
of the country and displays the same.
 Open a new file in the editor and enter the following code:

class Saarc extends Nations {


int i;
string[] names = { "India", "Pakistan", "Sri Lanka",
“Nepal”,"Bangladesh", "Bhutan", "Maldives" };
void show() {
super.show();

111
System.out.println("Executing derived class's show
function………..”)’;
System.out .println("=========================");
System.out.println("SAARC countries are listed below ...");
for (i=0;i<7;i++)
{
System.out.println(names[i]);
}
}
public static void main(String args[]) {
Saarc s = new Saarc();
s.get();
s.show();
}
}
 Save the file as Saarc.java
 Compile the file using javac Saarc.java
 Run the file using java Saarc

Suppose our input is India, the output appears as shown below:


Enter name of a country
you can check if the country name you have entered is a member of SAARC
India
Executing base class's show function from the derived class
This is Possible due to use of super
your courntry name :India
Executing derived class’s show fucntion ...
=====================================
SAARC countries are listed below...
India
Pakistan
Sri Lanka
Nepal
Bangladesh

112
Bhutan
Maldives
The derived class saarc also has a method named show(). Actually the compiler must
execute this show() function, when called, because of overriding. Due to the presence
of the line number 5 in this derived class, the base class show() method is also
executed.

5.4 Summary/ Let Us Sum Up

 Inheritance is the process of inheriting all features from a class. The class from
which another class is derived is called base class or super class and the class
that is derived is called derived or sub class. Java class hierarchy has class
object. as its super class
 The advantages of inheritance are reusability of code fee accessibility of
variables and of the base class by the derived classes.
 Any derived class is it in the same package or in another package is ensured
the availability of the base class variables by the use of the modifier protected.
 Whenever there are methods of the same name both in the base class as well
as in the derived class and if that method is called by main, the method in the
derived class is always executed. This concept is called overriding.
 When an object of a class is initialized to an instance of its sub class and when
a method is called, the compiler verifies for the presence of that method
definition within the object’s class. But at runtime, since the stored reference
is an instance of the derived class, executes the derived class’s method.

5.5 Keyw0rds

Super Class , Inheritance

5.6 Questions for Self Study

1. What are the advantages of inheritance?


2. What are the different forms of inheritance? Does Java support all of them?
3. Explain Super Class with an example.

113
5.7 Suggested readings

1. David J. Eck Introduction to Programming Using Java.


2. Elliotte Rusty Harold Java I/O published by O'Reilly
3. Ken Arnold, James Gosling . The Java Programming Language

4. Patrick, Naughton The Java Handbook

5. Dwight Deugo More java gems

6. Sun Microsytems Java tutorial,

7. E Balaguruswamy Programming with java

8. Schum series publications Programming in java

9. Doug Lea . Concurrent Programming in Java: Design Principles and Patterns

10. Jose M. Garrido Object-Oriented Programming: From Problem Solving to


Java
11. Bill Venners Object-Oriented Design with Java
12. E. Balaguruswamy Programming with java
13. Internet

114
UNIT 6: OVERRIDING
Structure
6.0 Objectives
6.1 Introduction
6.2 Overriding
6.3 Object Classes
6.4 Polymorphism
6.5 Summary
6.6 Keywords
6.7 Questions for Self Study
6.8 Suggested Readings

6.0 Objectives
At the end of this unit you will be able to
 Discuss Overriding
 Explain Overriding
 State Object Classes
 Describe Polymorphism

115
6.1 Introduction

In the previous unit, we talked about superclasses and subclasses. If a class inherits a
method from its superclass, then there is a chance to override the method provided
that it is not marked final.

The benefit of overriding is: ability to define a behavior that's specific to the subclass
type, which means a subclass can implement a parent class method based on its
requirement.

In object-oriented terms, overriding means to override the functionality of an existing


method.

6.2 Overriding

Overriding
Methods in the derived class can have a similar name as the base class. This is to
ensure that a method, when called in the program, works the same for both the base
and the derived class.
Definition
Overriding is the creation of a method in the subclass that has the same signature, i.e..
name number and type of arguments, as a method in the super class. This new method
hides the method of the super class.
When a method is called on an object, the Java compiler first searches for the method
in the class of that object. If the method is not found there, then the compiler searches
for the method in the hierarchy until it is found.
The concept is clearly elucidated in Example 5.4. Assume that a class hierarchy -
publish-----------books ----------- category exists. Each class has distinct attributes and
methods. Note that the name of methods in all three classes is identical.
Example 5.4
 Open a new file in the editor and enter the following code:

import java.io.*;
class Publish {
protected String pubid;
protected String pname;
void getDet() {

116
try {
BufferedReader br = new BufferedReader (new
InputStreamReaderSystem.in));
System.out.println("enter data ");
System.out.printin("enter publisher id");
pubid=br.readLine();
System.out.println("enter publisher name");
pname=br.readLine();
} catch (IOException e) {}
}
void showDet() {
System.out.println("showing publisher details ...”};
System.out.println(“==========================”);
System.out.println("publisher id :" + pubid);
System.out.println("publisher name :" + pname);
}
}
 Save the file as Publish.java.
 Compile the using javac Publish.java

Caution: Do not run this file


The base class Publish has method getDet() and showDet() for accepting and
displaying values of its attributes
 Open a new file in the editor and enter the following code:
import java.io.*;
class Books extends Publish {
protected string aut;
protected string name;
void getDet () {
try {
BufferedReader br = new pufferedReader (new Input streamReader (system.
in)); System.out println(“enter author name") ;
aut=br. readLine();

117
System.out println(“enter book name") ;
name=br- readLine();
} catch (roException e) {
}
void showDet() {
System.out.println( "showing book details --- ");
System.out.println(“=======================”) ;
System.out.println("author :" + aut);
System.out.println(“bookname :" + mame);
}
}
 Save the file as Books.java
 Compile the file using javac Books.java

Note: The line numbers given are not part of the source code and should not be
typed so.

Caution : Do not run this file


The class category contains the attribute catcode which is accepting by the method
getDet ( ) and is displayed and is displayed using the method showDet ().The main
program calls these two methods in lines 18 and 19.
 Open a new file in the editor and enter the following code:
import java.io.*;
class category extends Books {
private string catcode;
try (BufferReader br = new BufferedReader (new Input StreamReader
(system. in) ) ;s
system.out.printin("enter category code");
catcode=br. readLine();
}
catch (IOException e) {}
}
void showDet() {

118
system.out .print1n("showing category details ...");
system.out. println( “======================");
system.out.println("Category code :" + catcode);
}
public static void main(String args[]) {
Category c = new Category ();
¢.getDet();
c.showDet ();
}
}
 Save the file as Category.java
 Compile the file using javac Category.java
 Run the file using java Category

If we input the category code as 100, the output appears as shown below:
showing category details...
====================
category code : 100
When the category class file is run, it is the category class’s methods that get
executed, though there are methods of the same name getDet () and showdet( ) in all
the three classes.
Overriding Constructors
Constructors are methods that have the same name as that of the class. It initializes the
values for all the class attributes. Constructors cannot be overridden. This is because
each class has its constructor with its own name.
The usage of super was illustrated along with a method that resulted in the execution
of the immediate super class’ method. Similarly to call the constructor of the base
class inside the derived class ,super(arguments) should be used. This can call the
constructor of its own base class and so on.
Dynamic Method Dispatch
Assume that an object of a class has been created. When a method is called on that
object the Java compiler ensures that a method definition exists within the class. At
runtime this object may refer to an instance of a subclass of the declared class. Java
uses the actual instance to decide the method that has to be called, in case the sub

119
class overrides the method being called.
This concept is illustrated in Example 5.6. The example consists of a base class called
Sphere. It has two methods, one to accept an integer as radius and another to calculate
the volume of the sphere. The sub class Hemisphere also has a method to calculate the
volume of the hemisphere.

Example 5.6
 Open a new file in the editor and enter the following code:

import java.io.*;
class Sphere {
protected int r;
final float pi=3.14f;
sphere () {
r=0;
}
void get() {
try {
BufferedReader br = new BufferedReader (new Input StreamReader (System.
in) );
system.out.println("enter a number as radius ");
String aut=br.readLine();
r=Integer.parseiInt (aut);
} catch (IOException e) {}
}
float volume() {
float v=(4*pi*r*r*r)/3;
System.out.println("Volume of sphere is : " + v);
return v;
 Save the file as Sphere.java
 Compile the file using javac Sphere.java

Methods get () and volume() are defined in line numbers 8 and 16.
 Open a new file in the editor and enter the following code:

120
class Hemisphere extends Sphere {
Hemisphere() {
Super();
}
float volume() {
float h=(2*pi*r*r*r) /3;
system.out.println(“Volume of hemisphere with radius "+ r +" is :”+h);
return h;
}
public static void main(String args[]) {
Sphere s = new Hemisphere () ;
s.get();
s.volume();
}
}

 Save the file as Hemisphere.java


 Compile the file using javac Hemisphere.java
 Run the file using java Hemisphere

Let us input 10 as the radius. The output appears as shown below:

Volume of hemisphere with radius 10 is :2093.3333


A method called volume() is defined in this class at line number 5. At line number 11,
inside the main, an object s of type sphere has been declared. The reference has been
stored in an instance of the class Hemisphere. When the method volume() is called on
s at line number 13, the compiler verifies if s has a method called volume(). At
runtime it notices that the reference is actually to an instance of class Hemisphere and
hence the Hemisphere’s volume() method is executed.
In the case of finalizers, the super. finalize() is used to destroy objects belonging to
the base class.

121
6.3 Object Class

Object class in Java

The Object class is the parent class of all the classes in java by default. In other
words, it is the topmost class of java.

The Object class is beneficial if you want to refer any object whose type you don't
know. Notice that parent class reference variable can refer the child class object,
know as upcasting.

Let's take an example, there is getObject() method that returns an object but it can be
of any type like Employee,Student etc, we can use Object class reference to refer that
object. For example:

Object obj=getObject();//we don't know what object will be returned from this method

The Object class provides some common behaviors to all the objects such as object
can be compared, object can be cloned, object can be notified etc.

00:14/02:28
26.9M524
History of Java

122
6.4 Polymorphism

Polymorphism is the ability of an object to take on many forms. The most common
use of polymorphism in OOP occurs when a parent class reference is used to refer to
a child class object.

Any Java object that can pass more than one IS-A test is considered to be
polymorphic. In Java, all Java objects are polymorphic since any object will pass the
IS-A test for their own type and for the class Object.

It is important to know that the only possible way to access an object is through a
reference variable. A reference variable can be of only one type. Once declared, the
type of a reference variable cannot be changed.

The reference variable can be reassigned to other objects provided that it is not
declared final. The type of the reference variable would determine the methods that it
can invoke on the object.

A reference variable can refer to any object of its declared type or any subtype of its
declared type. A reference variable can be declared as a class or interface type.

Example

Let us look at an example.

public interface Vegetarian{}


public class Animal{}
public class Deer extends Animal implements Vegetarian{}

Now, the Deer class is considered to be polymorphic since this has multiple
inheritance. Following are true for the above examples −

 A Deer IS-A Animal

 A Deer IS-A Vegetarian

 A Deer IS-A Deer

123
 A Deer IS-A Object

 When we apply the reference variable facts to a Deer object reference, the
following declarations are legal −

Example
 Deer d = new Deer();
 Animal a = d;
 Vegetarian v = d;
 Object o = d;

 All the reference variables d, a, v, o refer to the same Deer object in the heap.

 Virtual Methods

 In this section, we will see how the behavior of overridden methods in Java
allows you to take advantage of polymorphism when designing your classes.

 We already have discussed method overriding, where a child class can


override a method in its parent. An overridden method is essentially hidden in
the parent class, and is not invoked unless the child class uses the super
keyword within the overriding method.

Example
/* File name : Employee.java */
public class Employee {
private String name;
private String address;
private int number;

public Employee(String name, String address, int number) {


System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}

124
public void mailCheck() {
System.out.println("Mailing a check to " + this.name + " " + this.address);
}

public String toString() {


return name + " " + address + " " + number;
}

public String getName() {


return name;
}

public String getAddress() {


return address;
}

public void setAddress(String newAddress) {


address = newAddress;
}

public int getNumber() {


return number;
}
}

Now suppose we extend Employee class as follows −

/* File name : Salary.java */


public class Salary extends Employee {
private double salary; // Annual salary

public Salary(String name, String address, int number, double salary) {


super(name, address, number);
setSalary(salary);
}

125
public void mailCheck() {
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}

public double getSalary() {


return salary;
}

public void setSalary(double newSalary) {


if(newSalary >= 0.0) {
salary = newSalary;
}
}

public double computePay() {


System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}

Now, you study the following program carefully and try to determine its output −

/* File name : VirtualDemo.java */


public class VirtualDemo {

public static void main(String [] args) {


Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();

126
}
}

This will produce the following result −

Output
Constructing an Employee
Constructing an Employee

Call mailCheck using Salary reference --


Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--


Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0

Here, we instantiate two Salary objects. One using a Salary reference s, and the other
using an Employee reference e.

While invoking s.mailCheck(), the compiler sees mailCheck() in the Salary class at
compile time, and the JVM invokes mailCheck() in the Salary class at run time.

mailCheck() on e is quite different because e is an Employee reference. When the


compiler sees e.mailCheck(), the compiler sees the mailCheck() method in the
Employee class.

Here, at compile time, the compiler used mailCheck() in Employee to validate this
statement. At run time, however, the JVM invokes mailCheck() in the Salary class.

This behavior is referred to as virtual method invocation, and these methods are
referred to as virtual methods. An overridden method is invoked at run time, no
matter what data type the reference is that was used in the source code at compile
time.

127
6.5 Summary
In this unit, we have learnt about the concept of overriding, object classes and
polymorphism
6.6 Keywords
Overriding, object classes , polymorphism, virtual method
6.7 Questions for Self Study
1. What is meant by overriding?
2. Discuss Object Classes.
3. Explain Virtual methods.
6.8 Suggested Readings

1. David J. Eck Introduction to Programming Using Java.


2. Ken Arnold, James Gosling . The Java Programming Language

3. Patrick, Naughton The Java Handbook

4. Dwight Deugo More java gems

5. Internet

128
UNIT-7: DYNAMIC BINDING

Structure
7.0 Objectives
7.1 Introduction
7.2 Dynamic binding
7.3 Generic programming
7.4 Casting Objects
7.5 Instance of Operator
7.6 Summary
7.7 Keywords
7.8 Questions for Self Study
7.9 Reference books

7.0 Objectives
At the end of this unit you will be able to
 Explain Dynamic binding
 State Generic programming
 Describe Casting Objects
 Analyze Instance of Operator

129
7.1 Introduction
In this unit you will study about Dynamic binding , Generic programming, Casting
Objects and Instance of Operator .

7.2 Dynamic binding

Static Binding and Dynamic Binding

Connecting a method call to the method body is known as binding.

There are two types of binding

1. Static Binding (also known as Early Binding).

2. Dynamic Binding (also known as Late Binding).

Understanding Type

Let's understand the type of instance.

130
1) variables have a type

Each variable has a type, it may be primitive and non-primitive.

int data=30;

Here data variable is a type of int.

2) References have a type


class Dog{
public static void main(String args[]){
Dog d1;//Here d1 is a type of Dog
}
}

3) Objects have a type

An object is an instance of particular java class,but it is also an instance of its superclass.

class Animal{}

class Dog extends Animal{


public static void main(String args[]){
Dog d1=new Dog();
}
}
Here d1 is an instance of Dog class, but it is also an instance of Animal.

static binding

When type of the object is determined at compiled time(by the compiler), it is known
as static binding.

If there is any private, final or static method in a class, there is static binding.

Example of static binding


class Dog{
private void eat(){System.out.println("dog is eating...");}

131
public static void main(String args[]){
Dog d1=new Dog();
d1.eat();
}
}

Dynamic binding

When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding

class Animal{
void eat(){System.out.println("animal is eating...");}
}

class Dog extends Animal{


void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){


Animal a=new Dog();
a.eat();
}
}

Output::dog is eating...

In the above example object type cannot be determined by the compiler, because the instance
of Dog is also an instance of Animal.So compiler doesn't know its type, only its base type.

7.3 Generic programming

JAVA’S GENERIC PROGRAMMING FEATURES are represented by group of

132
generic classes and interfaces as a group are known as the Java Collection
Framework. These classes represent various data structure designed to hold Objects
can be used with objects of any type. Unfortunately the result is a category of errors
that show up only at run time, rather than at compile time. If a programmer assumes
that all the items in a data structure are strings and tries to process those items as
strings, a run-time error will occur if other types of data have inadvertently been
added to the data structure. In JAVA, the error will most likely occur when the
program retrieves an Object from the data structure and tries to type-cast it to type
String. If the object is not actually of type String, the illegal type-cast will throw an
error of type ClassCastException.
JAVA 5.0 introduced parameterized types, such as ArrayList<String>. This made it
possible to create generic data structures that can be type-checked at compile time
rather than at run time. With these data structures, type-casting is not necessary, so
ClassCastExceptions are avoided. The compiler will detect any attempt to add an
object of the wrong type to the data structure; it will report a syntax error and will
refuse to compile the program. In Java 5.0, all of the classes and interfaces in the
Collection Framework, and even some classes that are not part of that framework,
have been parameterized. In this chapter, I will use the parameterized types almost
exclusively, but you should remember that their use is not mandatory. It is still legal
to use a parameterized class as a non-parameterized type, such as a plain ArrayList.

With a Java parameterized class, there is only one compiled class file. For example,
there is only one compiled class file, ArrayList.class, for the parameterized class
ArrayList. The parameterized types ArrayList<String> and ArrayList<Integer> both
use the some compiled class file, as does the plain ArrayList type. The type
parameter—String or Integer—just tells the compiler to limit the type of object that
can be stored in the data structure. The type parameter has no effect at run time and is
not even known at run time. The type information is said to be “erased” at run time.
This type erasure introduces a certain amount of weirdness. For example, you can’t
test “if (list instanceof {ArrayList<String>)” because the instanceof operator is
evaluated at run time, and at run time only the plain ArrayList exists. Even worse, you
can’t create an array that has base type ArrayList<String> using the new operator, as
in “new ArrayList<String>(N)”. This is because the new operator is evaluated at run
time, and at run time there is no such thing as “ArrayList<String>”; only the non-

133
parameterized type ArrayList exists at run time. Fortunately, most programmers don’t
have to deal with such problems, since they turn up only in fairly advanced
programming. Most people who use the Java Collection Framework will not
encounter them, and they will get the benefits of type-safe generic programming with
little difficulty.

7.4 Casting Objects

In java object typecasting one object reference can be type cast into another object
reference. The cast can be to its own class type or to one of its subclass or superclass
types or interfaces. There are compile-time rules and runtime rules for casting in java.
How to Typecast Objects with a dynamically loaded Class? - The casting of object
references depends on the relationship of the classes involved in the same hierarchy.
Any object reference can be assigned to a reference variable of the type Object,
because the Object class is a superclass of every Java class.
When we cast a reference along the class hierarchy in a direction from the root class
towards the children or subclasses, it is a downcast. When we cast a reference along
the class hierarchy in a direction from the sub classes towards the root, it is an upcast.
We need not use a cast operator in this case.
The compile-time rules are there to catch attempted casts in cases that are simply not
possible. This happens when we try to attempt casts on objects that are totally
unrelated (that is not subclass super class relationship or a class-interface relationship)
At runtime a ClassCastException is thrown if the object being cast is not compatible
with the new type it is being cast to.

Casting Object References: Implicit Casting using a Compiler


In general an implicit cast is done when an Object reference is assigned (cast) to:
 A reference variable whose type is the same as the class from which the object
was instantiated. An Object as Object is a super class of every Class.
 A reference variable whose type is a super class of the class from which the
object was instantiated.
 A reference variable whose type is an interface that is implemented by the
class from which the object was instantiated.

134
 A reference variable whose type is an interface that is implemented by a super
class of the class from which the object was instantiated.

Consider an interface Vehicle, a super class Car and its subclass Ford. The following
example shows the automatic conversion of object references handled by the compiler
interface Vehicle {
}
class Car implements Vehicle {
}
class Ford extends Car {
}
Let c be a variable of type Car class and f be of class Ford and v be an vehicle
interface reference. We can assign the Ford reference to the Car variable:
I.e. we can do the following
'''Example 1
c = f; //Ok Compiles fine'''
Where c = new Car();
And, f = new Ford();
The compiler automatically handles the conversion (assignment) since the types are
compatible (sub class - super class relationship), i.e., the type Car can hold the type
Ford since a Ford is a Car.
'''Example 2
v = c; //Ok Compiles fine
c = v; // illegal conversion from interface type to class type results in compilation
error'''
Where c = new Car();
And v is a Vehicle interface reference (Vehicle v)
The compiler automatically handles the conversion (assignment) since the types are
compatible (class - interface relationship), i.e., the type Car can be cast to Vehicle
interface type since Car implements Vehicle Interface. (Car is a Vehicle).
Casting Object References: Explicit Casting
Sometimes we do an explicit cast in java when implicit casts don't work or are not
helpful for a particular scenario. The explicit cast is nothing but the name of the new
"type" inside a pair of matched parentheses. As before, we consider the same Car and

135
Ford Class
class Car {
void carMethod(){
}
}
class Ford extends Car {
void fordMethod () {
}
}
We also have a breakingSystem() function which takes Car reference (Superclass
reference) as an input parameter.
The method will invoke carMethod() regardless of the type of object (Car or Ford
Reference) and if it is a Ford object, it will also invoke fordMethod(). We use the
instanceof operator to determine the type of object at run time.
public void breakingSystem (Car obj) {
obj.carMethod();
if (obj instanceof Ford)
((Ford)obj).fordMethod ();
}
To invoke the fordMethod(), the operation (Ford)obj tells the compiler to treat the Car
object referenced by obj as if it is a Ford object. Without the cast, the compiler will
give an error message indicating that fordMethod() cannot be found in the Car
definition.

The following program shown illustrates the use of the cast operator with references.
Note: Classes Honda and Ford are Siblings in the class Hierarchy. Both these classes
are subclasses of Class Car. Both Car and HeavyVehicle Class extend Object Class.
Any class that does not explicitly extend some other class will automatically extends
the Object by default. This code instantiates an object of the class Ford and assigns
the object's reference to a reference variable of type Car. This assignment is allowed
as Car is a superclass of Ford. In order to use a reference of a class type to invoke a
method, the method must be defined at or above that class in the class hierarchy.
Hence an object of Class Car cannot invoke a method present in Class Ford, since the
method fordMethod is not present in Class Car or any of its superclasses. Hence this

136
problem can be colved by a simple downcast by casting the Car object reference to
the Ford Class Object reference as done in the program. Also an attempt to cast an
object reference to its Sibling Object reference produces a ClassCastException at
runtime, although compilation happens without any error.
class Car extends Object {
void carMethod() { } }
class HeavyVehicle extends Object { }
class Ford extends Car {
void fordMethod() { System.out.println("I am fordMethod defined in Class Ford"); }
}
class Honda extends Car {
void fordMethod() { System.out.println("I am fordMethod defined in Class Ford"); }
}
public class ObjectCastingEx {
public static void main(String[] args) { Car obj = new Ford(); // Following will result
in compilation error // obj.fordMethod(); //As the method fordMethod is undefined for
the Car Type // Following will result in compilation error //
((HeavyVehicle)obj).fordMethod(); //fordMethod is undefined in the HeavyVehicle
Type // Following will result in compilation error ((Ford) obj).fordMethod();
//Following will compile and run // Honda hondaObj = (Ford)obj; Cannot convert as
they are sibblings } }
One common casting that is performed when dealing with collections is, you can cast
an object reference into a String.
import java.util.Vector;
public class StringCastDemo {
public static void main(String args[]) { String username = "asdf"; String password =
"qwer"; Vector v = new Vector(); v.add(username); v.add(password); // String u =
v.elementAt(0); Cannot convert from object to String Object u = v.elementAt(0);
//Cast not done System.out.println("Username : " + u); String uname = (String)
v.elementAt(0); // cast allowed String pass = (String) v.elementAt(1); // cast allowed
System.out.println(); System.out.println("Username : " + uname);
System.out.println("Password : " + pass); } }
Output
Username : asdf

137
Username : asdf
Password : qwer

7.5 Instance of Operator


The instanceof operator is called the type comparison operator, lets you determine if
an object belongs to a specific class, or implements a specific interface. It returns true
if an object is an instance of the class or if the object implements the interface,
otherwise it returns false.
Below is an example showing the use of instanceof operator
class Vehicle
{
String name; Vehicle() { name = "Vehicle"; }
}
class HeavyVehicle extends Vehicle
{
HeavyVehicle() { name = "HeavyVehicle"; }
}
class Truck extends HeavyVehicle
{
Truck() { name = "Truck"; }
}
class LightVehicle extends Vehicle
{
LightVehicle() { name = "LightVehicle"; }
}
public class InstanceOfExample
{
static boolean result;
static HeavyVehicle hV = new HeavyVehicle();
static Truck T = new Truck();
static HeavyVehicle hv2 = null;
public static void main(String[] args)
{

138
result = hV instanceof HeavyVehicle;
System.out.print("hV is an HeavyVehicle: " + result + "\n");
result = T instanceof HeavyVehicle;
System.out.print("T is an HeavyVehicle: " + result + "\n");
result = hV instanceof Truck; System.out.print("hV is a Truck: " + result + "\n");
result = hv2 instanceof HeavyVehicle;
System.out.print("hv2 is an HeavyVehicle: " + result + "\n");
hV = T; //Sucessful Cast form child to parent
T = (Truck) hV; //Sucessful Explicit Cast form parent to child
}
}
Output
hV is an HeavyVehicle: true
T is an HeavyVehicle: true
hV is a Truck: false
hv2 is an HeavyVehicle: false

Summary

In this unit you studied about Dynamic binding , Generic programming,


Casting Objects. Instance of Operator

7.7 Keywords
Dynamic Binding, Generic, Casting objects

7.8 Questions for Self Study

1. Explain generic programming in java


2. With an example discuss dynamic binding
3. Write a note on
a. instanceof Operator
b. Casting objects

139
7.9 Reference Books

1. Thinking in Java, Fourth Edition by: Bruce Eckel

2. Java How to Program (3rd Edition) by H.M. Deitel

3. Beginning Java 2 - Jdk 1.3 Edition: Jdk 1.3 Edition (Programmer to


Programmer) by Ivor Horton

4. Internet.

140
UNIT 8: ABSTRACT CLASS

Structure
8.0 Objectives
8.1 Introduction
8.2 Abstract Class
8.3 Interface in Java
8.4 Package in Java
8.5 UTIL package
8.6 Summary
8.7 Keywords
8.8 Unit-end exercises and answers
8.9 Reference books

8.0 Objectives
At the end of this unit you will be able to
 Define Abstract Class
 Describe Interface in Java
 State Package in Java
 Explain UTIL package

8.1 Introduction

In this unit is we will learn about. Abstract Class, Interface in Java, Package in Java
and UTIL package

8.2 Abstract Class

Abstract class in Java

A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).

Before learning the Java abstract class, let's understand the abstraction in Java first.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only

141
functionality to the user.

Another way, it shows only essential things to the user and hides the internal details,
for example, sending SMS where you type the text and send the message. You don't
know the internal processing about the message delivery.

of Prime Minister of India (1947-2020)

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)

2. Interface (100%)

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have


abstract and non-abstract methods. It needs to be extended and its method
implemented. It cannot be instantiated.

Points to Remember

o An abstract class must be declared with an abstract keyword.

o It can have abstract and non-abstract methods.

o It cannot be instantiated.

o It can have constructors and static methods also.

o It can have final methods which will force the subclass not to change the body
of the method.

142
Example of abstract class

abstract class A{}

Abstract Method in Java

A method which is declared as abstract and does not have implementation is known as
an abstract method.

Example of abstract method

abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract method run.
Its implementation is provided by the Honda class.

143
abstract class Bike{
abstract void run( );
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

Output:: running safely

Final and Abstract Classes


This section deals with final modifier involving final classes, final variables and final
methods. The concept of abstract classes is also explained concisely.
Final Modifier
The word “final” is used to indicate that no further alterations can be made.
Final Classes
Classes can be declared as final to ensure security. The class can be declared as final,
if instances or subclasses are not to be created. Java’s class hierarchy has many final
classes. Some of them are String, Boolean, Math, Character, etc.
Final Variables
Attributes of a class can be declared as final indicating that the value of those
particular variables cannot be changed. The value of final variables must be provided
at the time of declaration. These are similar to the # define statements of C. Local
variables cannot be declared as final variables.
For example, the following declaration is incorrect.
public class abc {
void temp( ){
final int k; // local variable, wrong declaration
}
}

144
The usage of this modifier is discussed in Example 5.7, which accepts the radius of a
circle and calculates its circumference and area.
Example 5.7
 Open a new file in the editor and enter the following code:

import java.io.*;
class Circum {
public static final float pi = 3-14f;
private int x;
public void getint() {
try {
BufferedReader br = new BufferedReader (new InputStreamReader
(System.in));
System.out.println("enter a number for radius");
String s=br.readLine();
x=Integer.parseInt (s);
} catch(IOException e) { }
}
public void cir() {
float c = (2*pi*x);
System.out.println("circumference of circle :" + c);
}
public void area () {
float a = (pi*x*x);
System.out.println("area of circle : " + a);
}
public static void main(String args[]) {
Circum j = new Circum();
j.getInt();
j.cir();
area();
}
}

145
 Save the file as Circum,java
 Compile the file using javac Circum.java rat
 Run the file using java Circum

Let us input the radius as 3. The output appears as shown below:


Circumference of circle: 18.84
area of Circle: 28.26
The class circum has methods get rat (), cir() and area() to accept an integer as radius
and calculate circumference and area. Note the declaration of the float variable pi at
line number 3. Since the value of pi is constant, it has been declared as final, At no
point of time can its value be changed.
Final Methods
Methods can be declared as final indicating that they cannot be overridden by
subclasses. Generally when a method is overridden, the compiler must know which
overridden function is to be executed. This slows down the whole process. The usage
of the word final before a method helps in faster compilation. This is because the
compiler knows that when a method is declared as final, it cannot be overridden. Thus
the efficiency of the program is enhanced by the usage of these methods.
Abstract Methods and Classes
Abstract classes are classes from which instances are usually not created. It is
basically used to contain common characteristics of its derived classes. Abstract
classes are generally higher up the hierarchy and act as super class. Methods can also
be declared as abstract. This implies that non-abstract classes must implement these
methods. Implement of the abstract method is absolutely essential .For example,
observe the hierarchy Fig 5.3.
Employees

Teaching Non – Teaching

Professor Lecturers Clerical Administrative

146
Fig. 5.3

The classes Employees, Teaching and Non-Teaching are all abstract classes. This is
because an instance of these classes cannot be created. It will not contain full details.
Take the case of Professors .An instance of Professors class has attributes of Teaching
class, the Employee class and as well some of its own .Thus the instance is well
defined. We should note that the above mentioned classes are placed higher in the
hierarchy and they also act as super classes for the classes Professors, Lecturers,
Clerical and Administrative classes
Java’s class hierarchy provides a number of classes that are abstract. Some of them
are Number class, Security manager class, Class Loader class; etc. The Number
abstract class has derived classes like Integer, Long, Float and Double

8.3 INTERFACE IN JAVA

Interface in Java

An interface in Java is a blueprint of a class. It has static constants and abstract


methods.

The interface in Java is a mechanism to achieve abstraction. There can be only


abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.

Java Interface also represents the IS-A relationship.

t cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.

147
o By interface, we can support the functionality of multiple inheritance.

o It can be used to achieve loose coupling.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction;


means all the methods in an interface are declared with the empty body, and all the
fields are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.

Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
Java 8 Interface Improvement

Since Java 8, interface can have default and static methods which is discussed later.

Internal addition by the compiler

The Java compiler adds public and abstract keywords before the interface method.
Moreover, it adds public, static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and the methods
are public and abstract.

148
The relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface
extends another interface, but a class implements an interface.

Java Interface Example

In this example, the Printable interface has only one method, and its implementation
is provided in the A6 class.

interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

Output :Hello

149
8,4 PACKAGE IN JAVA

Java Package

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined
package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc.

Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

150
Simple example of java package

The package keyword is used to create a package in java.

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
Note: The line numbers given are not part of the source code and should not be
typed so.

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename

151
For example

javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can
use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc.
If you want to keep the package within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file
i.e. it represents destination. The . represents the current folder.

How to access package from another package?

There are three ways to access the package from outside the package.

1. import package.*;

2. import package.classname;

3. fully qualified name.

1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.

The import keyword is used to make the classes and interface of another package
accessible to the current package.

Example of package that import the packagename.*


//save by A.java
package pack;

152
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

2) Using packagename.classname

If you import package.classname then only declared class of this package will be
accessible.

Example of package by import package.classname


//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();

153
obj.msg();
}
}

Output: Hello

3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.

Example of package by import fully qualified name


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello

Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import

154
the subpackage as well.

Note: Sequence of the program must be package then import then class.

Subpackage in java

Package inside the package is called the subpackage. It should be created to


categorize the package further.

Let's take an example, Sun Microsystem has definded a package named java that
contains many classes like System, String, Reader, Writer, Socket etc. These classes
represent a particular group e.g. Reader and Writer classes are for Input/Output
operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun
has subcategorized the java package into subpackages such as lang, net, io etc. and
put the Input/Output related classes in io package, Server and ServerSocket classes in
net packages and so on.

The standard of defining package is domain.company.package e.g.


com.javatpoint.bean or org.sssit.dao.
Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");

155
}
}
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output: Hello subpackage

How to send the class file to another directory or drive?

There is a scenario, I want to put the class file of A.java source file in classes folder of
c: drive. For example:

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

To Compile:

e:\sources> javac -d c:\classes Simple.java

156
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where the class fil
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple

Another way to run this program by -classpath switch of java:

The -classpath switch can be used with javac and java tool.

To run this program from e:\source directory, you can use -classpath switch of java
that tells where to look for class file. For example:

e:\sources> java -classpath c:\classes mypack.Simple

Output:Welcome to package

Ways to load the class files or jar files


There are two ways to load the class files temporary and permanent.

o Temporary

o By setting the classpath in the command prompt

o By -classpath switch

o Permanent

o By setting the classpath in the environment variables

o By creating the jar file, that contains all the class files, and copying the
jar file in the jre/lib/ext folder.

Rule: There can be only one public class in a java source file and it must be saved by
the public class name.

//save as C.java otherwise Compilte Time Error

157
class A{}
class B{}
public class C{}

How to put two public classes in a package?


If you want to put two public classes in a package, have two java source files
containing one public class, but keep the package name same. For example:

//save as A.java

package javatpoint;
public class A{}

//save as B.java
package javatpoint;
public class B{}

8.5 UTIL package

java.util

The basic utility classes required by the programmer are provided by this #.

Class Description

AbstractCollection< The class is used for providing a rough implementation of


E> the Collection interface. The class is declared as:
public abstract class AbstractCollection<E>
extends Object
implements Collection<E>
The class methods are extended from the Object class.

AbstractList<E> The class is used for providing a rough implementation of

158
the List interface. The class is declared as:
public abstract class AbstractList<E>
extends AbstractCollection<E>
implements List<E>
The class methods are extended from the
AbstractCollection<E> class.

AbstractMap<K,V> The class is used for providing a rough implementation of


the List interface. The class is declared as:
public abstract class AbstractMap<K,V>
extends Object
implements Map<K,V>
The class methods are extended from the Object class.

AbstractMap.Simple The class instance is used for maintaining the value and
Entry<K,V> key. The class is declared as:
public static class AbstractMap.SimpleEntry<K,V>
extends Object
implements Map.Entry<K,V>, Serializable
The class methods are extended from the Object class.

AbstractMap.Simple The class instance is used for maintaining the value and
ImmutableEntry<K, key which is immutable. The class is declared as:
V> public static class
AbstractMap.SimpleImmutableEntry<K,V>
extends Object
implements Map.Entry<K,V>, Serializable
The class methods are extended from the Object class.

AbstractQueue<E> The class is used for providing a rough implementation of


the Queue interface. The class is declared as:
public abstract class AbstractQueue<E>
extends AbstractCollection<E>
implements Queue<E>

159
The class methods are extended from the
AbstractCollection class.

AbstractSequentialLi The class is used for providing a rough implementation of


st<E> the List interface. The class is declared as:
public abstract class AbstractSequentialList<E>
extends AbstractList<E>
The class methods are extended from the AbstractList<E>
class.

AbstractSet<E> The class is used for providing a rough implementation of


the Set interface. The class is declared as:
public abstract class AbstractSet<E>
extends AbstractCollection<E>
implements Set<E>
The class methods are extended from the
AbstractCollection<E> class.

ArrayDeque<E> The class is used for providing a rough implementation of


the Deque interface. The class is declared as:
public class ArrayDeque<E>
extends AbstractCollection<E>
implements Deque<E>, Cloneable, Serializable
The class methods are extended from the
AbstractCollection<E> class.

ArrayList<E> The class is used for providing a rough implementation of


the List interface. The class is declared as:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable,
Serializable
The class methods are extended from the AbstractList<E>
class.

160
Arrays The class contains various methods which can be used for
the performing large number of operations on arrays. The
class is declared as:
public class Array extends Object
The class methods are extended from the Objetct class.

BitSet A vector consisting of bits is created by this class. The


class is declared as:
public class BitSet extends Object
implements Cloneable, Serializable
The class methods are extended from the Object class.

Calendar It is an abstract class for providing the date time related


conversions. The class is declared as:
public class BitSet extends Object
implements Cloneable, Serializable
The class methods are extended from the Object class.

Collections The class consists of various methods which is used for


performing of various operations on collections in java.
The class is declared as:
public class Collections extends Object
The class methods are extended from the Object class.

Currency The class is used for the representation of currency in


various dominations.The class is declared as:
public final class Currency extends Object
implements Serializable
The class methods are extended from the Object class.

Date The class is used for representation of date. The class is


declared as:
public class Date extends Object
implements Serializable, Cloneable, Comparable

161
The class methods are extended from the Object class.

Dictionary<K,V> The following abstract class is a parent of many. It is used


for the mapping of key into values. The class is declared
as:
public abstract class Dictionary<K,V> extends Object
The class methods are extended from the Object class.

EnumMap,V> The class is a special implementation of Map class


designed for enum values. The class is declared as:
public class EnumMap,V>
extends AbstractMap<K,V>
implements Serializable, Cloneable
The class methods are extended from the
AbstractMap<K,V> class.

EnumSet The class is used for providing a rough implementation of


the Set interface for the enum values. The class is declared
as:
public abstract class EnumSet
extends AbstractSet<E>
implements Cloneable, Serializable
The class methods are extended from the AbstractSet<E>
class.

EventListenerProxy It is the wrapper class for the Event Listener. The class is
declared as:
public abstract class EventListenerProxy extends Object
implements EventListener
The class methods are extended from the Object class.

EventObject All the objects of Event states are derived from this class.
The class is declared as:
public class EventObject extends Object

162
implements Serializable
The class methods are extended from the Object class.

GregorianCalendar It is the child class of Calendar class. The class is declared


as:
public class GregorianCalendar
extends Calendar
The class methods are extended from the Calendar class.

HashMap<K,V> The class is an implementation of the map interface which


basically is designed for hash tables. The class is declared
as:
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
The class methods are extended from the
AbstractMap<K,V> class.

HashSet<E> The class is an implementation of the set interface which


basically is designed for hash tables. The class is declared
as:
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, Serializable
The class methods are extended from the AbstractSet<E>
class.

Hashtable<K,V> Hash table is implemented by this class. The class is


declared as:
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, Serializable
The class methods are extended from the Dictionary<K,V>
class.

163
IdentityHashMap<K, The class is an implementation of the map interface for
V> hash tables. The class is declared as:
public class IdentityHashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Serializable, Cloneable
The class methods are extended from the
AbstractMap class.

LinkedHashMap<K, The class is an implementation of the map interface for


V> hash tables with linked list. The class is declared as:
public class LinkedHashMap<K,V>
extends HashMap<K,V>
implements Map<K,V>
The class methods are extended from the HashMap<K,V>
class.

LinkedHashSet<E> The class is an implementation of the set interface for hash


tables with linked list. The class is declared as:
public class LinkedHashSet<E>
extends HashSet<E>
implements Set<E>, Cloneable, Serializable
The class methods are extended from the HashSet<E>
class.

LinkedList<E> Interfaces such as List and Deque are implemented by


using doubly linked list. The class is declared as:
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, Serializable
The class methods are extended from the
AbstractSequentialList<E>class.

ListResourceBundle The class is the successor of ResourceBundle which is


designed to make the resources available to the locale. The

164
class is declared as:
public abstract class ListResourceBundle
extends ResourceBundle
The class methods are extended from the ResourceBundle
class.

Locale It is used to reflect a region on space of any type. The class


is declared as:
public final class Locale extends Object
implements Cloneable, Serializable
The class methods are extended from the Object class.

Locale.Builder Instances of the class are used to make the Locale class
objects. The class is declared as:
public static final class Locale.Builder
extends Object
The class methods are extended from the Object class.

Objects The various methods of the class are used to manipulate


the number of operations to be performed on objects. The
class is declared as:
public class Objects extends Object
The class methods are extended from the Object class.

Observable The objects that we can see, monitor or observe are


represented by this class. The class is declared as:
public class Observable extends Object
The class methods are extended from the Object class.

PriorityQueue<E> The class represents a priority queue. It is a data structure


in which each element has a assigned priority with it. The
class is declared as:
public class PriorityQueue<E> extends AbstractQueue<E>
implements Serializable

165
The class methods are extended from the
AbstractQueue<E> class.

Properties A wide set of properties are defined by this class. The class
is declared as:
public class Properties
extends Hashtable<Object,Object>
The class methods are extended from the
Hashtable<Object,Object> class.

PropertyPermission Various permissions related to the property of any entity in


the program is handled by this class. The class is declared
as:
public final class PropertyPermission
extends BasicPermission
The class methods are extended from the BasicPermission
class.

PropertyResourceBu It is a child class of the ResoruceBundle class. The class


ndle manages the resource allocation to the locale with the
specific set of properties. The class is declared as:
public class PropertyResourceBundle
extends ResourceBundle
The class methods are extended from the ResourceBundle
class.

Random The class instances are used to design a set of random


numbers. The class is declared as:
public class Random
extends Object
implements Serializable
The class methods are extended from the Object class.

ResourceBundle The class contains various objects which are specific to

166
locale. The class is declared as:
public abstract class ResourceBundle
extends Object
The class methods are extended from the Object class.

Scanner It is a very important utility class which is used to add user


defined values to the class. The class is declared as:
public final class Scanner
extends Object
implements Iterator, Closeable
The class methods are extended from the Object class.

ServiceLoader<S> It is a basic service providing class. The class is declared


as:
public final class ServiceLoader<S>
extends Object
implements Iterable<S>
The class methods are extended from the Object class.

SimpleTimeZone The class instances represent time zone to be used with the
Georgians Calendar. The class is declared as:
public class SimpleTimeZone
extends TimeZone
The class methods are extended from the TimeZone class.

Stack<E> The class represents a data type based on the LIFO


principle. The class is declared as:
public class Stack<E>
extends Vector<E>
The class methods are extended from the Vector<E> class.

StringTokenizer It is used for creation of various tokens from a string. The


class is declared as:
public class StringTokenizer

167
extends Object
implements Enumeration<Object>
The class methods are extended from the Object class.

Timer The class provides facility of scheduling of tasks. The class


is declared as:
public class Timer
extends Object
The class methods are extended from the Object class.

TimerTask The instances of the class represent various tasks which are
scheduled using the timer. The class is declared as:
public abstract class TimerTask
extends Object
implements Runnable
The class methods are extended from the Object class.

TimeZone The instances of the class represent the offset of the time
zone. The class is declared as:
public abstract class TimeZone
extends Object
implements Serializable, Cloneable
The class methods are extended from the Object class.

TreeMap<K,V> It is a map implementation which is based on the tree


structure. The class is declared as:
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, Serializable
The class methods are extended from the
AbstractMap class.

UUID The instances of the class represent UUID. The class is


declared as:

168
public final class UUID
extends Object
implements Serializable, Comparable
The class methods are extended from the Object class.

Vector<E> The class represents an array of object which can further


also be extended. The class is declared as:
public class Vector<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable,
Serializable
The class methods are extended from the AbstractList<E>
class.

WeakHashMap<K,V The class implements the map interface based on the hash
> table. The class is declared as:
public class WeakHashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>
The class methods are extended from the extends
AbstractMap<K,V> class.

8.6 SUMMARY
In this unit you studied about Abstract Class , Interface in Java , Package in Java
And UTIL package

8.7 KEYWORDS

Abstract Class, Interface in Java , Package in Java , UTIL package

8.8 QUESTIONS FOR SELF STUDY


1. Describe Abstract Class with an example.
2. Explain Interface in Java

169
3. Write short note on Packages and UTIL Package.
8.9 REFERENCE BOOKS
1. David J. Eck Introduction to Programming Using Java.
2. Elliotte Rusty Harold Java I/O published by O'Reilly
3. Ken Arnold, James Gosling . The Java Programming Language

4. Patrick, Naughton The Java Handbook

5. Dwight Deugo More java gems

6. Jose M. Garrido Object-Oriented Programming: From Problem Solving to Java


7. Internet

170
UNIT 9: Event and GUI Programming

Structure
9.0 Objectives
9.1 Introduction
9.2 Event Handling in Java, Event Types , Mouse and key events, GUI Basics
9.3 Summary
9.4 Key words
9.5 Questions for Self Study
9.6 Suggested readings

9.0 OBJECTIVES

 At the end of this unit you will be able to

 Explain Event Handling in Java


 Event Types
 Mouse and key events
 GUI Basics

171
9.1 INTRODUCTION

In this unit we learn about Event Handling in Java, Event Types, Mouse and key
events , GUI Basics

9.2 EVENT HANDLING IN JAVA


Events

If any interactive environment, the program should be able to respond to actions


performed by the user. These actions can be, mouse click, key press or selection of a
menu item. The basis of event-driven programming is tying events to code that
responds to those events. After Working this far and grasping some of the
fundamentals of object-oriented programming, it is possible to think that events will
be handled using object-oriented approach.

Java Abstract Windowing Toolkit (AWT) communicates these actions to the program
using events. When the user initiates an action, the AWT generates an event and
communication it to event handlers. These event handlers can respond to the events
appropriately.

The whole of the event handling in Java 1.0 AWT is done using two method action ()
and handlevent ( ) method. The action () method has three parameters namely the
event that has occurred the x and y co-ordinates at which this event occurred. To find
the AWT component (like button, checkbox, radio button, text box discussed in the
next chapter) in which the event was generated, the instance of operator is used. The
handle event () method is called automatically for an object and an event object is
created and passed on to it. This type of event handling had various problems which is
addressed and solve in java V1.1

Event Delegation Model

In the new event model, an event is propagated from a "Source" object to a "Listener

172
“object by invoking a method on the listener and passing in the instance of the event
subclass which defines the event type generated. To say it in simple terms, when an
event is fired, it is received by one or more listeners that act on that event. Each event
listener is an object of a class that implements a particular type of listener interface.
Event types are encapsulated in a class hierarchy rooted at java.util.Eventobject and
one level below this is java.awt.AWTEvent package. Given below are some of the
common terms related to event handling:

 A Listener is an object that implements a specific EventListener interface


extended from the generic java.util. EventListener.
 An EventListener interface defines one or more methods that are to be invoked by
the event source in response to each specific event type handled by the interface.
 An Event Source is an object that originates or "fires" events. The source define
the set of events it emits by providing a set of set <EventType> Listener (for
single-cast) and/or add<EventType>Listener (for multi-cast) methods which are
used to register specific listeners for those events.
 An Adapter class includes all methods specified by the corresponding interface
bur not providing any functionality.

In an AWT program, the event source is typically a GUI component and the listener
id commonly an "adapter" object which implements the appropriate listener (or set of
listeners) in order for an application to control the flow/handling of events. The
listener object could also be another AWT component that implements one or more
listener interfaces.
All AWT event sources support a multicast model for listeners. This means the
multiple listeners can be added and removed from a single source. There is no
guarantee about the order in which the events are delivered to a set of registered
listeners for a given event on a given source .

HANDLING AN EVENT

The primary design goals of the new model in the AWT are;

173
 To make it simple and easy to learn
 To support c clean separation between application and GUI code
 To facilitate the creation of robust event handling code which is less error-
prone(strong compile-time checking)
 To make it flexible enough to enable varied application models for event flow
and Propagation
 To support backward binary compatibility with the old model

A java programmer has three options of handling an event:

 Ignoring the event


 Handling of the event by the component where the event originated
 Delegating event handling to objects called listeners

Whenever an AWT component wants to handle its own events, the component’s
subclass created has to do two things:

 Enable receipt of events by calling enable Events ()


 Provide a processActionEvent () method which is called whenever the component
is activated

The delegation method is the best-suited method to handle events. It is not possible
for a component to handle its events at all times. Hence this should be assigned to a
different object called listeners. This process is called delegation. Each component
class in the AWT has one addxxxListener () method for each event type that the
component generates.

Types of event handling

The AWT provides two conceptual types of events: low-level and semantic. An
Eventlistener interface typically has a separate method for each distinct event type the
event class represents. It is also divided into low-level and semantic.

174
Low -level event

A low level event is one that represents a low-level input or window-system


occurrence on a visual component on the screen. The low-level events classes define
by the AWT are as follows.

 COMPONENT EVENT(Component resized, moved, etc.)


 FOCUSEVENT(component got focus, lost focus)
 INPUTEVENT
 KEYEVENT (component got key-press, key-release, etc.)
 MOUSEEVENT (component got mouse-down, mouse-move, etc.)
 CONTAINEREVENT
 WINDOWEVENT

The low-level event listeners are as follows:

 ComponentListener
 ContainerListener
 FocusListener
 KeyListener
 MouseListener
 MouseMotionListener
 WindowListener

Semantic Events

Semantic events are defined at a higher-level to encapsulate the semantics of a user


interface component's model. The semantic event classes defined by the AWT are as
follows:

 ActionEvent ("do a command")


 AdjustmentEvent ("value was adjusted")

175
 ItemEvent ("item state has changed")
 TextEvent ("the value of the text object changed")

The semantic listener interfaces defined by the AWT are as follows:


 ActionListener
 AdjustmentListener
 ItemListener
 TextListener

Mouse Events

These are generated whenever a mouse is moved, clicked, pressed, released, etc. The
MouseEvent Class represents these events as six constant values. This class has
method to get the co-ordinates at which a mouse event has occurred. The mouse move
and mouse drag are treated differently from the other four types namely mouse
pressed, mouse released, mouse entered and mouse exited. Hence there are two types
of mouse event listeners - MouseListener and MouseMotionListener.

This MouseListener interface has the following definition:

public interface mouseListener {


public void mouseClicked (MouseEvent e);
public void mousePressed (MouseEvent e);
public void mouseEntered (MouseEvent e);
public void mouseExited (MouseEvent e);
public void mouserReleased (MouseEvent e);
}

The MouseMotionListener interface has the following definition:

public interface MouseMotionListener {


public void mouseDragged (MouseEvent e);
public void mouseMoved (mouseEvent e);

176
}

An alternate way of handling mouse events is by letting components process their


own ordinary mouse events using enableEvents (AWTEvent
.MOUSE_EVENT_MASK) and processMouseEvent () methods.

The following illustrates the usage of mouse event listeners. Watch out for messages
on the status line of the applet as and when there is a mouse event performed by the
user. It also shows the co-ordinates at which such an event has occurred.

Example 10.2

 Open a new file in the editor and type the following code:

import java.awt. *;
import java.awt. event. *;
import java. applet. *;
public Class MouseTest extends Applet implements MouseListener,
MouseMotionListener ({
Public void init () {
addMouseListener(this);
addMouseMotionListener (this);
}
public void mouseClicked (MouseEvent e) (
showStatus (“mouse clicked at “+e. getX () +","+e. getY ());
}
public void mouseEntered (MouseEvent e) (
showStatus(“mouse entered at "+e.getx()+", "+e.getY());
for(int i=0;i<1000000; ++i);
}
public void mouseExited(MouseEvent e) {
showstatus(“mouse exited at “+e.getx()+","+e.getY());
}
public void mousePressed (MouseEvent e){

177
showStatus ("mouse pressed at age ‘’+e.getx() +’’,’’+e.getY());
}
public void mouseDragged (MouseEvent e){
showStatus ("mouse dragged at ‘’+e.getx()+’’,’’+e.getY());
}
public void mouseMoved (MouseEvent e){
showStatus ("mouse moved at ‘’+e.getx()+","+e.getY());
}
}

The MouseTest.html file contains code as given below:

<applet code="MouseTest .class" width=200 height=200>


</applet>

Since this applet implements MouseListener as well as MouseMotionListener, it has


to provide the functionality for all their methods. Observe that the mouseEntered ()
method has a small for loop. This is to ensure that the mouse entered message remains
on the status line for some time. Otherwise, it is not possible to see this very clearly.
On executing this the applet appears as shown in fig. 10.2.

KEYBOARD EVENT
These are generated on pressing or releasing a key. The keyEvent class contains
constants to represent the keys pressed or typed. The event listener corresponding to
these types of event is the KeyListener.This interface has the following definition;

public interface KeyListener {


public void keyPressed (KeyEvent e);
public void keyReleased (KeyEvent e);
public void keyTyped (KeyEvent e);
}

Components can process their own key events using


enableEvents (AWTEvent. KEY_EVENT MASK) and processKeyEvent () methods.

178
The following example clarifies the usage of key event listeners. This applet contains
a label and a text field (dealt in detail in next chapter), Recently typed character in the
text field is displayed in the status line. Here the text field delegates its key events to
the applet.The add () method adds the components to the applet.

Example 10.3

 Enter the following code in a new file and save the file as KeyTest.java
import java.awt. *;
import java.awt.event.*;
import java. applet. Applet;
public class KeyTest extends Applet implements KeyListener {
Public void init () {
Label l=new Label ("Enter characters");
add (1);
TextField tf = new TextField (20);
tf. addKeyListener (this);
add(tf);
)
Public void keyPressed (KeyEvent e) {}
public void keyReleased (KeyEvent e) {}
Public void keyTyped (KeyEvent e) {
showStatus ("Recently typed character in the text field is:’’+e. getKeyChar ());
}
}
On execution of this, the applet as shown in fig 10.3 is obtained.

179
User Interface Components

A place in which the various drawing needs to be done must be provided and this is
called the container the container is derived from java.awt. Container class. The
elements of the user interface are called components. These components are derived
from the java.awt. Component class.
The Component class is the abstract superclass of the nonmenu-related Abstract
Window Toolkit components. All the user interface components and container classes
and derived from this class. This class is responsible for a variety of activities like
display. Event handling and front management.

These are two major sets of classes derived from the component class:
 CONTAINER classes-They are generic AWT components that can contain other
components.
 USER INTERFACE COMPONENT classes-These include components like
button, lable etc.

CONTAINERS
A generic Abstract Window Toolkit (AWT) container object is a component that can
contain other AWT components. User interface components added to a container are
tracked in a list. The order of the list will contain the components’ front-to-back
stacking order within the container. It no index is specified when adding a component

180
to a container. It will be added to the end of the list. Components have to be
necessarily added to a container if they have to be displayed on the screen. Fig. 10.4
shows the class hierarchy of the classes that can act as container.

The basic functionalities of containers are encapsulated in an abstract class,


Container. This class has methods that allow other components to be nested within it.
The Panel is a simple non-abstract container that can contain other components. The
add () method of the Container, class can be used to add components to a Panel.

The Applet class is derived from the Panel class and, hence, can act as a container.
This property applet shall be exploited by adding user interface components and other
container directly to the applet.

NOTE: The Applet class, though derived from Panel, does not belong to the AWT
package.

USER Interlace Component Classes


The AWT package Contains a number of component classes that are typical elements
of any Interactive user interface. These classes, collectively called UI component
classes, are derived from the abstract Component class. Fig. 10.5 shows the class
hierarchy of these
Classes.

181
The Component class defines a number of methods that can be used on any of the
classes that are derived from it. The methods listed below in table 10.1 can be used on
all UI components as well as containers.
Method DESCRIPTION
setSize (Dimension d) Resizes the corresponding components it
has width d. width and height d. height
setSize (int width, int height) Resizes the corresponding components so
that it has width and height
setFont (font f) Sets the font of the corresponding
setEnabled (boolean b) Enables or disables the corresponding
components, depending on the values of
the parameter b.
setVisible (Boolean b) Shows or hide the corresponding
component depending on the value
parameter b
setForeground (Color c) Sets the foreground color of the
corresponding component
setBounds (int x, int y, int width, int Moves and resizes the corresponding
Height) components.

182
SetBounds (Rectangle r) Moves and resizes the corresponding
components to conform to the new
bounding rectangle r.
setBackground (Color c) Sets the background color of the
corresponding component
getBackground () Gets the background color of the
corresponding component
getBounds () Gets the bounds of the corresponding
component in the form of a Rectangle
object
getfont () Gets the font of the corresponding
component.
getForeground () Gets the foreground color of the
corresponding component.
getsize () Returns the size of the corresponding
component in the form of a Dimension
object
Table 10.1

The various user interface components have been shown in Fig. 10.5. The following
sections will discuss each of these components in detail.

To effectively use these components, the following steps have to be carried out.

 First, the user interface component has to be created using the constructor of the
corresponding class. For example, to create a Button object, the following code
fragment can be used:

Button mybutton = new Button(“OK”);


 Next, the component created is added to a container using the add () method of the
Container class. For example, add(but); adds the button created to the container.
Since, the Applet itself is derived from the Container class, the add () method can
be used on an applet.

183
 Depending on the user interface component, it is necessary to handle the event
generated by it. There are two ways of handling events as mentioned in the last
chapter. But it is always wise to use listeners rather than letting the component
handle its events by itself.
 To determine the component in which an event has occurred, it is necessary to
Use inner classes which was dealt in the fourth chapter. Each object has an inner
class defined for is that implement their respective event listeners. The object of
this inner class forms a parameter addXXXListener () function in its outer class.
The user interface component classes also have a number of method that can be used
to change the attributes of the component like, the label of a button, text of a text field
etc. The user interface components classes including their events and methods, are
discussed next

9.3 SUMMARY / TO SUM / LET’S SUM UP


In this unit we have learnt about:
 Java's Abstract Windowing Toolkit generates events when user performs actions
like, mouse click, key press etc.
 When an event is fired, it is received by one or more listeners that act on that
event.
 Components can handle events by themselves or can delegate it to objects called
listeners.
 An EventListener interface typically has a separate method for each distinct event
type the event class represents.
 There are two types of mouse event listeners — MouseListener and
MouseMotionListener.
 KeyListener interface is called whenever any component delegates its key events.
 The Component class, which is the base class of all user interface components and
containers, provides the basic functionality needed for display and event handling.
The containers are generic AWT components that can contain other components,
including other containers

184
9.4 KEYWORDS / GLOSSARY

Event Handling, Event Types, Mouse, key events, GUI

9.8 QUESTIONS FOR SELF STUDY


1. What is MouseEvent? What are the two types of mouse event listeners?
2. What are the primary design goals of the new model in the AWT?
3. List the three option
4. Write short note on Event Handling.

9.9 SUGGESTED READINGS AND REFERENCE

1. Patrick, Naughton The Java Handbook

2. Sun Microsytems Java tutorial,

3. E. Balaguruswamy Programming with java


4. Internet

185
UNIT 10: PANELS

Structure
10.0 Objectives
10.1 Introduction
10.2 Panels , Frames, Layout Managers –(Flow Layout, Border Layout, Grid
Layout)
10.5 Summary
10.6 Key words
10.7 Questions for Self Study
10.8 Suggested readings

10.0 OBJECTIVES

At the end of this unit you will be able to

 Explain Layout Managers


 Elucidate Frames & Menus
 Describe Dialogs

186
10.1 INTRODUCTION
This unit illustrates the layout manager classes that are used to position the components in a
container. This chapter also discusses the classes in AWT that allow creation of pop-up
windows, menus and dialogs. It also gives an introduction to creating stand-alone Java
programs using AWT.

10.3 PANELS

The Panel is a simplest container class. It provides space in which an application can
attach any other component. It inherits the Container class.

It doesn't have title bar.

AWT Panel class declaration


public class Panel extends Container implements Accessible

Java AWT Panel Example

import java.awt.*;
public class PanelExample {
PanelExample()
{
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);

187
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}

Output:

Layout Managers
The layout manager classes are a set of classes that implement the java
AWT.LayoutManager interface and help to position the components in a container. The
interface takes the task of laying out the child components in the container. This task is
achieved by resizing and moving the child components. The advantage of this type of
mechanism is that when the container is resized the layout manager automatically updates the
interface.
The basic layout managers include:

188
 FlowLayout
 BorderLayout
 GridLayout
 GridBagLayout
 CardLayout

The following step have to be undertaken in order to derive the benefits of layout managers.
 The first step is to instantiate a layout manager class, such as FlowLayout,
BorderLayout etc. The constructor of these classes, which comes in different flavors,
can be used to create a new layout manager object.
 The next step is to associate the layout manager with the container on which it should
operate .The method setLayout () sets the layout manager of a container.

Once the layout manager for the container is set, components added to it will be arranged
depending on the layout specified.
Flow Layout
The FlowLayout class is a simple manager that works like a word processor. Components are
displayed with their preferred size in the order in which they are added to the container. The
flow layout lays out components linewise from left to right .When the line of components is
filled, flow layout creates a new line and continues laying out components on the next line.
Like a word processor a FlowLayout +
FlowLayout can be created using the constructors given in Table 11.1. 1
Constructor Description
FlowLayout( ) Constructs a new flow layout with centered alignment,
leaving a vertical and horizontal gap of 5 pixels.
FlowLayout(int align) Constructs a new flow layout with the alignment specified
leaving a vertical and horizontal gap of 5 pixels.
FlowLayout(int align , Constructs a new flow layout with the alignment specified
Int vgap, int hgap) leaving a vertical and horizontal gap as specified.

Table 11.1
The various methods that can be used in combination with the flow layout is given in Table
11.2.

189
Method Description
getAlignment( ) Gets the alignment for the layout.

getHgap( ) Gets the horizontal gap between components.

getVgap( ) Gets the vertical gap between components.

setAlignment(int align) Sets the alignment for the specified layout.

setHgap(int hgap) Sets the horizontal gap for the specified layout.

setVgap(int vgap) Sets the vertical gap for the specified layout.

Table 11.2
Example 11.1 creates an applet that uses the flow layout to arrange the user interface
components.
Example 11.1
 Enter the following code in a file and save it as FlowTest.java.

import java.awt.*;
public class FlowTest extends java.applet.Applet {
String str[ ]= {"One", "Two", "Three", "Four","Five","Six","Seven"};
public void init( ) {
setLayout (new FlowLayout ());
for(int i=0;i<str.length; ++i)
add(new Button(str[i]));
}
}

 Enter the following script in a file and save it as FlowTest.html.

<APPLET CODE="FlowTest.class" WIDTH=175 HEIGHT=75> </APPLET>


 On execution, the following figure 11.1 is obtained.

190
The init ( ) method instantiates an object of FlowLayout class and associates it with the
applet. Then, a few buttons are created and added to the applet. The output of the program
(Fig. 11.1) that the buttons are added to the applet from left to right. When the first line is
filled, the buttons are added to the next line, again from left to right. If a line is half filled, the
buttons are arranged centered, since, the default FlowLayout alignment is FlowLayout.
CENTER.
Grid Layout
The GridLayout class lays out components in a way very similar to a spreadsheet – in rows
and columns. Specifying the number of rows and columns in the grid creates the GridLayout.
The components in a grid are resized to fit their cell. All components in a grid layout are of
the same size. The position of a component in a grid is determined by the order in which the
components are added to the grid. Components are displayed from left to right and top to
bottom.
The grid layout can be constructed using the constructors listed in Table 11.3.
Constructor Description
GridLayout( ) Creates a grid layout with a default of one
column per component in a single row.
GridLayout(int rows, int cols) Creates a grid layout with the specified rows
and columns.
GridLayout(int rows, int cols, Creates a grid layout with the specified rows and
int hgap, int vgap) columns and specified horizontal and vertical gaps.

Table 11.3
The various methods that can be used in conjunction with the grid layout are listed in Table
11.4.
Method Description

191
getColumns( ) Gets the number of columns in corresponding layout.
getRows( ) Gets the number of rows in the corresponding layout.
getHgap( ) Gets the horizontal gap for the corresponding layout.
getVgap( ) Gets the vertical gap for the corresponding layout.
setColumns(int cols) Sets the number of columns to the specified number in
the corresponding layout
setHgap(int hgap) Sets the horizontal gap to the value specified in the corresponding
layout
setVgap(int vgap) Sets the vertical Bap to the value specified in
the corresponding layout
setRows(int rows ) Sets the number of rows in the corresponding
layout the specified value
Table 11.4
The Grindlayout object is associated with a container by using the setLayout ( ) method. The
components added to the container occupy one cell each. The first component is placed in the
first element of the grid. The subsequent components added are placed in adjoining cells,
from left to right. When the right hand side of the container is reached, the components are
added to the next row, again, from left to right.
Grid layout is often used along with Panels to divide the screen space into number of cells.
The components added to the panels are to be fitted inside the cell.
Example 11.2 demonstrates the grid layout arrangement.
Example 11.2
 Enter the following code in a file and save it as GridTest.java.

import java.awt.*;
public class GridTest extends java.applet.Applet {
public void init() {
setFont (new Font ("TimesRoman", Font .BOLD+Font . ITALIC, 24));
setLayout (new GridLayout (3,4,10,10));
for(int i=1;i<=12;++i)
add(new Button(""+i));
}
}

192
The output is shown in Fig. 11.2

In line 4 of the example, the font of the applet is set using the setFont () method. This method
belongs to the component class and bears no relation to the setFont() method used with
Graphics class objects. In line 5, a GridLayout object is created with 3 rows and 4 columns
and with horizontal and vertical gaps of 10 pixels each. The layout of the applet is set using
the setLayout () method.
In lines 6 and 7, 12 buttons are added to applet. Each of these buttons occupies a cell in the
grid. These buttons are separated by a horizontal and vertical gap of 10 pixels each as
specified in the constructor of the GridLayout ().
BorderLayout
The BorderLayout class enables specification, i.e., where on the border of a container each
component should be placed. All areas need not be filled. The size of the areas will depend
on the components they contain.
With border layout, the placement of the component is specified as being, North, South, East
and West. The border layout resizes the Center component to fill the remaining center space.
The various constructors that can be used to create a border layout is given in Table 11.5.
Constructor Description
BorderLayout( ) Creates a new border layout with no gap between
the components

BorderLayout(int hgap, int Creates a border layout with the specified


vgap) horizontal and vertical gap between components.

Table 11.5
The various methods that can be used in conjunction with the border layout is given in Table

193
11.6.
Method Description
getHgap( ) Returns the horizontal gap between components
getVgap( ) Returns the vertical gap between components
setHgap(int hgap) Sets the horizontal gap between components to
the value specified
setVgap(int vgap) Sets the vertical gap between components to the
value specified
Table 11.6
To add a component to a container with BorderLayout, an add ( ) method, that is slightly
different from the one we have been using, is used. The following code fragment adds a
component to the right border of the container.
add ( “East”, mybutton)
Similarly, North, South, West and Center can be used to place the component at the top,
bottom, left and the center of the container respectively. The components in the North and
South positions are sized to fit the container horizontally, but they are also sized to the
preferred height. The East and West components are sized to their preferred width, but they
are stretched to fill the available height. The Center component is sized to fit any remaining
area, ignoring its preferred size altogether.
The border layout is used when components are to be grouped on the borders of a container,
such as positioning of scroll bars on the bottom or right side of a container.
GridBagLayout
The GridBagLayout divides a container into a grid of equally sized cells. In this kind of
layout, a component can occupy more than one cell, if necessary. The total area occupied by
component is called its display area. We can specify the location of each component in this
layout, by specifying its x and y coordinates. The upper left corner of the GridBagLayout has
the coordinates (0,0). The x and y coordinates are specified by gridx and gridy respectively.
Similarly, gridwidth and gridheight specify the width and the height of the component,
respectively. The default value for the height and the width is one.
We can adjust the size of the component, when its size is less than the display area. The mode
of adjustment is specified by fill. If it takes the value GridBagLayout. NONE then the size of
the component remains unchanged. If the value is GridBagConstraints.HORIZONTAL then
the component is stretched horizontally. If the GridBagConstraints. VERTICAL then the

194
component is stretched vertically. If the GridBagConstraints.BOTH then the component is
stretched in both directions.
When the component is smaller than its display area, anchor determines where to place the
component. The values of the anchor are:
 GridBagConstraints.CENTER
 GridBagConstraints.NORTH
 GridBagConstraints.NORTHEAST
 GridBagConstraints.EAST
 GridBagConstraints.SOUTHEAST
 GridBagConstraints.SOUTH
 GridBagConstraints.SOUTHWEST
 GridBagConstraints.WEST
 GridBagConstraints.NORTHWEST

weightx and weighty determine how to distribute space. The GridBagLayout class contains
only one constructor, namely, GridBagLayout (). The methods of the class are listed in
Table 11.7.
Method Description
addLayoutComponent(Component c, Object a)Adds the component c to the layout using the
constraints specified by the object a
addLayoutComponent(String s, component c) Adds the component c with the name s to the
layout
getConstraints(Component c) Returns the constraints for the component c
getLayoutAlignmentX (Container c) Returns the alignment along the x-axis of the
container c
getLayoutAlignmentY (Container c) Returns the alignment along the y-axis of the
container c
getLayoutDimensions( ) Returns the Dimensions for the layout grid
GetLayoutInfo(Container c, int f) Prints the layout constraints
getLayoutOrigin( ) Returns the origin of the layout grid
getLayoutWeights( ) Returns the weights of the rows and columns
of the layout grid

195
invalidateLayout(Container c) Invalidates the layout
layoutContainer(Container c) Lays out the container c using the grid bag
layout
location(int x, int y) Returns the cell in the layout grid containing
the point specified by (x,y)

lookupConstraints(Component c) Returns the constraints for the component c


maximumLayoutSize(Container c) Given the components of the container c,this
method returns the maximum dimensions for
this layout
minimumLayoutSize(Container c) Returns the minimum size of the container c
using this grid bag layout
preferredLayoutSize(Container c) Returns the preferred size of the container c
using this grid bag layout
removeLayoutComponent(Component c) Removes the component c from this layout
setConstraints(Component c, Sets the constraints specified by cons to the
GridBagConstraints cons) Component c in this layout
toString( ) Returns a string representation of the values
of this grid bag layout
Table 11.7

CardLayout
The CardLayout allows only one of its components to be visible at a time. The CardLayout
considers each of its components as a card. A CardLayout is controlled by a combo box.The
state of the combo box determines which panel is displayed by the CardLayout. Using the
CardLayout, the user has the option to view the following:
 The first component
 The last component
 The previous component
 The next component
 Any component by specifying its name

The constructors of the CardLayout class are listed in Table 11.8

196
Constructor Description
CardLayout( ) Creates a new card layout whose gaps are of size zero
CardLayout(int h, int v) Creates a new card layout with the horizontal gap specified
by h and the vertical gap specified by v

Table 11.8
The methods available in the CardLayout are listed in Table 11.9.
Method Description
addLayoutComponent(Component c, Object a)Adds the component c to the internal table of names
of the card layout
first(Container c) Displays the first card of the container c
getHgap( ) Returns the horizontal gap between the components
getLayoutAlignmentX(Container c) Returns the alignment along the x-axis of the
container c
getLayoutAlignmentY(Container c) Returns the alignment along the y-axis of the
container c
getVgap( ) Returns the vertical gap between the components
InvalidateLayout(Container c) Invalidates the layout
last(Container c) Displays the last card of the container c
layoutContainer(Container c) Lays out the container c using the card layout
maximumLayoutSize(Container c) Given the components of c, this method
returns the maximum dimensions for this layout
minimumLayout(Container c) Returns the minimum size for the specified panel
next(Container c) Displays the next card of the container c
preferredLayoutSize(Container c) Returns the preferred size of the container c using
the card layout
previous(Container c) Displays the previous card of the container c
removeLayoutComponent(Container c) Removes the components c from the layout
setHgap(int h) Sets the horizontal gap between the components to h
setVgap(int v) Sets the vertical gap between the components to v
show(Container c, ¸String s) Displays the component added to the container c
with the name specified by s
Table 11.9

197
Insets
Insets are used to provide spacing around the container. To cause a container (Panel) to have
its edges inset, the insets () method must be overridden to return a new instance of Insets
which represents the width of the spacing at the top, bottom, left, and right edges.
To create an inset in the container, the following method should be added to the container
class (Applet).
public Insets getInsets () {
return new Insets (10, 5, 15, 20)
}
This provides an inset of 10 and 5 pixels at the top and bottom and, 15 and 20 pixels at the
left and right edges.
Example 11.3 shows an applet that uses the border layout to position the user interface
components and adds an inset to the applet to demonstrate its usefulness.

Example 11.3
 Enter the following code in a file and save it as BorderTest.java.

import java.awt.*;
public class BorderTest extends java.applet.Applet {
public void init ( ) {
setLayout (new BorderLayout(5,5,) ) ;
add("South", new Button ( "Bottom of the Applet”) );
add("North", new Button ( "Top of the Applet”) );
add(“East", new Button("Right”) );
add("West", new Button( “Left") );
add("Center", new TextArea("Appears at the centre") );
}
public Insets getInsets ( ) {
return new Insets(20,20,10,10);
}
}
 Enter the following code in a file and save it as BorderTest.html.

<APPLET CODE="BorderTest.class" WIDTH=400 HEIGHT=150> </APPLET>

198
In this example, the layout of the applet is set to the BorderLayout with a horizontal and
vertical gap of five pixels each. Then, four buttons are created and added to the four edges of
the applet. A Textarea is created and added to the center of the applet. Fig. 11.3 shows the
output of the program when it is run using the appletviewer.

Panel
The Panel class is a non-abstract, recursively nestable, container. The panel can contain UI
components and other containers.
A panel object can be constructed using the following code:
Panel pl=new Panel ( ) ;
The add( ) method of the Container class can be used to add a component to the
panel.pl.add(myButton);
Like all conatiners, the layout of the Panel can be set using the setLayout( ) method.
Frames and Menus
The Frame class is used to create standard application windows independent of the
browser(or the appletviewer) that contains the applet. The Frame window is a full-fledged
window by itself that can contain the following user interface elements:
 Title bar - the top section of window that holds the window’s title.
 Menu bar - the area just below the title bar which contains a number of menu labels.
 Control Elements - these are UI components that are added to the Frame using the
add() method of the Container.

199
To create a Frame, use one of the constructors listed in Table 11.10.
Constructors Description
Frame( ) Creates a title frame, which is initially invisible.
Frame(String) Creates a frame with the String as the title

Table 11.10
Unlike Panels, a Frame object is rarely created directly from the applet. Since the frame is a
separate pop-up window, the events generated by the UI elements in the Frame are not sent to
the applet. Instead, these events are sent to the Frame object. To handle these events ,the
Frame class should be customized by deriving a sub-class from it . This sub-class can have all
event handlers specific to the problem.
public class MyFrame extends Frame {
// add your methods and event handlers here
}
In the applet, an instance of the sub-class (MyFrame) is created. The newly created frame is
initially invisible.The setVisible method is used to make the frame window appear on the
screen. The Frame class and its ancestor classes provide a number of methods that help in
positioning the frame on the screen. A selection of these methods is shown in Table 11.11.
Methods Description
setVisible(boolean) Makes the frame or window visible.
setSize(Dimension) Resizes the frame to the specified width and height.
setLocation(int,int) Moves the frame to the specified coordinates.
getLocation( ) Returns the current coordinates of the Frame as a
Point object. In case of top level windows like
frames, the location is in screen coordinate system.

Table 11.11
Note : None of the methods listed in Table 11.11 actually belong to Frame class. All these
methods belong to the Component class, an ancestor class of the Frame class. These methods
can be used on all classes derived from the Component class.
The Frame class also provides methods that allow getting and setting the title of the frame.
These methods and the dispose() method, which disposes the frame, are discussed in Table
11.12.

200
Methods Description
getTitle() Returns the title of the Frame as a String.
SetTitle(String) Changes the title of the Frame to the specified String.
dispose( ) Releases all the resources related to the window. The
window is removed from the screen.

Table 11.12
When the user attempts to close the frame an event, with id WINDOW CLOSING event type
is generated. The customized frame class should handle this event to dispose the frame.

Example 11.4 shows an applet that pops up a frame window when a button in the applet is
pressed. Use an instance variable to keep track of the number of frames that are popped up.
Example 11.4
 Type the following code in a file and save it as MyFrame.java

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
class MyFrame extends Frame {
boolean a;
MyFrame( ) {
a=false;
addWindowListener (new W( ));
}
class W extends WindowAdapter {
public void windowClosing (WindowEvent e) {
try{
setVisible(false) ;
dispose( );
System.exit (0);
}catch(Exception g) {}
}
}

201
}
public class FrameTest extends Applet {
int num=0;
public void init( ) {
Button benew Button("create window");
b.addActionListener(new B( ));
add(b);
}
class B implements ActionListener {
public void actionPerformed (ActionEvent e) {
MyFrame mf=new MyFrame( ) ;
mf.setSize(300,200);
mf.setVisible(true);
mf.setTitle("window - “+num);
++num;
}
}
}

The FrameTest.java file contains two classes, the frame, MyFrame, and the applet, The
FrameTest. The MyFrame class handles the window closing event to dispose the resource
associated with it. To accomplish this the addwindowListener method is called which has a
WindowAdapter object as its parameter. The try block within the windowclosing ( ) method
ensures that exceptions associated with such events are handled.

The init () method of the FrameTest applet creates a new button and adds it to the applet. The
action event is associated with the button which is handled using addActionListener ( )
method within which a new MyFrame object is created and displayed. There is also an
increment of the instance variable, num that keeps tracks of the number of frames popped up.

Creating Stand-alone Applications


In the previous section, a frame was popped up from inside an applet. The frame can be made
the main window of an application since it is a full-fledged window by itself. An application,
as opposed to an applet, has a static main method that acts as the entry point to the program.

202
To create a stand-alone AWT application that constructs a Frame object in the main and pops
it up using setVisible (boolean) method, we use the following piece of code.

MyFrame f= new MyFrame ( );


f.setVisible (boolean);

When the user tries to close the frame window, a window closing event is generated that
should be handled for the following to be done:

 The resources related to the frame should be disposed.


 Since the frame window is the main window of the application, when the user closes
the frame , the application itself should be closed using the exit method in the System
class, System.exit(0);

The parameter passed to the exit method represents the error value returned by the
application. An error value of 0 indicates normal exit.

Example 11.5 is a Stand-alone Java program that has a frame window as its main window
Example 11.5

 Type the following code in a new file and save the file as FrameApp.java
import java.awt.*;
import java.awt.event.*;
class FrameApp extends Frame {
boolean a;
FrameApp( ) {
a=false;
setTitle("Stand-alone Application");
addWindowListener(new W( ));
}
class W extends WindowAdapter {
public void windowClosing (WindowEvent e) {
if(a)

203
dispose( );
else
System.exit (0);
}
}
public static void main(String args[]){
FrameApp fm=new FrameApp () ;
fm.setSize(300, 200);
fm.setVisible(true);
}
}

 Compile FrameApp.java using javac and run it from the DOS prompt using java. The
main method creates a new FrameApp object and displays it using the setVisible
(boolean) method. A blank frame window of the application, which acts as the main
window of the application, is displayed.
 When the frame is closed the window closing event handler closes the application by
the exit () method.

Menus
Java’s AWT provides a number of menu component classes to easily build and manage
menus. These menu component classes encapsulate the functionality of the three menu
elements, namely, the menu bar, the menu, and the menu item.

Fig. 11.4 indicates that the menu bar, displayed along the top of the window, has number
pull-down menus (File, Edit etc.). Each of these menus has a number of menu items. For

204
instance, the File menu has a number of menu items such as New, Open, and Save.

The classes that represent these menu elements are discussed in the following paragraphs.

The Menubar Class

The menu bar is the topmost menu element displayed along the top of the window to which it
belongs.
To create a menu bar, create an instance of the class Menubar.

Menubar mb= new Menubar ( );

The MenuBar has an add( ) method that permits addition of a number of selectable menus.
After adding menus, the Menubar should be assigned to a Frame to enable appearance of
menus on screen.

myframe.setMenubar (mb);

The Menu Class


The Menu class is used to implement a pull-down menu that provides a number of items to
select from. To create an instance of Menu, use the constructor Menu (String) that creates a
new menu object with the string specified as its label.

Creating a menu, which contains a number of menu items, involves the following steps.
 First. construct a new instance of the Menu class.
Menu m= new Menu(“File”);
 Then, add the menu items to the newly constructed menu using the add() method.
m.add(menuitem1) ;
m.add(menuitem2) ;
 Lastly, add the Menu to a Menubar.
mb.add(m);

Some methods in the Menu class are shown in Table 11.13

205
Methods Description
Add(Menultem) Adds the specified Menultem to the menu.
add(String) Adds the specified String to the menu. A new menu item with the
specified string as the label is created and is added to the menu
addSeparator( ) Adds a separator to the menu.
getItem( ) Returns the item at the specified index as a String.
Remove(int) Deletes the item at the specified index from the menu.
Table 11.13

The Menultem Class

The Menultem class encapsulates the functionality of the lower most component of the
menuing system namely, the menu item.

To create a menu item, use the following constructor.

 Menultem (String) creates new instance of Menultem with String specified as the
label.

The newly created Menultem can be added to a Menu using the add( ) method.

MenuItem mitem= new menuItem (“Open”);


m.add (mitem);

where m is an instance of the Menu class.

Since a reference to the Menultem is normally not required, the Menultem can be created and
added to the menu in a single step.

m.add (new MenuItem (”Open”));

A selection of methods in the Menultem class is listed in the Table 11.14

206
Methods Description
getLabel( ) Returns the label of the Menultem as a String.
setLabel(String) Changes the label of the Menultem to the specified String.
setEnabled(boolean) Makes the menu item selectable / deselectable depending
on whether the parameter is true or false.
Table 11.14

Menu Actions
When the user selects a menu item, an action event is generated. This event can be handled
by using action event listeners.

The CheckboxMenultem Class


The CheckboxMenultem, a subclass of Menultem class, creates a dual state menu item. The
menu item’s state can be toggled on and off by clicking on it.

To create a CheckboxMenultem, the following constructor can be used.

 CheckboxMenultem (String) creates a checkbox menu item with the specified String
as the label. The menu item is initially unchecked.

Note : In Windows 95 environment, a tick mark appears to the left of the menu item to
indicate that it is checked.

The CheckboxMenultem class provide some additional methods to modify the state of the
menu item. These are listed in Table 11.15.

Methods Description
getState( ) Returns the state of the menu item as boolean value.
A value of true implies that the checkbox menu item is
selected.
setState(boolean) Sets the state of the menu item. If the value passed is true
the menu item is set to selected state.

207
Table 11.15

Example 11.6 adds appropriate messages to a text area as and when the respective menu
items are clicked. A label is placed on top of this text area asking the user to check out the
appearance of a pop up menu. This application introduces various features of menu:

 Adding a sub menu to a menu item


 Adding a separator between menu items
 Adding a popup menu
 Creating a short cut key to a menu item
 Disabling a menu item when the application is started
 Changing state of menu items using CheckboxMenuItem class

Example 11.6

 Enter the following code in a file and save it as MenuApplication.java

1 : import java.awt.*;
2 : import java.awt.event.*;
3 : public class MenuApplication extends Frame implements
ActionListener, ItemListener {
4: boolean inAnApplet = true;
5: TextArea output;
6: PopupMenu popup;
7: String newline;
8: public MenuApplication( ) {
9: MenuBar mb;
10: Menu m1, m2, m3, m4, m4_1, m5;
11: Menultem m1_1, m1_2, m3_1, m3_2, m3_3, m3_4,m4_1_1, m5_1,
m5_2,pal,pm2, m5_1_duplicate;
12: CheckboxMenuItem m2_1;
13: addWindowListener (new WindowAdapter( ) {

208
14: public void windowClosing (WindowEvent e) {
15: if (inAnApplet) {
16: dispose();
17: }
18: else {
19: system.exit (0);
20: }
21: }
22: } );
23: newline = System.getProperty("line.separator") ;
24: setLayout (new BorderLayout ());
25: output = new TextArea(5, 30);
26: output.setEditable(false);
27: add("Center", output);
28: Label label = new Label("Try bringing up" + " a popup menu!");
29: add("North", label);
30: mb = new MenuBar();
31: setMenuBar(mb) ;
32: //makes this a tear-off menu.
33: m1 = new Menu("Menu 1", true);
34: mb.add(m1) ;
35: m1_1 = new MenuItem("Menu item 1_1");
36: m1.add(m1_1);
37: m1_2 = new MenuItem("Menu item 1_2");
38: m1.add(m1_2);
39: //Build help menu.
40: m5 = new Menu("Help Menu") ;
41: mb.setHelpMenu(m5) ;
42: m5_1 = new MenuItem("Menu item 5_1");
43: m5_1.setShortcut (new MenuShortcut (KeyEvent .VK_5));
44: m5.add(m5_1);
45: m5_2 = new MenuItem("Menu item 5_2");
46: m5.add(m5_2); //Make a popup menu.
47: popup = new PopupMenu("A Popup Menu");

209
48: add(popup) ;
49: pm1 = new Menultem("A popup menu item");
50: popup.add(pm1) ;
51: m5_1_duplicate = new MenuItem("Duplicate of menu item 5_1",new
MenuShortcut (KeyEvent.VK_5));
52: popup.add(m5_1_duplicate);
53: pm2 =new Menultem(“An item with a shortcut", new
Menushortcut (KeyEvent.VK_6));
54: popup.add(pm2); //Build second menu in the menu bar.
55: m2 = new Menu ("Menu 2");
56: mb.add (m2) ;
57: m2_1 = new CheckboxMenuItem(“Menu item 2_1”);
58: m2.add(m2_1);
59: //Build third menu in the menu bar.
60: m3 = new Menu ("Menu 3");
61: mb.add (m3) ;
62: m3_1 = new MenuItem(“Menu item 3_1”);
63: m3.add(m3_1);
64: m3_2 = new MenuItem(“Menu item 3_2”);
65: m3.add(m3_2);
66: m3.addSeparator( );
67: m3_3 = new MenuItem(“Menu item 3_3”);
68: m3.add(m3_3);
69: m3_4 = new MenuItem(“Menu item 3_4”);
70: m3_4.setenableed(false);
71: m3.add(m3_4);
72: //Build fourth menu in the menu bar.
73: m4 = new Menu ("Menu 4");
74: mb.add (m4) ;
75: m4_1 = new Menu (“Submenu 4_1”);
76: m4.add(m4_1);
77: m4_1_1 = new MenuItem(“Menu item 4_1_1”);
78: m4_1.add(m4_1_1);
79: //register as an ActionListener for all menu items.

210
80: m1.addActionListener(this);
81: m2.addActionListener(this);
82: m3.addActionListener(this);
83: m4.addActionListener(this);
84: m4_1_1.addActionListener(this);
85: //m4 can’t detect
86: //submenu actions
87: m5.addActionListener(this);
88: popup.addActionListener(this);
89: //Set action commands for a few menu items.
90: m1_1.setActionCommand(“1_1”);
91: m1_2.setActionCommand(“1_2”);
92: m5_1.setActionCommand(“5_1”);
93: m5_2.setActionCommand(“5_2”);
94: pm1.setActionCommand(“popup item #1”);
95: m5_1_duplicate.setActionCommand(“5_1”);
96: pm2.setActionCommand(“popup item #2”);
97: //Register as ItemListener on checkbox menu item.
98: m2_1.addItemListener(this);
99: //Listen for when the popup menu should be shown.
100: MouseListener listener = new PopupListener();
101: addMouseListener(listener);
102: output.addMouseListener(listener) ;
103: label .addMouseListener(listener) ;
104: }
105: class PopupListener extends MouseAdapter {
106: public void mousePressed(MouseEvent e) {
107: maybeShowPopup(e);
108: }
109: public void mouseReleased(MouseEvent e) {
110: maybeShowPopup (e) ;
111: }
112: private void maybeShowPopup(MouseEvent e) {
113: if (e.isPopupTrigger( )) {

211
114: popup. show(e.getComponent( ),e.getX( ), e.getY( ));
115: }
116: }
117: }
118: public void actionPerformed(ActionEvent e) {
119: output.append("\"" + e.getActionCommand( )+ "\" action detected
120: in menu labeled \""+ ((MenulItem) (e.getSource())).getLabel()+
"\"." + newline);
121: }
122: public void itemStateChanged(ItemEvent e) {
123: output.append("Item state change detected on item \""*+
e.getItem()+ "\" (state is "+ ((e.getStateChange( ) ==
ItemEvent .SELECTED)? "selected).": “deselected).")+ newline);
124: }
125: public static void main(String[] args) {
126: MenuApplication m = new MenuApplication();
127: m.inAnApplet = false;
128: m.setTitle("Menu Application");
129: m.setSize(450, 200);
130: m.setVisible(true);
131: }
132: }
Note: The line numbers given are not part of the source code and should not be
typed so.

Let us go through the above code in parts. The declaration of the class Menu Application
includes implementation of ActionListener and ItemListener interfaces in order to enable
actions to be performed upon clicking a menu item.

The constructor of the MenuApplication class creates the following:

 MenuBar mb
 Menu m1, m2, m3, m4_1, m5

212
 CheckboxMenultem m2 with menu item m2_1
 Menu Items

 m1_1, m1_2 to be added to menu m1


 m3_1, m3_2, m3_3, m3_4 to add to menu m3
 m4_1_1 to add to menu m4
 m5_1, m5_2, m5_1_duplicate to add to menu m5

 A help menu is added to the menu bar using setHelpMenu() method


 A short cut is created for menu item m5_1 using setShortcut () method which accepts
a MenuShortCut Class object with short cut key combination as parameter.
 A popup menu is created and pm1, pm2 menu items are added to this.
 The addseparator() method is used to add a separator between menu items.

 Menu item m3_4 is disabled when the application is started using the
setEnabled(false) method.
 A sub menu is created and m4_1_1 menu item is added to this.
 Action listeners are added to implement action events in the menu items.
 Item listeners are added to enable item selection in the check box menu items.
 Mouse listeners and action listeners are added to enable action to bring up popup
menu.
 To close the frame window, the window listener is added by creating a
WindowAdapter object
 A text area
 A label
 A string, new line, to bring in the new line property.

The setactionCommand sets the command name of the action event that is fired by this menu
item. By default, the action command is set to the label of the menu item.

The PopupListener class is created as a sub class of MouseAdapter. The mousePressed and
mouseReleased methods are added to this class, which are responsible for bringing up and
closing the pop up window. The maybePopupShow method checks if the event triggered

213
isPopupTrigger and then shows the pop up window at the point of clicking.

The actionPerformed method is responsible for displaying messages on the text are whenever
there is any action performed on the menu items.

The itemStateChanged method displays the messages whenever there is an item selection or
deselection of the CheckboxMenuItem menu.

The main method creates an object of MenuApplication that brings up the frame window of
this application . The setVisible() and set Title() methods show the window and display
window respectively. The boolean value for the object is set to false, since the application
should terminate once the close button of the window is clicked . Try commenting out this
line and observe.

To bring up pop up menu, rightclick anywhere on the frame which brings up a strip. Click on
it again to obtain a popup menu.

The output is shown in Fig. 11.5.

A simple editor that too a custom built editor sounds like a good idea isn’t it. Well that’s what
XYZ enterprises decided to do. They did not want the fancy stuff of changing fonts, their size
etc. They could not afford to buy some software that would meet their requirements. They
had the expertise in the office and hence decided that they could go head and build one for
themselves.

Their Main idea was with to use the software that was already existing with them. They had

214
Java with them and since Java was portable across any platform without much difficulty they
decided to take up the chance and built an editor.

Their main requirement was to have a menu that would allow

 Opening of new files


 Opening an existing file
 Save the file
 Exit from the editor
 Cutting
 Pasting
 Copying
These were their main requirements.
In order to do this they decided on building a frame as the structure on which they would
build the menu. The area in which the file operations were carried out was decided to be , text
area and two menus i.e., file and edit were decided upon. The file menu would contain
various sub menu items such as open, new, save and close. The edit menu would contain
various sub menu items such as cut, copy and paste. Example 11.7 satisfies these
requirements.

Example 11.7

 Open a new file in the editor and type the following code:

1 : import java.awt.*;
2 : import java.awt.event.*;
3 : import java.awt.datatransfer.*;
4 : import java.io.*;
5 : public clase Editor extends Frame {
6: String filename;
7: TextArea tx;
8: Clipboard clip = getToolkit( ).getSystemClipboard( );
9: Editor( ) {

215
10: setLayout (new GridLayout (1,1));
11: tx = new TextArea();
12: add (tx);
13: MenuBar mb = new MenuBar();
14: Menu F = new Menu("File");
15: MenuItem n = new MenuItem("New") ;
16: Menultem o = new MenuItem("Open") ;
17: Menultem s = new Menultem("Save") ;
18: MenuItem e = new Menultem("Exit") ;
19: n.addActionListener(new New()) ;
20: F.add(n);
21: o.addActionListener(new Open()) ;
22: F.add(o);
23: s.addActiontListener(new Save()) ;
24: F.add(s);
25: e.addActionListener(new Exit ()),
26: F.add(e);
27: mb.add(F);
28: Menu E = new Menu ("Edit*);
29: MenuItem cut = new Menultem("Cut");
30: MenuItem copy = new Menultem("Copy") ;
31: MenuItem paste = new Menultem("Paste");
32: cut.addActionListener (new Cut());
33: E.add(cut);
34: copy.addActionListener (new Copy());
35: E.add(copy);
36: paste.addActionListener (new Paste());
37: E.add(paste);
38: mb.add(E);
39: setMenuBar(mb) ;

 The above code can be saved as Editor.java


 The above code should not be compiled as it is not in its entirety.

216
 Note: The line numbers given are not part of the source code and should
not be typed so.

Dialogs
Dialog box , like frame, is a pop-up window on which user interface components can be laid
out. Usually they are used to display messages and get specific information from the user.
Though a dialog resembles and behaves like a frame, there are some major differences
between the two. They are :

 Unlike frames, a dialog has a parent (or a owner) window. The dialog is automatically
closed when the parent window is closed.
 The dialog box usually contains a number of UI components suitably arranged (laid
out). Letting the user adjust the size of the dialog may affect the layout of the
components in the dialog.
 A dialog box can be made modal. A modal dialog prevents user input to other
windows in the application until the dialog is closed.

To create a dialog, use one of the constructors given in Table 11.16


Constructors Description
Dialog(Frame, boolean) Creates a new dialog, which is initially invisible.
The Frame acts as the parent of the dialog. The dialog is
closed when its parent is closed. The boolean value specifies
whether the dialog is modal or not.
Dialog (Frame,String, Creates a new dialog with the specified String as the title.
boolean) The other two parameters are the same as in the
previous constructor.

Table 11.16
Notice that both the Dialog constructors require a Frame as a parameter. This frame window
acts as the parent of the dialog.
The dialog, like a frame, can act as a container. The layout of the dialog can be using the
setLayout() method and components can be added to it using the add() method. Methods in
the Dialog class that distinguish it from the Frame are shown in Table 11.17

217
Methods Description
setResizable(boolean) Sets the resizable flag of the dialog. If the
boolean value passed is true, the dialog is made resizable.
isModal( ) Returns true if the dialog is modal. A modal dialog prevents
the
user input to other windows in the application until the dialog
is closed.
isResizable( ) Returns true if the dialog is resizable.

Table 11.17

Example 11.8 creates a MessageBox dialog class that displays a message in a dialog window.

Example 11.8

 Enter the following code in a file and save it as MessageBox.java.

1 : import java.awt.*;
2 : import java.awt.event.*;
3 : public class MessageBox extends Dialog {
4 : MessageBox(Frame fm,String lab) {
5 : super (fm, "Message", true);
6 : setLayout (new GridLayout (2,1,0,0));
7 : Panel p1=new Panel( );
8 : Panel p2=new Panel( );
9 : Button b1,b2;
10: p1.setFont (new Font ("TimesRoman", Font .BOLD, 18) );
11: p1.setLayout (new FlowLayout (FlowLayout .CENTER, 20,15));
12: p2.setLayout (new FlowLayout (FlowLayout .CENTER, 20,20));
13: p1.add(new Label (lab) );
14: b1=new Button("ok") ;
15: b1.addActionListener (new B1());

218
16: p2.add(b1);
17: b2=new Button ("cancel");
18: b2. addActionListener (new B1());
19: p2.add(b2) ;
20: add(p1);
21: add(p2);
22: setSize(350,125),
23: setTitle("Message Box");
24: addWindowListener(new WindowaAdapter () {
25: public void windowClosing (WindowEvent e) {
26: system.exit(0); } } ) ;
27: }
28: class B1 implements ActionListener {
29: public void actionPerformed (ActionEvent e) {
30: try {
31: Button ok=(Button)e.getSource();
32: String s=ok.getLabel ();
33: if(s.equals(“ok")||s.equals("cancel") ) {
34: dispose();
35: System.exit (0);
36: }
37: }catch(Exception n) { }
38: }
39: }
40: }
Note: The line numbers given are not part of the source code and should not be
typed so.

 Enter the following in a file and save it as MessageApplication.java

1 : import java.awt.*;
2 : import java.awt.event.*;
3 : public class MessageApplication extends Frame {
4 : boolean a;

219
5 : MessageApplication( ) {
6 : MessageBox mb=new MessageBox(this,"Java Alert : This is a Message Box");
7 : mb.setLocation(200, 200);
8 : mb.setVisible(true);
9 : a=false;
10: }
11: public static void main(String args[ ]) {
12: MessageApplication fm=new MessageApplication( );
13: System.out.println("popping out message box");
14: fm.setVisible(true) ;
15: }
16: }
Note: The line numbers given are not part of the source code and should not be
typed so.

 Compile the two files using javac and run the MessageApplication class using the
java interpreter.

The constructor of MessageApplication creates a new object of type MessageBox and


displays it. The MessageBox is a dialog that displays the message passed to it in a window.

Note : The MessageBox is a generic class that can be used from any application ( which uses
frames).The MessageApplication is a stand-alone frame application that creates a
MessageBox and pops it up.

File Dialog

File dialog provides a platform-specific dialog that lets us to choose a file and to save or open
it.

220
To create a file dialog use one of the constructors shown in table 11.18

Constructors Description
FileDialog(Frame, String) Creates an Open file dialog that lets the user select a file
name from a file listing. The Frame acts as the parent
(owner) of the dialog. The string is the title of the file
dialog.
FileDialog(Frame,String, This constructor behaves exactly the same way as the
int) previous one, except that the int parameter is used to
determine whether the dialog is for loading or saving
a file. The two options are FileDialog.LOAD and
FileDialog. SAVE.

Table 11.18

Note : The file dialog does not actually load or save files. It is used only to select a file from
the file listing. The file dialog is a modal dialog.

The following code fragment creates a file dialog and displays it.

FileDialog f = new FileDialog(this , “Select File”);


f.setVisible(true);

The userbutton fan select a file from the file dialog or dismiss it by clicking on the “Cancel”
button . When the setVisible method returns, the getFile() and getDirectory() methods can be
used to get the
name of the file chosen by the user. If the user dismisses the dialog without selecting a file,
the getFile() methods returns a null string.

if(if.getFile () ! = null ) {
String filename= f.getFileName ( );
String directory= f.getDirectory ( );
// perform some action (like opening the file selected)\

221
}

A selection of methods in the Filepiaiog class is shown in Table 11.19.

Methods Description
getDirectory( ) Returns the directory of the file selected as a
String
getFile( ) Returns the name of the file selected as a String. This
method returns a null string if the user dismisses the
dialog without selecting a file .

Table 11.19

Now that XYZ have built their menu, they would prefer to get their file operation done
through the FileDialog UI. Example 11.9 illustrates how to do this.

Example 11.9

 Open Editor.java in Notepad.


 Type in the script as shown below ( this script is a continuation of the script given in
example 11.7).

mylistener mylist = new mylistener( );


addWindowListener(mylist) ;
}
class mylistener extends WindowAdapter {
public void windowClosing (WindowEvent e) {
System.exit (0);
}
}
class New implements ActionListener {
public void actionPerformed(ActionEvent e) {
tx.setText(“ ");

222
setTitle(filename) ;
}
}
class Open implements ActionListener {
public void actionPerformed (ActionEvent e) {
FileDialog fd = new FileDialog(Editor.this, "select
File", FileDialog.LOAD);
fd.show( );
if (fd.getFile( ) ! = null) {
filename = fd.getDirectory( ) + fd.getFile( );
setTitle(filename) ;
ReadFile( );
}
tx.request Focus ( );
}
}
class Save implements ActionListener {
public void actionPerformed (ActionEvent e) {
FileDialog fd = new FileDialog(Editor.this, "Save
File", FileDialog.SAVE);
fd.show( );
if (fd.getFile( ) != null) {
filename = fd.getDirectory( ) + fd.getFile( );
setTitle(filename) ;
try {
DataOutputStream d = new DataOutputStream (new
FileOutputStream(filename) );
String lime = tx.getText( );
BufferedReader br = new BufferedReader (new StringReader (line) ) ;
while( (line = br.readLine( ) ) != null) {
d.writeBytes(line + "\r\n");
d.close();
}
} catch (Exception ex) {

223
System.out.println ("File not found");
}
tx. requestFocus( );
}
}
}
class Exit implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(o) ;
}
}
void ReadFile( ) {
BufferedReader d;
StringsBuffer sb = new StringBuffer ( );
try {
d = new BufferedReader (new FileReader (filename) );
String line;
while ( (line = 4.readtine( ) ) ! = null )
sb.append (line + “\n”) ;
tx.setText (sb.toString( ) );
d.close( );
} catch (FileNotFoundException fe) {
System.out.println (“File not found”);
} catch (IOException ioe) { }
}
class Cut implements ActionListener {
public void actionPerformed (ActionEvent e) {
String sel = tx.getSelectedText ( ) ;
StringSelection ss = new StringSelection(sel) ;
clip.setContents(ss,ss) ;
tx.replaceRange(“ ”, tx.getSelectionStart ( ) , tx.getSelectionEnd ( ) );
}
}
class Copy implements ActionListener {

224
public void actionPerformed (ActionEvent e) {
String sel = tx.getSelectedText ( ) ;
StringSelection clipString = new stringSelection (sel) ;
clip. setContents (clipstring, clipstring);
}
}
class Paste implements ActionListener {
public void actionPerformed (ActionEvent e) {
Transferable cliptran = clip.getContents (Editor.this);
try {
String sel = (String) cliptran.getTransferData
(DataFlavor.stringFlavor);
tx.replaceRange(sel , tx.getSelectionStart ( ), tx.getSelectionEnd ( ) );
} catch (Exception exc) {
System.out.printin ("not string flavor");
}
}
}
public static void main (String args[ ] ) {
Frame f = new Editor( );
f.setSize (500,400);
f.setVisible(true);
f.show ( );
}
}

 Save the file


 Compile it.
 The class file is now created
 Execute the file.
 The output appears as shown in Fig. 11.7.

225
10.2 SUMMARY / TO SUM / LET’S SUM UP

 The Layout manager classes are a set of classes that help in arranging the user
interface components in a container .
 The FlowLayout lays out component linewise from left to right while the Gridlayout
position components in the cells of the grid.
 The BorderLayout helps in laying out components relative to the edges of the
container.
 The GridbagLayout divides a container into a grid of equally sized cells.
 The CardLayout allows only one of its components to be visible at a time. The
CardLayout considers each of its components as a card.
 Insets a provide space around the panel .
 The frame is a pop-up window that is independent of the browser window containing
the applet.
 The frame window can have a title bar and a menu bar . It can contain user interface
elements.
 Java’s AWT provides three classes MenuBar ,Menu and MenuItem to build and
manage menus.
 The Menu class implements the functionalities of pull-down menu. The MenuItem
class
represents individual items in a menu.
 The CheckboxMenuItem creates a dual state menu item.
 Dialog is a pop-up window on which UI components can be laid out.
 A modal dialog prevents user input to other windows in the application until the
dialog is closed.

226
 The file dialog provides a platform-specific dialog that allows the user choose a file to
save or open.

10.3 KEYWORDS / GLOSSARY


Frame, Dialog box, menu, Insets

10.6 QUESTIONS FOR SELF STUDY

1. What is a Dialog box? How does it differ from Frames?


2. What are the various features of menu?
3. What are Insets?

10.7 SUGGESTED READINGS AND REFERENCE

1. Patrick, Naughton The Java Handbook

2. Sun Microsytems Java tutorial,

3. E. Balaguruswamy Programming with java


4. Internet

227
UNIT 11: GUI PROGRAMMING

Structure
11.0 Objectives
11.1 Introduction
11.2 GUI Components Like Buttons, Check Boxes, Radio Buttons, Labels,Text
Fields, Text Areas
11.3 Summary
11.4 Key words
11.5 Questions for Self Study
11.6 Suggested readings

11.0 OBJECTIVES

At the end of this unit you will be able to

 Explain GUI Components Like Buttons, Check Boxes, Radio Buttons,


Labels,Text , Fields, Text Areas, Combo

11.1 INTRODUCTION

In this unit we will learn about Java's GUI components include labels, text fields, text
areas, buttons, etc. The Abstract Windowing Toolkit (AWT) also includes containers
which can include these components. Containers include frames (windows), canvases
(which are used to draw on), and panels (which are used to group components).03-
Oct-199811.2

Button
Buttons are components that can contain a label. It has an outline, the button is similar
to a push button in any other GUI. Pushing a button causes the run time system to
generate an event. This event is sent to the program. The program in turn can detect
the event and respond to the event. Clicking a button generates an ActionEvent.

228
However, before a button can be used it has to be created. It can be created using the
new keyword in association with the constructors that are defined for it, buttons must
be added to the containers before they can be used. This is done using the keyworld
add. Once the buttons have been created and added they can be used.

When a button is clicked the AWT sends an instance of the ActionEvent to button by,
calling the processEvent on the button. The processEvent method of the button
receives all the events of the button. This then passes an action event along by calling
its processActionEvent. The processActionEvent then passes the action event to any
action listeners that have registered an interest in action events generated by the
button in question.Any application that has to perform an action based on the button
has implement the ActionListener and register the listener to receive the events from
the button, by calling is addActionListener method.

A button is basically a control component with a label that generates an event when
pushed. The Button class is used to create a labeled button that has platform
independent implementation. The application result in some action when the button is
pushed.When we press a button and release it, AWT sends an instance
of ActionEvent to that button by calling processEvent on the button.
The processEvent method of the button receives the all the events, then it passes an
action event by calling its own method processActionEvent. This method passes the
action event on to action listeners that are interested in the action events generated by
the button.To perform an action on a button being pressed and released,
the ActionListener interface needs to be implemented. The registered new listener
can receive events from the button by calling addActionListener method of the
button. The Java application can use the button's action command as a messaging
protocol.

AWT Button Class Declaration


public class Button extends Component implements Accessible
Button Class Constructors

229
Table 10.2 lists the constructors that can be used with the Button component.
Constructor Description
Button( ) Constructs a button with no label
Button( String label) Constructs a button with the label
specified
Table 10.2

Table 10.3 lists some of the methods that can be used in relation to a button
component
Method Description
addActionListener (ActionListener 1) Adds the specified action listener to
receive action events from corresponding
button.
getActionCommand () Returns the command name of the action
event fired by the corresponding button.
getlabel () Return the label of the Corresponding
button
paramString () Returns the parameter string representing
the state of the corresponding button.
setLabel (String label) Sets the label of the button to the value
specified.
Table 10.3

Example 10.4 contains two labels, and two buttons, “OK” and “Cancel”. Two labels
are used to display the text of the buttons namely — Button! and Button2, The status
bar indicates which button was clicked.

Example 10.4

 Enter the following code in a file and save it as ButtonTest.java.

230
import java.awt. *;
import java. applet. *;
import java.awt. event. *;
public class ButtonTest extends Applet {
Label lb1=new Label("Button1");
Button b1=new Button("ok");
Label 1b2=new Label ("Button2");
Button b2=new Button("cancel");
public void init () {
setLayout (new FlowLayout ());
b1. addActionListener (new B1());
b2.addActionListener (new B2());
add(lb1);
add(b1);
add ( lb2);
add(b2);
}
class B1 implements ActionListener{
public void actionPerformed( ActionEvent e){
getAppletcontext () . showstatus (“button1: ok clicked”);
}
}
Class B2 implements ActionListener {
public void actionPerformed (ActionEvent e) {
getAppletContext (). showStatus ("Button2; cancel clicked”);
}
}
}

 Enter the following script in a file and save it as ButtonTest.html


<APPLET CODE="ButtonTest.class" WIDTH=400 HEIGHT=1> </APPLET>

Two buttons and two labels are added to the applet in the init () method in line 13 to

231
16. Two action listeners are created in the inner classes B1 and B2 and are added to
the applet using the addActionListener () method. Note that these inner classes
implement the ActionListener interface. The getappletContext () method determines
this applets context and uses the showStatus () method to display appropriate message
on the status line when the buttons are clicked. The setLayout () method is dealt in the
latter half of this chapter.
CheckBox
Checkboxes are user interface components that have dual state: checked and
unchecked
Clicking on it can change the state of the checkbox.

Java supports two types of checkboxes: exclusive and non-exclusive.


 Incase of exclusive checkboxes, only one among a group of items can be selected
as a time. If an item from the group is selected, the checkbox currently checked is
deselected and the new selection is highlighted. The exclusive checkboxes are also
called radio buttons.
 The non-exclusive checkboxes are not grouped together and, each checkbox can
be selected independent of the other.

The various constructors of checkboxes are listed in Table 10.4.


Constructor DESCRIPTION
Checkbox () Creates a checkbox with no label.
Checkbox (String label) Creates a checkbox with the specified
label
Checkbox (string lable boolean state) Create a checkbox with the specified label
and sets the specified state
Checkbox (String label, boolean state, Create a checkbox with the specified label
Checkbox Group group) and sets the specified state and places it is
the specified group. The position of the
checkbox group and state can be
interchanged.

The various methods that are supported by checkboxes are listed in Table 10.5.

232
METHOD Description
getCheckboxGroup () Determines the group of the
corresponding check box
getLabel () Gets the name of the corresponding
check box
getSelectedObjects () Returns an array (length 1) containing the
checkbox label or null if the checkbox is
not selected.
getState() Determines if the checkbox is in the ‘on’
or ‘off’ state
setCheckboxGroup (CheckboxGroup g) Sets the corresponding checkbox’s group
to the specified one.
setLabel(String label) Sets the label of the corresponding
checkbox to the value specified.
setState(boolean state) Sets the state of the corresponding
checkbox to the value specified.
Table 10.5

The Choice class implements a pop-up menu that allows the user to select an item
from that menu. This UI component displays the currently selected item with an arrow
to its right. On clicking the arrow, the menu opens and displays options for a user to
select.

The create a choice menu, a Choice object is instantiated. Then, various items are
added to the choice by Using the addItem() method. The various constructors that can
be used to create a Choice object are given in Table 10.6.
Constructor Description
Choice() Creates a new choice menu
Table 10.6.
The various Methods that can be used along with a choice object are listed in Table
10.7.

233
METHOD Description
add (string item) Adds an item to the corresponding choice
menu
additem (string item) Adds an item to the corresponding choice
getitem (int index) Gets the string at the specified index of
the corresponding choice menu
getItemCount () Returns the number of items in the
corresponding choice menu
getSelectedindex() Returns the index of the currently select
item
getSelectedltem() Gets a representation of the current
choice as a string
getSelectedObjects( ) Returns an array (length 1) containing
the currently selected item.
insert(String item, int index) Inserts the item into the corresponding
the specified position.
remove(int position) Removes an item from the corresponding
choice menu at the specified position.
Remove the first occurrence of item from
remove(String item) the corresponding Choice menu.
removeAll() Removes all items from the
corresponding choice menu.

select (int pos) Sets the selected item in the


corresponding Choice menu to be the
item at the specified position
select (string str) Sets the selected item in the
corresponding Choice menu to be the
item whose name is equal to the specified
string.

Example 10.5

234
 Type the following code in a new file and save it as RadioTest.java

1: import java.awt. *;
2: import java.awt.event,*;
3: import java.applet.+*;
4: public class RadioText extends applet {
5: Public void init () (
6: CheckboxGroup c = new CheckboxGroup ();
7: Checkbox c1=new Checkbox (“Black and White”, c. true);
8: Checkbox c2=new Checkbox (‘Color’,c, false);
9: c1, addMouseListener (new Check1());
10: c2, addMouseListener (new Check2());
11: add(c1);
12: add(c2);
13: Choice abc = new Choice ();
14: abc. add("Onida");
15: abc.add("BPL");
16:abc.2dd("Samsung’’);
17:abc.2dd("Philips");
18: abc.add("Videocon”);
19:abc. addItemListener (new Ch());
20: add (abc);
21: }
22:class Check1 extends MouseAdapter {
23: public void mouseClicked (MouseEvent e) {
24: showStatus ("You have selected: Black and White TV");
25:}
26:}
27: class Check2 extends MouseAdapter{
28: public void mouseClicked (MouseEvent e) {
29: showStatus ("You have selected: Color TV");
30:}
31:}
32: class Ch implements ItemListener{

235
33: public void itemStateChanged(ItemEvent e) {
34: String s=(String)e.getItem();
35: showStatus ("You have selected "+s +" brand") ;
36: }
37: }
38: }
Note: The line numbers given are not part of the source code and should not be
typed so.

The RadioTest.html file code is as follows:

<applet Code="RadioTest class" height=100 width=300>


<\applet>

On execution, the figure as shown in Fig. 10.6 is obtained.

Canvas

236
A Canvas component represents a blank rectangular area of the screen onto which the
application can draw or from which the application can trap input events from the
user.An application must subclass the Canvas class in order to get useful functionality
such as creating a custom component. The paint method must be overridden in order
to perform custom graphics on the canvas. The canvas does not have a Size that is
useful to the end user and hence the setSize method has to be used to, render a
meaningful canvas on the screen.

Canvas component can also be created using the constructor listed in table 10.8
Constructor Description
Canvas( ) Constructs anew canvas
Table 10.8
The canvas component has some useful method that can be used and are listed in table
10.9
Method Description
addnotify () Creates a peer of the canvas
paint(graphics g) This method is called to repaint the
corresponding canvas.
Table 10.9
FileDialog

The FileDialog class displays a dialog window from which the user can select a file.
Being a modal dialog, it blocks the rest of the application until the user has chosen a
file. The constructors that can be used to create a FileDialog are listed in Table 10.10.
Constructors Description
FileDialog(Frame parent) Creates a file dialog for loading a file
FileDialog(Frame parent, string title) Creates a file dialog window with the
specified title for loading a file
FileDialog(Frame parent, String title, int Creates a file dialog window with the
mode) specified title for loading or saving a file.
Table 10.10
The various methods that can be used in conjunction with the FileDialog component

237
are
listed in Table 10.11.
Method Description
getdirecory () Gets the directory of the corresponding
File dialog
getFile( ) Gets the file of the corresponding file
dialog
get FilenameFilter( ) Determines the file dialog’s filename
filter
getmode( ) Indicates whether the file dialog is in the
save mode or open mode
setDirectory(String str) Sets the directory of the file dialog
window to the one specified
setFile(string file) Sets the selected file for the
corresponding file dialog window to the
one specified
setFilenameFilter(filename filter) Sets the filename filter for the specified
file dialog window to the specified
value.
setModel(int mode) Sets the mode of the file dialog.
Table 10.11

Label

The component can be used for displaying a single line of text in a container. The text
can be changed by an application but the user cannot edit the text. Labels do not
generate any event.

A lable is similar to a button can be created using its construction in combination with
the keyworld new. The various construction for labels is listed in table 10.12

Constructor Explanation
Lable() constructs as empty label

238
Label (string text) constructs a string with the corresponding
text
Label (string text, int Alignment) Constructs a string with the text, with the
specified alignment. The alignment could
be
CENTER, LEFT, RIGHT.
Table 10.12

The various methods that can operate on a lable object are listed in table 10.13
Method Explanation
gettext () Gets the text of the corresponding label
paramString () Return the parameter string representing
the state ff the corresponding label

setText (string text) Set the text for the corresponding label to
the specified text.
Table 10.13

List

The List component presents the user with a scrolling list of text items. The list can be
used so that the user can choose either one item or multiple items. The difference
between a line and a choice menu are given below.

 Unlike Choice, which displays only the single-selected item, the list can be made
to show any number of choices in the visible window.
 The list can be constructed to allow multiple selections.

The various constructors that can be used to create a list object are given in table
10.14
Constructors Description
List () Create a new scrolling list of items
List (int rows) Create a new scrolling list of items with

239
the Specified number of variable lines
List (int rows, boolean multiple code) Create a new scrolling list of items to
display the specified number of rows.
Table 10.14
The various methods that can be used in conjunction with the list component are
given in table 10.15

METHOD DESCRIPTION
add (string items) Adds the specified items at the end of the
scrolling list
add (string item, int index) Add the specified items at the position
specified
deselect (int Index) Deselects the item at the specified index
getitem count () Gets the number of items in the list
getitems () Gets the items in the list
getMinimumSize () Determines the minimum size of the
scrolling list
getMinimumSize (int rows) Gets the minimum dimensions for a list
with the specified number of rows
getPreferredSize () Gets the preferred size of the
corresponding scrolling list
getPreferredSize (int rows) Gets the minimum dimension of the list
with the specified number of rows
getrows () Gets the number of visible lines in the
corresponding list
getSelectedindex () Gets the index of the selected items in the
list
getselecteditem () Gets the selected items in the
corresponding list
select (int index) Select the item at the specified index in
the corresponding list
setMultipleMode (boolean b) Sets the flag that allows multiple
selection in the corresponding list

240
Table 10.15
SCROLLPANE
ScrollPane is a container class which implements automatic horizontal and /or vertical
scrolling for a single child component the display policy for the scrollbars can be set

 as needed
 always
 never

ScrollPane can be created using the constructors listed in table 10.16


CONSTRUCTOR DESCRIPTION
ScrollPane () Create a new scroll pane container with
the scroll bar policy of “as needed’’
ScrollPane( int Scrollbardisplaypolicy ) Create a new scrollpane container
Table 10.16

The various methods that can be used with the scrollpane component are listed in
table
10.17.
METHOD DESCRIPTION
getScrollbarDisplayPolicy () Returns the display policy for the
corresponding scroll bars
setScrollPosition (int x, int y) Scroll to the specified position within the
child component
Table 10.17

Scrollbar
Scrollbars are used to select a value between a specified minimum and maximum. It
has the following components:

241
 The arrows at either end allow incrementing or decrementing the value
represented by the scrollbar.
 The thumb’s (or handle’s) position represents the value of the scrollbar

The various constructors that can be used to create a Scrollbar are giver in table 10.18

Constructor Description
Scrollbar() Constructs a vertical scroll bar
Scrollbar (int orientation) Constructs a new scroll bar with the
specified orientation.
scrollbar (int orientation, int maxvalue, Constructs a new scroll bar with the
int visible, int minimum, int maximum) specified orientation, initial value, page
size
minimum and maximum values.
Table 10.18

The various methods can be used in conjunction with Scrollbar are given in table
10.19
Methods Description
getBlockIncrement () Gets the block increment of the
corresponding scroll bar
getMaximum () Gets the maximum value of the
corresponding scroll bar
getMinimum () Gets the minimum value of the
corresponding scroll bar
getOrientation () Determines the orientation of the
corresponding scroll bar
getValue () Gets the current value of the
corresponding scroll bar
setBlockIncrement (int v) Sets the block increment for the
corresponding scroll bar
setMaximum (int newMaximum) Sets the maximum value for the
corresponding scroll bar

242
setMinimum (int newminimum) Sets the minimum value for the
corresponding scroll bar
setValue (int newvalue) Sets the value pf the corresponding scroll
bar to the specified value
Table10.19

TEXTFIELD
Textfields are UI component that accept text input from the user. They are often
accompanied by a label control the provides guidance to he user on the content to be
entered in the Textfield.

Textfields only have single line text and are ideal in situation where a relatively small
piece of information such as name age etc, is to be got from the user. For more than
one line of text, TextArea is a better choice.

Table 10.20 below lists some of the construction that can be used to create TextFields
Constructors Description
TextField () Constructs a new text area
TextField (int columns) Constructs a text area with the specified
number of columns
TextField (String text) Constructs a new text field initialized
with the specified text
TextField (String text, int columns) Constructs a new text field initialized
with the specified text with the and
specified number of columns
Table 10.20
Some of the methods that may be used in association with a Textfield are given in
table 10.21
METHOD DESCRIPTION
getColumns () Gets the number of columns in the
Corresponding text field
getEchoChar () Gets the character that is to be used for
Echoing

243
setColumns (int column) Sets the number of columns in the text
field
setEchoChar (char c) Sets the echo character for the text field
setText (String t) Sets the text that is presented by the
corresponding text component to be
specified text.

TEXTAREA
Textareas behave like TextFields except that they have more functionality to handle
amounts the text these functionalities include.
 Text areas can contain multiple rows of text
 Text areas have scrollbars that permit handling of
large amount of data

The constructors that can be used to create a text area are listed in table 10.22

CONSTRUCTORS DESCRIPTION

TextArea () Constructs a new text area

TextArea (int rows, int columns) Constructs a 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 Constructs a new text area with the
Columns) specified text and specified number
of rows and columns
TextArea (String text, int rows, int Constructs a new text area with the
columns, int scrollbar) specified text and specified number
of rows and columns and visibility of
the scroll bar.
Table 10.22

244
The various methods that can be used in conjunction with the TextArea are given in
table 10.23.

Methods Description
append (String str) Appends the given text to the text areas
contents
getColumns () Gets the number of columns of the text
area
getMinimumSize( ) Determines the minimum area of the text
area
getRows() Gets the number of rows in the text area
insert (String str, int pos) Inserts the specified string at the
specified position
setColumns (int columns) Sets the number of columns for the text
area
setRows(int rows Sets the number of rows for the text area
Table 10.23
Example 10.6 opens an applet that has the following UI components.

 A TextField, to accept input from the user.


 A Label, to inform the user about contents that should be entered in the Textfield
 A List, that displays a number of items.
 An “Add” button, that lets the user add the text in the Textfield to the list.

Example 10.6

 Enter the following code in a file and save it as ListTest.java.

Import java.awt. *;
import java. applet. *;
import java.awt. event. *;
public class ListTest extends Applet {

245
List acts=new List ();
TextField tx=new TextField (10);
Button add=new Button("add");
String stringlist [] = {"one", "two", "three"};
public void start () {
add (new Label ("text"));
add(tx);
for (int i=0; i<stringlist. Length; ++i)
acts. addiItem(stringlist[i]);
add(acts);
add. addActionListener (new Add());
add(add);
}
class Add implements ActionListener {
public void actionPerformed (ActionEvent e) {
acts. addItem (tx. getText ());
}
}
}

Enter the following code in the ListTest.html file:

<applet code="ListTest class" width=300 height=150>


</applet>

On execution, the screen appears as given in Fig 10.7 is


obtained.

246
The init () method of the applet, creates the user interface component specified in the
problem and adds them to the applet. The addItem () method is used to add three
items to the List. The text entered in the text field is added to the list on clicking the
add button the addActionListener () method enables the program to listen to button
click events items are added to the list inside the actionPerformed() method within the
inner class add.

Event and Listener (Java Event Handling)

Changing the state of an object is known as an event. For example, click on button, dragging mouse e
provides many event classes and Listener interfaces for event handling.

Java Event classes and Listener interfaces

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

247
MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling

Following steps are required to perform event handling:

1. Register the component with the Listener

Registration Methods

For registering the component with the Listener, many classes provide the registration
methods. For example:

o Button

o public void addActionListener(ActionListener a){}

o MenuItem

o public void addActionListener(ActionListener a){}

o TextField

o public void addActionListener(ActionListener a){}

o public void addTextListener(TextListener a){}

o TextArea

248
o public void addTextListener(TextListener a){}

o Checkbox

o public void addItemListener(ItemListener a){}

o Choice

o public void addItemListener(ItemListener a){}

o List

o public void addActionListener(ActionListener a){}

o public void addItemListener(ItemListener a){}

Java Event Handling Code

We can put the event handling code into one of the following places:

1. Within class

2. Other class

3. Anonymous class

Java event handling by implementing ActionListener

import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){

//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

//register listener

249
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}

public void setBounds(int xaxis, int yaxis, int width, int height); have been used in
the above example that sets the position of the component it may be button, textfield
etc.

250
2) Java event handling by outer class

import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame{
TextField tf;
AEvent2(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}

import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}

251
}

3) Java event handling by anonymous class

import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame{
TextField tf;
AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);

b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}

11.3 SUMMARY / TO SUM / LET’S SUM UP

We have learnt GUI Components Like Buttons, Check Boxes, Radio Buttons, Labels,
Text Fields, Text Areas, Combo

252
11.4 KEYWORDS / GLOSSARY

Buttons, Check Boxes, Radio Buttons, Labels, Text


Fields, Text Areas, Combo

11.5 QUESTIONS FOR SELF STUDY


1. Explain GUI Components.
2. Explain Buttons

11.6 SUGGESTED READINGS AND REFERENCE

1. David J. Eck Introduction to Programming Using Java.


2. Elliotte Rusty Harold Java I/O published by O'Reilly
3. Ken Arnold, James Gosling . The Java Programming Language
4. Internet

253
UNIT 12: APPLET AND ITS LIFE CYCLE

Structure
12.0 Objectives
12.1 Introduction
12.2 Applet and its Life Cycle
12.3 Introduction to Swing
12.4 Summary
12.5 Key words
12.6 Questions for Self Study
12.7 Suggested readings

12.0 OBJECTIVES

At the end of this unit you will be able to

 Explain the Applet and its Life Cycle


 Describe Swings

12.1 INTRODUCTION
Introduction
The Abstract Windowing Toolkit (AWT) is an API that is responsible for building the
Graphical User Interface (GUI).It is part of the Java Foundation Classes (JFC). AWT
includes a rich set of user interface components, a powerful event handling model,
graphics and image tools, layout managers and support for data transfer using cut and
paste through clipboards. AWT also Supports JavaBeans architecture. Every AWT
component is a simple bean. The java.awt Package contains all classes for creating
user interfaces and for painting graphics and images.
The AWT has several subsystems that support the development of Graphical User
Interface (GUI) program. The Subsystems include:
 Graphics Primitives that allow the drawing and rendering of lines and images.
 Components such as Labels, Buttons and TextFields.
 Containers that include Frames, Panels and Dialogs.

254
 Layout Managers that control the display in a portable manner.
 Event system, which allows the user to respond to interactions between the
components and containers in the application
The Original AWT version 1.0 of the Java Development Kit (JDK) did its work by
instantiating peer objects from the native operating system, Starting with JDK 1.1,
Sun has made substantial changes 'o the user interface components. The AWT in
1.1.The interface in Java 1.1 still does its work through peer objects and these are now
known as heavyweight components. There are also lightweight components that do
not tie the user to the native operating system. These instead support the pluggable
look and feel. Java makes many details of the graphical user interface (GUI)
programming invisible but they are still present. This is possible because of the
platform independence of Java.

 Swing is a set of classes that provide more powerful flexible components than
possible with AWT
 In addition to familiar components, like button, checkbox, labels, swings
supplies several exciting additions including tabbded panes, scroll panes, tress
and tables.
 Even familiar components like button may have both an image and a text
string associated with it. The image can be changed as the state of the button
changes.
 Unlike AWT components, swing components are not implemented by
platform-specifiec code. Instead, they are written entirely in java therefore it is
platform-independent.

12.2 APPLETS AND ITS LIFE CYCLE


Applets
Java programs are classified into two groups namely applications and applets. So far
simple Java applications have been illustrated. Unlike applets, Java applications do
not require a browser to run. They can be created like any normal programming
language programs. This session is devoted to creating simple applets. Various classes
like Graphics, Color and Font are used to enhance applets are illustrated.

255
Definition
An applet is a dynamic and interactive program that can run inside a Web page
displayed by a Java-capable browser such as HotJava or Netscape. Hot Java Browser
is a World Wide Web Browser used to view Web pages, follow links and submit
forms. It can also download and play applets on our system.

Differences between Applets and Applications


Java applications are simple stand-alone programs that can run using the Java
Interpreter from the command line. Java applets are run from inside a World Wide
Web browser that supports Java applets. A reference to an applet is embedded in a
Web page special HTML tag. An applet is also executed using appletviewer
application, which is part of the Java Development Kit. Applets have an added
advantage as they are run inside Java bowser that provides frame, event-handling
facility, graphics context and surrounding user interface.
Java applets have restrictions to ensure security and to prevent them from being
affected by viruses. Some of the restrictions are listed below.
 Applets cannot read or write to the file system.
 Applets cannot communicate with any other server that the one in which they
were stored originally.
 Applets cannot run any programs on the system.

Steps to Create an Applet


Let us create an applet, which prints a message “My first Java applet”.

Example 9.1

 Open a new file in the editor and type the following code.

import java.awt
public class MyFirstApplet extends java.applet.Applet {
public void paint (Graphics g) {
g.drawString ("My first Java applet", 70,30) ;
}

256
}

 Save this file, as MyFirstApplet.java and compile it using javac. This will
result in the creation of a .class file for the same
 Now create an HTML file and within its body, type

<applet CODE = "MyFirstApplet.class" WIDTH = 400 HEIGHT = 400 >


</APPLET>

 Save this file as MyFirstApplet.html in the same directory as that of the java
file.
 Execute the applet using appletviewer MyFirstApplet.html
 The result is as shown in Fig. 9.1

In the program, line number 1 is used to import all the features of the awt
package. All import statements should be included in the beginning of the file.
In the number 2, the class MyFirstApplet that is sub class of the Applet class,
has been declared. All Applets are sub class of the Applet class of Java library.
Line number 3 has a method called paint ().It is responsible for printing the
required string using the drawstring() method .The two numbers entered along
with the string are the x and y co-ordinates to position the display of the string.

HTML Tags
Some of the HTML tags used in the.html file are discussed below.

257
Applet Tags
The <applet> tag is used to start the applet from inside the HTML document as well
as from the appletviewer. Each <applet> tag is executed in separate windows by the
appletviewer while the Java capable browser is capable of executing numerous
applets inside a Single web page. This code instructs the browser or the appletviewer
to load the compiled Java apply, namely the .class file. The size of display of the
applet is initialized using the WIDTH and HEIGHT tags. To indicate the end of the
applet, </applet> tag is used. It is essential to end the applet using this tag, otherwise
it will not be executed. Comment lines can be inserted below, above or at the side of
the applet within the HTML file. This is done by including those lines within the
<applet> and </applet> tags.

CODE and CODEBASE Tags


CODE is a necessary attribute that gives the name of the file that contains the applet’s
compiled class. It assumes that both the .java file and the .html file are in the same
directory.
If the -html file and the .class file are stored in different directories it is essential to
mention it specifically. To do this, the CODEBASE tag is used. The CODEBASE tag
contains the pathname where the .class file is stored. For example, if the .class file of
an applet named TestApplet is stored in the directory /test, the HTML file code will
appear as indicated below:
<APPLET CODE = "“TestApplet.class” CODEBASE = ”/test” WIDTH=400
HEIGHT=300></APPLET>
Passing Parameters to an Applet
We have discussed the passing of parameters to a Java application. To pass
parameters to an applet, two things are required - a special parameter tag in the
HTML file and the code in the applet to parse those parameters.
The special parameter tag in the HTML file is <PARAM>. This has two attributes
namely NAME and VALUE. The init () method of the applet, contains a method
called getParameter ().This method takes one argument - the string representing the
name of the parameter being looked for and returns a string containing the
corresponding value of that parameter .if this method is required to return types other
than string, it has to be converted explicitly.

258
Example9.2 helps in understanding the usage of passing parameters to an applet.

Example 9.2
 Open a new file in the editor and the following code:

import java.awt.*;
public class ParamTestApplet extends java.applet.Applet{
Font f = new Font (“TimesRoman”,Font. BOLD, 40);
String name;
public void init () {
name = gerParameter (“name”);
if (name = null)
name = “friend";
name = "Have a nice day “ + name ;
}
public void Paint (Graphics g ) {
g.setFont (f);
g.setColor (Color.darkGray) ;
g.drawString(name, 50,50);
}
}

In the Line number 3 an instance of the Float class f is declared. This object has been
initialized to contain “TimesRoman” as font name, font size as 40 and font style as
BOLD. The init() method declared in line number 5,contains the getParameter()
method, which accepts the name (a string ) as its parameter. If no value is given to the
variable “name”, then a default value is given line number 8. The paint () method of
the Applet class is overridden to execute the paint () method in our class. This method
contains the drawSting () method apart from, two methods namely setFont () and
setColor (). These two methods are used to set the desired font and color respectively.

<APPLET CODE = "ParamTestApplet. Class” CODEBASE =”test”


WIDTH=400 HEIGHT=300>
<ALIGN=TOP>

259
<PARAM NAME = name VALUE=’Abi’>
</APPLET>

The ParamTestApplet.html file code given above contains its. Class file in another
directory called “test”. Therefore the usage of the tag CODEBASES. Note the usage
of the tag <PARM> .Suppose the value of the parameter is to be changed, The
VALUE attribute of the <PARM> tag is substituted accordingly. Thus parameter
passing in an applet is done by changing the values in the .html file. When this applet
is run ,a screen as shown in figure 9.2 appears

If <param> tag is not given in the .html file, the resulting figure contains “friend”
instead of
“Abi” and it is exactly the same as the above figure.
Note: From now on, it is assumed that appropriate .html files will be created and there
will be no code given for it in the following examples.
Major Applet Activities
So far simple applets were created which did not require an explicit initialization,
clean-up activities at the end or a method to stop the applet which is running. There
are methods available to perform all these activities. Some of them are discussed
below. These are methods exist in the Applet class and are overridden to execute the
methods in a given class (except the repaint () method).

The init( ) Method


This method gets called as soon an applet is started. Initialization of all variables,
creation of objects, setting of parameters, etc. can be done in this method. In example
9.2, note that the parameters to be passed onto the applet were initialized in this
method.

260
The start () Method
This method is executed after the init () method. In case a Java enabled browser is
used to run the applets ,any time it is reloaded, the execution begins from the start ()
method

The stop () Method


This stop () method is used to halt the running of an applet. In case a Java enabled
browser is used to run the applets, the stop () method is called the moment the Web
page is existed.

The destroy () Method


This method is used to free the memory occupied by the variables and objects
initialized in the applet. Any clean up activity that needs to be performed can be done
in this method. The destroy () method is different from the finalize () method
discussed in Chapter 4.The destroy () method applies only to applets whereas the
finalize () method is generally used to clean up a single object.

The paint ( ) Method


This method helps in drawing, writing, and creating a colored background or an
image onto the applet. It takes an argument, which is an instance of the Graphics
class. To use this method, it is necessary to import the Graphics class as import java.
awt .Graphics.

The repaint ( ) Method


This method is used in case an applet is to be repainted. The repaint () calls the update
() method, to clear the screen of any existing content. The update () method in turn
calls the paint () method that then draws the contents of the current frame. Repaint ()
can be done mentioning time in milliseconds to be performed in future. If the time
expires before
“Update () can be called, update is not summoned.

repaint () takes four arguments to update only a part of the screen. The first two

261
arguments are the x and y coordinates, the next two arguments are the width and the
height of the image. This helps in faster updation of the screen.

12.3 INTRODUCTION TO SWINGS


Swing did not exist in the early days of Java. Rather, it was a response to
deficiencies present in Java’s original GUI subsystem: the Abstract Window Toolkit.
The AWT defines a basic set of controls, windows, and dialog boxes that support a
usable, but limited graphical interface.

One reason for the limited nature of the AWT is that it translates its various
visual components into their corresponding, platform-specific equivalents, or peers.
This means that the look and feel of a component is defined by the platform, not by
Java. Because the AWT components use native code resources, they are referred to as
heavyweight.

The use of native peers led to several problems. First, because of variations
between operating systems, a component might look, or even act, differently on
different platforms.

This potential variability threatened the overarching philosophy of Java: write


once, run anywhere. Second, the look and feel of each component was fixed (because
it is defined by the platform) and could not be (easily) changed. Third, the use of
heavyweight components caused some frustrating restrictions. For example, a
heavyweight component is always rectangular and opaque.

How it differ from AWT


 AWT Event is a super class of all events that are handled by the delegation
event model
 The main pu rpose of AWT is to create our own applets or stand alone
programs, stand-alone windows that run in a GUI environment such as
windows.
 The more control we will have over the look, feel performance of you applets
and applications

262
Two Key Swing Features

Swing was created to address the limitations present in the AWT. It does this through
two key features: lightweight components and a pluggable look and feel. Together
they provide an elegant, yet easy-to-use solution to the problems of the AWT. More
than anything else, it is these two features that define the essence of Swing.

Swing Components Are Lightweight


With very few exceptions, Swing components are lightweight. This means that they
are written entirely in Java and do not map directly to platform-specific peers.
Because lightweight components are rendered using graphics primitives, they can be
transparent, which enables nonrectangular shapes. Thus, lightweight components are
more efficient and more flexible.

Swing Supports a Pluggable Look and Feel


Swing supports a pluggable look and feel (PLAF). Because each Swing component is
rendered by Java code rather than by native peers, the look and feel of a component is
under the control of Swing. This fact means that it is possible to separate the look and
feel of a component from the logic of the component, and this is what Swing does.

Separating out the look and feel provides a significant advantage: it becomes possible
to change the way that a component is rendered without affecting any of its other
aspects. In other words, it is possible to “plug in” a new look and feel for any given
component without creating any side effects in the code that uses that component.

Pluggable look-and-feels offer several important advantages. It is possible to define a


look and feel that is consistent across all platforms. Conversely, it is possible to create
a look and feel that acts like a specific platform.

For example, if you know that an application will be running only in a Windows
environment, it is possible to specify the Windows look and feel. It is also possible to
design a custom look and feel. Finally, the look and feel can be changed dynamically
at run time.

263
Components and Containers;

A Swing GUI consists of two key items: components and containers.

The difference between the two is found in their intended purpose: As the term is
commonly used, a omponent is an independent visual control, such as a push button or
slider. A container holds a group of components. Thus, a container is a special type of
component that is designed to hold other components. Thus, all Swing GUIs will have
at least one container. Because containers are components, a container can also hold
other containers. This enables Swing to define what is called a containment hierarchy,
at the top of which must be a top-level container.

Components
In general, Swing components are derived from the JComponent class. JComponent
provides the functionality that is common to all components. For example,
JComponent supports the pluggable look and feel. JComponent inherits the AWT
classes Container and Component. Thus, a Swing component is built on and
compatible with an AWT component.
All of Swing’s components are represented by classes defined within the package
javax.swing. The following table shows the class names for Swing components

264
Containers
Swing defines two types of containers. The first are top-level containers: JFrame,
JApplet, JWindow, and JDialog. These containers do not inherit JComponent.
They do, however, inherit the AWT classes Component and Container. Unlike
Swing’s other components, which are lightweight, the top-level containers are
heavyweight. This makes the top-level containers a special case in the Swing
component library.

As the name implies, a top-level container must be at the top of a containment


hierarchy. Atop-level container is not contained within any other container.
Furthermore, every containment hierarchy must begin with a top-level container. The
one most commonly used for applications is JFrame. The one used for applets is
JApplet.

The second type of containers supported by Swing are lightweight containers.


Lightweight containers do inherit JComponent. An example of a lightweight container
is JPanel, which is a general-purpose container. Lightweight containers are often used
to organize and manage groups of related components because a lightweight container
can be contained within another container. Thus, you can use lightweight containers
such as JPanel to create subgroups of related controls that are contained within an
outer container.

The Top-Level Container Panes


At the top of the hierarchy is an instance of
JRootPane. JRootPane is a lightweight container whose purpose is to manage the
other panes. It also helps manage the optional menu bar. The panes that comprise the
root pane are called the glass pane, the content pane, and the layered pane.

The glass pane is the top-level pane. It sits above and completely covers all other
panes. By default, it is a transparent instance of JPanel. The glass pane enables you to
manage mouse events that affect the entire container (rather than an individual
control) or to paint over any other component, for example. In most cases, you won’t
need to use the glass pane directly, but it is there if you need it.

265
The layered pane is an instance of JLayeredPane. The layered pane allows
components to be given a depth value. This value determines which component
overlays another. The layered pane holds the content pane and the (optional) menu
bar.

The glass pane and the layered panes are integral to the operation of a top-level
container and serve important purposes, much of what they provide occurs behind the
scene. The pane with which your application will interact the most is the content pane,
because this is the pane to which you will add visual components. In other words,
when you add a component, such as a button, to a top-level container, you will add it
to the content pane. By default, the content pane is an opaque instance of JPanel.

The Swing Packages;

Swing is a very large subsystem and makes use of many packages. These are the
packages used by Swing that are defined by Java SE 6.

The main package is javax.swing. This package must be imported into any program
that uses Swing. It contains the classes that implement the basic Swing components,
such as push buttons, labels, and check boxes.

A simple Swing Application;

Swing programs differ from both the console-based programs and the AWT-based
programs. For example, they use a different set of components and a different
container hierarchy than does the AWT. Swing programs also have special
requirements that relate to threading. There are two types of Java programs in which
Swing is typically used. The first is a desktop application. The second is the applet.

266
The program uses a JFrame container to hold an instance of a JLabel. The label
displays a short text message.

// A simple Swing application.


import javax.swing.*;
class SwingDemo {
SwingDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("A Simple Swing Application");
jfrm.setSize(275, 100);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a text-based label.
JLabel jlab = new JLabel(" Swing means powerful GUIs.");
// Add the label to the content pane.
jfrm.add(jlab);
// Display the frame.
jfrm.setVisible(true);
}
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SwingDemo();
}
});
}
}
Swing programs are compiled and run in the same way as other Java applications.
Thus, to compile this program, you can use this command line:
javac SwingDemo.java
To run the program, use this command line:
java SwingDemo

267
Create a Swing Applet;
The second type of program that commonly uses Swing is the applet. Swing-based
applets are similar to AWT-based applets, but with an important difference: A Swing
applet extends JApplet rather than Applet. JApplet is derived from Applet. Thus,
JApplet includes all of the functionality found in Applet and adds support for Swing.
JApplet is a top-level Swing container, which means that it is not derived from
JComponent. Because JApplet is a top-level container, it includes the various panes
described earlier. This means that all components are added to JApplet’s content
pane in the same way that components are added to JFrame’s content pane.
Swing applets use the same four lifecycle: init( ), start( ), stop( ), and destroy( ). Of
course, you need override only those methods that are needed by your applet. Painting
is accomplished differently in Swing than it is in the AWT, and a Swing applet will
not normally override the paint( ) method.
One other point: All interaction with components in a Swing applet must take place
on the event dispatching thread, as described in the previous section. This threading
issue applies to all Swing programs.
Here is an example of a Swing applet. It provides the same functionality as the
previous\ application, but does so in applet form.
// A simple Swing-based applet
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
This HTML can be used to launch the applet:
<object code="MySwingApplet" width=220 height=90>
</object>
*/
public class MySwingApplet extends JApplet {

268
JButton jbtnAlpha;
JButton jbtnBeta;
JLabel jlab;
// Initialize the applet.
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable () {
public void run() {
makeGUI(); // initialize the GUI
}
});
} catch(Exception exc) {
System.out.println("Can't create because of "+ exc);
}
}

// Set up and initialize the GUI.


private void makeGUI() {
setLayout(new FlowLayout());
// Make two buttons.
jbtnAlpha = new JButton("Alpha");
jbtnBeta = new JButton("Beta");
// Add action listener for Alpha.
jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jlab.setText("Alpha was pressed.");
}
});
// Add action listener for Beta.
jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jlab.setText("Beta was pressed.");
}
});

269
// Add the buttons to the content pane.
add(jbtnAlpha);
add(jbtnBeta);
// Create a text-based label.
jlab = new JLabel("Press a button.");
// Add the label to the content pane.
add(jlab);
}
}
OUTPUT :

Jlabel and ImageIcon;

JLabel is Swing’s easiest-to-use component.


JLabel can be used to display text and/or an icon. It is a passive component in that it
does not respond to user input. JLabel defines several constructors. Here are three of
them:
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
Here, str and icon are the text and icon used for the label. The align argument
specifies the horizontal alignment of the text and/or icon within the dimensions of the
label. It must be one of the following values: LEFT, RIGHT, CENTER,
LEADING, or TRAILING.
These constants are defined in the SwingConstants interface, along with several
others used by the Swing classes. Notice that icons are specified by objects of type
Icon, which is an interface defined by Swing. The easiest way to obtain an icon is to

270
use the ImageIcon class. ImageIcon implements Icon and encapsulates an image.
Thus, an object of type ImageIcon can be passed as an argument to the Icon
parameter of JLabel’s constructor.
ImageIcon(String filename)
It obtains the image in the file named filename.
The icon and text associated with the label can be obtained by the following methods:
Icon getIcon( )
String getText( )
The icon and text associated with a label can be set by these methods:
void setIcon(Icon icon)
void setText(String str)
The following applet illustrates how to create and display a label containing both an
icon and a string. It begins by creating an ImageIcon object for the file france.gif,
which depicts the flag for France.
// Demonstrate JLabel and ImageIcon.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JLabelDemo" width=250 height=150>
</applet>
*/
public class JLabelDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}

271
}
private void makeGUI() {
// Create an icon.
ImageIcon ii = new ImageIcon("france.gif");
// Create a label.
JLabel jl = new JLabel("France", ii, JLabel.CENTER);
// Add the label to the content pane.
add(jl);
}
}

Output from the label example is shown here:

JTextField;
JTextField is the simplest Swing text component. It is also probably its most widely
used text component. JTextField allows you to edit one line of text. It is derived from
JTextComponent, which provides the basic functionality common to Swing text
components. JTextField uses the Document interface for its model.
Three of JTextField’s constructors are shown here:
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)

272
Here, str is the string to be initially presented, and cols is the number of columns in
the text field. If no string is specified, the text field is initially empty. If the number of
columns is not specified, the text field is sized to fit the specified string.
JTextField generates events in response to user interaction. For example, an
ActionEvent is fired when the user presses ENTER. A CaretEvent is fired each time
the caret (i.e., the cursor) changes position.
To obtain the text currently in the text field, call getText( ). The following example
illustrates JTextField. It creates a JTextField and adds it to the content pane. When the
user presses ENTER, an action event is generated. This is handled by displaying the
text in the status window.
// Demonstrate JTextField.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet {
JTextField jtf;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {

273
// Change to flow layout.
setLayout(new FlowLayout());
// Add text field to content pane.
jtf = new JTextField(15);
add(jtf);
jtf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// Show text when user presses ENTER.
showStatus(jtf.getText());
}
});
}
}

The Swing Buttons;


Swing defines four types of buttons: JButton, JToggleButton, JCheckBox, and
JRadioButton.
All are subclasses of the AbstractButton class, which extends JComponent. Thus,
all buttons share a set of common traits.

JButton
The JButton class provides the functionality of a push button. You have already seen
a simple form of it in the preceding chapter. JButton allows an icon, a string, or both
to be associated with the push button. Three of its constructors are shown here:
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)

274
Here, str and icon are the string and icon used for the button. When the button is
pressed, an ActionEvent is generated. Using the ActionEvent object passed to the
actionPerformed( ) method of the registered ActionListener, you can obtain the
action command string associated with the button. By default, this is the string
displayed inside the button. However, you can set the action command by calling
setActionCommand( ) on the button.
You can obtain the action command by calling getActionCommand( ) on the event
object. It is declared like this:
String getActionCommand( )
The action command identifies the button. Thus, when using two or more buttons
within the same application, the action command gives you an easy way to determine
which button was pressed.
// Demonstrate an icon-based JButton.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JButtonDemo" width=250 height=450>
</applet>
*/
public class JButtonDemo extends JApplet
implements ActionListener {
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);

275
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Add buttons to content pane.
ImageIcon france = new ImageIcon("france.gif");
JButton jb = new JButton(france);
jb.setActionCommand("France");
jb.addActionListener(this);
add(jb);
ImageIcon germany = new ImageIcon("germany.gif");
jb = new JButton(germany);
jb.setActionCommand("Germany");
jb.addActionListener(this);
add(jb);
ImageIcon italy = new ImageIcon("italy.gif");
jb = new JButton(italy);
jb.setActionCommand("Italy");
jb.addActionListener(this);
add(jb);
ImageIcon japan = new ImageIcon("japan.gif");
jb = new JButton(japan);
jb.setActionCommand("Japan");
jb.addActionListener(this);
add(jb);
// Create and add the label to content pane.
jlab = new JLabel("Choose a Flag");
add(jlab);
}
// Handle button events.
public void actionPerformed(ActionEvent ae) {
jlab.setText("You selected " + ae.getActionCommand());
}}

276
JToggleButton
Auseful variation on the push button is called a toggle button. A toggle button looks
just like a push button, but it acts differently because it has two states: pushed and
released. That is, when you press a toggle button, it stays pressed rather than popping
back up as a regular push button does. When you press the toggle button a second
time, it releases (pops up). Therefore, each time a toggle button is pushed, it toggles
between its two states.
Toggle buttons are objects of the JToggleButton class. JToggleButton implements
AbstractButton. In addition to creating standard toggle buttons, JToggleButton is a
superclass for two other Swing components that also represent two-state controls.

277
These are JCheckBox and JRadioButton, which are described later in this chapter.
Thus, JToggleButton defines the basic functionality of all two-state components.
JToggleButton defines several constructors. The one used by the example in this
section is shown here:
JToggleButton(String str)
This creates a toggle button that contains the text passed in str. By default, the button
is in the off position. Other constructors enable you to create toggle buttons that
contain images, or images and text.
JToggleButton uses a model defined by a nested class called JToggleButton
.ToggleButtonModel. Normally, you won’t need to interact directly with the model
to use a standard toggle button.
// Demonstrate JToggleButton.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JToggleButtonDemo" width=200 height=80>
</applet>
*/
public class JToggleButtonDemo extends JApplet {
JLabel jlab;
JToggleButton jtbn;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}}

278
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Create a label.
jlab = new JLabel("Button is off.");
// Make a toggle button.
jtbn = new JToggleButton("On/Off");
// Add an item listener for the toggle button.
jtbn.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if(jtbn.isSelected())
jlab.setText("Button is on.");
else
jlab.setText("Button is off.");
}
});
// Add the toggle button and label to the content pane.
add(jtbn);
add(jlab);
}
}
The output from the toggle button example is shown here:

279
Check Boxes
The JCheckBox class provides the functionality of a check box. Its immediate
superclass is JToggleButton, which provides support for two-state buttons, as just
described. JCheckBox defines several constructors. The one used here is
JCheckBox(String str)
It creates a check box that has the text specified by str as a label. Other constructors
let you specify the initial selection state of the button and specify an icon.
When the user selects or deselects a check box, an ItemEvent is generated. You can
obtain a reference to the JCheckBox that generated the event by calling getItem( ) on
the ItemEvent passed to the itemStateChanged( ) method defined by ItemListener.
The easiest way to determine the selected state of a check box is to call isSelected( )
on the JCheckBox instance.
The following example illustrates check boxes. It displays four check boxes and a
label. When the user clicks a check box, an ItemEvent is generated. Inside the
itemStateChanged( ) method, getItem( ) is called to obtain a reference to the
JCheckBox object that generated the event. Next, a call to isSelected( ) determines if
the box was selected or cleared. The getText( ) method gets the text for that check
box and uses it to set the text inside the label.
// Demonstrate JCheckbox.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JCheckBoxDemo" width=270 height=50>
</applet>
*/
public class JCheckBoxDemo extends JApplet
implements ItemListener {
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {

280
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Add check boxes to the content pane.
JCheckBox cb = new JCheckBox("C");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("C++");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("Java");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("Perl");
cb.addItemListener(this);
add(cb);
// Create the label and add it to the content pane.
jlab = new JLabel("Select languages");
add(jlab); }
// Handle item events for the check boxes.
public void itemStateChanged(ItemEvent ie) {
JCheckBox cb = (JCheckBox)ie.getItem();
if(cb.isSelected())
jlab.setText(cb.getText() + " is selected");
else
jlab.setText(cb.getText() + " is cleared");

281
}}

Develop an applet to create a label, a text field and 4 check boxes with the caption
“red”, “green”,”blue” and “yellow” (jun-2012)
import java.awt.*;
import java.awt.event*;
import java.applet;
public class checkdemo extends applet implements item Listener {
checkbox rd,gn,be,yw;
public void init()
{rd=new checkbox(“rd”nulltrue);
gn=new checkbox(“green”);
be=new checkbox(“blue”);
yw=new checkbox(“yellow”);
add(rd); add(gn);
add(be); add(yw);
Lable np=new Label (“Name:”,Label. RIGHT);
nm = new TextField(12);
add(np);
add(nm);
nm.add Action Listener(this);
}
Publiv void Itemstate changed (ItemEvent ie)
{ repaint();}
Public void paint(Graphics g)
{
g.drawstring(“Name:”+nam.getText(),6,60);
msg=”color is”;
g.drawstring(msg,6,60);
msg=”red”+rd.getstate();

282
g.drawstring(msg,6,100);
msg=”green”+rd.getstate();
g.drawstring(msg,6,120);
msg=”blue”+rd.getstate();
g.drawstring(msg,6,140);
msg=”yellow”+rd.getstate();
g.drawstring(msg,6,160);
}}

Radio Buttons
Radio buttons are a group of mutually exclusive buttons, in which only one button can
be selected at any one time. They are supported by the JRadioButton class, which
extends JToggleButton. JRadioButton provides several constructors. The one used
in the example is shown here:
JRadioButton(String str)
Here, str is the label for the button. Other constructors let you specify the initial
selection state of the button and specify an icon.
In order for their mutually exclusive nature to be activated, radio buttons must be
configured into a group. Only one of the buttons in the group can be selected at any
time.
For example, if a user presses a radio button that is in a group, any previously selected
button in that group is automatically deselected. Abutton group is created by the
ButtonGroup class. Its default constructor is invoked for this purpose. Elements are
then added to the button group via the following method:
void add(AbstractButton ab)
Here, ab is a reference to the button to be added to the group.
// Demonstrate JRadioButton
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JRadioButtonDemo" width=300 height=50>
</applet>
*/

283
public class JRadioButtonDemo extends JApplet
implements ActionListener {
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}});
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Create radio buttons and add them to content pane.
JRadioButton b1 = new JRadioButton("A");
b1.addActionListener(this);
add(b1);
JRadioButton b2 = new JRadioButton("B");
b2.addActionListener(this);
add(b2);
JRadioButton b3 = new JRadioButton("C");
b3.addActionListener(this);
add(b3);
// Define a button group.
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);
// Create a label and add it to the content pane.
jlab = new JLabel("Select One");

284
add(jlab);
}
// Handle button selection.
public void actionPerformed(ActionEvent ae) {
jlab.setText("You selected " + ae.getActionCommand());
}
}
Output from the radio button example is shown here:

JTabbedpane;
JTabbedPane encapsulates a tabbed pane. It manages a set of components by linking
them with tabs. Selecting a tab causes the component associated with that tab to come
to the forefront. Tabbed panes are very common in the modern GUI, and you have no
doubt used them many times. Given the complex nature of a tabbed pane, they are
surprisingly easy to create and use.
JTabbedPane defines three constructors. We will use its default constructor, which
creates an empty control with the tabs positioned across the top of the pane. The other
two constructors let you specify the location of the tabs, which can be along any of
the four sides. JTabbedPane uses the SingleSelectionModel model.
Tabs are added by calling addTab( ). Here is one of its forms:
void addTab(String name, Component comp)
Here, name is the name for the tab, and comp is the component that should be added
to the tab. Often, the component added to a tab is a JPanel that contains a group of
related components. This technique allows a tab to hold a set of components.
The general procedure to use a tabbed pane is outlined here:
1. Create an instance of JTabbedPane.
2. Add each tab by calling addTab( ).
3. Add the tabbed pane to the content pane.

285
// Demonstrate JTabbedPane.
import javax.swing.*;
/*
<applet code="JTabbedPaneDemo" width=400 height=100>
</applet>
*/
public class JTabbedPaneDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Cities", new CitiesPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel());
add(jtp);
}
}
// Make the panels that will be added to the tabbed pane.
class CitiesPanel extends JPanel {
public CitiesPanel() {
JButton b1 = new JButton("New York");
add(b1);

286
JButton b2 = new JButton("London");
add(b2);
JButton b3 = new JButton("Hong Kong");
add(b3);
JButton b4 = new JButton("Tokyo");
add(b4);
}
}
class ColorsPanel extends JPanel {
public ColorsPanel() {
JCheckBox cb1 = new JCheckBox("Red");
add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
add(cb2);
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
}
}
class FlavorsPanel extends JPanel {
public FlavorsPanel() {
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}
Output from the tabbed pane example is shown in the following three illustrations:

287
JScrollPane;
JScrollPane is a lightweight container that automatically handles the scrolling of
another component. The component being scrolled can either be an individual
component, such as a table, or a group of components contained within another
lightweight container, such as a JPanel.
If the object being scrolled is larger than the viewable area, horizontal and/or vertical
scroll bars are automatically provided, and the component can be scrolled through the
pane. Because JScrollPane automates scrolling, it usually eliminates the need to
manage individual scroll bars.
JScrollPane defines several constructors. The one used in this chapter is shown here:
JScrollPane(Component comp)
The component to be scrolled is specified by comp. Scroll bars are automatically
displayed when the content of the pane exceeds the dimensions of the viewport.
Here are the steps to follow to use a scroll pane:
1. Create the component to be scrolled.
2. Create an instance of JScrollPane, passing to it the object to scroll.

288
3. Add the scroll pane to the content pane.

// Demonstrate JScrollPane.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JScrollPaneDemo" width=300 height=250>
</applet>
*/
public class JScrollPaneDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Add 400 buttons to a panel.
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
jp.add(new JButton("Button " + b));
++b;
}
}

289
// Create the scroll pane.
JScrollPane jsp = new JScrollPane(jp);
// Add the scroll pane to the content pane.
// Because the default border layout is used,
// the scroll pane will be added to the center.
add(jsp, BorderLayout.CENTER);
}
}
Output from the scroll pane example is shown here:

JList;
In Swing, the basic list class is called JList. It supports the selection of one or more
items from a list. Although the list often consists of strings, it is possible to create a
list of just about any object that can be displayed. JList is so widely used in Java that
it is highly unlikely that you have not seen one before.
JList provides several constructors. The one used here is
JList(Object[ ] items)
This creates a JList that contains the items in the array specified by items.
JList is based on two models. The first is ListModel. This interface defines how
access to the list data is achieved. The second model is the ListSelectionModel
interface, which defines methods that determine what list item or items are selected.

290
AJList generates a ListSelectionEvent when the user makes or changes a selection.
This event is also generated when the user deselects an item. It is handled by
implementing ListSelectionListener. This listener specifies only one method, called
valueChanged( ), which is shown here:
void valueChanged(ListSelectionEvent le)
Here, le is a reference to the object that generated the event.
ListSelectionEvent does provide some methods of its own, normally you will
interrogate the JList object itself to determine what has occurred. Both
ListSelectionEvent and ListSelectionListener are packaged in javax.swing.event.
By default, a JList allows the user to select multiple ranges of items within the list,
but you can change this behavior by calling setSelectionMode( ), which is defined by
JList. It is shown here:
void setSelectionMode(int mode)
Here, mode specifies the selection mode. It must be one of these values defined by
ListSelectionModel:
SINGLE_SELECTION
SINGLE_INTERVAL_SELECTION
MULTIPLE_INTERVAL_SELECTION
// Demonstrate JList.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="JListDemo" width=200 height=120>
</applet>
*/
public class JListDemo extends JApplet {
JList jlst;
JLabel jlab;
JScrollPane jscrlp;
// Create an array of cities.
String Cities[] = { "New York", "Chicago", "Houston",
"Denver", "Los Angeles", "Seattle",

291
"London", "Paris", "New Delhi",
"Hong Kong", "Tokyo", "Sydney" };
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
setLayout(new FlowLayout());
// Create a JList.
jlst = new JList(Cities);
// Set the list selection mode to single selection.
jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// Add the list to a scroll pane.
jscrlp = new JScrollPane(jlst);
// Set the preferred size of the scroll pane.
jscrlp.setPreferredSize(new Dimension(120, 90));
// Make a label that displays the selection.
jlab = new JLabel("Choose a City");
// Add selection listener for the list.
jlst.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent le) {
// Get the index of the changed item.
int idx = jlst.getSelectedIndex();
// Display selection, if item was selected.
if(idx != -1)

292
jlab.setText("Current selection: " + Cities[idx]);
else // Otherwise, reprompt.
jlab.setText("Choose a City");
}
});
// Add the list and label to the content pane.
add(jscrlp);
add(jlab);
}
}
Output from the list example is shown here:

JComboBox;
Swing provides a combo box (a combination of a text field and a drop-down list)
through the JComboBox class. A combo box normally displays one entry, but it will
also display a drop-down list that allows a user to select a different entry. You can
also create a combo box that lets the user enter a selection into the text field. The
JComboBox constructor used by the example is shown here:
JComboBox(Object[ ] items)
Here, items is an array that initializes the combo box. Other constructors are available.
JComboBox uses the ComboBoxModel. Mutable combo boxes (those whose entries
can be changed) use the MutableComboBoxModel.
In addition to passing an array of items to be displayed in the drop-down list, items
can be dynamically added to the list of choices via the addItem( ) method, shown
here:

293
void addItem(Object obj)
Here, obj is the object to be added to the combo box. This method must be used only
with mutable combo boxes.
// Demonstrate JComboBox.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JComboBoxDemo" width=300 height=100>
</applet>
*/
public class JComboBoxDemo extends JApplet {
JLabel jlab;
ImageIcon france, germany, italy, japan;
JComboBox jcb;
String flags[] = { "France", "Germany", "Italy", "Japan" };
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Instantiate a combo box and add it to the content pane.
jcb = new JComboBox(flags);

294
add(jcb);
// Handle selections.
jcb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String s = (String) jcb.getSelectedItem();
jlab.setIcon(new ImageIcon(s + ".gif"));
}
});
// Create a label and add it to the content pane.
jlab = new JLabel(new ImageIcon("france.gif"));
add(jlab);
}
}
Output from the combo box example is shown here:

JTable.
JTable is a component that displays rows and columns of data. You can drag the
cursor on column boundaries to resize columns. You can also drag a column to a new
position. Depending on its configuration, it is also possible to select a row, column, or
cell within the table, and to change the data within a cell. JTable is a sophisticated
component that offers many more options and features than can be discussed here. (It
is perhaps Swing’s most complicated component.) However, in its default
configuration, JTable still offers substantial functionality that is easy to use—
especially if you simply want to use the table to present data in a tabular format.
JTable does not provide any scrolling capabilities of its own. Instead, you will
normally wrap a JTable inside a JScrollPane.

295
JTable supplies several constructors. The one used here is
JTable(Object data[ ][ ], Object colHeads[ ])
Here, data is a two-dimensional array of the information to be presented, and
colHeads is a one-dimensional array with the column headings.
JTable relies on three models. The first is the table model, which is defined by the
TableModel interface. This model defines those things related to displaying data in a
two-dimensional format.
The second is the table column model, which is represented by TableColumnModel.
JTable is defined in terms of columns, and it is TableColumnModel that specifies
the characteristics of a column. These two models are packaged in javax.swing.table.
The third model determines how items are selected, and it is specified by the
ListSelectionModel, which was described when JList was discussed.
Here are the steps required to set up a simple JTable that can be used to display data:
1. Create an instance of JTable.
2. Create a JScrollPane object, specifying the table as the object to scroll.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane.

// Demonstrate JTable.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTableDemo" width=400 height=200>
</applet>
*/
public class JTableDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}

296
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Initialize column headings.
String[] colHeads = { "Name", "Extension", "ID#" };
// Initialize data.
Object[][] data = {
{ "Gail", "4567", "865" },
{ "Ken", "7566", "555" },
{ "Viviane", "5634", "587" },
{ "Melanie", "7345", "922" },
{ "Anne", "1237", "333" },
{ "John", "5656", "314" },
{ "Matt", "5672", "217" },
{ "Claire", "6741", "444" },
{ "Erwin", "9023", "519" },
{ "Ellen", "1134", "532" },
{ "Jennifer", "5689", "112" },
{ "Ed", "9030", "133" },
{ "Helen", "6751", "145" }
};
// Create the table.
JTable table = new JTable(data, colHeads);
// Add the table to a scroll pane.
JScrollPane jsp = new JScrollPane(table);
// Add the scroll pane to the content pane.
add(jsp);
}
}
Output from this example is shown here:

297
Here are the steps required to set up a simple JTable that can be used to display data:
1. Create an instance of JTable.
2. Create a JScrollPane object, specifying the table as the object to scroll.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane.

import java.awt.*;
import java.swing.*;
public class JTable Demo extends JApplet{
public vod init(){
container content pane=get content pane();
content pane.set Layout(new Border Layout());
final string[ ] collteads={“Name”,”USN”,”Age”,”Address”};
final object [ ] [ ] data = {
{“Swamy”,”12cs403”,”26”,”Sargur”},
{“Sunil”,”11cs047”,”21”,”Nanjanagude”,},
{“gagana”,12cs401”,”21”,”Mysore”}
};
JTable table = new JTable(data,collteads);
int v=Scroll pane constants.VErTICAL-SCrOLLBAr-AS-NEEDED;
int h=scroll pane constants.HOrIZONTAL-scrollbar-as-needed;
JScroll pane jsp=new JScroll pane(table, v, h);
Content pane.add(jsp,Border Layout.cednter);
}}

298
AWT SWINGS
We can build user interfaces with AWT Swings is a set of classes that provides
classes more powerful and flexible components
AWT supports all the types of controls Familiar components like buttons, check
like labels, push buttons, check boxes, bixes etc.. have more capabilities in
choice list scroll bars Text editing. These swing
controls are subclasses of component Ex: button may have both image and
container is also sub class of component string associated with it. Also, image can
panel and window is a concrete subclass be changed as the button state changes.
of container
Frame is a subclass of window Swings are nit subclass of windows
AWT is implemented by platform- Swing components are not implement by
specific code platform-specific code Instead, they are
written entirely in Java, and therefore are
platform independent
AWT examines standard controls and
layout managers defined by Java
Controls are components that allow user The term light weight is used to describe
interaction such elements
Layout manager automatically positions The number of class and interfaces in the
components within a container swing packages is substantial
In addition to component, a frame- Swing related classes ave contained in
window is included as standard style JavaX. Swing and its subpackages javaX
menu bar Swing tree

299
12.4 SUMMARY / TO SUM / LET’S SUM UP

At the end of this unit we have learnt the Applets and its life cycle and swings.

12.5 KEYWORDS / GLOSSARY

Applets, Swings

12.5 QUESTIONS FOR SELF STUDY


1. What is AWT?
2. What are the main methods of the Applet class? Explain in brief about each of
them.
3. Briefly explain container and components in swings
4. Write the steps to create Jtable. Write a program to create a table with column
heading, name, USN, Age Address, and insert atleast 5 records in the table and
display

300
5. What is Swing? List the main Swing features. Explain the different types of panes
of swing containers
6. How AWT is different from Swings? What are the two key features of it ?
Explain

12.6 SUGGESTED READINGS AND REFERENCE

1. David J. Eck Introduction to Programming Using Java.


2. Elliotte Rusty Harold Java I/O published by O'Reilly
3. Ken Arnold, James Gosling . The Java Programming Language

4. Patrick, Naughton The Java Handbook

5. Dwight Deugo More java gems

6. Sun Microsytems Java tutorial,

7. E Balaguruswamy Programming with java

8. Schum series publications Programming in java

9. Doug Lea . Concurrent Programming in Java: Design Principles and Patterns

10. Jose M. Garrido Object-Oriented Programming: From Problem Solving to


Java
11. Bill Venners Object-Oriented Design with Java
12. E. Balaguruswamy Programming with java
13. Internet

301
UNIT-13 TEXT AND BINARY I/O CLASSES, OBJECT I/O, RANDOM
ACCESS FILES ( I/O STREAMS)
STRUCTURE

13.0 Objectives
13.1 Introduction
13.2 I/O Streams
13.3 Summary
13.4 Keywords
13.5 Questions for Self Study
13.6 Questions for Self Study
13.7 References

13.0 OBJECTIVES
In this unit you will able to learn as follows.

 Define virus
 Elucidate the different types of computer viruses
 Understand the importance of antivirus
 State Functions of computer security

302
13.1 INTRODUCTION VIRUS

A virus is a computer code or program, which is capable of affecting your computer


data badly by corrupting or destroying them. Computer virus has the tendency to
make its duplicate copies at a swift pace, and also spread it across every folder and
damage the data of your computer system. A computer virus is actually a malicious
software program or "malware" that, when infecting your system, replicates itself by
modifying other computer programs and inserting its own code.

13.2 I/O STREAMS


I/O Streams
About this chapter: This chapter deals in detail about the Input and Output Streams
like FilterInputStream, ByteArrayInputStream, ByteArrayOutputStream,
FileOutputStream,etc. It also gives an introduction to Readers and Writers.
Objectives
 Types of 1/O Streams

Types of I /O Streams
There are various types of streams found in the java.io package as shown in fig.8.1. In
the following paragraphs we will discuss about some of them.

303
The various input stream, their functions and the methods supported by them are
given by them in Table 8.1

Class Function Supported methods


available( ), mark(
Allows a buffer in memory to be ),marksupported(
ByteArrayInputStream used as an InputStream ),read(),skip(),insert
available (), close(), finalize(
FileInputStream For reading information from a file ),read(),skip()
Abstract class providing an
interface for useful available( ), close(),mark(),
FilterInputStream
functionality to the other marksupported( ),read( ),
InputStream classes. reset( ),skip()
Table 8.1

304
The streams under FilterInputStream are dealt with under the section FilterStream.The
various output streams, their functions and the supported methods are given in Table
8.2

Class Function Supported methods


Creates a buffer in memory.All the
data we send to the stream is placed reset( ), size( ),toByteArray(
ByteArrayOutputStream in this buffer ), toString,write(),writeto()

FileOutputStream For sending information to a file. close( ), finalize( ),write()


Abstract class providing an
FilterOutputStream interface for useful functionality to
the other OutputStream classes. close( ), flush( ),write()
Table 8.2
The streams under FilterOutputStream are dealt with under the topic FilterStream
File Streams
File stream comprise of the FileInputStream and FileOutputStream
FileInputStream
The FileInputStream class helps in reading data from the-actual disk files. All the
methods discussed above under the InputStream are applicable to this class. Any
object of this class can be created using the keyword new. There are three types of
constructors available with this class.
The first constructor takes a filename as a string. Thus it is possible to create an object
f of the FileInputStrem class as given below.
InputStream f = new FileInputStream (“c:/java/temp”) ;
The next constructor takes a file object as its parameter.
File f = new File(“c:/java/temp”) ;
Inputstream f1 = new FileInputStream(f) ;

The next type of constructor accepts a file descriptor as its parameter.


FileOutputStream
The FileOutputStream class helps to create a file and write data into it using the
methods
discussed under the OutputStream class. The two types of constructors shown above

305
are
applicable to this class also. The FileOutputStream class creates a file, if it does not
already
exist, before opening it for output. In case of writing into a read-only file, an
IOException is thrown. Example 8.1 is an illustration of FileOutputStream.

Example 8.1
 Open a new file in the editor and enter the following code:

import java.io.*;
Class ReadWriteFile {
public static byte getInput( )[] throws Exception {
byte inp[] = new byte[50];
System.out.println("enter text.");
System.out.println(“only 50 bytes i.e about 2 lines……”);
System.out.println(“press enter after each line to get input into the program”);
for (int i=0;1<50;i++) {
inp[i] = (byte) system. in. read( );
}
return inp;
}
public static void main (String args[]) throwsException {
byte input[] = getInput();
OutputStream f = new Fileoutputstream
for (int i=0;i<50;i++){
f.write(input[i]);
f.close();
int size;
InputStream f1 = new FileInputStream("c:/java/write.txt”);
size=fl.available();
System.out .println("reading contents of file write.txt.. “);
for (int i=0;i<xsize;i++) {
System.out.print ( (char) f1l.read( ));
}

306
f.close();
}
}

 Save the file as ReadWriteFile.java


 Compile the file using javac ReadWriteF ile.java
 Run the file using java ReadWriteFile

The output appears as shown below:


Enter txt
only 50 bytes i.e. about 2 lines ……….
Press enter after each line to get input into the program
Let us give the following line as the input
SSI is one of the best software companies in India
The output appears as shown below:
reading contents of file write.txt...
SSI is one of the best software companies in India
Line numbers 3 ‘to 12 contain a method called getInput( ) that returns the number of
bytes read from the input source. An array of 50 bytes is created and input accepted.
In the main (), first input is accepted and the same is written on the file
c:/java/write.txt.The next part of the program reads from this file character by
character. This continues until there are no further bytes to be read from the file
write.txt.
Note : The class Fileoutputstream does not allow appending data to an existing file.

ByteArrayStream
This stream contains ByteArrayInputStream and ByteArrayOutputStream .
ByteArrayinputStream
This class uses a byte array as its input source. It has two types of constructors, The
first one takes a byte array as Its parameter.
ByteArrayinput Stream b = new ByteArrayInputStream (buf []);
The next constructor helps to create a ByteArrayInputStream from the specified array
of bytes.

307
ByteArrayInputStream b = new ByteArrayInputStream(buf[],int off,int len);
Off is the offset of the first byte to be read and len is the number of bytes to be read
into the array.
ByteArrayOutputStream

ByteArrayOutputStream class implements a buffer, which can be used as an


OutputStream. The size of the buffer increases as data is written into the stream. The
data is retrieved using the methods toBytearray( ) and tostring( ).
Two types of constructors exist. They are given below:
OutputStream o = new ByteArrayoutputstream ( int);
This creates a buffer of 32 bytes to store the data.
OutputStream o1 = new ByteArrayoutputstream ( int);
The above constructor creates a buffer of size int.These methods return void and
thrown an IOExpection on error conditions.
Example 8.2 accepts a specific number of characters as input and coverts them into
uppercase characters.
Example 8.2
 Open a new file in the editor and enter the following code:

import java.io.*;
class ByteArray {
public static void main(String args[]) throws Exception {
ByteArrayOutputStream f = new ByteArrayOutput Stream(12);
System.out.println("enter 10 characters and press the Enter key");
System.out.println("These will be converted to uppercase and displayed") ;
while (f.size( ) != 10) {
f.write(System.in.read( ));
}
System.out.println("Accepted characters into an array");
byte b[] = f.toByteArray( );
System.out.println("displaying characters in the array");
for(int 1=0;l<b.length;l++) {
System.out.println((char) b[1]);
}

308
ByteArrayInputStream inp = new ByteArrayInputStream(b);
int c;
System.out .println("Converted to upper case characters");
for (int i=0;i<1;i++) {
while ((c = inp.read( )) != -1) {
System. out .print (Character.toUpperCase((char)c));
} Sysetem.out.println( );
inp.reset( );
}
}
}
 Save the file as ByteArray.java
 Compile the file using javac ByteArray.java
 Run the file using java ByteArray al

The first few lines of the output are shown below:


enter 10 characters and press the Enter key
These will be converted to uppercase and displayed
Let us give the input as A test line
The remaining part of the output appears as shown:
Accepted characters into an array
Displaying characters in the array
A
t
e
s
t
1
I
n
Converted to upper case characters
A TEST LIN
The first part of the program accepts ten characters as input. At line number 4 an
instance of the ByteArrayOutputStream is initialized. The input accepted inside the

309
while loop. The next part of the program dumps the input into an array b, initialized at
the line number 11.For better understanding, line numbers 13 to 15 display the
accepted characters from the array. The subsequent part of the program deals with the
conversion of the input into upper case characters and then displays them. At line
number 16, an instance of the ByteArraytnputStream is created. The characters inside
the array b are converted to uppercase characters using the touppercase( ) method
found in the characte class.
FilterStream
FilterStream is dealt under FilterInputStream and FilterOutputStream.The following
classes under the FilterInputStream – BuffereInputStream ,DataInputstream and
PushbackInputStream and the following classes under FilterOurputStream –
BufferedOutStream , DataInputstream ,PrintStream

The classes under FilterInputStream and their functions are discussed in the Table 8.3

Class Function Supported methods


DataInputStream Used in Context with read(),readBoolean(),
DataOutputStream.Hence readByte(),
we can read readChar().readDouble(),
primitives(int,char,long,etc.) readFloat()
from a stream in a portable
fashion
BufferedInputStream Use this to prevent a available( ), mark( ),
physical read every time marksupported( ), read( ),
more data is needed unread(),skip( )
PushbackInputStream Has a one-byte push-back available( ), mark(),
buffer, so the last character reset( ),
read can be pushed back. read(), unread(
),marksupported( )
Table 8.3.

310
The various classes under the FilterOutputStream are discussed in Table 8.4.

Class Function Supported methods


DataOutputStream Used in Context with writeShort( )
DataInputStream.Hence we flush( ),
can write size( ), write(),
primitives(int,char,long,etc.) writeBoolean( ), writeBytes( ),
to a stream in a portable writeChars( ), writeDouble(),
fashion writeFloat( ), writeInt(),
writeLong()
PrintStream For producing formatted checkError(),close(),flush(),
output.While DataOutput print(),println(),setError(),write()
Stream handles the storages
of data .PrintStram handles
display.
BufferedOutputStream This is used to prevent a flush(),write()
physical write every time
we send a piece of data
.Flush can be called to flush
the buffer.

Table 8.4

BufferedinputStream
The BufferedInputStream class accepts input by using a buffered array of bytes that
acts as cache and it utilizes the mark( ) and reset( ) method. Chunks of bytes from the
buffered array can be chosen and read. To create a Filernputstream that can handle
marking and resetting properly, the nested stream to read a specified portion of a file
called temp is given below.
InputStream s = new BufferedInputStream (new FileInputstream (“temp”));
The above line of code BufferedInputStream for the file Temp.
BufferedOutputStream
The output is stored in a buffered array by bytes, which acts as a cache for writing. As

311
above, a specific number of bytes can be buffered using the nesting facility offered by
the FileStream.

QutputStream b = new BufferedOutputStream (new FileOutputStream(“temp”));


This class extensively uses the flush( ) Method, Which pushes the written bytes
through the buffer and passes it outside,
DataInputStream
The DatalnputStream class contains a set of methods to accept various types of data
.Some of them are
Int readInt() throws IOException - reads one integer of input.
Char readChar() throws IOException - reads one Character of input.
DataOutputstream
A set of Methods exists in this class to write the data to the output source. Some of the
them are

void writeBytes(String s) throws IOException – writes a string to the output


void writeInt(int j) throws IOException – writes a integers to the output
void writeBytes(int k) throws IOException – writes a character to the output
Example x 3 elucidates a few methods in DataStreams and usage DataStreams.The
example takes input from the file temp, converts the entire file into uppercase
characters and writes it onto another file called temp1.
Example 8.3
 Open a new file in the editor and enter the following code:

import java.io.*;
class DataStream {
public Static void main(String args(]) throws IOException {
BufferedReader d = new BufferedReader (new InputStream(new
FileInputStream("c:/java/temp”);
DataOutputStream o = new DataOutputStream(new FileOutputStream("c:
/java/temp1") ;
String line;
while ((line = d.readLine( )) != null) {
String a = (line.toUpperCase( ));

312
System.out.printin(a);
o.writeBytes(a + "\r\n");
}
d.close( );
o.close( );
}
}
 Save the file as DataStream.java
 Compile the file using javac DataStream.java aed
 Ensure that there exists a file temp, in the directory ¢:\java. os
 Run the file using java DataStream

Suppose the file contains the line "This is an example of DataStreams" as its content.
The output appears as shown below:

THIS IS AN EXAMPLE OF DATASTREAMS


The input is taken using nested streams. The source file temp is stored in an instance
of BufferedReader. Similarly at line number 5, the Dataoutput Stream is declared to
send the output to the file called temp1. The while loop continues as long as there are
lines to be read from the temp file. Inside the while loop,each input line is converted
to uppercase at line number 8. The converted lines are sent to the output file temp1
using the writeBytes() method at line 10.
PushbackinputStream
This class is used to read a character from the InputStream and returns the same .This
is done without disturbing the InputStream.
PrintStream
The methods of this class are widely used in Java applications, The two methods that
are very familiar to us are system. out .println() and system. out print ().The system
.err method is used to print error messages and system. in is an InputStream.

Random Access files


Random Access file class can be used for both input and output to a single file
.Although it is not a stream class, it provides the same platform-independent
formatting methods as the DataStream classes. The constructor to create a

313
RandomAcessFile object takes two arguments. The first argument specifies the file
either as a string containing the file name or as a file object. The second arguments is
a string that takes the value “r” if the files is to be read but not written ,or the value
“rw” if the file is to be both read and written. If the specified file does not exist, it is
automatically created.
The following Statement opens the file Test.txt for reading and writing:
RandomAccessFile thefile = new RandomAccessFile (“Test -txt”, "rw");
Unlike InputStream and OutputStream, which access their data sequentially. It is
possible direct to direct a random access file to read or write at any position within a
file by using the seek() method .The seek() method specifies the byte offset from the
beginning of the file ,at which the input and output is to commence.
Stream Tokenizer
Stream Tokenizer class helps in identifying the patterns in the input stream. It is
responsible for breaking up the InputStream into tokens, which are delimited by a set
of characters .The best use of this class is to identify the number of words or lines
within a file .A stream is tokenized by creating a Stream Tokenizer with a Reader
Object as its source and then setting parameters for the screen. A scanner loop
invokes nextToken,which returns the token type of the next token in the screen.
When NextToken recognizes a token, it returns the token type as its value and also
sets the type field to the same value. There are four token types:
TT_WorD : A word is scanned. The String field sval contains the word that is
scanned.
TT_NUMBER. A number is scanned. The double field nval contains the value of the
Number. Only decimal floating numbers are recognized.
TT_EOL : An end-of-line is found.

TT_EOF: An end-of-file is reached.


Example 8.4 shows how to use a Stream Tokenizer to count the number of words in a
file.
Example 8.4
Open a new file in the editor and enter the following code:
import java.io.*;
public class WordCounter{
public static void main(String args[]) throws IOException {

314
FileReader fr = new FileReader(”“C:\\temp.txt”);
StreamTokenizer input = new StreamTokenizer (fr) ;
int tok;
int count = 0;
while ((tok = input.nextToken( )) != StreamTokenizer.TT _EOF)
if (tok == StreamTokenizer.TT WORD) {
System.out.println("Word found :" + input.sval);
count++;
}
System.out.println("Found "+ count+" words in temp.txt");
}
o Save the file as WordCounter.java
o Compile the file using javac WordCounter.java
o Ensure that a file temp exists in the directory c:\
Run the file using java WordCounter

‘The output appears as shown:


Word found : Example
Word found : for
Word found : Stream
Word found : Tokenizer
Found 4 words in temp.txt
Reader and Writer Classes
The difference between readers and input stream is that while readers are able to read
characters, input stream read bytes. This increases the power of the Java iostream
classes by being able to read any character and thus enabling internationalization. To
say it in simple terms, it is possible to write the Java program in language like
German, French, Japanese, etc.
The functionality of the writers is similar to the output streams and it is possible to
write one block of bytes or characters.
Following section deals with a few subclasses of Reader and Writer Classes.
Reader Class
Some of the subclasses Of Reader class are:
FileReader

315
The FileReader class enables reading character files. It uses default character
encoding. FileReader class usage is similar to FileInputStream class and its
constructors are identical to those of FilelnputStream class. The constructor is given
below:
public FileReader(File f)
This constructor can throw a FileNotFound Exception.
CharArrayReader
The Char ArrayReader allows the usage of a character array as an InputStream. The
usage of CharArrayReader class is similar to ByteArrayInputStream. The constructor
is given below:
Public CharArrayReader(char ch[]);
String Reader.
The StringReader class reads character from the string. The constructor is given
below.

public StringReader (String s);


InputStreamReader
The InputStreamReader class reads bytes from an input stream and converts them to
characters according to a mapping algorithm. The default mapping identifies bytes as
common ASCII and converts them to Java's Unicode characters. The constructor
given below
public Input StreamReader (InputStream istream)
FilterReader
The FilterReader class allows the reading of filtered character streams. There is one
instance variable in, which is a protected reference to the Reader that is being filtered.
protected FilterReader (Reader r)
BufferedReader
BufferedReader class accepts a Reader object as its parameter and adds a buffer of
characters to it. This class is mainly useful because of its readLine( ) method
public BufferedReader (Reader r)
Writer Class
A few of the subclasses of the Writer class are:
FileWriter
The FileWriter allows writing character files. It uses the default character encoding

316
and buffer size. The usage of FileWriter class is similar to that of FileOutputStream
class. The constructor is given below and it can throw an IOException.
public FileWriter(File f)
CharArrayWriter
CharArrayWriter allows to use a character buffer as an output stream, It is used in
situations where ByteArrayOutputStream is used. The constructor is:
public CharArrayWriter( )

Printer Writer
The PrintWriter class contains methods that makes the generation of formatted output
simple. It can be used instead of PrintStream.The constructor is
public PrintWriter(OutputStream ostream)
The stream is not flushed each time print () method is called.

FilterWriter
The FilterWriter class is used to Write filtered Character streams. It has one instance
variable out, which is a protected reference to the Writer that is being filtered.
protected FilterWriter(Writer w)

BufferedWriter
The BufferedWriter Class buffers data to the character output stream.BufferWriter
class functionality is the same as BufferedOutputStream class .The constructor is
public BufferWriter(Writer w)
Example 8.5
@ Open a new file in the editor and enter the following code:
import java.io.*;
public class WordCounter{
public static void main(String args[]) throws IOException {
BufferReader in =new BufferedReader (new FileReader(args[0}));
String s,
s1=new string();
BufferedReader Stdin=new BufferedReader (new Input StreamReader (System.in));
in.close();
System.out.println(“usage of BufferedReader and Input StreamReader………”);

317
System.out.println(“enter a line”);
System.out.println(stdin.readLine());
Str ingReader in2=new StringReader(s1);
int c;
System.out.println(“printing individual characters of the file ”+args[0]);
while ((c=in2.read()!=-1)
System.out.print1in( (char)c);
BufferedReader in4 =new BufferedReader(new StringReader(s1));
PrintWriter p=new PrintWriter(new BufferedWriter (new Filewriter( “demo.out”)));
while((s=in4.readLine( )) !=nul1)
p.println("output " + s);
p-close( );
}catch(IOException e) { }
}
}
 Save the file as ReaderWriter.java
 Compile the file using javac ReaderWriter.java
 Ensure that a file named temp exists in ¢:\java directory
 Run the file using java ReaderWriter c:\java\temp Ze

Let the contents of the temp file be the line "You are Welcome". The output appears
as shown:

usage of BufferedReader and InputStreamReader...


enter a line
Let us input the line "This is a test". The remaining part of the output is shown below:
This is a test
Printing individual characters of the File c:\java\temp

Y
o
u

318
a
r
e

W
e
l
c
o
m
e
Between lines 5 and 9, input is accepted from the keyboard and the same is printed on
the screen. The next part of the program uses the file name provided at the command
line. Individual characters in the file are printed on the screen, using the StringReader
object.The Printwriter class object writes the content of the accepted file onto
demo.out.

13.10 SUMMARY
 In this Unit we have leant that , There are different subclasses of the Input
Stream and the outputstream. The FileInputstream and Fileoutput stream help
in reading / writing data from actual
disk files.

 ByteArrayinput stream and ByteArrayOutput stream make use of byte array as


the source and perform the reading and writing operations on that array.
SringButfertnput stream is similar to ByteArrayInput Stream except that the
former uses a stored string as the source.

 Bufferedtnputstream and Bufferedoutput stream utilize a buffered array of


bytes,which act as a cache to perform the read and write operations.
DataInputstream and DataOutputStream perform the read / write operations by
taking one byte at a time.

319
 PushbackInputStream takes input from the InputStream and places it back
without disturbing it. The Printstream has two methods syetem.out .print( )
and System.out. printin( ) which are widely used. The streamTokenizer helps
to break the InputStream into tokens.

 The Reader and writer classes are used to read / write characters respectively
instead of bytes.

13.11 KEYWORDS

I/O Streams, Random Access File

13.12 QUESTIONS FOR SELF STUDY


1. What are the two types of File stream available in Java?
2. Name the various Input streams available in Java.
3. What is the function of FileOutputStream?
4. Name the ByteArrayStreams available in Java
5. Which method in DatalnputStream class is used to read an integer of input?
6. What is the function of StreamTokenizer class?

7. Write a note on Random Access File Class

13.14 REFERENCES

1. David J. Eck Introduction to Programming Using Java.


2. Elliotte Rusty Harold Java I/O published by O'Reilly
3. Ken Arnold, James Gosling . The Java Programming Language

4. Patrick, Naughton The Java Handbook

5. Dwight Deugo More java gems

6. Sun Microsytems Java tutorial,

7. E Balaguruswamy Programming with java

8. Schum series publications Programming in java

9. Doug Lea . Concurrent Programming in Java: Design Principles and Patterns

320
10. Jose M. Garrido Object-Oriented Programming: From Problem Solving to
Java
11. Bill Venners Object-Oriented Design with Java
12. E. Balaguruswamy Programming with java
13. Internet

321
UNIT-14 MULTITHREADING IN JAVA

STRUCTURE

14.0 Objectives
14.1 Introduction
14.2 Multithreading in Java
14.3 Thread life cycle and methods
14.4 Runnable Interface
14.5 Summary
14.6 Keywords
14.7 Questions for Self Study
14.8 Keys Questions for Self Study
14.9 References
14.0 OBJECTIVES
Upon completion of this unit you will be able to:

 Define Multithreading in Java


 Explain Thread life cycle and methods
 Describe Runnable Interface
14.1 INTRODUCTION
This unit familiarizes us to the concept of interfaces in Java. It is also introduces the
notion of multithreading. Interfaces ,Fundamentals of Threads and More on Threads

14.2 MULTITHREADING IN JAVA


Fundamentals of Threads

A process is a program in execution. Two or more processes running concurrently in a


computer is called multitasking. Java provides support for multithreading. To know
multithreading, first it is essential to define a thread.
Definition of a Thread
A thread is a line execution. It is the smallest unit of code that is dispatched by the
scheduler.
Thus, a process can contain multiple threads to execute its different sections. This is

322
called multithreading.
For example, to calculate (b*b)-(4*a*c) in quadratic equation, b*b can be calculated
independently of 4*a*c.One thread can execute the first and another next. Thus
completion of this process is faster. Generally, the main thread executing a program is
terminated after all its other threads have been destroyed.
When a program requires user input, multithreading enables creation of a separate
thread for this task alone. The main thread can continue with the execution of the rest
of the program. Programs not using multithreading will have wait the user has input a
value for the continuation of the execution of the program.
The advantages of using threads over processes are as follows.
 Can be created faster
 Requires less overheads
 Interprocess communication is faster
 Context switching is faster
 Maximum use of CPU time

14.3 THREAD LIFE CYCLE AND METHODS


States of a Thread
There are four states associated with a thread namely - new, runnable, dead and
blocked.
New - When a thread is created, it is in the new state. New implies that the thread
Object has been created but it has not started running. It requires the start () method to
start it
Runnable - A thread is said to be in runnable state, when it is executing a set of
instructions. The run () method contains the set of instructions. This method is called
automatically after start () method.
Dead -The normal way for a thread to die is by returning from it’s run () method. We
can also call stop ( ), but this throws an exception that’s a subclass of Error (which
means we normally do not catch it). Remember that throwing an exception should be
a special event and not part of normal program execution; thus the use of stop ( ) is
discouraged (and it is deprecated in Java 1.2). There is also a destroy ( ) method
(which has never been implemented) that should never be called if we can avoid it,
since it is drastic and does not release object locks.

323
Blocked - The thread could be run but there is something that prevents it. While a
thread is in the blocked state the scheduler will simply skip over it and not give it any
CPU time. Until a thread re-enters the runnable state it will not perform any
operations.
Common Thread Methods
Let us discuss some of the common thread methods:
Start ( ) - The start method starts execution of the invoking object. It can throw an
Illegal exception if the thread was already started
stop () - This method terminates the invoking object.
suspend ( ) - This method suspends the invoking object. The Thread will become
runnable again if it gets the resume () method
sleep ( ) – This method suspends execution of the executing thread for the specified
number of mill second s. It can throw an Interrupted Exception.
public Static void sleep (long ms)
The following statement can suspend execution of the executing thread for the
specified number of milliseconds plus nanoseconds.
public Static void sleep (long ms,int ns)
resume () - The resume ( ) method restarts the suspended thread at the point at which
it was halted. The resume ( ) method is called by some thread outside the suspended
one, there is a separate class called Resumer which does just that. Each of the classes
demonstrating suspend/resume has an associated resume.

Fig 15.1 depicts the states of the

324
thread.
Fig. 15.1 - States of a thread
Creation of a Thread
A thread in Java is created as an object of class Thread. It has an interface which is
used along with it concurrently - Runnable interface. Creation of new threads can be
done as follows.
 Creating objects of class Thread
 Using Runnable interface

Methods of Thread Class


Some of the common methods of Thread class like start (), sleep (), run () have been
discussed in the above examples. This section intends to discuss some more methods
available with Thread class.
Methods
activeCount() Returns the current number of active
Threads in this Thread group
currentThread() Returns a reference to the currently
executing Thread & is s static method
isAlive() To check whether given thread alive.

325
getName() Gets and returns this Thread’s name
getPriority() Gets and returns the Thread’s priority
setName(String) Sets the Thread’s name
setPriority(int) Sets the Thread’s priority
join() Waits forever for this Thread to die
toString() Returns a String representation of the
Thread ,including the thread’s name,
priority and thread group.

Example 15.5 portrays the usage of some of the methods discussed earlier
Example 15.5
 Open a new file in the editor and enter the following code

class ThreadMethodl {
public static void main(String args[]) {
Thread t=Thread.current Thread ();
System.out.printIn("current thread : " + t);
System.out.printin("Name of the current thread : " +t.getName());
System.out.println("Priority : " + t.getPriority());
t.setName(“mythread") ;
System.out.println("after name change : "+t);
t.setPriority(2);
System.out.println("after priority change : " +t);
System.out.printin("number of active threads : "; +t.activeCount () );
}}
 Save the file as ThreadMethod1.java
 Compile the file using javac ThreadMethod1. java
 Run the file using java ThreadMethod1

The output appears as shown below:


Current thread: Thread [main, 5, main]
Name of the current thread : main
Priority : 5

326
after name change : Thread [main, 5, main]
after priority change : Thread [main, 5, main]
number of active threads : 1
This program gets a reference to the current thread by calling currentThread ()
method, makes use of the methods using this reference and prints relevant details
about it.
Example 15.6 illustrates usage of some more Thread class methods.
Example 15.6
 Open a new file in the editor and enter the following code

class CreateThread extends Thread {


String tname;
Thread t;
CreateThread(String s){
tname=s;
t=new Thread (this.s);
System.out.printIn("New thread : " + t);
t.start();
}
public void run(){
try{
for (int i=5;i>0;i--){
System.out.printIn(tname + “:” +t);
Thread.sleep(500);
}
}catch(InterruptedException e){}
System.out.printIn(tname + “exiting …..”);
}
}
class ThreadMethod2 {
public static void main(String args[]) {
CreateThread m1 = new CreateThread(“one”);
CreateThread m2 = new CreateThread(“Two”);
System.out.println("Thread m1 is alive : " +m1.t.isAlive());

327
System.out.println("Thread m2 is alive : " +m2.t.isAlive());
try{
System.out.printin("Waiting for threads to finish……..” );
m1.t.join();
m2.t.join();
} catch (InterruptedException e) {}
System.out.println ("Thread m1 is alive: " +m1.t.isAlive ());
System.out.println("Thread m2 is alive : " +m2.t.isAlive());
System.out.println("Main thread exiting “);
}

 Save the file as ThreadMethod2.java


 Compile the file using javac ThreadMethod2. java
 Run the file using java ThreadMethod2

The output appears as shown below:

New thread: Thread [one, 5, main]


New thread: Thread [two, 5, main]
Thread m1 is alive : true
One : 5
Two : 5
Thread m2 is alive: true
One : 4
Two : 4
One : 3
Two : 3
One : 2
Two : 2
One : 1
Two : 1
One existing …………
Two existing …………

328
Thread m2 is alive : false
Thread m2 is alive : true
Main thread exiting……

Two threads are created by main by main m1 and m2.The constructor of


CreateThread class accepts the name for the created and starts it .While the
run () method is getting executed, the main thread continues its execution of
the program by checking whether threads are running or not .The join()
method enables termination of threads created. At the end of the program, a
check is made again to verify the status of the created threads.

14.4 RUNNABLE INTERFACE


Creation Using Runnable Interface
Creation of a thread object using Runnable interface has already been dealt in the
earlier session while discussing animation. This is the easiest way of creating a
Thread object. The Runnable interface contains only run () method, which should be
included in classes implementing them.
The following program illustrates creation of a thread using Runnable interface.
Example 15.3
@ Open a new file in the editor and enter the following code:
//to illustrates creation of threads using Runnable
class IntThread implements Runnable {
Thread t;
Int Thread () {
t=new Thread(this, “Test thread”);
System.out.println("Child thread : ” +c);
t.start();
}
public void run(){
try{
for(int i=5;i>0;i--){
System.out.println("Child thread: "+i);
Thread. sleep (500);
}

329
} catch (InterruptedException e) {}
System. Out .println ("Exiting child thread ...");
}
public static void main (String args[]){
IntThread i=new IntThread();
try{
for (int j=5;j>0;j--){
System.out.println("Main thread : "+j);
Thread.sleep(1000);
}
}catch(InterruptedException e) {}
System.out.println("Main thread exiting ….”);
}
}
 Save the file as IntThread.java
 Compile the file using javac IntThread.java
 Run the file using java IntThread

A new object of IntThread class is created as the first step, which calls its constructor.
Inside the constructor ,a new thread is created using one of Thread class constructor,
which takes as parameters- the object itself and a string .This helps in creating new
child threads apart from the main thread .The start() method starts each of the newly
created threads.
Automatically, control passes to the run () method. Within it, the sleep () method of
the Thread class suspends the thread for 500 milliseconds. Since this method
generates an exception .it is enclosed within the try block.
Simultaneously, the main thread continues with execution of the main program. The
main thread enters the try block inside main () method and exists at the end of the for
loop. It is ensured that the child thread created is destroyed before main thread
terminates. Note that the output obtained may vary from one system to another.
The output of the above program is :
Child thread: Thread [Test thread, 5, main]
Main thread : 5
Child thread : 5

330
Child thread : 6
Main thread : 4
Child thread : 3
Child thread : 2
Main thread : 3
Child thread : 1
Existing child thread……
Main thread: 2
Main thread: 1
Main thread exiting……
The first line of the output contains Child thread: Thread [Test thread, 5, main].Here
Test thread is the allocated name of the thread.5 is the default thread priority and the
third argument main represents the main represents the default thread group. Thread
priority is discussed in the latter part of this session. Thread group is a data structure
that controls the state of a collection of threads as a whole.
Creating Thread Class Objects
A thread object can be created from Thread class. The run () method should
necessarily exist in classes created as subclass of Thread .The first constructor of
Thread class can be given as follows.
Thread (Runnable, String)
A new thread is created with specified name. It applies the run () method on the
specified target.
The next constructor creates a new thread in the specified Thread group with the
specified name and it applies the run () method on the specified target.
Thread (ThreadGroup, Runnable, string)
The following program illustrates the creation of a thread object using Thread class
and the output produced is the same as example 11.3.
Example 15.4
 Open a new file in the editor and enter the following code:
class MyThread extends Thread {
MyThread () {
super ("Using Thread class");
system. out .println ("Child thread : " +this);
start ();

331
}
public void run(){
try{
for (int i=5;i>0;i--) {
System.out .print1n("Child thread "+i);
Thread.sleep(500);
}
}catch(InterruptedException e) {}
System.out .printin("exiting child thread...");
}
}
class TestMyThread {
public static void main(String args[]) {
new MyThread();
try{
for(int k=5;k>0;k--) {
System.out.println("Running main thread :"+k);
Thread.sleep(1000);
}
}catch(InterruptedException e) {}
System.out.println("Exiting main thread ...");
}
}
 Save the file as TestMyThread.java
 Compile the file using javac TestMyThread.java
 Run the file using java TestMyThread

The output of the above program is :


Child thread: Thread [Using thread class, 5, main]
Running main thread : 5
Child thread : 5
Child thread : 4
Running main thread : 4
Child thread : 3

332
Child thread : 2
Running main thread : 3
Child thread : 1
Existing child thread……
Running main thread : 2
Running main thread : 1
Existing main thread……

In the main method, a new object of MyThread a subclass of Thread is created. The
constructor of MyThread class calls the base class constructor using super and starts
the thread .The run() method of the call starts after this .It can be observed that both
the main thread and created child thread are executed concurrently.

14.5 SUMMARY

In this Unit we have learnt Multithreading in Java, Thread life cycle and methods
And also Runnable Interface

14.6 KEYWORDS

Multithreading, Thread life cycle, methods , Runnable Interface

14.7 QUESTIONS FOR SELF STUDY

1. Explain the Fundamentals of Threads


2. What are the advantages of using threads over processes?
3. Write a program to create multiple threads .The main method sleeps for about
10 seconds at the end of which all the threads should be terminated.
4. Write a program to create two threads .Reset their priorities to two levels
above and below the NORM_PRIORITY.Display the changed priorities.
5. Write a program to create two threads .Each of the threads should sleep for 5
seconds. Resume the threads, check for their active status. The main thread
sleeps for 10 seconds after which all threads are terminated.

333
14.8 REFERENCES

1. David J. Eck Introduction to Programming Using Java.


2. Elliotte Rusty Harold Java I/O published by O'Reilly
3. Ken Arnold, James Gosling . The Java Programming Language

4. Patrick, Naughton The Java Handbook

5. Dwight Deugo More java gems

6. Sun Microsytems Java tutorial,

7. E Balaguruswamy Programming with java

8. Schum series publications Programming in java

9. Doug Lea . Concurrent Programming in Java: Design Principles and Patterns

10. Jose M. Garrido Object-Oriented Programming: From Problem Solving to


Java
11. Bill Venners Object-Oriented Design with Java
12. E. Balaguruswamy Programming with java
13. Internet

334
UNIT-15 THREAD SYNCHRONIZATION
STRUCTURE
15.0 Objectives
15.1 Introduction
15.2 Thread Synchronization
15.3 Exception Handling with try-catch-finally
15.4 Summary
15.5 Keywords
15.6 Questions for Self Study
15.7 Keys Questions for Self Study
15.8 References

15.0 OBJECTIVES

Upon completion of this unit you will be able to:

 Explain the Thread Synchronization


 Discuss Exception Handling with try-catch-finally

335
15.1 INTRODUCTION

This unit intends to introduce concept like synchronization of threads to enable data
integrity, inter thread communication using wait (), notify () and thread priorities.

Exception Handling : Errors and abnormal conditions arising while executing a


program need to be handled. Usually code snippets are written to handle such
situations. Java offers various classes to handle exceptions thus making its programs
robust.

15.2 THREAD SYNCHRONIZATION


More on Threads

Synchronization

Two or more threads accessing the same data simultaneously may lead to loss of data
integrity. For example, when two people access a saving account, it is possible that
one person may overdraw and the cheque may bounce. The important of updation of
the passbook can be well understand in this case.

Java uses the concept of monitor or a semaphore to enable this .A monitor is an


object, used as mutually exclusive lock. At a time only one thread can access the
monitor. A second thread cannot enter the monitor until the first comes out .Till such
time, the other thread cannot enter the monitor until the first comes out .Till such
time, the other thread is said to be waiting .The keyword synchronized is used in the
code to enable synchronization. The word synchronized keyword with a method or
within a block.

Example 15.7 illustrates the usage of synchronized keyword within a method.

Example 15.7
 Open a new file in the editor and enter the following code

Class Inventory {
static int qoh = 500;
static int req = 0;
static public synchronized void request(int order){
if(order<=qoh){

336
System.out.printIn ("Quantity Ordered: " + order);
qoh-=order;
req+=order;
System.out.printIn("Quantity on hand : " + qoh);
System.out.printIn("Total quantity taken away by way of order : " + req);
}
else {
System.out.printIn ("Ordered quantity more than quantity on hand”);
}
}
public static void main(String args[]) {
new OurThread();
new OurThread();
try{
for (int p=3;p>0;p--){
System.out.printIn ("================================”);
System.out.printIn ("main thread : ” +p);
System.out.printIn ("================================”);
Thread. Sleep (10000);
}
}catch (Interrupted Exception e){}
System.out.printIn (“exiting main thread”);
}
}
class OurThread extends Thread {
OurThread () {
super (“test thread”);
System.out.printIn( “child thread : ”+ this);
start ();
}
public void main run(){
for (int i=5;i>0;i++){
try{
sleep(100);

337
}
public void run() {
for (int i=5;i>0;i--){
try{
sleep(100);
} catch (Interrupted Exception e){}
Inventory.request((int )(Math.random()*100))
}
}
}
 Save the file as Inventory.java
 Compile the file using javac Inventory. java
 Run the file using java Inventory

The output depends on the random number generated in Line 41.

Two objects of class OurThread are created, which call their constructor .Since the
class OurThread is a subclass of Thread, the base class constructor is called using
super. The child Thread is also started within this.
The run method of OurThread class calls the request () method of Inventory class.
Note the usage of random () method of the Math class .Since it returns a double value
and the request () method takes an integer parameter, there arises a necessity for
typecasting at line number 41.The random () method is used to generate values for
orders. In case, generated number exceeds the qoh, an error message is printed.
The important methods of this program is request ().Both the threads that are created
are trying to access request () at the same time, hence it is declared as synchronized,
static, public and void .Inside this method, a check is made if quantity on hand is
greater than or equal to the quantity on hand is greater than or equal to the quantity
ordered. If so, then qoh is updated.

Interthread Communication
There may be cases where one of the created threads requires data from another. It
becomes essential to check every few seconds, whether the second thread has

338
produced the required information or not .Till such time, the first thread waits,
wasting CPU time.
Java offers interprocess communication through the usage of wait (), notify (),
notifyAll () methods of object class and all are synchronized methods.
Wait () – This method waits indefinitely on another thread of execution until it
receives a notify () or notifyAll () message.
notify () – This method wakes up a single thread waiting on the Object’s monitor.
notifyAll () – this method wakes up all threads waiting on the Object monitor.

The following example explains the usage of interthread communication in Java.


Three classes called Consumer, Producer and Stock are created. The stock class
contains a buffer stock of goods .It receives goods produced using random generation
and adds to the buffer stock .Using the same random generation, goods are also taken
away. Stock acts as the central class into which goods are added as well as taken away
.Pictorially, the following program can be represented as given in Fig 15.2.

Example 15.8
 Open a new file in the editor and enter the following code
class Consumer implements Runnable {
Stock c,
Thread t;
Consumer (Stock c){
this .c=c;
t=new Thread (this,”producer thread”);
t.start();
}
public void run(){

339
while (true)
try {
t.sleep(500);
} catch(Interrupted Exception e){}
c.getStock((int)(Math.random()*100));
}
}
void stop(){
t.stop();
}
}
 Save the file as Consumer.java
 Open another new file and enter the following code:

Class Producer implements Runnable {


Stock s;
Thread t;
Producer(stock s){
this.s=s;
t=new Thread (this,”producer thread”);
t.start();
}
public void run(){
while (true)
try {
t.sleep(750);
} catch(Interrupted Exception e){}
c.getStock((int)(Math.random()*100));
}
}
void stop(){
t.stop();
}

340
}

 Save the file as Producer.java

Both the Producer class and the Consumer class create a thread, using goods are
added are consumed respectively. The run () method of both the classes use the
random () method of Math class to generate random numbers.
 Open a new file in the editor and enter the following code

Class Stock {
int goods=0;
public synchronized void addStock (int i){
goods=goods+i;
System.out.printIn ( “Stock added: ”+ i);
System.out.printIn ( “Present Stock: ”+ goods);
notify();
}
public synchronized void getStock (int j){
goods=goods-j;
System.out.printIn ( “Stock taken away: ”+ j);
System.out.printIn ( “Present Stock: ”+ goods);
break;
}
else{
System.out.printIn ( “Stock not enough……….:”);
System.out.printIn ( “Waiting for stocks to come ………..”);
try{
wait();
} catch(Interrupted Exception e){}
}
}
return goods;
}

341
public static void main(String args[]) {
Stock j = new Stock();
Producer p= new Producer(j);
consumer c = new Consumer(j);
try{
Thread.sleep(100000);
p.stop();
c.stop();
p.t.join();
c.t.join();
System.out.printIn ( “Thread stopped”);
} catch(Interrupted Exception e){}
System .exit(0);
}
}
 Save the file as Stock.java
 Compile the file using javac Stock. java
 Run the file using java Stock

The output depends on the random number generated in the Consumer and Producer
classes.
The main method creates a Producer and Consumer object, which call their respective
constructors. Within the constructors of these classes, threads are created and started.
The run () method of both these classes are executed concurrently. Within the run
methods, addstock () and getStock () methods of the stock class are called. If the
requested goods for consumptions is greater than the stock at hand (goods produced +
buffer stock), the wait () method of the object class is called which waits until it gets
information from notify () method within the addstock () method. As soon as goods
and added buffer stock, the notify () method is called. This process continues, while
the main thread resumes, both the child threads are terminated using join ().
Thread Priorities
Each thread created has a priority attached to it .The scheduler allocates time in
accordance to these priorities. A thread with higher priority can preempt lower
priority thread, thus taking CPU’s time. The yield () method enables provision of

342
CPU’s time to thread with equal priority and prevents monopolization of a single
thread.
The usage of setPriority and getPriority method is already explained. These are used
to set and get the priorities respectively .Threads have maximum and minimum
priorities set by default .The Thread class has final variables declared like –
NORM_PRIORITY,MINIMUM_ PRIORITY and MAXIUM _ PRIORITY to set
default priorities. A thread can have a maximum priority of 1.Normal priority is set at
5.

15.3 EXCEPTION HANDLING WITH TRY-CATCH-FINALLY

Basics of Exception Handling


Errors and abnormal conditions arising while executing a program need to be handled.
Usually code snippets are written to handle such situations. Java offers various classes
to handle exceptions thus making its programs robust.
Definition of an Exception
An exception is an abnormal condition, which occurs during the execution of a
program. Exceptions are erroneous events like division by zero, opening of a file that
does not exist, etc. A Java exception is an object, which describes the error condition
that has materialized in the program.
Java handles exceptions using five keywords - try, catch, finally, throws and throws.
These are explained in detail in the following paragraphs.
Class Hierarchy
The Object class has a subclass called Throwable to handle exceptions and errors. The
Throwable Class has two subclasses - Exception and Error.
Error conditions are normally not trapped by Java programs. Error conditions
normally occur in Case of drastic failures, which cannot be handled by the programs.
These are generated indicate errors generated by runtime environment. Stack
overflow is an example of error condition.
The main subclass of Exception Class is the Runtimesxception class. This class

343
generates error that occurs during the execution of a program. For example, trying to
access an invalid array index, division by zero, etc. cannot be known at compilation
time. They are generated at runtime .It is good programming practice to anticipate
such error and handle them. RuntimeException is defined, by default all program .Fig
6.1 illustrate the Exception class hierarchy.

Default Exception Handling


When a program throws an exception, it comes to a stop. This exception should be
caught by an exception handler and dealt with immediately .In case of provision of an
exception handler, the handling is done by handler. This displays a string, which
describes the exception and the point at which the exception occurred, after which the
program terminates.

Object

Throwable

Error Exception

IOException RuntimeException

Example 6.1 tries to set a value to the tenth element of the integer array, which
generated ArrayIndexOutOfBoundsException.
Example 6.1
 Open a new file in the editor and enter the following code:

//usage of default exception handler


Class DefException {
public ststic void main(String args()) {
int i[] = {};
i[10]=20;
}

344
}
 Save the file as DefException.java
 Compile the program using javac DefException.java
 Run the program using java DefException

The output of this program is as follows.


Exception in thread “main” java. lang. arrayindexOutOfBoundsException :10 at
DefException,main( DefException, java:4)
The string contains the description of the Exception generated and the point at which
it was generated (line number 4 of the program)

Try and catch


Whenever there is possibility of an exception being generated in a program, it is better
to handle it explicitly. This can be done using the try and catch keywords. The
advantages of using the try and catch keywords are that, it fixes the error and prevents
the program from terminating abruptly.
The code sequence, which is to be guarded, should be placed inside the try block. The
catch clause should immediately follow the try block. The catch clause can have
statement explaining the cause of the exception generated. The scope of each catch is
restricted to try block .It is possible to have multiple catch statement for one try block.
The execution of a program can continue once the exception has been handled.
The following example describes the usage of try and catch block.
 Open a new file in the editor and enter the following code:
//usage of try and catch
Class NegTest {
public static void main(string args[]) {
Try{
intt arr[] =new int[-2];
System.out.println(“first element :”+arr[0]);
} catch(NegativeArraySizeException n) {
System.out.println("generated exception : "n);
}
System.out.println("after the try block");

345
}
}
 Save the file as NegTest.java
 Compile the file using javac NegTest.java wand
 Run the file using java NegTest

The output is as follows.


generated exception: java.lang.NegativeArraySizeException
after the try block
This program tries to print the first element in the array that is created. Since the array
size is declared as negative, an exception is generated. This is caught by catch clause,
which prints the name of the exception generated. Note that the program does not
terminate abruptly, but continues further execution.
Multiple catch Statements
Multiple catch statements are required in the program when more than one exception
is generated by a program. These catch statements are searched by the exception
thrown in order. The first matching catch clause is executed. Finally, if the exception
does not find a matching catch clause, it is passed on to the default handler. As an
illustration for multiple catch statements, let us take a look at Example 6.3.

Example 6.3
 Open a new file in the editor and enter the following code:

// usage of multiple catch statements


import java.io
class MultiCatchException (
public static void main (String args[]) {
int arr[] = (100, 200, 300, 400, 500);
system.out.println(“enter a number as array index and find out its value ”);
system.out.println(“enter end to come out of the program”);
try {
String line;
int x;
BufferedReader d=new “BufferedReader (new InputStreamReader(System.in);

346
while (line = d.readLine()) !null){
if (line.equals(“end”))
break;
else {
try {
x=Integer.parseInt(line);
system.out.println(“valid element and it is :”+arr[x] );
}catch(ArrayIndexOfBoundException e){
system.out.println(“invalid ekement”);
system.out.println(“exception generated :”+e);
}catch(NumberFormatException n){
system.out.println(“sorry no characters”);
system.out.println(“generated exception :””+n);
}
}
}
}catch(IOException i) {}
}
}
 Save the file as MultiCatchException java
 Compile the Program Using javac MultiCatchException,java
 Run the program Using java MultiCatchException

The program executes different catch statements depending on our input. The
program initially displays the following lines:
enter a number as array index and find out its value
enter end to come out of the program
If we input a character or a string or a string then the output appears as:
sorry no characters
generated exception :‘java. lang –NumberFormatExcept : e
if we input number greater than 4 Or less than 0 then the output appears as:
invalid element
exception generated : java.lang.ArrayIndexOutOfBoundsException
If we input a number between 0 and 4, say 3, then the output appears as:

347
valid element and it is:400
The above program accepts an array index from the user. To exit the program, the
user should type “end”. If the accepted input is a valid index, the corresponding value
is displayed. If the array index is invalid, an ArrayIndexOutOfBoundsException is
generated, On entering characters as input, a NumberFormatException is generated.
The parsetnt() method of the integer class generates a NumberFormatException, when
the string passed does not represent a number. Note that, in case of generation of both
the exceptions the program does not terminate abruptly. Each catch clause is searched
in order by the exception to identify its matching one. The 10Exception takes care of
identifying exceptions generated while accepting input.
Care should be taken to ensure that the subclass exception precedes the base class
exception. For example, in order to catch FileNotFoundException and 10Exception
within a try block. it is essential to catch FileNotFoundException earlier than
IoException. Example 6.4 illustrates sub class exception precedence over the base
class.
Example 6.4
 Open a new file in the editor and enter the following code:
// To illustrate sub class exception precedence over base class
import java.io.*;
class BaseSubException {
public static void main(String args[]) {
if(args.length=<0) {
System.out.println("invalid usage");
System.out.println("Usage : java <filename> filel file2 -file3 ...”);
return;
}
for (int i=0;i<arge.length;i++) {
File f= new File(argse[i]);
try {
String line;
DataInput d = new DataInputStream(new FileInputstream(args[i})),
if (f.exists() && f.isFile()) {
System.out.println("file exists");
System.out.println(f + " is ordinary file");

348
System.out .println("printing the contents of file named : " + args[i]);
System.out .println(“===========================”);
while ((line = d.readLine())!=null) {
System.out.println(line);
} //end while
} // end if
} catch (FileNotFoundException e) {
if (f.exists() && £.isDirectory()){
System.out -printin( “===============") ;
System.out.printin("Name : " + f + " is a directory");
System.out.printlin("inside catch of FileNotFoundException") ;
System. out .print1n(“=======================");
}else{
System. out .print1n (“===================");
System.out.println("Name : " + args[i] + " does not exist");
System.out.print1n("generated exception :"+e);
System.out. println( “============================" ) ;
}
} catch(IOException p) {
System.out.println("super class is higher up in the program");
}// end of for
}
}
}

 Save the file as BaseSubException,java


 Compile file using javac BaseSubException.java
 Type edit test.txt at the command prompt and click Enter
 In the editor,type the following lines:

This is a test file


It is used to test whether the specified file exists
 Select File>Save from the menu

349
 Select File>Exit from the menu
 Type mkdir testdir in the command line and click Enter
 Run the BaseSubException program using java BaseSubException testdir
test.txt
try.txt (where try.txt does not exist in the current directory)

The output appears as shown below:


============================================
Name: testdir is a directory
Inside catch of FileNotFoundException
==============================================
file exists
test.txt is ordinary file
printing the contents of file named:test.txt
=====================================================
This is a test file
It is used to test whether the specified file exists
==========================================
Name: try.txt does not exist
Generated exception :java.io.FileNotFoundException: try.txt (The system
cannot find the file specified)
============================

Let us suppose that we have a file named test.txt and a directory named testdir inside
the current directory. Let us also assume that the file test.txt does not exist
 Run the file using java BaseSubException

The above program accepts file names as commandline arguments. It displays the
contents of the file, if the file exists and if it is an ordinary file. Otherwise, an
exception is generated which is caught by the FileNotFroundexception. Inside this
catch, a check is made to ascertain if the file is a directory or if it does exist at all.
Accordingly the statements within the if Or else are executed. Try inserting the catch
clause of IOException first and then the catch of the FilenotFoundException,
Compilation error results saying that catch of the FileNotFoundException is not

350
reached. Since FileNotFoundexception is a subclass of the IOException, it is essential
that it should precede the base class.
try, catch and finally
When an exception is generated in a program, sometimes it may be necessary to
perform certain activities before termination. The activities may be closing of a file,
deleting a graphics object created, etc. In such cases, the try block, apart from the
catch clause, also has finally block within which the activities mentioned above can
be performed. This block is executed after the execution of statements within the
try/catch block. Thus it bypass all the other methods existing in the program, In case
an exception is thrown, the finally block will be executed even if no catch matches it.
The try block requires either a finally clause or a catch clause.
Example 6.5 illustrates the usage of the try / catch with finally clause.
Example 6.5

¢ Open a new file in the editor and enter the following code:

Output

// Illustrates usage of try / catch with finally clause


import java.io.*;
class FinallyException {
public static void main(String args[]) {
try {
InputStream f1 =null;
int size=f1l.available();
for (int i=0;i<size;i++) {
System.out.print ((char)f1.read());
}
} catch (IOException e) {}
catch (NullPointerException n) {
System.out.println("exception generated : " + n);
}
finally{
System.out.printiln("========================");

351
System.out.println("inside finally ");
System.out.println("ha! I always have the final say");
System. out -println(“========================");
}
}
}
 Save the file as FinallyException.java
 Compile the file using javac FinallyException.java
 Run the file using java FinallyException

The output of the Program appears as follows:


Exception generated: java.lang.NullPointerException
===============================================
inside finally
ha! I always have the final say
================================================
The above program creates an InputStream object and initializes it to null. Utilizing
this object, it checks for the size of the file and tries to read the contents within the for
loop.Since the Inputstream object is initialized to null, a NullPointerException is
generated while trying to read it. This is caught by the catch clause. After the
execution of the statements inside the catch clause, finally clause is reached. Once the
statements inside this block are executed, the program terminates.
Usage of throws
Whenever a program does not want to handle exceptions using the try block, it can
use the
throws clause. The throws clause is responsible to handle the different types of
exceptions generated by the program. This clause usually contains a list of the various
types of exceptions that are likely to occur in the program. Let us discuss this with
Example 6.6.
Example 6.6
 Open a new file in the editor and enter the following code:
// To describe usage of throws clause

class ThrowsException {

352
public static void main(String args[])throws ArithmeticExceptiont {
System.out.println("inside main");
int i=0;
int j=40/i;
Syetem.out.printlin("this statement is not printed");
}
}
 Save the file as ThrowsException.java
 Compile the file using javac ThrowsException.java '
 Run the file using java ThrowsException

The output generated is as follows.


inside main
Exception in thread “main” java.lang.ArithmeticException: / by zero at
ThrowsException.main(ThrowsException. java: 5)
The main() method of this program expects the generation of ArithmeticException
but does not want to handle it using the try/catch block. Hence the inclusion of throws
clause in the definition of this method. Note that, after the display of the description
of the exception, the program terminates abruptly. The last print statement in the
program is never executed.

Usage of throw
The throw statement is used to explicitly throw an exception. First, a handle on an
instance of Throwable must be got (via a parameter) into a catch clause or by creating
one using the new operator. The general form of a throw statement is given below:
throw <Throwableinstance>
where <Throwableinstance> is the instance when the throw has to be executed.
The flow of execution stops immediately after the throw statement and the next
statement is not reached. The closest enclosing try block is inspected to see if it has a
catch clause which matches the type of the Throwable instance. If it finds a match,
then control is transferred to that statement. If no match is found, the next enclosing
try statement is inspected and the cycle continues till the outermost exception handler
stops the program.
Example 6.7 demonstrates throwing a new instance of an exception, then rethrowing

353
the same Exception to the outer handler.
 Open a new file in the editor and enter the following code:

Class Throwdemo{
static void demoproc() {
try{
throw new Null PointerException ("demo") ;
}catch(Null PointerException e) {
system.out.print(“Caught inside demoproc");
throw e;
}
}
public static void main(String args[]){
try{
demoproc
}catch (NullPointerException e) {
System.out.println("Recaught:" +e);
}
}
}
 Save the file as Throwdemo.java
 Compile the file using javac Throwdemo.java a.
 Run the file using java Throwdemo

The output appears as shown below:


Caught inside demoproc
Recaught: java.lang.NullPointerException: demo
This example gets two chances to deal with same error. First, main( ) sets up an
exception context (by starting the try block) and then calls demoproc(). The
demoproc() method then sets up another exception handling context and immediate
throws a new instance of NullPointerException. This is caught on the next line and
the exception that was thrown is referred to by e. The message is printed and the same
instance is thrown again.
Exception Restrictions

354
When we override a method, we can throw only the exception that has been specified
in the base-class version of the method. This is a very useful restrictions since it
means that the code which works with the base class will automatically work with any
object derived from the base class(a fundamental OOP concept),including exception.
It is useful to realize that, although exception specifications are enforced by the
compiler during inheritance, the exception specifications are not part of the type of a
method. The method is comprised of only the method name and argument types.
Therefore, we cannot overload methods based methods on exception specification. In
addition, because an exception specification exists in a base-class version of a method
does not mean it must exist in the derived-class version of the method, and this is
quite different from inheriting the methods themselves.

15.4 SUMMARY

In this Unit we have learnt Thread Synchronization and Exception Handling with try-
catch-finally

15.5 KEYWORDS

Thread Synchronization , Exception Handling, try , catch, finally

15.6 QUESTIONS FOR SELF STUDY

1. What is Synchronization?
2. What is an Exception ? Explain different types of Excepion handlers.

355
15.7 REFERENCES

1. David J. Eck Introduction to Programming Using Java.


2. Elliotte Rusty Harold Java I/O published by O'Reilly
3. Ken Arnold, James Gosling . The Java Programming Language

4. Patrick, Naughton The Java Handbook

5. Dwight Deugo More java gems

6. Sun Microsytems Java tutorial,

7. E Balaguruswamy Programming with java

8. Schum series publications Programming in java

9. Doug Lea . Concurrent Programming in Java: Design Principles and Patterns

10. Jose M. Garrido Object-Oriented Programming: From Problem Solving to


Java
11. Bill Venners Object-Oriented Design with Java
12. E. Balaguruswamy Programming with java

356
UNIT-16 INTRODUCTION TO JAVA BEANS AND NETWORK
PROGRAMMING

STRUCTURE
16.0 Objectives
16.1 Introduction
16.2 Collections in Java
16.3 Introduction to Java Beans
16.4 Network Programming
16.5 Summary
16.6 Keywords
16.7 Questions for Self Study
16.8 Keys Questions for Self Study
16.9 References

16.0 OBJECTIVES
After going through this unit you will able to learn:

 Explain How computer network is done

 How to connect point to point and multipoint connections

 Elucidate the Different uses of Network Topologies

 Understand the basics of cyber laws

 In detail explained about the Role of IT Act

357
16.1 INTRODUCTION
In this unit we will learn Collections in Java , Introduction to Java Beans and
Network Programming.

16.2 COLLECTIONS IN JAVA

Collections in Java
1. Java Collection Framework

2. Hierarchy of Collection Framework

3. Collection interface

4. Iterator interface

The Collection in Java is a framework that provides an architecture to store


and manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque) and classes (ArrayList

, Vector, LinkedList
, PriorityQueue
, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java

A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java

o It provides readymade architecture.

o It represents a set of classes and interfaces.

o It is optional.

358
What is Collection framework

The Collection framework represents a unified architecture for storing and


manipulating a group of objects. It has:

1. Interfaces and its implementations, i.e., classes

2. Algorithm

16.3 INTRODUCTION TO JAVA BEANS

JavaBean

A JavaBean is a Java class that should follow the following conventions:

o It should have a no-arg constructor.

o It should be Serializable.

o It should provide methods to set and get the values of the properties, known as
getter and setter methods.

Why use JavaBean?

According to Java white paper, it is a reusable software component. A bean


encapsulates many objects into one object so that we can access this object from
multiple places. Moreover, it provides easy maintenance.

Simple example of JavaBean class


//Employee.java

package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}

359
}
How to access the JavaBean class?

To access the JavaBean class, we should use getter and setter methods.

package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
System.out.println(e.getName());
}}

Note: There are two ways to provide values to the object. One way is by constructor
and second is by setter method.

JavaBean Properties

A JavaBean property is a named feature that can be accessed by the user of the object.
The feature can be of any Java data type, containing the classes that you define.

Nested Structure in C
Keep Watching

A JavaBean property may be read, write, read-only, or write-only. JavaBean features


are accessed through two methods in the JavaBean's implementation class:

1. getPropertyName ()

For example, if the property name is firstName, the method name would be
getFirstName() to read that property. This method is called the accessor.

2. setPropertyName ()

For example, if the property name is firstName, the method name would be
setFirstName() to write that property. This method is called the mutator.

Advantages of JavaBean

The following are the advantages of JavaBean:/p>

o The JavaBean properties and methods can be exposed to another application.

360
o It provides an easiness to reuse the software components.

Disadvantages of JavaBean

The following are the disadvantages of JavaBean:

o JavaBeans are mutable. So, it can't take advantages of immutable objects.

o Creating the setter and getter method for each property separately may lead to
the boilerplate code.

16.4 NETWORKING

Java networking

This unit familiarizes us to Networking in Java. Terms like TCP\IP,


URL,Inetaddress, Domain name, etc. are explained with simple examples.
Objectives
 Introduction to Networking
 Datagram
 TCP/IP
 URL
 JDBC

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

361
certain set of rules called protocals.java networking is done using TCP/IP protocol.
Some of the different kinds of protocols available are HTTP (Hyper Text Transfer
Protocol – enables Interaction with the internet), FTP (File Transfer Protocol - enables
transfer of files between Computers), SMTP (simple Mail Transfer Protocol —
provides e-mail facility) and NNTP (network news transfer Protocol — acts as a
bulletin board for sharing news).
Socket
Sockets can be understood as a place used to plug in just like electric sockets.in case
of electric sockets, if a toasters plug is plugged into a socket, communication start at
the time. It is essential that they should follow a set of rules to communicate called
protocals.Assuming that the toaster has been plugged in the socket at the kitchen, the
power grid of the house should know the point of communication or the address of the
socket. A network socket can be similarly understood. Here TCP/IP as protocol for
communication and IP addresses are the addresses of the sockets.
Specific ports are assigned to some protocols by TCP/IP A few examples are port
number 21 is assigned for FTP, 23 is assigned for Telnet, 25 is assigned for e-mail, 80
for HTTP and so on. Each protocol establishes specific set of rules to communicate.
For example, to transfer hypertext pages and images, Web browsers and servers use
the HTTP protocol.
Client / Server
A computer, which requests for some service from another computer, is called a client
.The one that processes the request is called as Server. A server waits till one of its
clients makes a request. It can accept multiple connections at a time to the same port
number. Multithreading is used to serve multiple users at the same time.
Internet Address
Every computer connected to a network has a unique IP address. It is similar to every
student of a batch having a unique id. An IP address is a 32-bit number which has four
number separated by periods.It is possible to connect to the Internet either directly or
by using internet service provider.by connecting directly to the Internet, the computer
is assigned with a permanent IP address. In case connection is made using ISP,it
assigns a temporary IP address for each session. A sample IP address is given below.

362
Domain Naming Service
It is very difficult to remember a set of numbers (IP address) to connect to the
Internet. The Domain Naming Service (DNS) is used to overcome this problem. It
maps one particular IP address to a string of characters. For example,
"www.mascom.com" implies com is the domain name reserved for US commercial
sites, mascom is the name of the company and www is the name of the specific
computer, which is mascom’s server.
InetAddress
There are classes provided in Java to enable networking. They are found In the
java.net package. InetAddrese is one such class, which is used to encapsulate the IP
address and the DNS. To create an instance of inetaddress class, factory methods are
used as there are no visible constructors available for this class. Factory methods are
conventions where static methods return an instance of that class.
Methods
Static InetAddress getlocalHost() Return InetAddress object representing
local host.
Static inetaddress getbyname(string Return InetAddress for the host passed to
hostname) it.
Table 16.1
Both the methods throw UnknownHostNamEexception, if they are unable to local the
host.
The following program illustrates the creation of an inetaddress object.
Example 16.1
 Open a new file in the editor and enter the following code:

import java.net,*;
class InetAddresstest{
public static void main(string args[]) {
try {
InetAddress add=InetAddress.getlocalhost();

363
System.out.printin(‘’address of local host is : “” + add);
} catch (unknownhostexception u) {}
}
}
 Save the file as inetaddresstest.java
 Compile the file using javac inetaddresstest.java
 Run the file using java inetaddresstest

The output appears as shown below:


Address of local host is : grd-32/80.0.0.32

Datagram
Datagram is a type of packet that represents an entire communication. There is no
necessity to have connection or disconnection stages when communicating using
datagram. This is less reliable than communication using TCP/IP.
There are two classes in Java, which enable communication using datagrams,
DatagramSocket is the class, which acts as the data container, and DatagramSocket is
a mechanism used to send or receive DatagramPackets.

DatagramPacket
A DatagramPacket object can be created as follows.
Constructors
DatagramPacket (byte data [], int size)
The above constructor takes a byte array and its size as its parameter.
DatagramPacket (byte data[], int size, InetAddress I, int port)
In addition to the byte array and its size, the above constructor takes the InetAddress
and the port as its parameters.
DatagramSocket
The class DatagramPacket does not provide methods to send or receive data. This job
is taken up by the Datagram socket class. Listed below are its constructors and some
of its methods.
Constructors

364
The creation of a DatagramSocket object throws a SocketException, which must be
handle.
There are two constructors of DatagramSockets class, the first constructor does not
take any parameters and is created as given below:
Datagramsockets s= new datagramsockets ();
The next constructor is given as follows.
DatagramSocket s=new DatagramSocket (int port);
Methods
send (DatagramPacket d) Dispatches the given DatagramPacket
object
receive(DatagramPacket p) Receives the given DatagramPacket
object
Close() Close the socket connection
Table 16.2
Note: The send and receive methods of the DataFramSockets class throw an
IOException which must be caught.
Example 16.2 contains a program code for client and server using Datagram. Any
string entered as input in the window running the server program is displayed in the
client’s window. The user has to enter “end’’ to exit the server program and press
Ctrl+C to exit the client program. Note the client and the server program should run
on the same machine. Open two instances of the MS-DOS prompt and simultaneously
run both the programs.
Example 16.2
 Open a new file in the editor and enter the following code:

Input/
Output
1: import java.net.*;
2: import java.io.*;
3: class datagramclient {
4: public static datagramsocket ds;
5: public static byte buffer[]=new byte[1024];
6: public static int clientport =789,serverport=790;
7: public static void main(string args[]) throws Exception {

365
8: ds=new datagramsocket(clientport);
9 System. out .printin( "Client je waiting for server to send data’’);
10: system. out .printin("pres® ctrl4c to come to dos prompt");
11: while(true) {
12: DatagramPacket p= new patagramPacket (buffer, buffer.length);
13: de. receive (p);
14 String pex=new string (p.getData(),0,p.getLength());
15: system. out .print1n (psx);
16: }
17: }
18: }
Note: The line numbers given are not part of the source code and should not be
typed so.
 Save the file as DatagramClient.java
 Compile the file using javac DatagramClient.java
 Run the file using java DatagramClient

The first few lines of output appear as shown below:


Client is waiting for server to send data
press Ctrl+C to come to dos prompt
The client program creates a DatagramSocket at clientport,(say 789,which can be any
random number) and a serverport(say 790, which also can be any random number).As
mentioned earlier, creation of a DatagramSocket object throws an exception, which
has to be caught. throws Exception phrase is used at this junction. The socket created
with 789 as port number waits till the server sends in input. The Datgrampacket object
stores the information in packets obtained from the receive method. This information
is converted to string and displayed.
Open another new file in the editor and type the following code:
1: import java.net.*;
2: import java.io.*;
3: clase DatagramServer {
4: public static DatagramSocket ds;
5: public static int clientport =789, serverport=790;
7: byte buffer[]=new byte [1024];

366
8: ds=new DatagramSocket (serverport) ;
9: BufferedReader dis=new buffereader(new Inputstreamreadersystem.in));
10: system.out.printin(‘’server waiting for input’’);
11: inetaddress ia=inetaddress.getbyname(‘’localhost’’);
12: while(true) {
13: string str- dis.readline();
14: if((str==null // str.equals(‘’end’’)) }
15: break;
16: buffer=str.getbytes();
17: ds.send(new Datagrampacket(buffer,str,length(),ia,clientport));
18: }
19: }
20: }

 Save the file as Datagramserver.java


 Open another instance of MS-DOS prompt
 Compile the file using javac Datagramserver.java in that instance
 Run the file using java Datagramserver

Note: The line numbers given are not part of the source code and should not be
typed so.

The first line of output appears as shown below:


Server waiting for input
Let us type the following lines on the server side:
This is a test
It is used to test how the data is transferred to the client
When we press the Enter key after each line, the line appears on the client side.
The above program demonstrates a server using Datagram. Note that the same
clientport and serverport are used. The inetaddress of the local machine is obtained. A
DatagramPacket object is created using this inetaddress and the clientport at line
number 17.the object thus created is dispatched to client using the send method.

367
TCP/IP
TCP/IP sockets are the most reliable, bi-directional, stream protocols. It is possible to
send arbitrary amounts of data using TCP/IP. Sockets are used for data
communication using this protocal. There are two kinds of sockets in Java - a server
and a client. The ServerSocket class is used by the server to wait for the client and the
client connects to the server using Socket class.
Socket Class
A socket object establishes connection between the client and the server. Given below
are its constructors and some of the methods associated with it.
Constructors
The first constructor takes the hostname and port as its parameters to create a socket
object. Creation of a Socket object throws an UnknownHost Exception or an
IOException which must be caught.
Socket s= new Socket (String hostName, int port);
The next constructor takes the Inetaddress and port number as its parameters s to
Socket Object. The constructor throws an IOException or an UnknownHost
Exception which must be caught and handled.
Socket s=new Socket (InetAddress a, int port);
Methods
InetAddress getInetAddress() Returns Inetaddress associated with
socket
object

Int getPort() Returns remote port to which this socket


object is connected

Int getLocalPort() Return the local port to which the socket


object is connected

InputStream getInputStream() Returns the InputStream associated with


this socket

368
OutputStream getOutputStream() Returns the output Stream associated
with this socket
void close() Closes both Input stream and Output
Stream
Table 16.2
ServerSocket Class
The ServerSocket object waits for the client to make a connection. An object of this
class registers itself as having an interest in client connections. Apart from using the
methods listed above, this class has accept () method which is used to wait for a client
to initiate communications. The normal Socket object is used for further transfer of
data.
Constructors
There are two types of constructors available. The first constructor accepts a port
number as parameter to create a ServerSocket object on that port. Creation of this
object throws an IOException, which must be caught and handled.
ServerSocket ss=new ServerSocket (int port);
The next constructor accepts a port and maximum queue length as parameters. The
queue length indicates the maximum number of client connections that the system can
have before refusing further connections.
ServerSocket ss=new ServerSocket (int port, int maxqu);
The following example has code for a server and client program. Use two instances of
MS-DOS prompt, run the client program on one window and the server program on
the other. Note that the client and the server program should run on the same machine.
Run the FileSarver before running the FileClient program. This program displays the
contents of thefile specified in the server on to the client. Ensure that the specified file
exists in the same directory as the server program.
Example 16.3
 Open a new file in the editor and enter the following code:

1. import java.net.*;
2. import java.io.*;
3. public class FClient {
4. public static void main(string[] args) throws IOException (
5. Socket echoSocket = null;

369
6. BufferedReader in = null;
7. try {
8. echoSocket = new socket (Inetaddress.getLocalHost (),95);
9. in = new BufferedReader (new Input StreamReader (echoSocket .get Input
Stream() )) ;
10. } catch (UnknownHostException e) {
11. system.err.print1n("Don't know about host");
12. System. exit (1) ;
13. } catch (IOException e) {
14. system.err.printin("Couldn't get I/O for the connection");
15. System.exit (1);
16: }
17: String userInput;
18: while ((userInput = in.readLine() ) != null) {
19: System.out.println(userInput) ;
20: }
21: in.close();
22: echoSocket .close();
23: }
24: }
Note: The line numbers given are not part of the source code and should not be
typed so.

 Save the file as FClient.java


 Compile the file using javac Felient.java
 Run the file using java FClient
 Start the Notepad application and type the following line:

Welcome to socket programming, hope you enjoy this


 Save the file as soc.txt

A new socket object is created using the local host name and the port number. To read
the Input sent from the server, a Buffered Reader object is created, The get Input
stream of the socket class is used to obtain the input stream from the server .

370
 Open another new file and type the following code:

1: import java.net.*;
2: import java.io.*;
3: public class Fserver {
4: public static void main(String[] args) throws IOException {
5: serversocket serverSocket = null;
6. try {
7: serversocket = new ServerSocket (95);
8: } catch (IoException e) {
9: system.err.println("Could not listen on port:95.");
10. System.exit (1);
11. }
12. Socket clientSocket = null;
13. try {
14. clientSocket = serverSocket .accept ();
15. system.out.printIn("Connected to:" + clientSocket) ;
16. } catch (IOException e) {
17. System.err.println("“Accept failed.");
18. System.exit (1);
19. }
20: PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
21: String inputLine, outputLine;
22: bufferedReader stdin=new BufferedReader (new
inPutStreamReader (System. in) );
23: system.out Print In ("enter data in server");
24: string s=stdin.readline();
25: file f=new file(s);
26: if(f.exists()) {
27: bufferedreader d=new bufferedreader(new Filereader(s));
28: string line;
29: while((line=d.readline()) !=null) {
30: out.write(line);

371
31: out.flush();
32. }
33. d.close();
34. }
35. out.close();
36. elientsocket .close();
37. serverSocket ,close();
38. }
39. }
Note: The line numbers given are not part of the source code and should not be
typed so.

 Save the file as FServer.java


 Open another instance of MS-DOS prompt
 Compile the file using javac FServer.java
 Run the file using java FServer

The ServerSocket object waits for a client to make a connection at some port number
95.Once a client makes a connection, the accept method is called to accept the
connection, after which a message is displayed giving details about the local port
number. Client address and the port number of the client.
The server program requests for a file name. This file must be present in the current
working directory. A check is made at the server end and if the file exists, the data is
read by the socket object using the getInputstream method. The transfer of data
between the client program and the server program takes place using the socket
object. The client end displays the file contents. Both the programs terminate after the
request is serviced.
The output from both ends is shown below.
C:\>java FServer
Connected to ‘Socket [addr=GAYA/130.2.0.164, port=1100, localport-=95]
enter data in server
Let us give the input as soc.txt
C:\>java FClient

372
Welcome to socket Programming, Hope you enjoyed this
In the ouput shown above, GAYA is the name of the machine and 130.2.0.164 is its
IP address.

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

Components of URL

The URL has four components-the protocal. IP address or the hostname, port number
and actual file path. The protocols may be http, smtp, nntp, ftp or gopher. The most
commonly used protocal of the web is the hypertext transfer protocal (HTTP). The IP
address is delimited on the left by double slashes (//) and on right by a slash (/) or a
colon. The component, port, is optional and is delimited on the left by a colon and on
the right by a slash. The last component specifies the actual file path.
Given below is an example of an url.
http://www.freeway.com:80/root/htmlfiles/index.html
http is the protocal.www.freeway.com is the host name,80 is the port number and the
file index.html is stored under root/htmlfiles directory.
Constructors
There are four constructors and creation of URL, object throws a
MalefromedURLExceptions.
The first constructor takes the urlname as parameter and creates an object. This is the
most commonly used constructor to create the URL object.
URL u = new URL (String urlname) ;
The next constructor takes the name of the protocol, host name, port number and the
file path as parameters.
URL u=new URL (String protocolname, String hostname, int port, String path);

373
The third constructor accepts three parameters as given below.
URL u=new URL(String protocolname, String hostname, String path);
The last constructor accepts the URL object and a string.
URL u=new URL(URL urlobj, String urlspecifier);
Methods
Returns specified port number in URL /
get Port () returns —1 if port is not explicitly set .

getHost () Returns host name specified in URL


getFile() Returns the path of file specified in URL
openstream() Opens file specified in the URL
Table 16.3
URLConnection
URL Connection is a general-purpose class, which provides methods to know more
about the remote resource.
Methods
openconnection returns a URLConnection object associated
with URL object

Getcontenttype()
returns content type & returns null if not
known .

Getlastmodified() Returns last modified date of object & 0 if


not known

Getcontentlenght() returns length of content &-1 if not known

Table 16.4

16.9 SUMMARY
 In this unit the Network one of the main attractions in java, is possible
through the use of java.net package.

374
 Communication between computers is a network or a different network
requires certain set of rules called protocals.
 A computer, which requests for some service from another computer, is
called a client and the one, which processes the request, is called as server.
 Domine naming service9DNS) is used to map one particular IP address to
a string of characters.

 Inetaddress is a class, which is used to encapsulate the IP address and the


DNS.

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


Datagrampacket is the class , which acts as the data container, and
datagramsocket is a mechanism used to send or receive datagrampackets.

 TCPAP sockets are the most reliable, bi-directional, stream protocols. The
server to wait for the client uses the serverSocket class and the client to
connect to the server uses the socket class.
 The URL class helps in locating files on the Net using their addresses class is
a general . URLConnection class is a general -purpose class that provides
methods to know more about the remote resource.

16.10 KEYWORDS

 Java Beans, Networking , Datagram , TCP/IP, URL, JDBC

16.11 QUESTIONS FOR SELF STUDY


1. Explain Collections in Java
2. Write s note on Java Beans
3. Discuss Network Programming
4. Find more details on SMTP and FTP protocols.
5. Write a program to display the host name, port number and the file name of a
file found in a remote server. (use URL class and its methods)

375
6. Write an applet to display the home page of any html file using URL class.
(Hint : use getAppletContext() and showDocument() methods).
7. Write a code snippet where a ServerSocket waits for a connection from
clients. It should send a string “welcome to java networking” to all its
connected clients.
8. Write a code snippet where a Socket object prints the string on to the client.

9. Explain Protocols
10. What is a Datagram?
11. Give the Components of URL

16.13 REFERENCES

1. David J. Eck Introduction to Programming Using Java.


2. Elliotte Rusty Harold Java I/O published by O'Reilly
3. Ken Arnold, James Gosling . The Java Programming Language

4. Patrick, Naughton The Java Handbook

5. Dwight Deugo More java gems

6. Sun Microsytems Java tutorial,

7. E Balaguruswamy Programming with java

8. Schum series publications Programming in java

9. Doug Lea . Concurrent Programming in Java: Design Principles and Patterns

10. Jose M. Garrido Object-Oriented Programming: From Problem Solving to


Java
11. Bill Venners Object-Oriented Design with Java
12. E. Balaguruswamy Programming with java
13. Internet

376

You might also like