Somasekhara - OBJECT ORIENTED PROGRAMMING WITH JAVA - Sample Chapters
Somasekhara - OBJECT ORIENTED PROGRAMMING WITH JAVA - Sample Chapters
l
ia
Programming with
er
at
M
JAVA yr
ig
ed
ht
op
C
g
in
rn
ea
IL
PH
M.T. Somashekara
D.S.Guru
K.S. Manjunatha
Object Oriented Programming
with JAVA
l
ia
er
at
M
M.T. SOMASHEKARA
ed
Department of Computer Science and Applications
Bangalore University, Bengaluru
D.S. GURU ht
ig
Department of Studies in Computer Science
yr
University of Mysore, Mysuru
op
K.S. MANJUNATHA
Department of Computer Science
C
Delhi-110092
2017
l
ia
Contents
er
at
M
ed
Foreword xv
ht
ig
Preface xvii
Acknowledgements xix
yr
op
Summary 13
Review Questions 14
PH
l
3.4 Variables 27
ia
3.5 Data Types 27
er
3.6 Console I/O 28
3.7 Structure of a Java Program 31
at
3.8 Sample Program 31
3.9 Executing a Java Program 32
M
3.10 Errors 32
Summary 33
ed
Review Questions 34
ht
4. Operators and Expressions............................................................... 35–74
ig
4.1 Introduction 35
yr
4.2 The Assignment Operator [=] 36
4.3 The Arithmetic Operators [unary +, unary –, +, –, *, /, %] 37
op
4.4 The Relational Operators [<, <=, >, >=, ==, !=] 44
4.5 The Short Circuit Logical Operators [&&,||,!] 46
g
l
5.6 The Switch Statement 88
ia
5.7 Nested Switch Statement 96
er
Summary 98
Review Questions 98
at
True/False Questions 99
Programming Exercises 100
M
6. Iteration................................................................................................................102–135
ed
6.1 Introduction 102
The while loop 103
6.2
6.3 The for loop 109
ht
ig
6.3.1 Variations of for Loop 112
yr
6.4 The Do-While loop 114
6.5 Which Loop to Use When? 119
op
Summary 133
in
Review Questions 133
True/False Questions 134
rn
Programming Exercises 134
ea
7.1 Introduction 136
7.2 Class Definition Instance Variables and Member Methods 136
PH
l
ia
7.14.2 Static Nested Classes 178
7.15 Local Classes 179
er
7.16 Anonymous Classes 181
at
7.17 Final Members 182
7.18 Variable Arguments 184
M
7.19 Objects of One Class as Instance Variables of Another Class (Containment) 187
7.20 Garbage Collection and Finalise Method 189
ed
Summary 189
Review Questions 190
True/False Questions 191
Programming Exercises 192 ht
ig
yr
8. Inheritance..........................................................................................................194–234
8.1 Introduction 194
op
Summary 231
Review Questions 232
True/False Questions 233
Programming Exercises 233
9. Interfaces..............................................................................................................235–254
9.1 Introduction 235
9.2 Defining Interfaces 235
9.3 Implementing Interfaces 236
Contents ix
9.4 Polymorphism through Interfaces 239
9.5 Implementing an Interface Partially 240
9.6 Extending Interfaces 242
9.7 Implementing Multiple Interfaces 245
9.8 Multiple Inheritance through Interfaces 248
Summary 253
Review Questions 253
l
ia
True/False Questions 254
Programming Exercises 254
er
at
10. Packages.......................................................................................... 255–288
10.1 Introduction 255
M
10.2 Classification of Packages 255
10.3 Creating and Using a Package 256
ed
10.4 To Create a Package Spread across Multiple Files 258
10.5 Importing Classes from a Package (Hiding Classes in a Package) 260
10.6
10.7
Nested Packages 263
Extending Imported Classes 266 ht
ig
10.8 Classes and Interfaces in a Package and Using Them 267
yr
10.9 Static Importing 269
10.10 Access Control 274
op
Summary 287
in
Review Questions 287
True/False Questions 287
rn
Programming Exercises 288
ea
11. Arrays.....................................................................................................................289–339
IL
11.1 Introduction 289
11.2 One-dimensional Arrays 290
PH
l
ia
12.1 Introduction 340
er
12.2 The String Class 340
12.2.1 The Constructors of the String Class 340
at
12.2.2 The Member Methods of the String Class 342
M
12.3 The StringBuffer Class 350
12.3.1 The Constructors of the StringBuffer Class 350
ed
12.3.2 The Member Methods of the StringBuffer Class 351
Summary 354
Review Questions 354
True/False Questions 355 ht
ig
Programming Exercises 355
yr
13.1 Introduction 357
13.2 Types of Exceptions 357
C
l
14.6 Creating Our Own Threads 393
ia
14.6.1 Extending the Thread Class 393
er
14.6.2 Implementing Runnable Interface 395
14.7 Creating Multiple Children Threads 397
at
14.8 Forming Groups of Threads 401
14.9 Thread Priorities 403
M
14.10 Synchronisation 406
14.10.1 Synchronised Method 409
ed
14.10.2 The Synchronised Statement 412
14.11 Deadlock 415
14.12 Suspending and Resuming Threads 418
ht
ig
14.13 Producer-Consumer Relationship between Threads 426
14.14 Daemon Threads 433
yr
Summary 435
op
Review Questions 436
True/False Questions 436
Programming Exercises 437
C
15.1 Introduction 438
15.2 The File Class 439
rn
Summary 470
Review Questions 471
True/False Questions 472
Programming Exercises 472
16. Applets..................................................................................................................473–494
16.1 Introduction 473
16.2 Types of Applets 474
xii Contents
l
ia
Programming Exercises 494
er
17. Introduction to AWT.....................................................................................495–554
at
17.1 Introduction 495
17.2 AWT Hierarchy 495
M
17.3 Event Handling 496
17.4 AWT Controls 499
ed
17.4.1 Labels 499
17.4.2 Buttons 501
17.4.3 Checkbox 503
17.4.4 CheckboxGroup 506 ht
ig
17.4.5 Lists 509
yr
17.4.6 Choice Control 512
17.4.7 Scrollbar Control 514
op
17.4.8 TextField 519
17.4.9 TextArea 521
C
17.5.5 GridbagLayout 531
ea
17.5.6 Panels 531
17.6 AWT Window-Level Controls 534
IL
17.6.1 Windows 534
17.7 Handling Keyboard Events 541
PH
l
18.2.4 The Integer Class 559
ia
18.2.5 The Long Class 562
er
18.2.6 The Float Class 565
18.2.7 The Double Class 567
at
18.2.8 The Character Class 569
18.2.9 The Boolean Class 571
M
18.3 The System Class 572
18.4 The Object Class 574
ed
18.5 The Class Class 575
18.6 The Runtime Class 577
18.7 The Process Class 579
18.8 The Void class 579 ht
ig
18.9 The Math Class 579
yr
Summary 581
Review Questions 581
op
True/False Questions 582
C
Bibliography.................................................................................................................583–583
g
Index...............................................................................................................................585–590
in
rn
ea
IL
PH
l
ia
Foreword
er
at
M
ed
ht
Computer programming has evolved over the last six decades, starting from assembly language
ig
programming and progressing through simple procedural languages, block structured procedural
languages, object oriented languages, functional languages, and scripting languages. Each
yr
evolution was started by the prevailing hardware and the demand for applications. One major
op
evolution was the emergence of object oriented languages, which were later adapted to be
applicable in this era of the Internet in which diverse computers distributed all over the world
are interconnected.
C
Java, which was initially developed as a small object oriented language to program
embedded systems, evolved as a general purpose programming language to meet the needs of
g
programmers who were required to write programs which could be executed on the Internet.
in
Currently, Java is the programming language of choice in many industries, particularly those
rn
useful addition to the library of books on Java programming. The main merit of this book is
that it starts from basics and builds gradually to a substantially high level to enable students
IL
to write programs for Internet applications. All important concepts are illustrated with Java
programs, an important pedagogical tool. The book is well written with a number of learning
aids such as summary, review questions, true-false questions, and programming exercises. This
PH
book has been classroom tested by the experienced authors Dr. Somashekara, Dr. Guru, and
Mr. Manjunatha. The book is suitable for the undergraduate students of Computer Science.
I am sure students as well as working professionals will find this book an invaluable aid in
learning how to program using Java.
V. Rajaraman
Indian Institute of Science Bengaluru
xv
l
ia
Preface
er
at
M
ed
ht
The Java language is a general purpose and a purely object oriented language invented by a
ig
group of computer scientists at Sun Micro Systems during 1990s to meet the varied needs of
embedded world. The fascinating and principal features of the language such as object oriented,
yr
platform independence, architectural neutral, robust and security were needed to support the
op
development of embedded software for various electronic devices like TVs, refrigerators, etc.
Incidentally the same features were required to be supported for computing in the internet
world and also considering the heterogeneous nature of the computing devices employed in
C
the internet world. As a result, the Java language became very close to the internet computing
world. Because of its affinity to the internet, the language is referred to as the language of
g
the internet.
in
The book is expected to cater to the needs of both undergraduate and postgraduate students
rn
of Computer Science and Information Technology offered by Indian universities because the
contents of the book has been developed after paying due attention to the syllabi of various
ea
Indian universities. Another hallmark of the book is that it needs no previous knowledge of
programming. The book takes the reader from the basic principles of Java programming towards
IL
The book has been organised in well-planned 18 chapters. Chapter 1 introduces the object
oriented paradigm, its advantages and disadvantages; identifies the languages supporting the
object oriented paradigm; and also sets the tone for learning the Java language. Chapter 2
highlights the importance of the Java language by discussing the striking features offered by
it to align itself to support platform independence and thereby finding a predominant place
in the internet programming. Chapter 3 talks about the preliminaries of the Java language.
Chapter 4 discusses the operators supported by the Java language with suitable illustrations
for each kind of operators. Chapter 5 throws light on the selection structures supported by
xvii
xviii Preface
Java with examples and programs for each variation of the structures. Chapter 6 throws light
on the iterative structures supported by Java with examples and programs for each variation
of the structures. Chapter 7 introduces the concepts of classes, objects and methods, the core
concepts underlying the object oriented programming. Chapter 8 discusses another important
feature of OOP, the concept of inheritance in detail. Chapter 9 deals with the concept of
interfaces. Chapter 10 deals with the concept of packages, wherein we can logically group
classes and interfaces depending on the requirement. The concept of packages enables us to
l
ia
compartmentalise the classes and interfaces for better management of them. Chapter 11 delves
into the concept of arrays in detail. Here arrays of one dimension, two dimensions, three
er
dimensions and array of objects, and methods with arrays are explained in detail. Chapter 12
details string handling in Java. The detailed discussion includes various string manipulation
at
methods available in the String class and also the String buffer class. Chapter 13 delves into
M
exception handling mechanism supported by Java. It also discusses types of exceptions and the
ways they are handled. Chapter 14 focuses on multithreaded programming, which is one of the
striking features of Java supporting optimisation of the systems resources and enhancement of
ed
the speed of execution of programs. Chapter 15 provides a thorough discuss on IO-Streams
and their handling with the help of the built-in classes and their methods. Chapter 16 turns
ht
our attention towards applets, a special category of programs that are developed in Java and
ig
their relationship to web programming. Chapter 17 deals with the graphical user interface
facility provided by Java through a group of classes embodied in a toolkit called AWT toolkit.
yr
The toolkit contains a number of classes each representing a type of window control used
in the design of the graphical user interface. Chapter 18 details most of the commonly used
op
utility classes housed in the java.lang package which are used frequently while developing
applications with Java.
C
Almost all the chapters are followed by a brief summary of the concepts covered to
better enable the readers to consolidate their learning, review questions, true-false questions
g
Constructive criticism and suggestions from the readers are always welcome. They will
go a long way in further improvement of the book. In fact, this is how the knowledge and the
rn
M.T. Somashekara
D.S. Guru
PH
K.S. Manjunatha
16
l
ia
er
Applets
at
M
ed
ht
16.1 INTRODUCTION
ig
yr
All the Java programs developed so far in the previous chapters are called application programs
developed for the purpose of accomplishing a task. There is another type of programs which can
op
be developed using Java. They are called applets that run on WWW. The applets are small Java
programs written for the purpose of accomplishing a part of a task. The applets reside in web
C
pages in the WWW and they are executed by the web browsers when the web pages containing
them are loaded in the client systems. They are capable of displaying graphics, playing audio,
ng
etc. In all, the applets enable the Java programmers to provide the right graphical user interface.
As we have noticed, the Java applications are characterised by the following features:
i
2. They have main() method, from where the execution of the program starts.
ea
5. They can access the files and other resources at the local system, where they are
launched for execution.
PH
473
474 Object Oriented Programming with JAVA
3. Applets are run by Java enabled browsers and appletviewer tool shipped with the JDK.
4. They advocate graphical user interface.
5. Applets are web based programs.
l
ia
(i) Local applets and (ii) Remote applets.
er
Local applets, as the name itself indicates, are those that are created at the local system and
they can be run in the system.
at
Remote applets are those that are created in the remote systems and downloadable from the
M
remote systems to the local systems and they can be run.
As there are chances of security violations by the applets, certain restrictions are imposed
ed
on applets in the interest of the security of the systems. They are the following:
1. They cannot access the files and other resources at the local system for security
ht
reasons.
2. They cannot communicate with other servers in the network.
ig
3. They cannot execute other programs.
yr
The Applet class in the Java.applet package hierarchy is central to implementing the
applets.
The Java.applet.Applet class extends the Java.awt.panel class, the Java.awt.Container
C
class, the Java.awt.Component class and the Java.lang.Object class in a multilevel hierarchy.
The hierarchy is depicted in Figure 16.1.
i ng
rn
ea
IL
PH
The most commonly used methods in the Applet class are given in Table 16.1 and
important methods of the component class are given in Table 16.2.
Applets 475
dĂďůĞ ϭϲ͘ϭപMethods in the Applet class
l
ia
execution if the applet had been stopped earlier.
er
void stop() Stops the applet temporarily.
Informs the applet to destroy itself after releasing the resources
at
void destroy()
used by it.
M
AppletContext getAppletContext() Returns the context associated with the applet.
String getAppletInfo() Returns a string that describes the applet.
ed
AudioClip getAudioClip(URL url) Returns an AudioClip object for the audio clip found at the
location identified by URL.
ht
URL getCodeBase() Returns the URL associated with the applet.
ig
URL getDocumentBase() Returns the URL of the html document of the applet.
yr
Image getImage(URL url) Returns an Image object for the image found at the location
identified by url.
op
Image getImage(URL url, String Returns an Image object for the image found at the location
imagename) identified by url and with the same name as imagename.
C
String getParameter(String param) Returns the parameter associated with the name param. Returns
null if the parameter is not found.
ng
void play(URL url) Plays an audio clip found at the location identified by url.
i
void play(URL url, String clipname) Plays the audio clip found at the location identified by url
rn
void resize(Dimension d)
void showStatus(String str) Displays the string str in the status window of the browser
or the appletviewer. No action takes place if the browser or
IL
(Contd...)
476 Object Oriented Programming with JAVA
l
Sets the size of the component with the dimension d. The
ia
void setSize(Dimension d)
Dimension class has width and height as the data members.
er
void setSize(int width, int height) Sets the size of the component with the given width and height.
Dimension getSize() Retrieves the size of the component.
at
M
16.3 THE LIFE CYCLE OF AN APPLET
ed
An applet goes through a number of states from the point of its creation to the point of
destruction. They are: ht
1. Initialization state
2. Running state
ig
3. Idle state or stopped state
yr
4. Dead state
The life cycle of an Applet is shown in Figure 16.2.
op
C
i ng
rn
ea
IL
Initialisation State
When an applet is loaded into memory of the client machine by the web browser or the
appletviewer, the init() method of the applet of the Applet class is invoked. The execution of
the init() method brings the applet to the initialisation state. During the initialisation state, we
can initialise the required variables, create the required objects, load the required images and
fonts and set the required colours, etc. An applet assumes the initialisation state only once in
its life cycle. The initialisation behaviour of an applet can be realised by overriding the init()
method of the Applet class as follows:
Applets 477
void init()
{
// code for the expected behaviour here
}
Running State
l
ia
After the initialisation state, the start() method of the Applet class is invoked automatically.
Then the applet is said to have moved to the running state. The start() method also gets
er
invoked on the resumption of the execution of an applet automatically when the applet had
been stopped for a while (when we leave a web page temporarily and return back to the same
at
web page). We may override the start() method also of the Applet class to alter the course
M
of action of the applet as follows:
void start()
ed
{
// code for the expected behaviour here
ht
}`
ig
Soon after the applet moves into the running state, the applet’s paint() method gets
executed which displays the outputs in a window of the applet on the screen.
yr
op
Idle State
An applet enters into the idle state when its execution is stopped temporarily. Stopping the
C
execution of the applet can be done by leaving the web page containing the applet temporarily
or invoking the stop() method on the applet explicitly. An applet in the idle state can be brought
ng
back to running state by bringing the web page containing the applet into focus or by calling
the start() method on the applet explicitly. In essence, an applet can switch from idle state
i
Dead State
An applet enters into dead state when the web browser or the appletviewer invokes the destroy()
IL
method on the applet. The dead state is the final state of an applet. Normally the destroy()
method does not need to be overridden to reclaim the resources used by the applets as the
PH
Java has a built-in mechanism called garbage collector to do the job. However, if an applet has
created threads, the destroy() is overridden to release them. The overridden destroy() method
takes care of the expected behaviour has the following form:
void destroy()
{
// code for the expected behaviour here
}
478 Object Oriented Programming with JAVA
Painting
The process of displaying of outputs on the window of an applet is accomplished by paint()
method of the Applet class. In fact, the paint()in the Applet class method does nothing. It
needs to be overridden to display the required text, graphics on the window of the applet. It
gets called automatically whenever the applet gets into the running state. It also gets called
when the window of the applet is resized or when the window is moved from one location to
l
another location. The overridden paint() method takes the form as:
ia
void paint(Graphics g)
er
{
at
// painting code here
}
M
Note that the paint() method is the only method which takes an argument. Here the
argument is of type Graphics class. The package Java.awt which contains the class should be
ed
imported into the program. ht
16.4 CREATING AND EXECUTING AN APPLET
ig
There are four steps involved in creating and executing an applet. They are:
yr
2. Compiling the Java source file to get the equivalent class file (.class file)
3. Creating an html file
C
Here we create the Java source file namely AppletDemo.Java and write in it the required Java
ea
import Java.awt.*;
PH
import Java.applet.*;
public class AppletDemo extends Applet
{
public void paint(Graphics g)
{
g.drawString(“First Applet”, 100, 100);
}
}
Applets 479
The classes in the packages Java.awt and Java.applet are imported with the statements
import Java.awt.*; and import Java.applet.*;.
The public class AppletDemo extends the class Applet and it overrides the paint() method.
Note that the method paint() takes an object of type Graphics as its argument and in the body
of the method, the drawString() method of the Graphics class is invoked to display the string
“First Applet” at the position 75, 75 in the window of the applet.
l
ia
Compiling the Java source file
er
We compile the Java source file AppletDemo.java using the Java compiler Javac:
at
Javac AppletDemo.Java [return]
M
The class file AppletDemo.class is created on successful compilation of the source file
AppletDemo.Java.
<html>
<head>
C
<body>
ng
</body>
</head>
ea
</html>
IL
Here we use the appletviewer tool of the JDK to run the applet. Note that the input to the
appletviewer is the html file.
appletviewer AppletDemo.html [return]
The applet window appears as below on its execution.
480 Object Oriented Programming with JAVA
Output
l
ia
er
at
M
ed
ht
ig
yr
We can even embed the applet tag within the Java source file itself and make it a comment
op
and compile the source file using javac compiler and the program can also be run using the
Java tool appletviewer. The argument to the appletviewer is the Java source file itself.
C
Let us modify the AppletDemo.Java to have the applet tag as a comment and compile it
using Javac and execute it using the Java tool appletviewer.
ng
// AppletDemo1.Java
i
rn
import Java.awt.*;
import Java.applet.*;
IL
</applet> */
PH
l
ia
Output
er
at
M
ed
ht
ig
yr
op
C
i ng
rn
// AppletDemo2.Java
ea
import Java.awt.*;
import Java.applet.*;
PH
/*
<applet code = AppletDemo2.class Height = 200 width = 200>
</applet> */
public class AppletDemo2 extends Applet
{
public void paint(Graphics g)
{
int length, breadth;
482 Object Oriented Programming with JAVA
length = 10;
breadth = 5;
int area = length * breadth;
String str1 = “Length = “ + String.valueOf(length);
String str2 = “Breadth = “ + String.valueOf(breadth);
String str3 = “Area = “ + String.valueOf(area); String str = “Area = “ +
l
ia
String.valueOf(area);
g.drawString(str1, 50, 60);
er
g.drawString(str2, 50, 75);
at
g.drawString(str3, 50, 100);
}
M
}
ed
Javac AppletDemo2.Java [return] ht
Running the applet
ig
Appletviewer AppletDemo2.Java [return]
yr
Output
op
C
i ng
rn
ea
IL
PH
Applets 483
16.5 THE ATTRIBUTES IN THE <APPLET> TAG
Table 16.3 contains the attributes of the applet tag and their purposes.
dĂďůĞ ϭϲ͘ϯപAttributes of the applet tag and their purposes
Attribute Purpose
Specifies the URL of the directory where the applet resides. If
l
CODEBASE = codebase_URL (Optional)
ia
the applet and the html file reside in the same directory, then
the codebase attribute may be omitted.
er
CODE = AppletFilename.class Specifies the name of the applet class file and it should be
specified.
at
WIDTH = pixels Specifies the width of the applet window.
M
HEIGHT = pixels Specifies the height of the applet window.
NAME = instance name of the applet A name may be specified for an applet to identify it.
ed
(Optional) Naming of applets is useful in case of inter-applet communication.
ALIGN = alignment (Optional) Specifies the position of the applet on the webpage.
ht
This attribute can take any of the following values:
TOP, BOTTOM, LEFT, RIGHT, MIDDLE, ABSMIDDLE,
ig
ABSBOTTOM, TEXTTOP, BASELINE
Specifies the amount of horizontal space surrounding the applet.
yr
LEFT or RIGHT.
VSPACE = pixels (Optional) Specifies the amount of vertical space surrounding the applet .
This is used only when the attribute ALIGN is set to either
C
TOP or BOTTOM.
Non-Java browsers will display this text.
ng
<APPLET
[CODEBASE = codebase_URL]
ea
CODE = AppletFileaname.class
[ALT = alternate text]
IL
HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels]
[HSPACE = pixels] >
[ <PARAM NAME = param1 VALUE = value1> ]
[ <PARAM NAME = param2 VALUE = value2> ]
……………………
…………………
</APPLET>
17
l
ia
Introduction to AWT
er
at
M
ed
ht
17.1 INTRODUCTION
ig
One of the notable things of the Java programming language is its ability to support graphical
yr
user interface (GUI). We have already seen the usage of the GUI elements like textboxes,
buttons, labels, etc. that are used in applets in the previous chapter. These are user friendy as
op
they offer ease of use and flexibility to interact with the applets. A separate package namely
java.awt is dedicated for the purpose of encapsulating the facility of GUI elements like labels,
C
buttons, textfields, scrollbars, lists, choices, etc. Each of these controls is implemented with
the help of a separate dedicated class. All these classes are held in the java.awt package. The
ng
AWT facility uses the native GUI support of the system. It provides an abstraction of the
native GUI and thus offers flexibility to the programmers shielding the internal details of the
i
native GUI. The package java.awt should invariably be imported into the program which uses
rn
The AWT hierarchy comprises of a number of classes useful for creating and using the AWT
controls like Labels, TextField, TextArea, List, Choice, Window, Frame, Dialog, etc. The
PH
Figure 17.1 depicts the hierarchy of the classes for the AWT components.
Component
Component is the super class for all the classes related to AWT components. It represents an
object having graphical representation that can be displayed on the screen and the user can
interact with it. It has a number of methods for various operations like event handling, managing
graphics, dealing with size of the component, etc. Labels, Buttons, Choices and Lists are all
examples of components.
495
496 Object Oriented Programming with JAVA
l
ia
er
at
M
&ŝŐƵƌĞϭϳ͘ϭപAWT window hierarchy.
Container
ed
ht
A Container is a component which can hold other components. Examples of Containers in the
ig
GUI are Frames, Dialogs, Windows and Panels. All these are inherited from the Container class.
All the other components are discussed in detail in the sections to follow:
yr
op
Central to interaction with the GUI elements used by Java applets and Java applications are
handling the events generated by the GUI elements. An event is defined to be a change in the
state of an object. The object which generates the events is called the event source. Examples
ng
for event sources include the input devices such as keyboard, and mouse. The event sources
also include all the AWT controls like Button, TextField, List, Choice, Scrollbar, etc. In the
i
rn
section to follow, we delve into the details of all the events and their sources.
ea
The delegation event model is the modern and sophisticated approach towards handling events
generated by different sources. Here the sources are registered with predefined interfaces
designated as event listeners, which embody the signatures of the methods responsible
PH
for handling the events. The events handling is delegated to classes, which provide the
implementation for the methods. Hence here we see a clean separation between the events
sources and the event handlers.
Event source is registered with event listener implemented by event handler.
Registering an event listener for an event source is done with the method:
void addEventListener(EventListener el)
We can even unregister an event listener, if need be. Unregistering an event listener for
an event source is done with the method:
/ŶƚƌŽĚƵĐƟŽŶƚŽtd 497
void removeEventListener(EventListener el)
The event handler class has the following form:
class classname implements EventListener
{
Methods for handling the events
}
l
ia
Let us now get to know the participants in the delegation event model which play their
roles in handling events in a clean and efficient way. The participants include event classes,
er
events, event listeners and event handling methods.
at
Table 17.1 shows the list of events and the situations in which the events are generated.
M
dĂďůĞ ϭϳ͘ϭപName of the event class and situation in which the event is generated
ed
ActionEvent Whenever a menu item is selected or ENTER key is pressed, a list item is
double-clicked in a TextField or in a TextArea
ht
AdjustmentEvent Whenever a scrollbar is manipulated
Whenever a component is hidden, moved, resized and made visible
ig
ComponentEvent
ContainerEvent Whenever a component is added or removed from a container
yr
MouseEvent Whenever the mouse is dragged, moved, pressed, released and when the
mouse enters or leaves a component
i
or closed
IL
(Contd...)
498 Object Oriented Programming with JAVA
l
MouseEvent MouseListener
ia
TextEvent TextListener
er
WindowEvent WindowListener
at
Each event is associated with one or more methods for handling the event. Table 17.3
shows the list of events and the corresponding event handling methods.
M
dĂďůĞ ϭϳ͘ϯപEvents and event handling methods
ed
Events Event handling methods
ht
ActionEvent actionPerformed()
AdjustmentEvent adjustmentValueChanged()
ig
ComponentEvent componentHidden()
yr
componentMoved()
componentResized()
componentShown()
op
ContainerEvent componentAdded()
componentRemoved()
C
FocusEvent focusGained()
focusLost()
ng
ItemEvent itemStateChanged()
KeyEvent keyPressed()
i
keyReleased()
rn
keyTyped()
MouseEvent MouseClicked()
ea
MouseEntered()
MouseExited()
MousePressed()
IL
MouseReleased()
MouseDragged()
MouseMoved()
PH
TextEvent textValueChanged()
WindowEvent windowActivated()
windowClosed()
windowClosing()
windowDeactivated()
windowIconified()
windowDeiconified()
windowOpened()
/ŶƚƌŽĚƵĐƟŽŶƚŽtd 499
17.4 AWT CONTROLS
The AWT controls that can be placed on the containers like Labels, Buttons, TextFields, etc.
are discussed with the supporting programs in detail here.
17.4.1 Labels
l
A Label is a control used for holding a static text. It is usually placed before a control which
ia
can hold text that can be changed, for instance a TextField. For example, a label with the
er
text “Name:” is placed before a TextField which is meant for receiving a string for the name
of a person from a user.
at
Following are the constructors of the Label class which may be used for creating a label:
M
Label()
Creates a label with no string assigned to it.
ed
Label(String s)
Creates a label with the string s assigned to it.
ht
ig
Label(String s, int align)
Creates a label with the string s assigned to it and also sets the alignment of the string
yr
within the label through the argument of int type align. The possible values that can be taken
by the int argument align are LEFT, RIGHT and CENTRE to indicate that the string in the label
op
void setText(String s)
Sets the text of a label with the string s.
i
rn
String getText()
Retrieves the text of a label.
ea
l
ia
er
[java.lang Package]
at
M
ed
ht
18.1 INTRODUCTION
ig
yr
The java.lang package houses a number of classes that are of importance. Here we discuss
some of the most frequently used classes and their methods in a reasonable detail.
op
A Wrapper class is one which wraps a primitive type within it. As there are eight primitive
ng
types in Java, there are eight wrapper classes, one for each primitive type. They are Byte,
Short, Integer, Long, Float, Double, Character and Boolean for the primitive types byte, short,
i
int, long, float, double, char and boolean respectively. The wrapper classes provide the ability
rn
to create object representations to the primitive types. The objects of wrapper classes are
ea
The Number class is the abstract class which is used as the super class for all the wrapper
PH
classes. Table 18.1 shows the list of abstract methods available in the class which are to be
implemented by the wrapper classes.
Boolean(String str)
Creates an object of Boolean class wrapping the boolean value extracted out of the argument
str of String type.
Example 2:
Boolean bt = new Boolaen(“false”);
l
Creates the object bt of Boolean type with the boolean value false.
ia
Table 18.9 depicts the methods of the s class.
er
dĂďůĞ ϭϴ͘ϵപDĞƚŚŽĚƐ ŽĨ Ɛ ĐůĂƐƐ ǁŝƚŚ ƚŚĞŝƌ ƉƵƌƉŽƐĞƐ
at
Methods Purposes
M
boolean booleanValue() Returns the Boolean value equivalent
boolean equals(Object bool) Returns true if the invoking object is equivalent to the
ed
object bool, otherwise, it returns false
String toString() Returns the string equivalent of the invoking object
ht
Static boolean valueOf(String bool) Returns true if the string bool contains the string either
“true” or “TRUE”, otherwise it returns false
ig
yr
The following program illustrates the Boolean class by displaying the values of the constants
Boolean.TRUE, Boolean.FALSE and Boolean.TYPE to be true, false and Boolean respectively.
op
{
public static void main(String s[])
{
i
rn
System.out.println(“Boolean.TRUE = “ + Boolean.TRUE);
System.out.println(“Boolean.FALSE = “ + Boolean.FALSE);
ea
System.out.println(“Boolean.TYPE = “ + Boolean.TYPE);
}
IL
Output
PH
Boolean.TRUE = True
Boolean.FALSE = False
Boolean.TYPE = Boolean
l
}
ia
Output
er
Total Memory = 12189696
at
Free Memory = 11682696
Used Space = 507000
M
Maximum Memory = 192610304
ed
18.7 THE PROCESS CLASS ht
The Process class is an abstract class in the java.lang package. It encapsulates a process,
which is a program in the status of execution. The class process acts as a super class for the
ig
objects created by the method exec() in the Runtime class of the same Java package.
yr
The Process class contains a number of abstract methods. Following are the frequently
used methods of the Process class (Table 18.14).
op
Methods Purposes
Terminates the process
ng
void destroy()
int exitValue() Returns the exit code obtained from a subprocess
i
InputStream getInputStream() Returns an input stream that reads input from the out output
rn
OutputStream getOutputStream() Returns an output stream that writes output to the in input stream
of the process
Returns an input stream that reads input from the err output
IL
InputStream getErrorStream()
stream of the process
PH