0% found this document useful (0 votes)
81 views33 pages

Somasekhara - OBJECT ORIENTED PROGRAMMING WITH JAVA - Sample Chapters

This document provides an introduction to object oriented programming and the Java programming language. It covers topics like the evolution of OOP, principles of OOP, features of Java, data types, operators, selection, iteration, classes and objects in Java.

Uploaded by

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

Somasekhara - OBJECT ORIENTED PROGRAMMING WITH JAVA - Sample Chapters

This document provides an introduction to object oriented programming and the Java programming language. It covers topics like the evolution of OOP, principles of OOP, features of Java, data types, operators, selection, iteration, classes and objects in Java.

Uploaded by

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

Object Oriented

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

Maharani’s Science College for Women, Mysuru


g
in
rn
ea
IL
PH

Delhi-110092
2017
l
ia
Contents

er
at
M
ed
Foreword  xv
ht
ig
Preface  xvii
Acknowledgements  xix
yr
op

1. Introduction to Object Oriented Programming Paradigm............... 1–14


1.1 Introduction  1
C

1.2 Evolution of Higher Level Languages   1


1.2.1 The General Topology of Object Based and Objects Oriented Language   4
g

1.3 Complexity of Softwares and their Attributes   5


in

1.4 Object Orientated Programming Paradigm    7


rn

1.4.1 Basic Principles of Object Oriented Programming   8


1.4.2 Advantages of Object Oriented Programming   12
ea

1.4.3 Applications of Object Oriented Programming   12


1.4.4 Object Oriented Programming Languages   13
IL

Summary  13
Review Questions  14
PH

2. Introduction to the JAVA Language............................................................15–20


2.1 Introduction  15
2.2 Evolution of Java   15
2.3 Salient Features of Java Language   16
2.4 Java, Internet and World Wide Web   19
2.5 The Java Environment    19
Summary  20
Review Questions  20
v
vi Contents

3. The JAVA Language Preliminaries...............................................................21–34


3.1 Introduction  21
3.2 Keywords and Identifiers   22
3.3 Constants    23
3.3.1 Numeric Constants  23
3.3.2 Character Constants  26

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.3.1 Types of Arithmetic Expressions   40


4.3.2 Precedence of Arithmetic Operators and Associativity   41
C

4.4 The Relational Operators [<, <=, >, >=, ==, !=]  44
4.5 The Short Circuit Logical Operators [&&,||,!]  46
g

4.6 The Arithmetic Assignment Operators [+=,  –=,  *=,  /=,  %=]  49


in

4.7 The Increment/Decrement Operators [++,  ––]  51


4.8 The Conditional Operator [?:]  53
rn

4.8.1 Nesting of Conditional Operators   54


ea

4.9 The InstanceOf() Operator   55


4.10 The Dot Operator [.]  56
4.11 The Bitwise Operators [ &,  |,  ^,  ~,  <<,  >>,  >>>]  56
IL

4.11.1 Application of Bitwise Operators   62


PH

4.12 Type Conversion   64


4.13 Precedence Levels and Associativity among all the Operators   69
Summary  70
Review Questions  70
True/False Questions  73
Programming Exercises  73
Contents vii
5. Selection................................................................................................................. 75–101
5.1 Introduction  75
5.2 The Simple if Statement   76
5.3 The If-Else Statement   78
5.4 The Nested  If-Else Statement   80
5.5 The else-if Ladder   82

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

6.6 Jumps in Loops   119


6.7 Nesting of Loops   124
C

6.7.1 Jumps in Nested Loops   127


6.8 Labeled Loops   132
g

Summary  133
in

Review Questions  133
True/False Questions  134
rn

Programming Exercises  134
ea

7. Classes, Objects and Methods....................................................................136–193


IL

7.1 Introduction  136
7.2 Class Definition Instance Variables and Member Methods   136
PH

7.3 Declaration and Creation of Objects, Accessing Members   137


7.4 Classification of Member Methods   139
7.5 Constructors    147
7.5.1 Constructors without Arguments   147
7.5.2 Constructors with Arguments   149
7.5.3 Copy Constructors   151
7.6 The this Keyword   153
7.7 Passing Objects to Methods as Arguments   154
7.8 Methods Returning an Object   157
viii Contents

7.9 Static Member Data   162


7.10 Static Member Methods   167
7.11 Static Blocks   169
7.12 Nesting of Member Methods   170
7.13 Recursion  172
7.14 Nested Classes    176
7.14.1 Non-static Nested Classes or Inner Classes   176

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

8.2 Types of Inheritance   198


8.2.1 Single Level Inheritance   198
C

8.2.2 Multilevel Inheritance   201


8.2.3 Multiple Inheritance   206
g

8.2.4 Hierarchical Inheritance   207


in

8.2.5 Hybrid Inheritance   212


rn

8.3 Constructors and Inheritance   213


8.4 Abstract Classes and Methods   217
ea

8.5 Dynamic Method Dispatch   222


8.6 Object Slicing   226
IL

8.7 Object Typecasting   228


8.8 The Final Keyword   230
PH

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

10.10.1 Private Access   274


10.10.2 Default Access   276
C

10.10.3 Protected Access   278


10.10.4 Public Access   282
g

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

11.3 Multi-dimensional Arrays   306


11.3.1 Two-dimensional Arrays (2-D arrays)   307
11.3.2 Three-dimensional Arrays   313
11.4 Arrays and Methods   318
11.4.1 One-dimensional Arrays as Arguments to Methods    318
11.4.2 Passing Two-dimensional Arrays to Methods   322
11.5 Arrays within Class   325
11.5.1 One-dimensional Array within Class   325
11.5.2 Two-dimensional Array within Class   329
x Contents

11.6 Arrays of Objects   332


Summary  335
Review Questions  335
True/False Questions  336
Programming Exercises  336

12. String Handling.................................................................................................340–356

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. Exception Handling.........................................................................................357–387


op

13.1 Introduction  357
13.2 Types of Exceptions   357
C

13.2.1 Built-in Exceptions   358


13.2.2 Custom Exceptions   359
g

13.3 Default Exception Handling Mechanism   359


in

13.4 User-Defined Exception Handling Mechanism   360


rn

13.5 Single Try Block and Multiple Catch Blocks   365


13.6 Catching Multiple Exceptions with a Single Catch Block   367
ea

13.7 Nested Try Blocks   369


13.8 Stack Unwinding   374
IL

13.9 Chained Exceptions   376


13.10 Throw Statement   377
13.11 Throws Statement   378
PH

13.12 Finally Statement   379


13.13 Try with Resources Statement   383
13.14 Custom Exceptions   384
Summary  386
Review Questions  386
True/False Questions  387
Programming Exercises  387
Contents xi
14. Multithreaded Programming.....................................................................388–437
14.1 Introduction  388
14.2 The Java Thread Model   389
14.3 The Life Cycle of a Thread   389
14.4 The Thread Class    390
14.5 The Main Thread   392

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. File Handling.......................................................................................................438–472


g
in

15.1 Introduction  438
15.2 The File Class   439
rn

15.3 I/O Stream Classes Related to File Handling   447


15.4 The Character Stream Classes   449
ea

15.5 The Byte Stream Classes    458


15.6 Mixed Data I/O Streams   463
IL

15.7 Object I/O Streams   466


15.8 Random Access File   469
PH

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

16.3 The Life Cycle of an Applet   476


16.4 Creating and Executing an Applet   478
16.5 The Attributes in the <applet> Tag    483
16.6 Passing Parameters to Applets   484
Summary  492
Review Questions  493
True/False Questions  493

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 Layout Managers   523


17.5.1 Flow Layout   523
g

17.5.2 Border Layout   525


in

17.5.3 Grid Layout   526


17.5.4 Card Layout   528
rn

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

17.8 Handling Mouse Events   543


17.9 Handling Events with Specialised Classes   545
17.9.1 Handling MouseEvents through MouseAdapter Class   546
17.9.2 Inner Classes   548
17.9.3 Anonymous Inner Classes   549
Summary  551
Review Questions  552
True/False Questions  552
Programming Exercises  553
Contents xiii
18. Basic Utility Classes [java.lang Package].............................................555–582
18.1 Introduction  555
18.2 The Wrapper Classes   555
18.2.1 The Number Class   555
18.2.2 The Byte Class   556
18.2.3 The Short Class   558

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

involved in creating large-scale applications using the Internet.


This book by Dr. M.T. Somashekara, Dr. D.S. Guru, and Mr. K.S. Manjunatha is a very
ea

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

advanced aspects like exception handling, multithreading, IO streams, etc. in an incremental


fashion. The readers will, no doubt, experience comfort while assimilating the concepts and
programming using them.
PH

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

and programming exercises.


in

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

book grow. You may kindly reach us at [email protected] or [email protected]


or [email protected] with your feedback.
ea
IL

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

1. They are normally programs of bigger size.


rn

2. They have main() method, from where the execution of the program starts.
ea

3. The Java applications are run by the Java interpreter.


4. The Java applications are standalone programs as they can be executed directly by
launching them.
IL

5. They can access the files and other resources at the local system, where they are
launched for execution.
PH

6. They advocate character user interface.


Because of the association of the Java language with the internet and ability to contribute
to the internet application developers and the users powered by its inherent features, one more
kind of Java programs originated are called applets.
Following are the features of Applets which are different from the Java applications:
1. Applets are tiny programs.
2. Applets do not have main() method. They must be embedded in a web program to
run them.

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.

16.2 TYPES OF APPLETS


The applets can be classified into two types depending on where they originate from. They are

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

4. They can not invoke routines of other languages like C, C++.


op

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

&ŝŐƵƌĞϭϲ͘ϭപApplet class inheritance hierarchy.

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

Method with signature Purpose


void init() Begins the execution of the applet. This is the first method
called on an applet.
void start() Starts the executing the applet. Gets called automatically
when init() is called. It also called to resume the applet’s

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

and having the name clipname.


Resizes the applet according to the dimension d.
ea

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

the appletviewer does not support a status window.


PH

dĂďůĞ  ϭϲ͘ϮപMethods of the Component class

Component class Purpose


void paint(Graphics g) Draws text or graphics on the screen.
void update(Graphics g) Fills the screen with the background colour and calls the paint()
method.
void repaint() Schedules call to the update() method.
void setBackground(Colour bColour) Sets the background colour of the component with bColour.

(Contd...)
476 Object Oriented Programming with JAVA

dĂďůĞ  ϭϲ͘ϮപMethods of the Component class (Contd...)


Component class Purpose
void setForeground(Colour fColor) Sets the foreground colour of the component with fColour.
synchronised void setFont(Font f) Sets the font of the component with the font f.
Font getFont() Retrieves the font of the component.

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

&ŝŐƵƌĞϭϲ͘ϮപLife cycle of an applet.


PH

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

to running state and vice-versa many times.


rn
ea

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

1. Creating a Java source file for the applet (.java file )


op

2. Compiling the Java source file to get the equivalent class file (.class file)
3. Creating an html file
C

4. Executing the applet


Let us now follow these steps to create a simple applet and execute it.
ng

Creating a Java source file for the applet (.java file )


i
rn

Here we create the Java source file namely AppletDemo.Java and write in it the required Java
ea

code for an applet.

Creating the AppletDemo.Java file


IL

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.

Creating an html file


ed
ht
Here we create an html file with the same name as that of the class for the applet in the Java
ig
source code with the extension .html. So the html file being created is AppletDemo.html.
yr

The AppletDemo.html file


op

<html>
<head>
C

<body>
ng

<applet code = AppletDemo.class width = 50 height = 50>


</applet>
i
rn

</body>
</head>
ea

</html>
IL

Executing the applet


PH

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

PROGRAM 16.1 To illustrate an applet


ea

import Java.awt.*;
import Java.applet.*;
IL

/* <applet code = AppletDemo1.class width = 300 height = 300 align = top>

</applet> */
PH

public class AppletDemo1 extends Applet


{
public void paint(Graphics g)
{
g.drawString(“First Applet”, 125, 150);
}
}
Applets 481
Compiling AppletDemo.Java
Javac AppletDemo1.Java [return]
After successful compilation, we will run it using the Java interpreter as given below:
Running the applet
Appletviewer AppletDemo1.Java

l
ia
Output

er
at
M
ed
ht
ig
yr
op
C
i ng
rn

// AppletDemo2.Java
ea

PROGRAM 16.2 To illustrate an applet


IL

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
}

Compiling the AppletDemo2.Java

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

HSPACE = pixels (Optional)


This is used only when the attribute ALIGN is set to either
op

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

ALT = alternate text (Optional)

The syntax of the <APPLET> tag in its full form is as follows:


i
rn

<APPLET
[CODEBASE = codebase_URL]
ea

CODE = AppletFileaname.class
[ALT = alternate text]
IL

[NAME = instance name of the applet]


WIDTH = pixels
PH

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

any of the classes in it.


ea

17.2 AWT HIERARCHY


IL

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

17.3 EVENT HANDLING


C

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


IL

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

Name of the event class Situations 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

FocusEvent Whenever a component gains or losses keyboard focus


op

InputEvent Whenever a mouse event or key event occurs


ItemEvent Whenever a checkbox is checked, an item in a list control is selected, a choice
C

control is selected, and a checkable menu item is selected or deselected


KeyEvent Whenever input from the keyboard is accepted
ng

MouseEvent Whenever the mouse is dragged, moved, pressed, released and when the
mouse enters or leaves a component
i

TextEvent Whenever the content in a TextField or a TextArea is changed


rn

WindowEvent Whenever a window is activated, deactivated, iconified, deiconified, opened


ea

or closed
IL

Events and Event Listeners


Each event is associated with its corresponding listener. Table 17.2 shows the list of events
PH

and the corresponding event listeners.


dĂďůĞ ϭϳ͘ϮപEvents and event listeners

Events Event listeners


ActionEvent ActionListener
AdjustmentEvent AdjustmentListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener

(Contd...)
498 Object Oriented Programming with JAVA

dĂďůĞ ϭϳ͘ϮപEvents and event listeners


Events Event listeners
FocusEvent FocusListener
ItemEvent ItemListener
KeyEvent KeyListener

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

be left justified, right justified and be centred respectively.


The following are the other methods in the Label class which are used to write and read
C

the text value and the alignment value of a label:


ng

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

void setAlignment(int align)


IL

Sets the alignment of the text within a label.


int getAlign()
PH

Returns the alignment of the text in a label.


The program 17.1 illustrates the usage of a label. The code for the applet to be created
to demonstrate Label control is provided in the class LabelDemo in the program.

PROGRAM 17.1 To illustrate Label control


import java.awt.*;
import java.applet.*;
18 Basic Utility Classes

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

18.2 THE WRAPPER CLASSES


C

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

immutable, i.e., the values assigned to the objects cannot be altered.

18.2.1 The Number Class


IL

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.

dĂďůĞ ϭϴ͘ϭപMethods with their signature and purpose

Methods with their signature Purpose


byte byteValue() Returns the value of the specified number as a byte
short shortValue() Returns the value of the specified number as a short value
(Contd...)
555
572 Object Oriented Programming with JAVA

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

PROGRAM 18.10 To illustrate Boolean class


C

public class Boolean1


ng

{
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

18.3 THE SYSTEM CLASS


The System class is at the core of the java.lang package. It holds a number of static member
methods and variables. The standard input, output and error of the Java runtime are stored
ĂƐŝĐhƟůŝƚLJůĂƐƐĞƐ΀ũĂǀĂ͘ůĂŶŐWĂĐŬĂŐĞ΁ 579
System.out.println(“Total Memory = “ + tm);
System.out.println(“Free Memory = “ + fm);
System.out.println(“Used Space = “ + (tm - fm));
System.out.println(“Maximum Memory = “ + mm);
System.out.println();
}

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

dĂďůĞ ϭϴ͘ϭϰപDĞƚŚŽĚƐ ŽĨ WƌŽĐĞƐƐ ĐůĂƐƐ ĂŶĚ ƚŚĞŝƌ ƉƵƌƉŽƐĞƐ


C

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

stream of the process


ea

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

18.8 THE VOID CLASS


The Void class has one field namely TYPE, which holds a reference to the Class instance for
the primitive type void. The Void class cannot be instantiated.

18.9 THE MATH CLASS


The Math class provides a number of static methods which are used for performing various
mathematical operations. Table 18.5 furnishes the commonly used ones.

You might also like