Вы находитесь на странице: 1из 379

dedicated to my beloved wife Nibedita

JAJATI MALLICK
About The Author
Jajati Mallick (mallick.jajati@gmail.com)
He holds his Bachelor Engineering in Computer Science &
Engineering from Bijupattaink University of Technology, Rourkela,
Odisha and Master Engineering in Electronics & Telecommunication
Engineering with specialization in Computer Engineering from
Jadavpur University, Kolkata, India. He is a senior professor in
department of Computer Science and Engineering in Purushottam
Institute of Engineering & Technology, Rourkela, Odisha. Since
2006 he is working as a senior faculty in CSE/IT at P.I.E.T,
Rourkela. Now he is doing research in intelligent object recognition
and managing concurrent/distributed events by robots. He has
published many papers in different International Journals and
conference.

II
Preface
Since the release of JAVA in 1995, Sun Microsystems has been all the time improvement its
products to make possible users build up and set up Java solutions with effortlessness and self-
confidence. Java evolved into a modern object oriented, functional, generic and powerful
language suitable for today‟s desktop, enterprise embedded and web application development.
The syntax and scope of Java language expanded from time to time; to meet the expectations of
modern-day programmers rather than taking a minimalist approach. Java platform, Standard
Edition Software is the leading platform for developing and deploying portable applications that
run on server and desktop systems spanning most operating systems. The current major release
of the Java SE platform is Java SE 7 that enhances the power and scope of the language by
incorporating key features and updates while preserving compatibility and stability.
This book is meant for students of various disciplines such as Engineering, Science, Computer
Application and Diploma courses etc. An attempt has been made to cover the subject JAVA as
per the syllabi of different branches of various universities. First Step in JAVA Programming
has been written for beginners those who have some knowledge of C and C++; and it will be a
useful text for the students who are learning the OOP subject. This book is for all those who
want to learn and expand their knowledge of JAVA object-oriented programming. The chapters
are planned in a systematic way. In order to bridge the gap between theory and practical, each
concept is explained in an easy-to-understand manner supported with numerous worked-out
examples and programs. The programmer can run the solved programs, see the output and enjoy
the concept of JAVA. The programs in the chapters are fully tested and executed with JAVA-5,
6, & 7 versions.

Book Organization

This book contains 18 chapters which provide comprehensive discussions on the various aspects
of JAVA programming.

Chapter 1 provides an introduction to Java programming language. The concepts presented in


this chapter are discussed in detail in the ensuing chapters.

Chapter 2 describes overview of Java language, JDK, JRE, JVM, JIT and Java program structure
to build a Java program. It includes comprehensive sections on installation of JDK and running a
Java program.

Chapter 3 elucidates Java character set, data types, variable, constants, operators, operator
precedence and associability and type conversion.

Chapter 4 details on flow of control and provides an in-depth introduction to selection and
iteration statements. Topics discussed here include selection, iteration, break, jump, continue and
return statement. A description of creating array is also included.

Chapter 5 discusses for creating and using class, objects and methods. Special emphasis is laid
on parameter passing by methods and constructors. Some predefined methods are discussed on
simple I/O methods.

III
Chapter 6 serves different forms of inheritance, method overriding and preventing inheritance. It
discusses the uses and differences on abstract class, interface, polymorphism and dynamic
method binding concept.

Chapter 7 introduces Java packages. In this chapter the building blocks of coding in Java and
high-level requirements for designing applet, io and application programs are explained.

Chapter 8 illustrates exception handling mechanisms. It also describes assertion and designing by
contract concept. Different mechanisms have evolved like exception handling and assertion to
tackle the errors.

Chapter 9 focuses on handling the strings. It includes description of the String, StringBuffer and
StringTokenizer class. Vector, Wrapper class, Cloanable interface, Class loader, autoboxing and
unboxing, enumerated type and annotations are also described in relevant detail.

Chapter 10 serves to illustrate the concept of multithreading programming. It also describe how
to prevent deadlock and system starvation. It provides a comprehensive introduction to various
methods present in Thread class and Runnable interface.

Chapter 11 offers details on applet programming. It describes the life cycle of applet and how
applets are differ from applications are explained.

Chapter 12 covers for creating graphical user interface (GUI) and various Java GUI classes and
interfaces. Beginning with abstract window tool kit (AWT) and grid layout, the chapter goes on
to encompass a variety of topics such as AWT components, swing and MVC architecture.

Chapter 13 dedicated to event handling programming for windows based applications and
includes discussions on applet, AWT and swing.

Chapter 14 discusses various types of I/O and methods used in Java. A brief discussion on file
programming and printing methods are presented.

Chapter 15 contains standard library and its associated components present in Util package.
Various types of predefined interface like Collection, List, Queue, Set, Map and Iterator are
elaborated.

Chapter 16 covers Java networking. In this chapter socket programming concept using TCP and
UDP for transmitting user data are explained.

Chapter 17 discusses Java Database Connectivity (JDBC). How various types of JDBC drivers
are used to connect the database for inserting, deleting, updating data are explained here.

Chapter 18 present most important feature of Java language i.e. Remote method invocation
(RMI) for accessing a remote method by client deployed at server.

IV
Acknowledgement
The author would like to thank many of his friends; colleagues and co-workers for help, co-
orperation and support, without which the book could not be completed in the present form.

First and foremost the author wishes to thank Professor K. M. Purohit, Director of Purushottam
Institute of Engineering & Technology for providing him the necessary support to write the
book. He is equally indebted to Professor Shishir Patra, Head of Department of Computer
Science & Engineering P.I.E.T , Rourkela and Professor T. R. Sahoo, Department of Computer
Science & Engineering I.I.I.T Bhubaneswar for his constant mental support in writing the book.
The author gladly acknowledges the support extended by the past two HODs Professor Nibedita
Adhikari and Professor Mitrabinda Roy for the successful completion of the book. The teachers
and current colleagues of the author also played vital roles in the preparation of the manuscript.
The author would like thank Professor Sunita Hati, Professor Anup Kumar Sahu, Professor
Jagadish Mohanta and Professor Sodyam Bebarta of his department who inspired his writing
skills, which later enabled him to write this book. The author owes a deep gratitude to Professor
Dulal Acharjee for his constructive encouragements, which helped him develop a habit of
checking a thought twice before deliberating. Among his colleagues and well-wishers the author
would like to mention the name of the following personalities: Professor Manidipa Acharya,
Professor S. K. Sharma, Tikan Pati, Pabitra Mallick and Umesh Pradhan. The author is indebted
to all his B.E and MCA students for sharing their views over the past 8 years, which ultimately
took shape in the form of the book. The author would like to mention his sincere thanks to
Professor Sasmita Nayak, Head of Chemistry department and Professor Punyaban Patel, Head of
IT department, who always wishes him a successful career since his joining. He would also like
to thank his one time favorite friend Professor P. K. Rath, Department of CSE/IT Sambalpur
University, who inspired the author to fix his goals ahead.

Lastly, the author expresses his deep gratitude to his parents: Mr. Jubak Chandra Mallick and
Late Basanti Lata Mallick who played a significant role in his success as a teacher. He also like
to thank his two brothers Jayakata , Jitendra and sister Kalyani, who always inspired the author
to fulfill his ambitions .The author mourns the sudden death of his wife Nibedita Lenka, who
could have been much happy to see the book in print. The author finally remembers the
charming faces of his daughter Chanchal whose love and imagination created inspiration and
encouragement for the successful completion of the book.

JAJATI MALLICK
Associate Professor
Department of Computer Science & Engineering
Purushottam School of Engineering & Technology
Madiakudar, Rourkela, Odisha, India
770034

V
CONTENTS

SL. Page No.


No.
Chapter-1
1 Introduction to Java Programming Language ………………….......................... 1
1.0 EVOLUTION OF JAVA……………………………………………………….. 1
1.1 OBJECT ORIENTED PROGRAMMING…… 1
1.2 BASIC CONCEPTS OF OBJECT-ORIENTED PROGRAMMING…………… 1
1.3 RELATIONSHIP BETWEEN CLASS AND OBJECTS……………………….. 3
1.3.1 Inheritance ……………………………………………………………………… 3
1.3.2 Polymorphism…………………………………………........................................ 4
1.4 LAYERS OF SOFTWARE……………………………………………………... 4
1.4.1 Characteristics of Procedure-Oriented Programming (POP)……………………. 5
1.4.2 Characteristics of Object-Oriented-Programming structure (OPPs)…………….. 5
Summary……………………………………………………………………….... 6
Review Question………………………………………………………………… 7
Chapter-2
2 Overview of Java Language……………………………………………………... 8
2.0 JAVA FEATURES……………………………………………………………… 8
2.1 JAVA DEVELOPMENT KIT (JDK)…………………………………………… 8
2.2 JAVA RUNTIME ENVIRONMENT…………………………………………… 9
2.2.1 Runtime Class Libraries…………………………………………………………. 9
2.2.2 User Interface toolkits…………………………………………………………… 9
2.2.3 Deployment Technologies………………………………………………………. 10
2.2.4 Java Virtual Machine (JVM)……………………………………………………. 10
2.3 JAVA PROGRAM STRUCTURE……………………………………………… 11
2.4 RULES FOR JAVA PROGRAM……………………………………………….. 12
2.5 HOW TO INSTALL JDK……………………………………………………….. 12
2.6 SIMPLE JAVA PROGRAM……………………………………………………. 12
2.7 COMMAND LINE ARGUMENTS…………………………………………….. 13
Summary………………………………………………………………………… 15
Review Question………………………………………………………………… 16
Chapter-3
3 Java Fundamentals………………………………………………………………. 17
3.0 INTRODUCTION………………………………………………………………. 17
3.1 JAVA CHARACTER SET……………………………………………………… 17
3.2 TOKENS………………………………………………………………………… 17
3.2.1 Keywords………………………………………………………………………... 17
3.2.2 Identifiers………………………………………………………………………... 18
3.2.3 Literals (constants)………………………………………………………………. 18
3.2.4 Punctuators (Separators)………………………………………………………… 19
3.2.5 Operators………………………………………………………………………… 19
3.3 DATA TYPES…………………………………………………………………... 19
3.3.1 Primitive Data Types……………………………………………………………. 19
3.3.2 Reference Data Types…………………………………………………………… 20
3.4 VARIABLES……………………………………………………………………. 21
3.5 CONSTANS…………………………………………………………………….. 22
3.6 JAVA OPERATORS……………………………………………………………. 22
3.6.1 Arithmetic Operator…………………………………………………………….. 22
3.6.2 Relational Operator……………………………………………………………… 25
3.6.3 Logical operator…………………………………………………………………. 25
3.6.4 Bitwise Operator………………………………………………………………… 25
3.6.5 Special Operators……………………………………………………………….. 28
3.6.6 Ternary operator………………………………………………………………… 28
3.7 OPERATOR PRECEDENCE AND ASSOCIATIVITY……………………….. 28

VI
3.8 TYPE CONVERSION IN EXPRESSIONS…………………………………….. 28
3.9 Widening and Narrowing Conversion…………………………………………... 30
Summary………………………………………………………………………… 31
Review Question………………………………………………………………… 32
Chapter-4
4 Flow of Control………………………………………………………………….. 35
4.0 INTRODUCTION……………………………………………………………….. 35
4.1 SELECTION STATEMENTS…………………………………………………... 35
4.1.1 The if Statement of Java………………………………………………………… 35
4.1.2 The if-else Statement……………………………………………………………. 36
4.1.3 Nested ifs………………………………………………………………………… 37
4.1.4 The if-else-if Ladder…………………………………………………………….. 38
4.1.5 The switch Statement……………………………………………………………. 38
4.2 ITERATION STATEMENTS…………………………………………………... 40
4.2.1 Syntax of for loop……………………………………………………………….. 40
4.2.2 while loop and do-while loop…………………………………………………… 45
4.2.3 Infinite Loop…………………………………………………………………….. 46
4.3 JUMP STATEMENTS………………………………………………………….. 46
4.3.1 The break Statement……… …………………………………………………….. 47
4.3.2 The continue Statement………. ………………………………………………… 47
4.3.3 The return statement……………………………………………………………... 48
4.4 ARRAY…………………………………………………………………………. 48
4.4.1 One-dimensional Array…………………………………………………………. 49
4.4.2 Multidimensional Arrays………………………………………………………... 49
4.4.3 Anonymous Arrays……………………………………………………………… 50
4.4.4 Finding Array Size………………………………………………………………. 51
4.4.5 Fetching Data in an Array……………………………………………………….. 51
Summary…………………………………………………………………………. 52
Review Question………………………………………………………………… 53
Chapter-5
5 Class, Objects and Methods……………………………………………………... 57
5.0 INTRODUCTION……………………………………………………………….. 57
5.1 DEFINING A CLASS…………………………………………………………… 57
5.1.1 User defined class………………………………………………………………... 57
5.1.2 Predefined class………………………………………………………………….. 57
5.2 DECLARING MEMBER VARIABLES………………………………………... 57
5.3 DEFINING METHODS…………………………………………………………. 58
5.3.1 User defined Methods……………………………………………………………. 58
5.3.2 Pre-defined Method……………………………………………………………… 59
5.4 CREATING AND USING OBJECTS…………………………………………... 59
5.4.1 Declaring object variable………………………………………………………… 59
5.4.2 Using objects…………………………………………………………………….. 59
5.5 GETTERS AND SETTERS (MUTATOR) MATHODS IN CLASSES………... 62
5.6 ACTUAL AND FORMAL PARAMETERS……………………………………. 63
5.7 RETURNING A VALUE BY METHOD……………………………………….. 64
5.8 CONSTRUCTORS……………………………………………………………… 65
5.8.1 Types of Constructors…………………………………………………………… 67
5.9 CONSTRUCTOR AND METHOD OVERLOADING………………………… 68
5.10 PASS BY VALUE / CALL– BY– VALUE…………………………………….. 68
5.11 PASS BY REFERENCE / CALL-BY-REFERENCE…………………………... 69
5.12 RECURSION……………………………………………………………………. 70
5.13 INNER CLASS………………………………………………………………….. 71
5.14 JAVA KEYWORDS…………………………………………………………….. 72
5.14.1 Static……………………………………………………………………………... 72
5.14.2 Final……………………………………………………………………………… 74
5.14.3 this ………………………………………………………………………………. 74

VII
5.15 SIMPLE INPUT AND OUTPUT……………………………………………….. 76
5.15.1 Formatting Console Output……………………………………………………… 76
5.15.2 Console Input Using Scanner Class……………………………………………... 77
Summary……………………………………………………………………….. 82
Review Question………………………………………………………………… 84
Chapter-6
6 Concept of Inheritance………………………………………………………….. 87
6.0 INTRODUCTION………………………………………………………………. 87
6.1 DIFFERENT FORMS OF INHERITANCE…………………………………….. 87
6.2 METHOD OVERRIDING………………………………………………………. 89
6.3 PREVENTING INHERITANCE………………………………………………... 89
6.3.1 Final Variable and Methods……………………………………………………... 89
6.3.2 Final Classes…………………………………………………………………….. 89
6.3.3 Finalizer Methods……………………………………………………………….. 89
6.4 THE SUPER KEYWORD………………………………………………………. 90
6.4.1 Accessing Base Class Data member and Overridden member function………. 90
6.4.2 Inheritance and Constructors……………………………………………………. 91
6.5 ABSTRACT CLASS…………………………………………………………….. 92
6.5.1 Abstract Methods………………………………………………………………… 93
6.6 INTERFACES…………………………………………………………………… 95
6.6.1 Interface Definition……………………………………………………………… 95
6.6.2 Implementation of Interface…………………………………………………….. 95
6.6.3 Difference between class and interface………………………………………….. 97
6.6.4 Difference between Interface and abstract class………………………………… 97
6.7 POLYMORPHISM……………………………………………………………… 98
6.7.1 Method Polymorphism (overloading)…………………………………………… 98
6.7.2 Object Polymorphism by Inheritance / Interface………………………………. 98
6.7.3 Dynamic Method Binding……………………………………………………….. 99
6.7.4 Static Binding or Early Binding…………………………………………………. 99
Summary………………………………………………………………………… 100
Review Question………………………………………………………………… 101
Chapter-7
7 Packages…………………………………………………………………………. 103
7.0 INTRODUCTION……………………………………………………………….. 103
7.1 JAVA PACKAGES………………………………………………………………. 103
7.2 USER DEFINED PACKAGES………………………………………………….. 104
7.2.1 Visibility Modifiers………………………………………………………………. 105
7.2.2 Immutable Objects and classes………………………………………………….. 107
7.2.3 Accessing a Package……………………………………………………………... 108
7.3 JAVA API PACKAGES…………………………………………………………. 109
7.4 STANDARD INPUT AND OUTPUT…………………………………………… 109
7.4.1 Character Oriented IO……………………………………………………………. 110
7.4.2 Integer Input……………………………………………………………………… 111
7.4.3 Byte Oriented IO………………………………………………………………… 111
7.4.4 Getting Input From Input Dialog Using GUI……………………………………. 112
7.4.5 Confirmation Dialogs……………………………………………………………. 115
7.5 STATIC IMPORT……………………………………………………………….. 116
Summary…………………………………………………………………………. 117
Review Question…………………………………………………………………. 118
Chapter-8
8 Exception Handling………………………………………………………………. 119
8.0 INTRODUCTION ………………………………………………………………. 119
8.1 EXCEPTION AND EXCEPTION HANDLING………………………………… 119
8.1.1 What happens when an Exception Occurs?............................................................ 120
8.1.2 Concept of Exception Handling………………………………………………….. 121
8.2 EXCEPTION HANDLING IN JAVA…………………………………………… 121

VIII
8.2.1 Exception Handling Using try{ } and Catch{ }…………………………………. 121
8.2.2 Rules for try, catch and finally Blocks…………………………………………… 124
8.2.3 The finally clause of Exception Handling……………………………………….. 124
8.2.4 The throws Clause……………………………………………………………….. 126
8.2.5 Using throw……………………………………………………………………… 127
8.2.6 The Exception Class……………………………………………………………… 128
8.2.7 Common Exceptions…………………………………………………………….. 128
8.2.8 Exception Hierarchy……………………………………………………………… 129
8.2.9 Checked and Unchecked Exceptions…………………………………………… 130
8.2.10 Chained Exception……………………………………………………………….. 131
8.3 ASSERTION AND DESIGN BY CONTRACT………………………………… 132
8.3.1 Implementing Assertion………………………………………………………… 133
8.3.2 Difference between Exception and Assertion……………………………………. 133
8.3.3 Assert Statement Commands…………………………………………………….. 133
8.3.4 Assertion Rules…………………………………………………………………... 134
Summary…………………………………………………………………………. 138
Review Question…………………………………………………………………. 139
Chapter-9
9 String……………………………………………………………………………... 140
9.0 INTRODUCTION……………………………………………………………….. 140
9.1 Constructing a String…………………………………………………………….. 140
9.2 IMMUTABLE STRINGS AND INTERNED STRINGS……………………….. 140
9.3 WORKING WITH STRINGS…………………………………………………… 141
9.4 CREATING StringBuffers………………………………………………………. 141
9.5 ACCESSOR METHODS………………………………………………………… 142
9.6 StringBuffer class………………………………………………………………… 146
9.6.1 StringBuffer Object………………………………………………………………. 146
9.6.2 Efficiency of StringBuffer compared to String class……………………………… 147
9.7 STRING TOKENIZER…………………………………………………………… 149
9.7.1 Processing a Number Sequence with StringTokenizer…………………………… 151
9.8 VECTORS………………………………………………………………………… 151
9.9 WRAPPER CLASSES……………………………………………………………. 153
9.10 USING clone( ) AND Cloneable INTERFACE………………………………….. 154
9.10.1 Deep and Shallow Cloning……………………………………………………….. 156
9.10.2 Implementing Deep cloning………………………………………………………. 157
9.10.3 Implementing Serialization……………………………………………………… 158
9.11 CLASS LOADER………………………………………………………………… 159
9.11.1 Flow between BootStrap, extension and System class loader…………………… 160
9.11.2 Difference between Static and Dynamic class loading…………………………… 161
9.12 Autoboxing and Unboxing………………………………………………………... 161
9.13 ENUMERATED TYPES…………………………………………………………. 162
9.14 ANNOTATIONS…………………………………………………………………. 163
Summary…………………………………………………………………………... 165
Review Question…………………………………………………………………... 166
Chapter-10
10 Multithreading……………………………………………………………………... 167
10.0 INTRODUCTION…………………………………………………………………. 167
10.1 THREAD CONCEPTS……………………………………………………………. 167
10.2 CREATING MULTITHREADED PROGRAM………………………………….. 168
10.2.1 Using Thread Class………………………………………………………………... 168
10.2.2 Using Runnable Interface…………………………………………………………. 169
10.2.3 Process of Setting Priority…………………………………………………………. 170
10.3 LIFE CYCLE OF THREAD………………………………………………………. 171
10.3.1 Knowing the Current Thread……………………………………………………… 173
10.3.2 Suspending Thread using sleep( ) method………………………………………… 173

IX
10.4 SYNCRONIZATION (LOCKING)………………………………………………. 174
10.4.1 Object Based Monitor……………………………………………………………... 174
10.4.2 Class Based Monitor………………………………………………………………… 175
10.4.3 wait( ) and notify( ) Method………………………………………………………… 177
10.4.4 Deadlock and System Thread Starvation………………………………………….. 180
10.4.5 Using isAlive( ) and join( ) method………………………………………………… 180
10.4.6 The transient and volatile Modifiers……………………………………………….. 182
10.4.7 Difference between multithreading and multitasking……………………………… 184
Summary……………………………………………………………………………. 185
Review Question……………………………………………………………………. 186
Chapter-11
11 Applets……………………………………………………………………………… 187
11.0 INTRODUCTION………………………………………………………………….. 187
11.1 APPLET FUNDAMENTAL………………………………………………………... 187
11.1.1 Local Applet………………………………………………………………………… 187
11.1.2 Remote Applet………………………………………………………………………. 187
11.1.3 How Applets differ from Applications……………………………………………… 188
11.2 CREATING A SIMPLE WEBPAGE………………………………………………. 188
11.3 CREATION PROCEDURE OF APPLET PROGRAMS………………………….. 190
11.4 APPLET LIFE CYCLE……………………………………………………………. 193
11.5 PASSING PARAMETERS TO APPLETS…………………………………………. 195
11.6 THE GRAPHICS CLASS…………………………………………………………... 197
11.7 DISPLAYING NUMERICAL VALUES…………………………………………… 200
Summary……………………………………………………………………………. 201
Review Question……………………………………………………………………. 202
Chapter-12
12 GUI Basics…………………………………………………………………………... 203
12.0 INTRODUCTION………………………………………………………………….. 203
12.1 AWT (Abstract Window Tool Kit)………………………………………………….. 203
12.2 AWT Classes……………………………………………………………………….. 204
12.2.1 Frame……………………………………………………………………………….. 204
12.2.2 Layout Managers…………………………………………………………………… 205
12.2.3 AWT Components………………………………………………………………….. 206
12.2.3.1 Label………………………………………………………………………………… 206
12.2.3.2 Button………………………………………………………………………………. 207
12.2.3.3 TextField……………………………………………………………………………. 207
12.2.3.4 CheckBox…………………………………………………………………………… 208
12.2.3.5 ComboBox………………………………………………………………………….. 209
12.2.3.6 List…………………………………………………………………………………. 209
12.2.3.7 MenuBar……………………………………………………………………………. 211
12.3 INTRDUCTION TO SWING………………………………………………………. 212
12.3.1 Container Classes…………………………………………………………………… 213
12.3.2 GUI Helper Classes…………………………………………………………………. 213
12.3.3 LookAndFeel class…………………………………………………………………. 213
12.4 JApplet……………………………………………………………………………… 213
12.5 JFrame……………………………………………………………………………… 215
12.6 JPanel……………………………………………………………………………….. 215
12.6.1 JSplitPane…………………………………………………………………………… 216
12.6.2 JScrollPane…………………………………………………………………………. 216
12.6.3 TabbedPane………………………………………………………………………… 216
12.7 JTree………………………………………………………………………………. 217
12.8 JTable …………………………………………………………………………….. 218
12.9 JImage ……………………………………………………………………………. 219
Summary…………………………………………………………………………… 222
Review Question…………………………………………………………………… 223

X
Chapter-13
13 Event Handling…………………………………………………………………….. 224
13.0 INTRODUCTION………………………………………………………………….. 224
13.1 THE EVENT MODEL……………………………………………………………… 224
13.2 EVENT CLASSES…………………………………………………………………. 225
13.3 PROCESS OF EVENT HANDLING………………………………………………. 226
13.4 METHODS OF LISTENER CLASS………………………………………………. 228
13.4.1 Adapter Class………………………………………………………………………. 230
13.4.2 Anonymous Inner Classes………………………………………………………….. 230
13.5 Applet-Applet Communication…………………………………………………….. 231
13.6 PLAYING SOUND………………………………………………………………… 236
13.7 KEY EVENT……………………………………………………………………….. 239
13.8 THE EVENT HANDLING PROCESS AND EVENT-DELEGATION MODEL… 241
13.9 Introduction to MVC Architecture…………………………………………………. 243
Summary……………………………………………………………………………. 245
Review Question…………………………………………………………………….. 246
Chapter-14
14 Input/Output: Exploring java.io…………………………………………………….. 247
14.0 INTRODUCTION………………………………………………………………….. 247
14.1 THE JAVA I/O CLASSES AND INTERFACES………………………………….. 247
14.2 FILE………………………………………………………………………………… 247
14.3 STREAM CLASSES……………………………………………………………….. 248
14.4 BYTE STREAM CLASSES……………………………………………………….. 249
14.4.1 Input Stream classes………………………………………………………………… 249
14.4.2 Output Stream Classes……………………………………………………………… 250
14.4.3 File Operation Using ByteStream classes………………………………………….. 251
14.5 CHARACTER STREAM CLASS…………………………………………………. 252
14.5.1 Reader Stream Classes……………………………………………………………… 253
14.5.2 Writer Stream Classes………………………………………………………………. 253
14.5.3 File Operation using Character Stream class……………………………………….. 254
14.6 BUFFERING……………………………………………………………………….. 254
14.7 PRINTING IN JAVA………………………………………………………….…… 255
14.7.1 Java Printing API………………………………………………………..……..…… 255
14.7.2 Rendering Models………………………………………………………………….. 256
14.7.3 Units of Measurement……………………………………………………………… 257
14.7.4 PrinterJob Class…………………………………………………………………….. 258
14.7.5 The Printing Sequence……………………………………………………………… 259
14.7.6 PrintYour First Page………………………………………………………………… 261
14.8 RANDOM ACCESS FILES………………………………………………………… 263
14.9 READING AND WRITING OBJECTS……………………………………………. 264
14.10 SERIALIZATION………………………………………………………………….. 265
14.11 TRANSIENT VARIABLES……………………………………………………… 266
14.12 GRAPHICAL INPUT AND OUTPUT…………………………………………… 266
Summary…………………………………………………………………………… 271
Review Question…………………………………………………………………… 272
Chapter-15
15 Util…………………………………………………………………………………. 273
15.0 INTRODUCTION…………………………………………………………………. 273
15.1 Collection FrameWork…………………………………………………………….. 273
15.1.1 Collection…………………………………………………………………………… 273
15.1.2 Iterator………………………………………………………………………………. 274
15.1.3 List…………………………………………………………………………………. 274
15.1.4 Set…………………………………………………………………………………… 275
15.1.5 SortedSet……………………………………………………………………………. 276
15.1.6 MAP………………………………………………………………………………… 277
15.1.7 SortedMap…………………………………………………………………………… 279

XI
15.1.8 Vector……………………………………………………………………………….. 279
15.1.9 Using System‟s Date and Time……………………………………………………….281
15.1.10 Random………………………………………………………………………………. 282
Summary…………………………………………………………………………… 282
Review Question……………………………………………………………………... 283
Chapter-16
16 Networking…………………………………………………………………………. 284
16.0 INTRODUCTION………………………………………………………………… 284
16.1 PROCESS-TO-PROCESS DELIVERY…………………………………………… 285
16.2 CLIENT-SERVER PARADIGM…………………………………………………… 286
16.2.1 Ports………………………………………………………………………………… 286
16.3 TCP BASED COMMUNICATION………………………………………………… 288
16.3.1 InetAddress class…………………………………………………………………… 290
16.4 UDP SOCKETS……………………………………………………………………… 291
16.5 LOCATING NETWORK RESOURCES……………………………………………. 293
16.6 Whois………………………………………………………………………………… 295
16.7 A CLIENT AND SERVER EXAMPLE…………………………………………….. 296
Summary……………………………………………………………………………. 300
Review Question……………………………………………………………………. 301
Chapter-17
17 JDBC……………………………………………………………………………… 302
17.0 INTRODUCTION………………………………………………………………… 302
17.1 JDBC (JAVA DATA-BASE CONNECTIVITY)…………………………………… 302
17.1.1 Components of JDBC………………………………………………………………... 303
17.2 TYPES OF JDBC DRIVERS……………………………………………………… 304
17.2.1 The Type-1 Driver (JDBC-ODBC Bridge)………………………………………… 304
17.2.2 The Type-2 Driver (Java to native API)…………………………………………… 305
17.2.3 The Type-3 Driver (Java to Network Protocol/All Java Driver)…………………… 305
17.2.4 The Type-4 Driver (Java to Database Protocol)…………………………………… 306
17.3 Developing Database Applications Using JDBC…………………………………… 307
17.3.1 Exploring the Methods of Statement………………………………………………… 310
17.3.2 Creating DSN ……………………………………………………………………… 311
17.3.3 Working with the ResultSet Interface……………………………………………… 314
17.3.4 Handling NULL Values……………………………………………………………… 319
17.4 WORKING WITH PREPARED STATEMENT INTERFACE…………………… 320
17.5 WORKING WITH THE CALLABLESTATEMENT INTERFACE……………… 324
17.5.1 Using CallableStatement…………………………………………………………… 325
17.5.2 Executing a Stored Procedure with IN Parameter………………………………… 325
17.5.3 Executing a Stored Procedure with OUT parameters……………………………… 327
17.5.4 Calling Functions by Using CallableStatement……………………………………… 328
17.6 WORKING WITH THE RESULTSETMETADATA INTERFACE……………… 329
17.6.1 Describing ResultSetMetaData…………………………………………………… 329
17.6.2 Using ResultsetMetaData…………………………………………………………… 331
17.7 Using DatabaseMetaData…………………………………………………………… 332
Summary…………………………………………………………………………… 333
Review Question…………………………………………………………………… 334
Chapter-18
18 RMI………………………………………………………………………………… 336
18.0 INTRODUCTION………………………………………………………………… 336
18.1 SYSTEM GOALS…………………………………………………………………… 336
18.2 DISTRIBUTED OBJECT MODEL………………………………………………… 336
18.2.1 Distributed Object Application……………………………………………………… 336
18.2.2 Defination of Terms………………………………………………………………… 337
18.2.3 The Distributed and Nondistributed Model Constrasted…………………………… 337
18.2.4 Overview of RMI Interface and Classes…………………………………………… 338

XII
18.2.5 Implementing a Remote Interface……………………………………………………. 340
18.2.6 Parameter Passing in RMI…………………………………………………………… 341
18.2.7 Loading remote Objects……………………………………………………………… 342
18.3 RMI ARCHITECTURE………………………………………………………………342
18.3.1 Creating RMI Application…………………………………………………………… 344
18.3.2 Implicity Starting Registry ………………………………………………………… 347
18.4 Exception in RMI…………………………………………………………………… 347
18.4.1 Exceptions during Remote Object Export…………………………………………… 347
18.4.2 Exceptions during RMI Call………………………………………………………… 348
18.4.3 Exceptions or Errors during Return………………………………………………… 348
18.4.3.1 Possible Causes of java.rmi.ServerException……………………………………… 349
18.4.4 Naming Exceptions………………………………………………………………… 349
18.4.5 Other Exceptions…………………………………………………………………… 349
18.5 BOOTSTRAPPING IN RMI………………………………………………………… 349
Summary…………………………………………………………………………… 351
Review Question…………………………………………………………………… 352
Appendices…………………………………………………………………… 354

XIII
Introduction to Java Programming Language
1.0 EVOLUTION OF JAVA

In January 1991, Bill Joy, James Gosling, Mike Sheradin, Patrick Naughton and
several other experts met in Aspen, Colorado for the first time to discuss about a
programming language, which was presented by Bill Joy. They wish to invent a better
programming tool in the direction of Sun‟s “Stealth Project”. The members of the Stealth
Project were later recognized by another name “Green Project”. James Gosling objectives
were to modify and extend C++. This gave a better path for the progress of project.
Originally, the language was given the name “Oak”, which later on was renamed as “Java”
in the year 1995. Java is a slang term for coffee.

Figure 1.1Overlapping of C,C++ and Java

1.1 OBJECT ORIENTED PROGRAMMING

It is a problem solving technique to develop software systems. It‟s a technique to


think real world in terms of objects. Object maps the software model to real world concept.
These objects have responsibilities and provide services to application or other objects.

1.2 BASIC CONCEPTS OF OBJECT-ORIENTED PROGRAMMING


The general concepts of OOP which form the heart of Java language are discussed now.
(i) Class
A class describes all the attributes of objects, as well as the methods that implement
the behavior of member objects. It‟s a comprehensive data type which represents a
blue print of objects.
Example: Student is a class and student name, student regdno are attributes of class
student. Each student is an object of Student class.
(ii) Object
- Objects are the basic runtime entities in an Object-Oriented System.
- Objects are member of class.
- Attributes and behavior of an object are defined by the class defination.
- All objects have life time. Objects are created, initialized, necessary functionalities
are done and later the object is destroyed.

1
- Object and class are very much same but are not same. Class is a definition while
object is instance (existing) of the class created.
- Class is a blue print (looks like) objects are actual objects existing in real world.
How to create a class in Java?
To create/define a class in Java, you use the keyword (predefined word) “class” as
per following structure:
<access specifier> class <class name>
{
}
Example: public class point
{
-----
-----
}
Access Specifier:
It is used in Java to give security to the members of a class. Java provides four access
specifiers as given below
- public
- protected
- default (i.e., no specifier)
- private
- public public classes, methods and fields can be accessed from everywhere. The only
constraint is that a file with Java source code can only contain one public class whose name must
also match with filename.
- protected protected methods and fields can only be accessed within the same class to which
the methods and fields belong, within its subclasses and within classes of the same package (like
a folder) but not from anywhere else.
- Default (no specifier) If you do not set access to specific level, then such a class, method
or field will be accessible from inside the same package to which the class, method, or field
belongs, but not from outside this package.
- private private methods and fields can only be accessed within the same class to which the
methods and fields belong. The private methods and fields are not visible with in subclasses and
are not inherited by subclasses. It is mostly used for encapsulation.
(iii) Data Abstraction and Encapsulation: The wrapping up data and methods into a
single unit (called class) is known as encapsulation. The data is not accessible to the outside
world and only those methods, which are wrapped in the class, can access it. These methods
provide the interface between the objects data and the program. This protection of the data from

2
direct access by the program is called data hiding (abstraction). Encapsulation is the process of
hiding all the internal details of an object from the outside world.
1.3 RELATIONSHIP BETWEEN CLASS AND OBJECTS
- An object exhibits the properties and behaviors defined by its class. The properties of an
object of a class are also called attributes and are defined by fields in Java.
- A field in a class definition is a variable which can store a value that represents a particular
property.
- The behaviors of an object of a class are also know as operations, and are defined using
methods in Java.
- Fields and methods in a class definition are collectively called members.
- A class provides contract and the implementation for objects. The contract defines what
services, and the implementation defines how these services are provided by the class.
- State of an object changes with behaviour.
Neha Neha

age 2 age 12

Weight 12Kg Weight 12Kg


g Growing up behaviour g

Height 3.2ft height 5.2ft

(state 1) (state 2)

When 2 year old When 12 year old

(Figure 1.2 State of an object changes with behaviour)

In object oriented world objects have relation and hierarchies in between class which are
implemented by inheritance and polymorphism.
1.3.1 Inheritance
Inheritance is the process by which objects of one class acquire the properties of objects of
another class. Inheritance supports the concept of hierarchical classification.
Bird (feathers, eggs types)
(Attributes of Bird class)
Flying Bird Non flying bird
(Additional Attributes) (Additional Attributes)

3
1.3.2 Polymorphism
Polymorphism is another important OOP concept. Polymorphism means the ability
to take more than one form. Polymorphism is extensively used in implementing inheritance.
Example: Abstract class, inheritance
Fruit class (Abstract Methods)

Mango class Banana class


(Over-ridding Methods) (Over-ridding Methods)
Compile Time and Run Time Mechanism:
Compile time may refer to any of the following:
- The operations performed by the compiler such as syntactic and semantic analysis.
- The pre-runtime assessment of the program‟s behavior.
Run time is the time period when a syntactically correct program is actually executed in
the computer system. Thus all the tasks that are performed during this time period are known as
runtime or dynamic.
Inheritance is the compile time implementation where as polymorphism is runtime
implementation.
Dynamic Binding:
Binding refers to the linking of a procedure call to the code to be executed in response to
the call. Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at runtime. Inheritance and polymorphism associated with
dynamic binding.
1.4 LAYERS OF SOFTWARE
As computer science progress its languages becomes much easier to the users which
can explain in software layers as shown in Figure1.3. In general we can compare between
Procedure-Oriented Programming (POP) and Object-Oriented Programming (OOP). POP
consists of a list of instructions for the computer to follow and organizing these instructions into
groups know as functions.In multi function program, many important data items are placed as
global so that they may be accessed by all functions. Each function may have its local
data.Global data are change by a function. In a large program it is very difficult to identify what
data is used by which function.The procedural approach does not model the real world problems
very well, this is because functions are action-oriented and do not really correspond to the
elements of the problem. Object-Oriented-Programming structure (OPPs) ties data more closely
to the functions that operate on it, and protects it from accidental modification from outside
functions.

4
1,0

Machine Language
Assembly language (ADD,MOVE)
Procedure Oriented Laguage(C,BASIC,COBOL)
Object Oriented Language (C++,JAVA,C#)

(Figure 1.3 Software Layers)


1.4.1 Characteristics of Procedure-Oriented Programming (POP)
- Emphasis is on doing things.
- Large programs are devided into smaller programs know as fuction.
- Most of the functions share global data.
- Data move openly around the system from function to function.
- Functions transform data from one from to another.

Main program

Gobal data Gobal data

Funn-1 Funn-2 Funn-3

Funn-1 Funn-2
Local Data Local Data
n n
Fun -4 Fun -5

Funn-3
Funn-6 Funn-7 Funn-8
Local Data

Figure 1.4 Procedure-Oriented Programming approach


1.4.2 Characteristics of Object-Oriented-Programming structure (OPPs)
- Emphasis is on data rather than procedure.
- Programs are divided into what are known as objects.
- Data structures are designed such that they characterize the objects.
- Functions that operate on the data of an object are tied together in the data structure.

5
- Data is hidden and cannot be accessed by external functions.
- Objects may communicate with each other through functions.
- New data and functions can be easily added whenever necessary.
Object A Object B

Data Data

Communication
Functions Functions

Object C

Data

Functions

Figure 1.5 Object-oriented-Programming approaches.

Summary
If today was first exposure to object-oriented programming, it probably seems theoretical
and a bit overwhelming. At this point, you should have a basic understanding of classes, objects,
attributes, and behavior. The other aspects like public, private and protected are use for security
propose. Also you know how OOP is better than POP. On the coming next chapters we discussed
about Java programming language which is an example of Object-oriented-Programming appro-
aches.

6
Review Question
1.1 What is Object Oriented Programming?
1.2 What is a class?
1.3 What is an Object?
1.4 What is the relation between classes and objects?
1.5 Define data abstraction and encapsulation.
1.6 Define Inheritance.
1.7 Define polymorphism.
1.8 Explain compile time and runtime mechanisms.
1.9 What is dynamic binding?
1.10 Define Object lifetime.
1.11 What do you mean by object oriented programming ? How is it different from conventio-
nal procedural/structural programming ?
1.12 What is Java?
Ans : Java is simple, object-oriented, distributed, interpreted, robust, secure, architecture-
neutral, portable, high-performance, multithreaded, and dynamic.

7
Overview of Java Language
2.0 JAVA FEATURES
The inventors of Java wanted to design a language which could offer solutions to
some of the problems encountered in modem programming. The following features are
present in Java.
- It is object oriented.
- It is architecture neutral and platform independent.
- It is distributed.
- It is dynamic and secure.
- Using Java we can write program for internet.
- Everything in Java must be written with in a class.
- There are two types of program we can do
(a) Application (In C++ Programming)
(b) Applet (Web basis)
Applications are general program you do in C++ but the applets are tiny program
which can be embedded in a web page.
- It is a garbage collection (automatic memory collection)
- In Java different API (Application Programming Interface) are provided for
specific purpose. For example JDBC API provides different classes and methods
for connecting with database.
Advantages of Java
- Directly the user can interact with the server.
- Web enabled programs can be developed through JSP, EJB, Servlets.
- GUI (Graphical User Interface) and graphics utilities can be done through Applet
and Swing.
- Java is help in website developing.
- It is platform independent.
The Java Platform
Over the years, the Java platform has evolved into three major editions, each
addressing a distinct set of programming needs. These editions are:
The Java Platform, Standard Edition (Java SE)  allows you to develop desktop and
console-based application.
The Java Platform Enterprise Edition (Java EE)  Allows you to build server-side
applications, by using its convenient component-based approach.
The Java Platform, Micro Edition (Java ME)  enables you to build Java application
for micro-devices, which include handheld devices (such as mobile phones) with
limited display and memory support.

2.1 JAVA DEVELOPMENT KIT (JDK)


The Java Development kit comes with a collection of tools that are used for developing
and running Java programs. They include

8
- Applet viewer ( for viewing Java applets)
- Javac (Java compiler)
- Java (Java interpreter which runs Java Program)
- Javap (Java disassemble converts byte code files into a program description)
- Javah (for C header files)
- Javadoc (for creating HTML documents)
- Jdb(Java debugger for finds error in programs)
Process of building and running Java programs is shown in figure 2.1.
2.2 JAVA RUNTIME ENVIRONMENT
The Java runtime environment (JRE) facilities the execution of program developed in
Java. It primarily comprises of the following

2.2.1 Runtime Class Libraries


These are a set of core class libraries that are required for the execution of Java programs.
2.2.2 User Interface toolkits
AWT and swing are example of toolkits that support varied input methods for the users to
interact with the application program.

Text Editor
Ex:Notpad,wordpad

Java Source Javadoc HTML


Code Files

Javac

Java Javah Header


class File Files

Java Jdb

Java Program
output

Figure 2.1 Process of building and running Java programs

9
2.2.3 Deployment Technologies
JRE comprises the following key deployment technologies.
- Java Plug-in: Enables the execution of a Java applet on the browser.
- Java web start: Enables remote deployment of an application. With web start, users can launch
an application directly from the web browser without going through the installation procedure.
2.2.4 Java Virtual Machine (JVM)
JVM is an abstract computer or virtual computer which runs the compiled Java programs.
It‟s a software implementation which stands on the top of the real hardware platform and
operating system. All Java programs are compiled into byte codes. JVM can only understand and
execute Java byte codes. Java compiler takes the .java files and compiles it to a “byte code” file
with .class file execution. Compiler generates one class file for one source file.Figure2.2 shows
the Java Virtual Machine.

Source code Java .class files Hardware


JVM
.java files compiler (Byte codes) and
Operating
system
Figure 2.2Java Virtual
Machine
JIT (Just-in-Time) compilation:
There are two basic ways languages are compiled.
- Compiled languages
- Interpreted languages
Machine understands only binary if (i = = 0)

Language. So finally source code {

has to compiled in binary format. int x=0;

if (i = = 0) }

{
Interprete
int x=0;
}

|&* $ # $ #% $
#%!~# @!$ $ #
Compiler %$%&&*&{}}

JVM
10101010
10101001
10001011
10101010
10101001
10001011
(Figure 2.2.1-a compiled language) (Figure 2.2.1 –b Interpreted language)

In the Figure 2.2.1-a (the left hand side) we have the compiled way of generating the
binary and on the Figure 2.2.1-b (right hand side) we have the interpreted way.

10
In the compiled way the compiler directly generates the binary file from the source code. While
which is then run by the JVM. That means the binary file is generated during runtime. When
JVM compiles the class file it does not compile the full class file in one shot. Compilation is
done on function basis or file basis. This type of compilation is termed as JIT compilation.
Compiled Languages:
- One of the biggest advantages of compiled languages in their execution speed. A
program written in C/C++ runs 30-70% faster than an equivalent program written
in Java.
- Compiled code takes less memory as compared to an interpreted program.
- Compiled programs are targeted towards a particular platform and hence are plat
form dependent.
- Compiled programs do not allow security to be implemented within the code. e.g.
a compiled program can access any area of the memory, and can do whatever it
wants with your PC.
- A Compiled language is not particularly suited to be used to develop Internet or
web-based applications.
Interpreted Languages:
- It makes program platform-independent.
- It gives high degree of security.
- Its code size is much smaller than a compiled executable code.
2.3 JAVA PROGRAM STRUCTURE

Documentation Section Suggested


Package Statement Optional
Import Statements Optional
Interface Statements Optional
Class Definations Optional
Main Method class Essential

Writing Java Program:


To write a Java program you have to follow the Java program structure as below
1- In document section you have to giving comment lines about program.
Example: /* This is my first Java program.*/
2- The first statement in Java program is package statement which is a optional. This
statement declares a package name and informs the compiler that the classes defined here
belong to this package.
Example: Package student;
3- The next thing after a package statement may be a number of import statements. This is
similar to the #include statement in C.
Example: import student test;

11
This statement instructs the interpreter to load the test class contained in the package
student. Using import statements, we can have access to classes that are part of their
named package.
4- Interface is used when you wish to implement multiple inheritances.
5- A Java program may contain multiple class definations (body part). Among multiple
class, one class must be public which contain main method. Public class name and Java
file must be same name.
6- The main method must contain in public class. In a program or file there is only one
public class.
2.4 RULES FOR JAVA PROGRAM (Case Sensitive)
- All keywords are in small case or lower case.
- All predefined classes and interface starts with capital case and follows Hungarian
notation.
Example: StringBuffer
- All predefined methods starts with small case and follows Hungarian notation.

Example: actionPerformed
lower case upper case
- Before compile a Java program you must installed JVM.
2.5 HOW TO INSTALL JDK(Java Development Kit)

Step.1- Download jdk1.5 from Java.sun.com


Step.2- Installed the Jdk
Step.3- Give the path
Example: After installation of jdk you must give path according to the operating system.
(i) For example in Windows XP, Server2003 goto start→ setting→ Control Panel →
Performance Maintenance→ System→ Advanced→ Environment Variable → System
Variable(select path)→Edit………… ;C:\Program Files\Java \jdk1.5.0\bin→ ok→ ok.
Restart your computer and open your command and try javac command as c:\>javac
if above command execute properly then jdk is properly load in your computer. In this
book we are discussing program which are written in notepad and run in command
prompt.We discussing various Java beans for creating faster graphical frame; advanced
Java programs in chapter-13.Path setting in different operating system like Windows
Vista, Windows7, Linux, Unix is little different.
2.6 SIMPLE JAVA PROGRAM
(i) open your notepad and write the program as
/*My First Java Program */
public class abc{
public static void main(String arg[ ])
{
System.out.println(“Good Morning”);
}
}

12
(ii) Save the file as filename → “abc.java”
Every file contain .Java extension for Javac compiler.
(iii) Compiling your “abc.java” file (assuming your abc.java file present on C: drive) as
C:\> javac abc.java
If it not generate any error then open your C:\> drive where “abc.java” file is stored,
now it generate a abc.class file automatically by interpreted.
(iv) Now you run your program as C:\> java abc
Output: Good Morning
Question: Create a folder any name in any drive store all java files in it. For example create
folder as java20 in D: drive and store all .java files in it (e.g. abc.java).How can we compile a
program.
Solution: open your command prompt and performs the steps
D:\java20>javac abc.java
D:\java20>java abc
Working Principle of abc.java file
(i) “public class abc” statement is a declaring a class named as abc. Here public is an
access specifier similar to the C++ public access specifier discus later on.
(ii) “public static void main(String arg[ ])” The keyword static which declares this
method as one that belongs to the entire class and not a part of any objects of the
class. The main must always be declared as static since the interpreter uses this
method before any objects are created.
Void states that the main method does not return any value to operating system.
Here String arg[ ] declares a argument or parameter named arg[ ] which contains an
array of objects of the class type String for main method.
(iii) System.out.println(“Good Morning”); It is the only executable statement in the
program. The println is a output method to display output on the monitor. The println
method present inside a predefined Java class known as System class. This line prints
Good Morning.
(iv) Every Java statements must be ended with a semicolon (statement terminator).
(v) Java provides single line comments (like //) and multiline comments(/* My First Java
Program*/)
2.7 COMMAND LINE ARGUMENTS
Command line arguments are used to take argument values for the array objects in
main method as arg[ ].
Example: Enter a number and display it.
Solution:
public class digit_Display
{
public static void main(String k[ ])
{
int i= Integer.parseInt(k[0]);
switch(i)
{
13
case 0: System.out.println(“Zero”);
break;
case 1: System.out.println(“One”);
break;
case 2: System.out.println(“Two”);
break;
case 3: System.out.println(“Three”);
break;
case 4: System.out.println(“Four”);
break;
case 5: System.out.println(“Five”);
break;
case 6: System.out.println(“Six”);
break;
case 7: System.out.println(“Seven”);
break;
case 8: System.out.println(“Eight”);
break;
case 9: System.out.println(“Nine”);
break;
default: System.out.println(“please enter one digit at run time”);
}
}
}
Compile: javac digit_Display.java
Run: java digit_Display 5
Output: Five
In place of arg[ ] you can take any name as k[ ]. So command line takes the argument
as String. So „5‟ is given from keyboard at run time of the program. So need type conversion
from string to integer as
int i = Integer.parseInt(k[0]);

Here Integer is a wrappar class of integer type object and parseInt( ) is method to convert
argument k[0] which now contain 5 as a string is converted to integer type.

Example: Display two student names as commandline arguments.


public class student_name
{
public static void main(String arg[ ])
{ System.out.println(“Your Names are”);
System.out.println(arg[0]+“ ”+arg[1]);
}
}
Save file: student_name.java
Compile: D:\java>javac student_name.java
Run : D:\java>java student_name Leja Siny

14
Command line arguments act as input method; it takes dynamic value as string type before
execution of program. There are various methods like scanner class; Graphical Dilogbox, etc are
present to take dynamic input in between starting and ending time of a program. These are
discussed later on.

Example: Find the output of the given program


public class find
{
Static public void main(String arg[ ])
{
System.out.println(“Welcome to Java”);
}
}

2.7 Summary

Java Libraries

JDK

JVM

Other Essential Components

(Java Runtime Environment)

15
Review Questions
2.1 Write a program for display weekday of calendar. Declare a class as weekday.
Which display name of the day entered at command line?
2.2 Entered your village name and display it.
2.3 What are the advantages of Java?
2.4 Explain jdk.
2.5 What is JRE?
2.6 How JVM functions?
2.7 What is JIT?
2.8 Give difference between Compiled languages and Interpreted languages.
2.9 Write all the steps to execute your first Java program in your computer.
2.10 What is the use of command line argument?
2.11Using command line arguments write a program to add to numbers and display the result.

16
Java Fundamentals

3.0 INTRODUCTION

In any language, there are some fundamentals that you need to know before you can
write even the most elementary programs. This chapter introduces Java fundamentals. How to
write a simple Java programs? You will be learning about Java tokens such as keywords,
identifiers, literals, operators and separators, along with data types, variables, constants,
operators, expressions. Let us being our discussion with Java characters set and tokens.

3.1 JAVA CHARACTER SET


Character set is a set of valid characters that a language can recognize. A character
represents any letter, digit or any other sign.
Java uses the Unicode character set. Unicode is a two-byte character code set that has
characters representing almost all characters in almost all human alphabets and writing systems
around the world including English, Arabic, Chinese and many ,ore. You can refer to a particular
Unicode character by using the escape sequence(“\u”) followed by a four digit hexadecimal
number.
Example: \u00AE © The copy right symbol
\u0022 © The double quote
Unicode characters can be represented in 16 bits where as American Standard Code for
Information Interchange (ASCII) characters can be represented in 8 bits.

3.2 TOKENS
The smallest individual unit in a program is known as a token. Java has the following
tokens. 1. Keywords 2.Identifier 3.Literals 4.Punctuators 5. Operators

3.2.1 Keywords
Keywords are the words that convey a special meaning to the language compiler. These
are reserved for special purpose and must not be used as normal identifier names. The following
keywords are reserved for use as keywords and cannot be used as identifiers.

abstract default implements protected throw


boolean do import public throws
break double instanceof return transient
byte else int short try
case extends interface static void
catch find long strictfp volatile
char finally native super while
class float new switch
const goto package synchronized
continue if private this

17
3.2.2 Identifiers
Identifiers are fundamentals building blocks of a program are used for giving names to
different parts of the program. Identifiers forming rules of Java state the following
- Identifiers can have alphabets, digits, underscore and doller sign characters.
- They must not be a keyword or Boolean literal or null literal.
- They can be of any length.
- Java is case sensitive i.e. upper-case letters and lower-case letters are treated differently.
Examples: Some of valid and invalid identifiers are given below
Valid Identifiers Invalid Identifiers
name1 name-1
age 2name
A_to_Z my-file
$1_to_$5

3.2.3 Literals (constants)


Literals are data items that are fixed data values. Java allows several kinds of literals.
(i) integer-literals (ii) floating-literals (iii) boolean-literals
(iv) character-literals (v) string-literals (vi)the null-literal
(i) Integer Literals
Integer literals are whole numbers without any fractional part. Java allows three types
of integer literals.
1. Decimal (base 10)-starts with a digit other than 0.e.g. 29
2. Octal (base 8)-starts with a digit 0 but can‟t contain digits 8, 9. e.g., 040
3. Hexadecimal (base 16)-starts with 0x and can‟t contain letters G-Z e.g., 0x18
(ii) Floating Literals
Floating literals are also called real literals. Real literals are numbers having fractional parts.
These may be written in one of the two forms called fractional form or the exponent form.
- A real literal in fraction form consists of signed or unsigned digits including a
decimal point between digits.
Example: 2.0, 17.5, -13.275, -0.00213
- A real literal in exponent form consists of two parts: mantissa and exponent.
Example: 152E05 (152 X 105) here E05 represents as 105
0.58E01 (0.58 X 101=5.8)
(iii) Boolean Literals
The Boolean type has two values, represented by the literals true and false, formed from
ASCII letters.

(iv) Character Literals


A character literal is one character enclosed in single quotes, as in „z‟. it can be an escape
sequence. Table 3.1 gives a listing of escape sequences.
Example:‟a‟, „%‟, „\t‟, „\\‟,‟\‟, „Ω‟

18
Escape Sequence Nongraphic Character
\a Alert
\b Backspace
\n Newline
\t Horizontal tab
\v Vertical tab
\\ Backslash
\‟ Single quote
\” Double quote
\? Question mark
\0 null
Table 3.1 Escape Sequence in Java

(v) String Literals


Multiple character constants are treated as string-literal.
Example: “abc” size 6byte (each character takes 2bytes)
“\ab” size 4byte (\a is one character)

3.2.4 Punctuators (Separators)


The following nine ASCII characters are the separators (Punchuators).
( ) { } [ ] ; , .

3.2.5 Operators
Operators are symbols that initiate an action. The following tokens are the operators
formed from ASCII characters:

= > < ! ~ ?:
== <= >= != && || ++ --
+ - * / & | ^ %
+= -= *= /= &= |= ^= %=
<< >> >>> <<= >>= >>>=

3.3 DATA TYPES


Java supports two types of data types.
(i) Primitive data types (ii) reference data types
Primitive data types are byte, short, int, long, float, double, char, Boolean. Reference data types
are constructed from primitive data types. These are classes, arrays and interface.
3.3.1 Primitive Data Types

Primitives are the “basic” data values. The word „primitive‟ means a fundamental
component that may be used to create other larger parts. Java supports following four types of
primitive data types.

19
(i) Numerical Integer primitive Types

There are four numeric integral types in Java-byte, short, int , long which store whole
numbers only.

Type Size Description Range


byte 1byte Byte-length integer -128 to +127
short 2byte Short integer -32,768 to +32,767
int 4byte Integer -231 to -231-1
long 8byte Long integer -263 to 263-1
(Table 3.2 Integer Primitive Data types)

(ii) Fractional Numeric Types


Fractional data types can store fractional numbers i.e., numbers having decimal points.
Type Size Description Range
float 4bytes Single-precision floating point -3.4E+38 to +3.4E+38
double 8bytes Double-precision floating point -1.7E+308 to 1.7E+308
(Table 3.3 Floating Point Primitive Data types)

By default, Java treats fractional numbers as of double data type, e.g. if you write 0.284, it will
be treated as a double value. To explicitly specify it to be of float type, use suffix „F‟ or „f‟ i.e.
write 1.284 F or 1.284f. Similarly, you can use suffix d or D it means double i.e.1.284D or
1.284d means it is a double value.

(iii) Character Types


Character data types can store character value (which is present in single quote e.g. „a‟).
Type Size Description Range
char 2bytes Single character 0 to 65,536
(Table3.4 Character Primitive Data types)
(iv) Boolean Type
A Boolean value can have only one if two values: true or false.

Type Size Description Range


boolean 8bits but only uses 1bit Logical or Boolean value True or false
(Table 3.5 Boolean Primitive Data types)

3.3.2 Reference Data Types


Primitive data type operations deal with value i.e. actual read-value (rvalue). For
example, the following code shows that assigning primitive data variable i to another named j
simply passes a copy of the value in i into j.
20
int i=10; i j
10 20
int j=i; //now j holds „10‟
i=2; //j still holds „10‟ 111 211
The reference types on the other hand,
deal with the address i.e., the location value. i 2 Memory address
They do not store the actual read-value,
rather they store the address where from 111
actual data is obtained. Array, classes and interfaces are reference types.
Consider the following code
class student
{
public int age;
public String name;
}
student obj1, obj2;
obj1=new student( );
- The statement student obj1, obj2; enough memory is allocated to store a reference
to an object (which can shown in 1).
- obj1 =new student ( ) enough memory is allocated for the actual object data
(which can shown in 2).

(1) obj1 obj2

(2) obj1
301

age name

301 305 Memory- Address

3.4 VARIABLES
A variable is a named memory location, which holds a data value of a particular data
type. When you create a variable you must follow the identifiers rules.
- Declaration of a variable
<access specifier> <modifier> [type] identifier name;

optional optional Essential


Example: int a;
double res;

- Initialization of variables (giving value to a variable)


Example: int a=10;
Res=10.5f;

- Variable scope
Scope generally refers to the program region with in which a variable is
accessible. A variable is accessible within the set of braces it is declared in e.g.

21
{
int a; /* a would be accessible as long as its block (a block is marked with a
. pair of matching brace) is not closed. Variable „a‟ is said to have block
. scope*/
.
}

3.5 CONSTANS
In a program you want to give a name to a constant value. For example you might have
a fixed value for “pi” ( ) for calculating mathematical expression. It is convenient to give these
constants a name. This can be done as follows:
final double pi=0.25
The keyword final makes a variable as constant. i.e.; whose value cannot change during program
execution.

3.6 JAVA OPERATORS


The operations are represented by operators and the objects of the operation(s) are
referred to as operands. Operators that act one operand are referred to as UNARY operators.
Operators that act upon two operands are referred to as BINARY operators.
Java‟s rich set of operators comprises of
(i) Arithmetic (+, -, *, /, %, ++, --)
(ii) Relational (<, >, <=, >=, !=, = =)
(iii)Logical (&&, ||, !)
(iv) Bitwise (&, |, ^, <<, >>, >>>)

3.6.1 Arithmetic Operator


(a) Addition operator + :
Example: 4+20 = 24

(b) Subtraction operator - :


Example: 14-9 = 5

(c ) Multiplication operator * :
Example: 3*9 =27

(d) Division operator / :


Example:100/5 = 20

(e) Modulus operator % :


Example: 19%6 = 1

(f) Increment operator ++ :


Example: int a=10;
++a; //evaluates 11
++a means a = a+1 or a++ means a = a+1
- ++a is known as prefix

22
Example: int a =10, s = 10;
s=s+ ++a; //now s value become 21 and a value 11

- a++ is known as postfix


Example: int a=10,s=10;
s=s+ a++; //now„s‟ value become 20 and „a‟ value 11

- The prefix increment or decrement operator first change the value of their operand
then uses the new value in evaluating the expression. The postfix increment or
decrement operator first uses the value of their operand in evaluating the
expression and then changes the operands value.

(g) Decrement Operator -- :


Example: int a=10;
--a; //evaluates 9
Or
int a=10;
a--; //evaluates 9

Example3.1: Mice’s basic salary is input through the keyboard (as command line argument). His
dearness allowance is 40% of basic salary, and house rent allowance is 20% of basic salary.
Write a program to calculate his gross salary.

Answer :

public class gross_salary


{
public static void main(String arg[])
{
double bs,da,hra,gs;
bs = Double.parseDouble(arg[0]);
da = bs * 0.4;
hra = bs * 0.2;
gs = bs + da + hra;
System.out.println("Mice's Gross Salary is "+gs);
}
}
Compile : javac gross_salary.java
Run : java gross_salary 1000 (Command line argument for keyboard Entry)
Output : Mice's Gross Salary is 1600.0

Example3.2: Two numbers are input through the keyboard into two locations A and B using
command line argument. Write a program to interchange the contents of A and B without using
third variable.

23
Answer :
public class Swapping
{
public static void main(String arg[])
{
int A = Integer.parseInt(arg[0]);
int B = Integer.parseInt(arg[1]);
A = A + B;
B = A - B;
A = A - B;
System.out.println("A = "+ A +" B = "+B);
}
}

Compile : javac Swapping.java


Run : java Swapping 10 20 (Here 10 and 20 are command line argument)
Output : A = 20 B = 10
Example3.3: The length and breadth of a rectangle and radius of a circle are input through the
keyboard. Write a program to calculate the area and perimeter of the rectangle, and the area
and circumference of the circle.

Rectangle: Area = length * breadth; perimeter = 2*(length + breadth)


Circle: Area = 3.14 * radius * radius circumference = 2 * 3.14 * radius
Answer:

public class Area_demo


{
public static void main(String arg[])
{
double L = Double.parseDouble(arg[0]);
double B = Double.parseDouble(arg[1]);
double R = Double.parseDouble(arg[2]);
double RArea = L * B;
double Rperimeter = 2*(L+B);
double CArea = 3.14 * R * R;
double Ccircum = 2 * 3.14 * R;
System.out.println("Rectangle Area = "+RArea);
System.out.println("Rectangle Perimeter = "+Rperimeter);
System.out.println("Circle Area = "+CArea);
System.out.println("Circle Circumference = "+Ccircum);
}
}

Compile : javac Area_demo


Run : java Area_demo 10 20 5
Output : Rectangle Area = 200.0

24
Rectangle Perimeter = 60.0
Circle Area = 78.5
Circle Circumference = 31.400000000000002
3.6.2 Relational Operator
In the term relational operator, relational refers to the relationships that values
(operands) can have with one another. Thus, the relational operators determine the relation
among different operands. The relational operators are:
< (less than) <= (less than or equal to) = = (equal to)
>( greater than) >= (greater than or equal to)
!= (not equal to)

p q p<q p<=q p= =q p>q p>=q p!=q


0 1 t t f f f t
1 0 f f f t t t
4 4 f t t f f f
3 6 t t f f f t
(Table 3.6 Relational Operators)

3.6.3 Logical operator


Relational operators often are used with logical operator (also known as conditional
operators sometimes) to construct more complex decision making.
&& (logical AND operator)
|| (logical OR operator)
! (logical NOT operator)

operator Use Returns true if


&& op1&& op2 op1 and op2 are both true
|| op1 || op2 Either op1 or op2 is true or
both are true
! !op op is false

(Table 3.7 Logical Operator)


3.6.4 Bitwise Operator
A bitwise operator performs bit manipulation on data. The bitwise operators are
& (bitwise AND) | (bitwise OR) ^ (bitwise XOR)
>> (Right Shift) << (Left Shift) >>> (Zero-fill-right-shift)
~ (one‟s complement)
(i) Bitwise AND „&‟
Let a=5, b=4 a=5 (101)
c=a & b b=4 (100)
c evaluates 4 c=a & b (100)

25
(ii) Bitwise OR „|‟
Let a=5, b=4 a=5 (101)
c=a | b b=4 (100)
c evaluates 5 c=a | b (101)
(iii) Bitwise XOR „^‟
Let a=5, b=4 a=5 (101)
c=a ^ b b=4 (100)
c evaluates 1 c=a ^ b (001)
(iv) Right shift „>>‟
Let a=13 (binary equivalence 1101) a 1 1 0 1
c= a>>2
Now c becomes 3 c 0 0 1 1
(v) Left shift „<<‟
Let a= 5(binary equivalence 101)
c= a<<2 a= 0 0 0 0 0 1 0 1

Now c becomes 20 c= 0 0 0 1 0 1 0 0

(vi) Zero-fill-Right Shift „>>>‟


Let a=8 (binary equivalence 1000)

c= a>>>1 a= 0 0 0 0 1 0 0 0

Now c becomes 4 c= 0 0 0 0 0 1 0 0

- Bitwise operators may not applied to float or double.


- In case of unsigned shift, if left hand operator is negative, then the result is
equivalent to left operand right shifted by right operand plus 2 left-shifted by
inverted value of right operand.
For example, -16 >>> 2=(-16 >> 2) + (2 << ~2) = 1,073,741,820
(vii) Bitwise Complement Operator
Let x = 1001 0110 1100 1011 (in binary format)
~x = 0110 1001 0011 0100

26
Example 3.4: Demonstration of bitwise &, | and ^ operator
public class Bitwise
{
public static void main(String arg[ ])
{
int x = 13, y = 25;
System.out.println(“ x = “+x);
System.out.println(“ y = “+y);
System.out.println(“ x & y = “+(x & y);
System.out.println(“ x | y = “+(x | y);
System.out.println(“ x ^ y = “+(x ^ y);
}
}

Compile: javac Bitwise.java


Run: java Bitwise
Output: x = 13
y = 25
x&y=9
x | y = 29
x ^ y = 20

Example 3.5: Demonstration of shift operators


public class Shift
{
public static void main(String arg[ ])
{
int x = 8, y = -8;
System.out.println(“ x = “+ x +” \ty = “ +y);
System.out.println(“ x >> 2 = ” + (x >> 2) );
System.out.println(“ x << 2 = “ + (x << 2) );
System.out.println(“x >>> 1 = “ + (x >>> 1) );
System.out.println(“ y >> 1 = “ + (y >> 1) );
System.out.println(“y >>> 1 = “ + (y >>> 1) );
}
}

Compile: javac Shift.java


Run: java Shift
Output: x = 8 y = -8
x >> 2 =2
x << 2 = 16
x >>> 1 = 4
y >> 1 = -4
y >>> 1 = 2147483644

27
3.6.5 Special Operators
Java supports some special operators of interest such as instanceof operator and
member selection operator (.).
(i)Instanceof Operator
The instanceof is an object reference operator and returns true if the object on the left-
hand side is an instance of the class given on the right-hand side.
Example: Neha instanceof Student
Is true if the object Neha belongs to the class Student, otherwise it is false.
(ii)Dot Operator
The dot operator (.) is used to access the instance variables and methods of class
objects. It is used to access classes and sub-packages from a package.
Example: Neha.age //reference to the variable use
Neha.mark( ) //reference to the method mark( )
3.6.6 Ternary operator (?:)
Condition ? expression1: expression2;
If condition becomes true ternary operator returns expression1 otherwise expression2.
Example3.4: public class ternary
{
public static void main(String arg[ ])
{ int a=10,b=20,c=0;
c=(a>b?a:b);
System.out.println(“c=”+c);
}
}
Output: c=20

3.7 OPERATOR PRECEDENCE AND ASSOCIATIVITY


Table 3.7 gives operator precedence and associativity. Precedence refers which
operator execute first according to rank. If two operators have same precedence then they are
evaluated according to associativity rule.

3.8 TYPE CONVERSION IN EXPRESSIONS


An expression in Java is any valid combination of operators, constants and variables i.e.
a legal combination of Java tokens. When constants and variables of different types are mixed in
an expression, they are converted to the same type. The process of converting one predefined
type into another is called type conversion.

28
Rank Operator Associativity
1 .()[] Left to right
2 -++ -- ! ~ Right left
3 */ % Left to right
4 +- Left to right
5 << >> >>> Left to right
6 < <= > >= instanceof Left to right
7 = = != Left to right
8 & Left to right
9 ^ Left to right
10 | Left to right
11 && Left to right
12 || Left to right
13 ?: Right to left
14 = Right to left
(Table 3.7 Operator Precedence and Associativity)
Type conversion in two forms
(i) Implicit Type Conversion
An implicit type conversion is a conversion performed by the compiler without
programmer‟s intervention. The Java compiler converts all operands up to the type of the largest
operand, which is called type promotion. This is done operation by operation, as described in the
following type conversion rules:
- If either operand is of type double, the other is converted to double.
- Otherwise, if either operand is of type float, the other is converted to float.
- Otherwise, if either operand is of type long, the other is converted to long.
- Otherwise, both operands are converted to type int.
(ii) Explicit Type Conversion
An explicit type conversion is user-defined that forces an expression to be of specific
type. Type casting in Java is done as shown in Figure3.1.
(type) expression;
Example: An explicit type conversion - (float) (x + y / 2);
Example: A implicit conversion example given on Figure3.1
char ch; int i; float f; double d;

29
Result=( ch / i ) + ( f * d ) – ( f + i ) + ( d / f )

int double float double

int double float double

double

double

double

Figure 3.1 A implicit conversion


3.9 Widening and Narrowing Conversion

When you try to move a big value data type to a small data type variable it leads to narrowing
conversion. In Example3.5 -explains in details of how the conversion happens.

Example3.5: Casting of narrowing conversion

public class clsCasting


{
public static void main(String arg[])
{
double db = 5.29;
int i;
i = (int)db;
System.out.println(i);
}
}
Output: 5

The above program gives output 5, which means you have lost the decimal portion of the
original value.

Widening conversion is exactly vice versa of the same in which try to move small data types
value to big one. The Figure3.2 shows the conversion tree which says when widening conversion
will happen and when narrowing conversion will do.

30
double

float
Widening Narrowing
Conversion Conversion
long

int

char
short

byte

Figure3.2 Conversion tree

Summary

We have discussed all the basic data types and operators available in Java and also seen
their use in expressions. Java expression is a legal combination of Java tokens. Type conversions
and order of precedence of operators during the evaluation have been highlighted. One thing you
have to point out that whenever you want to find left shift always multiply by 2n with the
operand or value, where n is the shifting bits towards left. Similar manner you can divide 2n with
the operand or value for finding right shift value.

31
Review Questions

3.1 Distinguish between a unary, a binary and a ternary operator. Give examples of Java
operators for each one of them.

3.2 Given the following two expressions:


(a) val = 5 (b) val= =5
(i) How are these two different?
(ii) What will be the result of the two if the value of val is 3 initially?
3.3 Given the following set of identifiers:
byte b;
char ch;
short sh;
int i;
long l;
float f;
Identify the data type of the following expression
(a) „a‟- 4 (b) i * l – ch (c ) f + l / sh
3.4 Let a1 and a2 are two double type variables that you want to add as integers and assign to an
integer variable. Construct a Java statement for doing so.
3.5 What is casting, when do we need it?
3.6 What is a literal? How many types of literals are available in Java.
3.7 Which of the following are valid identifiers and why/why not?
Data_rec , -data , 1data , my.file , break , switch
3.8 What kind of constants are the following:
14, 011, 0X2A, 17, 014, 0XBC1
3.9 Write the following real constants into exponent form:
23.197, 7.214, 0.00005, 0.319
3.10 Write the following real constants into fractional form:
0.13504, 0.417E-04, 0.4E-05, 0.123E02
3.11 Write a statement that uses a conditional operator to set grant to 1 if speed is more than 60,
and to 0 otherwise.
3.12 What is meant by implicit and explicit type conversion?
3.13 Give a difference between Unicode character and ASCII character.

32
3.14 What will be the result of the following expression?
(i) 13 & 25 (ii) 9 | 9 (iii) int a=16, a = a >> 2 (iv) int x = 32, a = a << 1
3.15 What are operators? What is their function? Give examples of some unary and binary
operators.

ANALYSIS THE OUTPUT


3.a public class operator1
{
public static void main(String arg[ ])
{
int x=5,y=-10,z;
int a=4,b=2;
z = x++ + ++y * b/a;
System.out.println("z = "+z);
}
}
/*ANSWER z = 1 */
3.b public class operator2
{
public static void main(String arg[ ])
{
int a=10;
System.out.println(" "+(a++ * ++a));
}
}
/* ANSWER 120 */
3.c public class operator3
{
public static void main(String arg[])
{
int a=10;
System.out.println(" "+(++a * ++a));
}
}
/* ANSWER 132 */
3.d public class operator4
{
public static void main(String arg[])
{
int a=10;
System.out.println(" "+(a++ * a++));
}
}
/* ANSWER 110 */

33
3.e public class operator5
{
public static void main(String arg[])
{
int a=10;
System.out.println(" "+(++a * a++));
}
}
/* ANSWER 121 */
3.f public class operator6
{
public static void main(String arg[])
{
int a=10;
System.out.println(" "+ ++a + a++);
}
}
/* ANSWER 1111 */
3.g public class operator7
{
public static void main(String arg[])
{
int p=0,q=1;
p = q++;
p = q++;
p = q--;
p = --q;
System.out.println("p = "+p +" q = "+q);
}
}
/* ANSWER p = 1 q = 1 */

34
Flow of Control
4.0 INTRODUCTION

A Java program is a set of statements, which are normally executed sequentially in the
order in which they appear. In practice, we have a number of situations, where we may have to
change the order of execution of statements based on certain conditions, or repeat a group of
Statements until certain specified conditions are met. Such statements are called program flow
control statements. This chapter is going to discuss various program flow control statements like
selection statements, iteration statements and jump statements.

4.1 SELECTION STATEMENTS

The selection statements allow choosing the set-of-instructions for executions


depending upon an expression‟s truth value. Java provides two types of selection statements: if
and switch. The selection statements are also called conditional statements or decision
statements.

4.1.1 The if Statement of Java

An if statement tests a particular condition; if the condition evaluates to true, a statement


or set-of-statements is executed. The syntax of the statement is given below:

if (expression)
{statement1;
.
.
Statement n;
}
Example 4.1 A demo program to if statement functionality.

public class if1_demo


{
public static void main(String arg[ ])
{
int a = 300, b = 0, c = 0;
if(a > 300)
b = 200;
c = 300;
System.out.println("b = "+ b +" c = "+c);
}
}
Output : b = 0 c = 300
Explanation: In the if1_demo.java program there is no curly braces is given. So only statement
(i.e. b=200) is considered as in if body. The condition a>300 is false so the output will be b=0,
c=300.

35
Example 4.2

public class if2_demo


{
public static void main(String arg[ ])
{
int a = 300, b = 0, c = 0;
if(a < 300)
b = 200;
c = 300;
System.out.println("b = "+ b +" c = "+c);
}
}
Output : b =200 c = 300

Note: If multiple statements are present in if body then must use { }. Otherwise “if” take the
statement1 as its body part.

4.1.2 The if-else Statement


There is another form of if that allows for this kind of either-or condition by
providing an else clause. The syntax for if-else statement is the following:
if(expression)
{ statement1;
.
. true body
.
statement n;
}
else
{ statement1;
.
. false body
.
statement n;
}
- In between if-else no more individual statement(s) are present.
Example: if( x > max);
{
max=x;
}
else
{
max=y;
}
It gives error because multiple individual statements are present in between if-else.

36
Example 4.3
public class if3_demo
{
public static void main(String arg[ ])
{
int a = 5,b = 2;
if(a = = 2)
b=0;
else
b *=10;
System.out.println("b = "+b);
}
}
Output: b = 20
- If you put a semicolon after the test condition, the if statement ends there. The block or
statements following are not the part of if in such cases.

Example: if( x > max); if block stops here


{
max = x; this statement is not part of if
}

4.1.3 Nested ifs


A nested if is an if that has another if in its if‟s body or in it else‟s body.
Example:
if(expression1)
{.
.
.
if(expression2)
{.
.
.
}
else
{.
.
.
}
}
else
{.
.
if(expression3)
{.
.
}
else
{.
.
}
}

37
4.1.4 The if-else-if Ladder
A common programming construct in Java is the if-else-if ladder, which is often also
called the if-else-if staircase because of its appearance. The general form is
if(expression1)
{.
.
}
else if(expression2)
{.
.
}
.
.
else
{.
.
}
Example 4.4Enter a point's x-coordinate and y-coordinate value, find in which quadrant the
point lie.
public class point_demo
{
public static void main(String arg[ ])
{
int x = Integer.parseInt(arg[0]);
int y = Integer.parseInt(arg[1]);
if(x>0 && y>0)
System.out.println("Point is on 1st quadrant");
else if( x<0 && y>0)
System.out.println("Point is on 2nd quadrant");
else if(x<0 && y<0)
System.out.println("Point is on 3rd quadrant");
else if(x>0 && y<0)
System.out.println("Point is on 4th quadrant");
else if(x==0 && y==0)
System.out.println("Point is on origin");
else
System.out.println("Point is not valid");
}
}
Compile : javac point_demo.java
Run : java point_demo 5 -6
Output : Point is on 4th quadrant

4.1.5 The switch Statement


Java provides a multiple-branch statement known as switch. This selection statement
successively tests the value of an expression against a list of integer or character constants. When
38
a match is found, the statements associated with that constant are executed. The syntax of switch
statement is as follows:
switch( <non-long integral expression>)
{
case label 1: <statement 1>
case label 2: <statement 2>
...
case label n: <statement n>
default: <statement>
}
The Nested-switch
Like if statements, a switch statement can also nested
switch(a)
{ case 1: switch(b)
{
case 0: System.out.println(“Divide by zero-error”);
case1:res=a/b;
break;
}
case 2: .
.
.
}
Comparison between switch and nested if-else statement:
(i)A switch statement is more efficient than nested if-else statement.
(ii) A switch statement only evaluates the expression once, while the if statement will evaluate it
repeatedly until it finds a match.
if(guess = = „a‟) switch(guess)
{. {
.
} case „a‟: …
else if(guess = =„b‟) break;
{.
. case „b‟: …
} break;
else if(guess = =„c‟)
{. case „c‟: …
. break;
}
default: …
else
{. break;
. }
}

39
4.2 ITERATION STATEMENTS
The iteration statements allow a set of instructions to be performed repeatedly until a
certain condition is satisfied. The iteration statements are also called loops or looping statements.
Java provides three kinds of loop: for loop, while loop, and do-while loop.
Every loop has its elements that control and govern its execution. Generally, a loop has
four elements that have different purposes. These elements are as given below:
1. Initialization Expression(s)
Before entering in a loop, its control variable(s) must be initialized. The initialization
expression(s) give(s) the loop variable(s) their first value(s). The initialization expression(s) is
executed only once, in the beginning of the loop.
2. Test Expression:
The test expression is an expression whose truth value decides whether the loop-body
will be executed or not.
In an entry-controlled loop, the test-expression is evaluated before entering into a loop
where as in a exit-controlled loop, the test-expression is evaluated before exiting from the loop.
In Java, the for loop and while loop are entry-controlled loops and do-while loop is exit-
controlled loop.
3. Update Expression(s)
The update expression(s) change the value(s) of loop variable(s). The update
expression(s) is executed; at the end of the loop after the loop-body is executed.

4. The Body-of-the-loop
The statements are executed repeatedly from the body of the loop.
4.2.1 Syntax of for loop
for ( initialization expression(s); test-expression; update expression(s) )
{
body-of-the-loop;
}
Example 4.1 Write a program for displaying a to z.
public class a_z
{
public static void main(String arg[ ])
{
char a ;
int i = 0;
for(a ='a';a <= 'z';++a)
{
System.out.print(" "+a);
++i;
}

40
System.out.println("\n for loop body executed "+ i +" times.");
}
}
Compile : javac a_z.java
Run : java a_z
Output : a b c d e f g h i j k l m n o p q r s t u v w x y z
for loop body executed 26 times.

Example 4.2Write a program to display 0 to 9.


public class forTest1
{
public static void main(String arg[ ])
{
int i;
for(i=0;i<10;i++)
System.out.print(" i = "+i);
}
}
Output: i = 0 i = 1 i = 2 i = 3 i = 4 i = 5 i = 6 i = 7 i = 8 i = 9

Example 4.3 for loop containing semicolon.

public class forTest2


{
public static void main(String arg[])
{
int i;
for(i=0;i<10;i++);
System.out.print(" i = "+i);
}
}
Output: i = 10

Example 4.4Printing value from 0 to 9.

public class forTest3


{
public static void main(String arg[ ])
{
int i=0;
for( ;i<10; )
System.out.print(" i = "+i++);
}
}
Output: i = 0 i = 1 i = 2 i = 3 i = 4 i = 5 i = 6 i = 7 i = 8 i = 9

41
Example 4.5 Write a program to find out factorial of a number.

public class factorial_demo


{
public static void main(String arg[ ])
{
int n = Integer.parseInt(arg[0]);
int fact = 1;
for(int i=2;i<=n;i++)
{
fact = fact * i;
}
System.out.println("\nFactorial of "+n+" is "+fact);
}
}
Compile : javac factorial_demo.java
Run : java factorial_demo 5
Output : Factorial of 5 is 120

Example 4.6 Write a program for finding power of a given number.

public class power_demo


{
public static void main(String arg[ ])
{
int x = Integer.parseInt(arg[0]);
int y = Integer.parseInt(arg[1]);
int pow = 1,i = 0;
for(i = 0;i<y;i++)
{
pow = pow * x;
}
System.out.println(""+x+" to the power "+y+" is "+pow);
}
}

Compile : javac power_demo.java


Run : java power_demo 3 2
Output : 3 to the power 2 is 9

Example 4.7 Write a program to reverse a number using command line argument.

public class reverseNumber


{
public static void main(String arg[ ])

42
{
int n = Integer.parseInt(arg[0]);
int r=0,n1 ;
for(n1=n;n1!= 0;n1=n1/10)
{
r = (10 * r) + (n1 % 10);
}
System.out.println("\nThe reverse of number "+ n +" is "+r);
}
}
Compile : javac reverseNumber.java
Run: java reverseNumber 1234
Output : The reverse of number 1234 is 4321

Example4.8 Write a program to add the n terms of the following series 1/1! + 2/2! + 3/3! +....+
n/n!.
public class series_demo
{
public static void main(String arg[])
{
int n = Integer.parseInt(arg[0]);
float sum = 0.0f;
for(int i=1;i<=n;i++)
{
int fact = 1;
for(int j=1;j<=i;j++)
fact = fact * j;
sum = sum + (float)i/fact;
}
System.out.println("\nSum of this series is : "+sum);
}
}
Compile : javac series_demo.java
Run : java series_demo 5
Output : Sum of this series is : 2.708335

Example 4.9 Write a program to find a number is prime or not.

public class prime_demo


{
public static void main(String arg[ ])
{
int n = Integer.parseInt(arg[0]);
int flag = 0;

43
for(int k = 2;k<n/2;k++)
{
if(n%k==0)
{
flag=1;
break;
}
}
if(flag==1)
System.out.println("Number "+n+" is not prime");
else
System.out.println("Number "+n+" is prime");
}
}
Compile : javac prime_demo.java
Run : java prime_demo 37
Output : Number 37 is prime

Example 4.10 Write a program for finding fibonacii series.


public class fibonacii
{
public static void main(String arg[ ])
{
int n = Integer.parseInt(arg[0]);
int a = 1, b = 1, c = 0,i = 0;
System.out.print("\n\n\t "+a);
System.out.print(" "+b);
for(i = 3;i<=n;i++)
{
c = a+b;
a = b;
b = c;
System.out.print(" "+c);
}
System.out.println("\n\n\t Fibonacii series upto... "+n);
}
}
Compile : javac fibonacii.java
Run : java fibonacii 8
Output : 1 1 2 3 5 8 13 21
Fibonacii series upto... 8
Example 4.11 Write a program in command line to from the pascal triangle.
*
* *
* * *

44
public class triangle{
public static void main(String arg[ ])
{
int n = Integer.parseInt(arg[0]);
int sp = 40;
for(int i=0; i<n;i++)
{
for(int k=0;k<=sp; k++)
System.out.print(" ");
sp = sp - 2;
for(int j=0;j<=i;j++)
System.out.print("...*");
System.out.println();
}
}
}

4.2.2 while loop and do-while loop


Syntax of while loop: Syntax of do-while loop:
initialization expression(s) initialization expression(s)
while(test-expression) do
{ {
loop-body loop-body
update expression(s) update expression(s)
} } while(test-expression);

Difference between while loop and do-while loop


while loop do-while loop
(1) while loop body never be (1) do-while loop body execute at
execute if the initial test- least once if the initial test-expression
expression is false. is false.
(2) while loop is a entry-controlled (2) do-while is a exit-controlled loop.
loop.
(3) Example: (3)Example:
int i=0; int i=10;
while(i>20) do
{ {
System.out.println(“Hello”); System.out.println(“Hello”);
++i; ++i;
} }while(i>20);
Output: no output Output: Hello

45
Example 4.12 Write a program to find the LCM and GCD of two numbers using command line
argument.
public class lcm_gcd
{
public static void main(String arg[ ])
{
int a = Integer.parseInt(arg[0]);
int b = Integer.parseInt(arg[1]);
int x = a, int y = b,z;
if(x<y)
{
z = x;
x = y;
y = z;
}
int r = x % y;
while(r != 0)
{
x = y;
y = r;
r = x % y;
}
System.out.println(“GCD= ” + y);
int l = (x * y) / y;
System.out.println(“LCM= ” + l);
}
}

4.2.3 Infinite Loop


In a loop it tests expression never becomes false then that loop goes to infinite
execution. For example
int i = 0;
while(i<20)
{
System.out.println(“Hello”);
}
or
for( ; ; )
{
System.out.println(“Hello”);
}

4.3 JUMP STATEMENTS


The jump statement unconditionally transfer program within a function. Java has three
statements that perform an unconditional branch: break, continue and return. Java also provides a
standard library function System.exit( ) that helps you break out of a program.

46
4.3.1 The break Statement
The break statement enables a program to skip over part of the code. A break statement
terminates the smallest enclosing while, do-while, for or switch. The following figure explains
the working of a break statement:

while(test-expression) for(int; expression; update) do


{ { {
statement1; statement1; statement1;
if( i > 20) if( i > 20) if( i > 20)
break; break; break;
. . .
. . .
. . .
statement2; statement2; statement2;
} } }while(expression);
statement3; statement3; statement3;

(Figure 4.1 the working of a break statement)

4.3.2 The continue Statement


The continue is another jump statement like the break statement as both the statement skip over a
part of the code. The continue statement do not forcing termination, it forces the next iteration of
the loop to take place, skipping any code in between. The figure4.2 explains the working of
continue statement.

while(test-expression) for(int; expression; update) do


{ { {
statement1; statement1; statement1;
if( condition) if( condition) if( condition)
continue; continue; continue;
statement2; statement2; statement2;
. . .
. . .
. . .
} } }while(expression);
statement3; statement3; statement3;

(Figure 4.2 the working of continue statement)

47
Example 4.13 A demo program of break and continue.

public class break_demo public class continue_demo


{ public static void main(String arg[ ]) { public static void main(String arg[ ])
{ {
for(int i=1; i<=5; i++) for(int i=1; i<=5; i++)
{ {
if(i = = 3) if(i = = 3)
break; continue;
System.out.println(“ ” + i); System.out.println(“ ” + i);
} }
} }
} }
Output: 1 2 Output: 1 2 4 5

4.3.3 The return statement


The return statement is used to stop execution of a method and transfer control back to
the calling code (caller). The return statements have two forms void and non-void method. The
void method does not return any value to the caller where as non void must return a value.
Example 4.14A demo program of void and non void method
public class return_demo
{ public static void main(String arg[ ])
{
output1(10);
int a =output2(10);
System.out.println(“ a =” +a);
}
static void output1(int k)
{ void method
System.out.println(“ k =” +k);
}
static int output2(int l)
{
if(l > 3)
return l*l;
else non void method
return ++l;
}
}
Output: 10 100
4.4 ARRAY
An array is a collection of related data items referenced by a common name, in
contiguous memory locations. Arrays are different types:
(i) One-dimensional array
(ii) Multi dimensional array

48
4.4.1 One-dimensional Array
One-dimensional array consists of single row and multiple columns.
- To declare a one-dimensional array you have to follow the following syntax:
(i) type array-name[ ] = new type[size]
(ii) type[ ] array-name = new type[size]
- The [ ] is called subscripts or indices.
Example:
int a[ ] = new int[5];

a[0] a[1] a[2] a[3] a[4]

- Initializing an array
int a[ ] = {1,2,4,5,6,8,9};
4.4.2 Multidimensional Arrays
In Java an array of arrays can be defined as multidimensional arrays.
Syntax: type array_name [ ] [ ] = new type[size][size];
type [ ][ ][ ] array_name = new type[size][size][size];
Example: int a[ ][ ] = new int[4][4];
int [ ][ ][ ] b = new int[5][3][2];
- Initializing two-dimensional array.
double a[ ][ ] = {
{2.0,0.0,0.0,0.0},//1st row
{0.0,1.0,0.0,0.0},//2nd row
{0.0,0.0,1.0,0.0},//3rd row
{0.0,0.0,0.0,1.0}//4th row
};
Example 4.15 Write a program insert five values into an array and display it, using command
line argument.
public class array1
{
public static void main(String arg[ ])
{
int [ ]a = new int[5];
int i=0;
for(i=0;i<5;i++)
a[i]=i;
for(i=0;i<5;i++)
System.out.println("a[ "+i+" ] = "+a[i]);
}
}
Output : a[ 0 ] = 0
a[ 1 ] = 1
a[ 2 ] = 2
a[ 3 ] = 3
a[ 4 ] = 4

49
Example 4.16 Write a program to convert Decimal number to Binary Number using command
line argument.
public class Decimal_Binary
{
public static void main(String arg[ ])
{
int n = Integer.parseInt(arg[0]);
int a[ ] = new int[20];
int b[ ] = new int[20];
int i=0,j=0,k=0;
while(n>0)
{
a[i++] = n%2;
n = n/2;
}
k = i -1;
for(j=0;j<i;j++)
{
b[j] = a[k--];
System.out.print(" "+b[j]);
}
}
} Compile : javac Decimal_Binary.java
Run : java Decimal_Binary 14
Output : 1 1 1 0
4.4.3 Anonymous Arrays
The construction of nameless array of a specific type is known as anonymous array.
Example 4.17Anonymous Array
public class anonymous_demo Anonymous Array elements
{
public static void main(String arg[ ])
{
System.out.println("Min value is "+findMinimum(new int[ ] {5,16,4,8,6}) );
}
public static int findMinimum(int arr[ ])
{
int min = arr[0];
for(int i=1;i<arr.length;i++)
{
if(arr[i]<min)
min = arr[i];
}
return min;
}
}
Output : Min value is 4

50
4.4.4 Finding Array Size
The array size can be found by using the “length” property of array.

Example 4.18
public class length_demo
{
public static void main(String arg[ ])
{
int a[ ] = {10,20,30,40,50};
System.out.print("size of array "+ a.length);
}
}
Output : size of array 5

4.4.5 Fetching Data in an Array


There are two ways you can display the array contents which are discussed in Example
4.19 and Example 4.20.

Example 4.19
public class array_old
{
public static void main(String arg[ ])
{
int a[ ] ={10,20,30,40,50};
for(int i=0;i<a.length;i++)
System.out.print(" "+ a[i]);
}
}
Output : 10 20 30 40 50

Example 4.20
public class array_new
{
public static void main(String arg[ ])
{
int a[ ] ={10,20,30,40,50};
for(int i: a)
System.out.print(" "+ i );
}
}
Output : 10 20 30 40 50
In the Example 4.20, “int i” statement; i referred to index as well as value. This syntax is
available in jdk1.5 onwards.

51
Summary
We have discussed in this chapter the features of the if, if-else, switch selection statements
supported by Java. The loops and conditional statements are backbone of any programming
language. We have also seen how to use the break and continue statements to skip or jump out of
a loop, if need be. Also we discussed one dimensional and multidimensional array for creating
more than one variable with single name differ by indices.

52
Review Question
4.1 Write a program to find whether the given character is a digit or a letter.
4.2 Write a program to input a digit and print it words.
4.3 Write a program to read three double numbers and print the largest of these.
4.4 Write a program to print a tribonacii series e.g., 0 1 2 3 6 11 20 37.
4.5 Write a program to find sum of the series s = 1 + x + x2 + . . . + xn
4.6 Write a program to find prime factors of a number.
4.7 Give difference between while loop and do while loop.
4.8 Write a Java program to check whether the given number is palindrome or not.
4.9 Give difference between switch and if…else if.
4.10 Rewrite the following fragment using switch
if( ch = = „e‟)
++a;
if( ch = = „w‟)
++b;
if( ch = = „n‟)
++c;
if( ch = = „s‟)
++d;
else
++k;
4.11 Enter a number and find its absolute value. For example │-a│= a.
4.12 Find out the output of given program?
4.12(a)
public class if4_demo
{
public static void main(String arg[ ])
{
int a = 3;
float b = 3.0f;
if(a == b)
{
System.out.println(" a and b are equal");
}
}
}
Output : a and b are equal

4.12(b)
public class if5_demo
{
public static void main(String arg[ ])
{
int A = 3;
double B = 3.0000000000;
if(A == B)

53
{
System.out.println(" A and B are equal");
}
}
}
Output : A and B are equal

4.12(c )
public class if6_demo
{
public static void main(String arg[ ])
{
int A = 65;
char B = 'A';
if(A == B)
{
System.out.println(" A and B are equal");
}
}
}
Output : A and B are equal
4.12(d)
public class cs1
{
public static void main(String arg[ ])
{
int i;
for(i=1;i<=4;i++)
{
switch(i)
{
case 1: System.out.println(" "+i);
break;
case 2: System.out.println(" "+i);
break;
case 3: System.out.println(" "+i);
break;
}
switch(i)
{
case 4:System.out.println(" "+i);
break;
}
}
}
}

54
4.12(e)
public class cs2
{
public static void main(String arg[ ])
{
int i = 20, k = 0;
for(int j = 1; j < i ; j = 1 + 4 * ( i / j ) )
{
k + = j < 10 ? 4 : 3;
}
System.out.println(" "+k);
}
}
4.12(f)
public class cs7
{
public static void main(String arg[ ])
{
for(int i = 0;i<20;i++)
{
switch(i)
{
case 0: i+=5;
case 1: i+=2;
case 2: i+=5;
default: i+=4;
break;
}
System.out.println(" "+i);
}
}
}
4.12(g)
public class cs9
{
public static void main(String arg[ ])
{
for(double x=0;x!=10;x=x+0.1)
System.out.println("x = "+x);
}
}
4.12(h)
public class cs8
{
public static void main(String arg[ ])
{

55
int i=2;
switch(i)
{
case 0: i+=2;
case 1: i+=4;
case 2: i+=8;
case 3: i+=16;
default: i+=32;
break;
}
System.out.println(" "+i);
}
}

4.13(i) Can a conditional operator replace an if statement?


(ii) What is the significance of a break statement in a switch statement?
(iii) What are iteration statements?
(iv) How to fetch data in a one-dimensional array?
(v) Suppose A, B, C are arrays of integers of size m, n, m+ n respectively. Give a program to
produce a third array C, containing all the data of array A and B.
(vi) What are the advantages and disadvantages of an array?
4.14 Write a program that checks whether or not two arrays are identical, that is, whether they
have same characters and all characters in corresponding positions are equal.

56
Class, Objects and Methods
5.0 INTRODUCTION
Ino Java programing, it is important to understand the basic terminology and concepts
in object-oriented programming.
Anything we wish to represent in a Java program must be encapsulated in a class that
defines the state and behavior of the basic program components known as object. Classes create
objects and objects use methods to communicate between them. In this chapter, the emphasis is
on providing how to create a class, method and object.
5.1 DEFINING A CLASS
In order to bring a class into existence in Java program, it should be declared. In Java
there are two types of class user defined class and predefined class.
5.1.1User defined class
User defined class is declared using keyword “class”. The generic syntax for class
declaration in Java is:
[access_specifier] [modifier] class <class_name>
optional optional essential essential
{
[Member Variable declaration;] class body
[ methods declaration]
}
Example: public final class abc
{

}
- access_specifier can be public, private or protected. If no access_specifier is mention it is
treated as “default” access specifier.
- modifier: this is a keyword which define the functionality of a class. These are final and
abstract.

5.1.2 Predefined class


Predefined class is already declared inside Java, as per requirement of problem these
classes are used to reduce the complex programming logic.
Example: Math class, Scanner class, Applet class etc.

5.2 DECLARING MEMBER VARIABLES


A class‟s state is represented by its member variables. You declare a class‟s member
variables in the body of the class. The class variables can be of two types.
(i) Class variable (static variable)
A data member is declared once in a class is known as class variable. All objects of the
class type, share these data members, as there is single copy of them available in memory.
(ii) Instance Variable
A data member is created for every object of the class. For n objects of a class type, there
would be n copies of instance variable, one for an object.
Syntax: [access_specifier] [modifier] [type] name
optional optional essential

57
Example: public class abc
{
int a; //instance variable
float b; //instance variable
static float c; //class variable
}

Variables default value: Every variable must have a value before its value is use. Table 5.1
shows default value of various types.

Type Default value


byte 0 bytes
short 0 of short type
int 0
long 0L
float 0.0 F
double 0.0 D
char null
boolean false
All reference type null
(Table 5.1 default value of variable)

5.3DEFINING METHODS
This is a block of code which performs well define job by accepting parameter from the
caller and at the time of requirement it can return value. It is of two types user defined methods
and pre-defined methods.
5.3.1 User defined Methods
The methods which are created by the user is known as user defined methods.
[access_specifier] [modifier] <return type> method_ name(parameter list)
{
Method Body;
.
.
.
Return value;
}
- Access specifier can be public, private, protected or default.
- Access modifier can be static, final, abstract, synchronized.
- Return type can be primitive data type ( int, float etc), class type or void.
- Parameter list is required as for the programming logic.
Example: int myMethod(int a)
{ .
. parameter
. Argument
}
myMethod(10);

58
5.3.2 Pre-defined Method
These methods are already present in Java for specific purpose. Some of predefined
math class methods are given below.
sin(x) – This method returns the sine of the angle x in radians.
cos(x) - This method returns the cosine of the angle x in radians.
tan(x) - This method returns the tangent of the angle x in radians.
asin(y) - This method returns the angle whose sine is y.
acos(y) - This method returns the angle whose cosine is y.
atan(y) - This method returns the angle whose tangent is y.
atan2(x,y) - This method returns the angle whose tangent is x/y.
pow(x,y) - This method returns x raised to y (xy).
exp(x) - This method returns e raised to x (ex).
log(x) - This method returns the natural logarithm of x.
sqrt(x) - This method returns the square root of x.
ceil(x) - This method returns the smallest whole number greater or equal to x (roundup).
floor(x) - This method returns the largest whole number less than or equal to x (round
down).
rint(x) - This method returns the rounded value of x.
abs(a) - This method returns the absolute value of a.
max(a,b) - This method returns the maximum of a and b.
min(a,b) - This method returns the minimum of a and b.

5.4 CREATING AND USING OBJECTS


As you know that a class provides a blue print for objects. From this blueprint, objects
are created using the new operator along with the class constructor e.g. following statement
creates an object of “abc” type.
abc a = new abc( );

class object operator constructor


name name
5.4.1 Declaring object variable
An object variable can be created as
<class_name> <object_name>
Example:
abc a; a null

a = new abc ( ); a 301

5.4.2 Using objects


Once you‟ve created an object you probably want to use it for something. Objects give
you two ways to do these things:
(1) Accessing Member Variables
Example: obj1.x;
(ii) Call its methods
Example: obj1.myMethod(10);

59
Example 5.1 accessing a data member by an object

public class myClass


{
int x;
public static void main(String arg[ ])
{
myClass m = new myClass( );
System.out.println(m.x);
}
} // Accessing member variable by object m
Output: 0

- x have default value „0‟ if no value is assigned due to integer constant.

Example 5.2 without object a class data member is not access

public class myClass1


{
int x;
public static void main(String arg[ ])
{
System.out.println(x);
}
}
Output: compile time error

Example 5.3 calling a method by an object


public class Car
{
public static void main(String arg[ ])
{
Car obj1 = new Car( );
obj1.move("faster");
}
public void move(String s)
{ // calling method named as „move‟ by object obj1
System.out.println(s);
}
}
Output: faster

Example 5.4Program to calculate and print roots of a quadratic equation ax2+bx+c=0(a!=0).


The coefficients of quadratic equation a, b, c are received as parameters.

60
public class QuadraticEquation
{
public void Test(double a,double b,double c)
{
double d,root1,root2;
d = b*b - 4*a*c;
if(d>0)
{
root1 = (-b + Math.sqrt(d)/(2*a));
root2 = (-b - Math.sqrt(d)/(2*a));
System.out.println("\nRoots are real and Unequal");
System.out.println("root1:"+root1+"\troot2:"+root2);
}
else if(d == 0)
{
root1 = -b/(2*a);
root2 = root1;
System.out.println("\nRoots are real and equal");
System.out.println("root1:"+root1+"\troot2:"+root2);
}
else
{
double real = -b/(2*a);
d = -d;
double num = Math.pow(d, 0.5);
double imag = num/(2*a);
System.out.println("\nRoots are Imaginary");
System.out.print("root1: "+real+" +j "+imag);
System.out.println("\troot2: "+real+" -j "+imag);
}
}
public static void main(String arg[ ])
{
double a = Double.parseDouble(arg[0]);
double b = Double.parseDouble(arg[1]);
double c = Double.parseDouble(arg[2]);
QuadraticEquation obj1 = new QuadraticEquation( );
obj1.Test(a,b,c);
}
}
Compile : javac QuadraticEquation.java
Run : java QuadraticEquation 2 6 2
Output : Roots are and unequal
root1:-4.881966011250105 root2:-7.118033988749895

61
Example5.5 Write a java program to compute cosine series :
cos(X) = 1 – x2/2! + x4/4! – x6/6! + ...+ xn/n!

public class Series_cosX


{
public void cosSeries(double x)
{
int n =20,i,j;
double sum = 1,t = 0, y = x,sign =1;
x = x*3.1412/180; //Converted into radians
t = t+1;
sum = 1;
for(i=2; i<=n;i=i+2)
{
double fact =1;
for(j=1;j<=i;j++)
{
fact = fact*j;
}
t = t *Math.pow(x,i);
sign *= -1;
sum = sum + (t/fact)*sign;
}
System.out.println("cos( "+ y +" ) = " + sum);
}
public static void main(String arg[ ])
{
double x = Double.parseDouble(arg[0]);
Series_cosX obj = new Series_cosX( );
obj.cosSeries(x);
}
}
Compile: javac Series_cosX.java
Run: java Series_cosX 5
Output: cos( 5.0 ) = 0.9961932524008871

5.5 GETTERS AND SETTERS (MUTATOR) MATHODS IN CLASSES


An accessor method or getter method is a method that returns the value of a data-
member of the class. The name of an accessor method for a variable is obtained by capitalizing
the name of variable and adding “get” in front of the name.
Example: public double getMarks( )
{
return marks;
}

62
An setter method (or mutator method) is a method that sets/changes the value of a data-member
of the class. The name of an method generally consists of “set” followed by a capitalized copy of
the variable‟s name and it may have a parameter with the same type as the variable.
Example: public void setMarks(double mark)
{
marks = mark;
}

5.6 ACTUAL AND FORMAL PARAMETERS


After the discussion so far, you have seen that there are parameters in the method
(function) definition and in the statement that invokes the function i.e., the function call
statement. The parameters that appear in function definition are called formal parameters and the
parameters that appear in function call statement are actual parameters.
public int setMultiplyvalue(int x, int y)
Function {
defination return x*y; formal parameter
}
// code fragment where setMultiplyvalue method is used.
int length = 0;
int width = 5;
int area = setMultiplyvalue(length,width); Function call statement
Actual parameters
Here „x and y‟ are formal parameters and length and width are actual parameter.
When you pass arguments to functions, you can pass any value of legal Java datatype. That is,
arguments to function can be:
(i) of primitive data types i.e., char, bytes, short, int etc.
(ii) or reference data types i.e., objects or arrays.
A function is invoked in two manner: call by value and call by reference.
Example 5.6 Write a program to declare a class as "Calculator" having attributes a,b and sum.
Create two objects of Calculator class with initial value of a and b and display the sum
value.(callby reference)

class Calculator
{
int a,b,sum;
}
public class runCalculator
{
public static void main(String arg[ ])
{
Calculator c1 = new Calculator( );
Calculator c2 = new Calculator( );
c1.a = 10;
c1.b = 20;
c2.a = 15;
c2.b = 30;

63
c1.sum = c1.a + c1.b;
c2.sum = c2.a + c2.b;
System.out.println("c1Sum = "+c1.sum);
System.out.println("c2sum = "+c2.sum);
}
}
Output: c1Sum = 30
c2sum = 45

Example 5.7 Use setData( ) method to set some value on a and b in Example-5.6. Also create a
display method to display sum value.(callby value method)

class Calculator
{
int a,b,sum;
void setData(int x,int y)
{
a = x;
b = y;
sum = x + y;
}
void display( )
{
System.out.println("Sum = "+sum);
}
}
public class runCalculator1
{
public static void main(String arg[ ])
{
Calculator c1 = new Calculator( );
Calculator c2 = new Calculator( );
c1.setData(10,20);
c2.setData(15,30);
c2.display( );
c1.display( );
}
}
Output: Sum = 45
Sum = 30

5.7 RETURNING A VALUE BY METHOD


The “return” keyword used to return a value or object from a method.

Example 5.8 Returning a value by a method

64
class fact
{
int factorial(int n)
{
int f = 1;
for(int i=1;i<=n;i++)
{
f=f*i;
}
return f;
}
}
public class factorial_Calculate
{
public static void main(String arg[ ])
{
int f;
fact obj1 = new fact( );
f = obj1.factorial(5);
System.out.println("Factorial of 5 is "+f);
}
}
Output: Factorial of 5 is 120

If you do not want to return a value from the method then use “void” in function
prototype (function declaration).

5.8 CONSTRUCTORS
- Constructor is a special member function which automatically executed when the object is
created.
- It‟s name must be same as class name.
- It initializes an object immediately upon creation.
- A constructor never returns value because its implicit return type of a class constructor is the
class type itself.

Example 5.9(a) Create a class Box, which uses a constructors to initialize the dimensions width,
height and depth of a box.

class Box
{
double width,height,depth;
Box( )
{
width = 10;
height = 10;
depth = 10;

65
}
double volume( )
{
return width*height*depth;
}
}
public class BoxDemo
{
public static void main(String arg[ ])
{
Box mybox = new Box( ); //constructor
double vol = mybox.volume( );
System.out.println("Volume is "+vol);
}
}
Output: Volume is 1000.0

Explanation: Box mybox = new Box( );


When this statement is executed it execute the constructor (here Box( ) ) and initialize the
member variable width, height, depth to 10.
vol = mybox.volume( );
This mybox.volume( ) instruction calculate the required logic and return a value to the variable
“vol”.
Example 5.9(b) Returning Objects using returnObject() method.

class Test
{
int a;
Test( ){}
Test(int i)
{
a = i;
}
Test returnObject( )
{
Test obj = new Test(a+10);
return obj;
}
}
public class RetObj
{
public static void main(String arg[ ])
{
Test obj1 = new Test( );
Test obj2 = new Test( );
obj2 = obj1.returnObject( );

66
System.out.println(" "+obj2.a);
}
}
Output: 10

5.8.1 Types of Constructors


There are two types of constructors
(i) Implicit or default constructor
(ii) Explicit constructor

(i) Implicit or default constructor


If no constructor is present in a class then a default constructor will available for the
class for providing memory to an “object”.

(ii) Explicit constructor


This type of constructor must be present in the class. If this constructor takes any
parameter then it is known as parameterized constructor.

Example 5.10 Explicit Constructor

class Car
{
int x ;
Car( )
{
System.out.println("this is a explicit constructor.");
}
Car(int a)
{
x = a;
System.out.println("This car has "+x+" wheels");
}
}
public class Constructor_Demo
{
public static void main(String arg[ ])
{
Car indigo = new Car( );
Car rinz = new Car(6);
}
}
Output: this is a explicit constructor.
This car has 6 wheels

67
5.9 CONSTRUCTOR AND METHOD OVERLOADING
If in a class have more than one forms of constructors are present then we can say
constructors are overloaded. As shown in Example 5.10.
Defining multiple functions with same name is known as function/Method overloading or
function polymorphism. Polymorphism means one function having many forms. The overloaded
method must be different in their argument list and with different data types.

Example 5.11 Method overloading

class Add
{
int x,y,z,sum;
void add(int a,int b)
{
x = a;
y = b;
sum = a+b;
System.out.println("Sum of two nos = "+sum);
}
void add(int p,int q,int r)
{
x = p;
y = q;
z = r;
sum = p+q+r;
System.out.println("Sum of three nos = "+sum);
}
}
public class MethodOverload
{
public static void main(String arg[ ])
{
Add obj1 = new Add( );
Add obj2 = new Add( );
obj1.add(10,20);
obj2.add(5,4,6);
}
}
Output: Sum of two nos = 30
Sum of three nos = 15

5.10 PASS BY VALUE / CALL– BY– VALUE


This method copies the value of an argument into the formal parameter of the
subroutine. Therefore changes made to the parameter of the subroutine have no effect on the
argument.

68
Example 5.12 Passed by value
class Test
{
int x,y;
void passValue(int i,int j)
{
x = i;
y = j; a b
x *=2; 15 20
y /=2;
} 409 502
}
public class CallByValue obj
{
public static void main(String arg[ ]) i j
{ 15 30 20 10
Test obj = new Test( );
2202
int a = 15,b = 20; 301 305
System.out.println("a and b before call: "+a+"055
"+b);
obj.passValue(a,b);
System.out.println("a and b after call: "+a+" "+b);
}
}
Output: a and b before call: 15 20
a and b after call: 15 20
You can see the value changed in x and y are not reflect to a,b due to callby value mechanism.
5.11 PASS BY REFERENCE / CALL-BY-REFERENCE
In this method, a reference to an argument is passed to the parameter. This means that
changes made to the parameter will affect the argument used to call subroutine.
Example 5.13 Pass by Reference

class Test
{
int a,b;
Test(int i,int j) obj
{ 301
a = i; a b
b = j; 15 30 20 10
}
void passReference(Test t) 301 305
{
t.a *=2; 301
t.b /=2; t
}
}
public class CallByReference

69
{
public static void main(String arg[ ])
{
int x = 15,y = 20;
Test obj = new Test(x,y);
System.out.println("obj.a and obj.b before call: "+obj.a+" "+obj.b);
obj.passReference(obj);
System.out.println("obj.a and obj.b after call: "+obj.a+" "+obj.b);
}
}
Output: obj.a and obj.b before call: 15 20
obj.a and obj.b after call: 30 10

5.12 RECURSION
If statement or group statements are executed repeatedly inside a method is known as
recursion. Java supports recursion. Recursion is of two type
(a) Direct Recursion: A method that calls itself is said to be direct recursion.
(b) Indirect Recursion: If two or more methods calls each other for executing a statement or
group statements is known as indirect recursion.

Example 5.14 Using direct recursion finds out factorial of a number.

class Factorial
{
int fact(int n)
{
int result;
if(n == 1)
return 1;
result = n * fact(n-1);
return result;
}
}
public class DirectRecursion
{
public static void main(String arg[ ])
{
Factorial f = new Factorial( );
System.out.println("Factorial of 3 is "+f.fact(3));
System.out.println("Factorial of 4 is "+f.fact(4));
}
}
Output: Factorial of 3 is 6
Factorial of 4 is 24

70
Example 5.15 Using Indirect recursion finds factorial of a number.
public class IndirectRecursion
{
int fact;
IndirectRecursion( )
{
fact = 1;
}
void calculate(int k)
{
if(k == 0)
{
System.out.println("Factorial value is "+fact);
}
else
{
num(k);
}
}
void num(int n)
{
fact = fact*n;
calculate(--n);
}
public static void main(String arg[ ])
{
IndirectRecursion obj = new IndirectRecursion( );
obj.num(5);
}
}
Output: Factorial value is 120
In example 5.15 calculate( ) and num ( )method call each other repeatedly to finding factorial of
a number.
5.13 INNER CLASS
This is a type of class which appears inside another class. The object creation process
of the inner class is dependent upon the object of its outer class.
Example 5.12 Inner Class
class outer
{
int x;
outer( )
{
x=10;
}
public void display( )
{

71
System.out.println("outer class");
}
class inner
{
public void print( )
{
System.out.println("inner class "+ x);
}
}
}
public class inner_demo{
public static void main(String arg[ ])
{
outer ou = new outer( );
outer.inner in = ou.new inner( );
ou.display( );
in.print( );
}
}
Output: outer class
inner class 10

5.14 JAVA KEYWORDS


Already we discuss variables keywords present in Java. Let‟s discuss some of import
java keywords like static, final and this.
5.14.1 Static
- If a variable declare as static then that variable occupy a single memory and all objects share
this memory.
- Static variable can be access by class name as well as object name.
Example 5.17(a) Static Variable

public class static_demo


{
int x;
static int y;
static_demo( ) y
{
0123
x = 0;
y = 0;
}
public void show( ) d1 d2 d3
{
System.out.print("x = " + ++x);
System.out.println("\t y = " + ++y); 01 01 01
} x x x
public static void main(String arg[ ])

72
{
static_demo d1 = new static_demo( );
static_demo d2 = new static_demo( );
static_demo d3 = new static_demo( );
d1.show( );
d2.show( );
d3.show( );
}
}
Output: x = 1 y = 1
x=1 y=2
x=1 y=3

Static Method:
The static can be called either from within class of origin or from any other class. That is
there two cases:
(i) The syntax for invoking a static method from within their own class
Static_method_name(<parameter_if_any>)
Example: double meanval = mean(attendance);
(ii) When called from outside the class of origin, then call it using the following syntax.
Class_of_origin . static_method_name(<parameters_if_any>)

Example 5.17(b) Static Method

public class Feet2Meters


{
public static final double feet2meters = 0.3045;
public static double convert(double feet)
{
return feet * feet2meters;
}
public static void main(String arg[ ])
{
double feet = 100;
double meters = Feet2Meters.convert(feet);
System.out.println(feet + “ feet is ” + meters + “ meters ”);
}
}
Output: 100.0 feet is 30.48meters

- Good practice in Java is that, static methods should be invoked with using the
class name through it can be invoked using an object i.e.
(i) className . methodName(arguments)
Example: Feet2Meters . convert(feet);
(ii) objectName . methodName(arguments)

73
5.14.2 Final
The value of a variable may changes during the execution of the program, but a
constant represents permanent data that never changes. The word final is a Java keyword which
means that constant cannot be changed. A constant must be declared and initialized in the same
statement. The below given syntax for declaring a final variable as
final data type constantname = value;

Example 5.18 Creating Constant Variable

public class ComputerArea


{
public static void main(String arg[ ])
{
final double PI = 3.14159;
double radius = 20;
double area = radius * radius * PI;
System.out.println("area = " + area);
}
}
Output: area = 1256.636

5.14.3 this
“this” is a keyword which returns the reference to the current objects.

Example 5.19(a) Accessing Data member by object using this keyword.


class CL
{
int x = 1;
CL me( )
{
return this;
}
}
public class thisExample5_19_a
{
public static void main(String arg[ ])
{
CL cl = new CL( );
System.out.println(cl.x);
System.out.println(cl.me( ).x );
System.out.println(cl.me( ).me( ).x);
}
}
Output: 1
1
1

74
Explanation: The statements - cl.x
- cl.me( ).x
- cl.me( ).me( ).x
all are same to accessing a data member by an object.

Example 5.19(b) Datamembers are same in class and methods

class OneNumber
{
int n;
void setValue(int n)
{
this.n = n; //n = n is absurd
}
}
public class thisExample5_19_b
{
public static void main(String arg[ ])
{
OneNumber x = new OneNumber( );
x.setValue(3);
System.out.println(x.n);
}
}
Output : 3
Explanation: Since the name n is already used in the parameter name so n= n is absurd. The
workaround is to use the “this” keyword to refer the object. Thus we have thin.n = n .

Example 5.19( c)

class B
{
int n;
void setMe(int m)
{
c obj = new c( );
obj.setValue(this,m);
}
}
class c
{
void setValue(B obj1, int k)
{
obj1.n = k;
}
}

75
public class thisExample5_19_c
{
public static void main(String arg[ ])
{
B x = new B( );
x.setMe(3);
System.out.println(x.n);
}
}
Output: 3

Explanation: In example 5.19(c ) class B has a member variable n. It has a method setMe( ).
Thus method setMe() call the method setValue() of class c passing objects as arguments.

5.15 SIMPLE INPUT AND OUTPUT


System.out refers to the standard output device. System.in refers to the standard input
device.
By default the output device is the console and input device is the keyword.

5.15.1 Formatting Console Output


The general syntax of console output is
System.out.printf(format,item1,item 2,…,item n);
Where format specifier specifies how an item should be display( );

Example: double x = 2.0/3;

System.out.printf(“The value of x =%f ”,x);


or
System.out.println(“ The value of x=” + (int) (x*100)/100.0);
which shows 0.66.
An item may be a numeric value, a character, a boolean value or a string. A simple specifier
consists of a percent sign (%) and a conversion code. The Table 5.1 gives some specifier format

Specifier Output Example


%b A boolean value true or false
%c A character „a‟
%d A decimal integer 200
%f A floating point number 45.460000
%e A number in standard scientific notation 4.556000e+01
%s A string “Java is”
Table 5.1 Format of different specifier
- System.out.printf(“ ”) : Print the output and cursor present on the same line.
- System.out.println(“ ”) : Print the output and cursor goto the next line.

Example: int count = 5;


double amount = 45.56;

76
System.out.printf(“count is %d and amount is %f “,count,amount);
Output: count is 5 and amount is 45.560000
Example: double x = 2.0/3;
System.out.println(“x is %4.2f ” + x);
Output: x is 0.67

5.15.2 Console Input Using Scanner Class


Console input is not directly support in Java, but you can use the scanner class to
create an object to read input from system in as follows:
Scanner input = new Scanner (System.in);
The syntax for Scanner class, input declares that “input” is a variable whose type is Scanner. The
whole line creates a scanner object and assigns its reference to the variable input. A scanner
object contains the methods for reading input.

method Description
nextByte( ) Reads an integer of the byte type
nextShort( ) Reads an integer of the Short type
nextInt( ) Reads an integer of the int type
nextLong( ) Reads an integer of the Long type
nextFloat( ) Reads a number of the float type
nextDouble( ) Reads a number of the double type
next( ) Reads a string ends before a white space
nextLine( ) Reads an line of character
Table 5.2 Methods of Scanner class
To implement a Scanner you must use java.util.Scanner class, like “import java.util.Scanner;”

Example 5.20 Enter a integer, double and string from keyboard and display it.

import java.util.Scanner;
public class ReadNum
{
public static void main(String arg[ ])
{
Scanner sin = new Scanner(System.in);
System.out.print("Enter an integer:");
int i = sin.nextInt( );
System.out.println("you entered: " + i);
System.out.print("Enter a double value:");
double d = sin.nextDouble( );
System.out.println("you entered: " + d);
System.out.print("Enter a string:");
String s = sin.next( );
System.out.print("you entered:" + s);
}
}
Output: Enter an integer:4

77
you entered:4
Enter a double value:4.8
you entered:4.8
Enter a string:Java is a simple language
you entered:Java

Example 5.21 create two matrix which takes value from keyboard and multiply these matrices
and store the result in a third matrix. Display all three matrices.

import java.util.Scanner;
public class matrix_multiplication
{
public static void main(String arg[ ])
{
int a[ ][ ] = new int[10][15];
int b[ ][ ] = new int[15][20];
int c[ ][ ] = new int[10][20];
int r1=0, c1=0, r2=0, c2=0, i=0, j=0;

Scanner s = new Scanner(System.in);


System.out.print("Enter row and column value for 1st Matrix : ");

r1 = s.nextInt();
c1 = s.nextInt();
System.out.print("Enter row and column value for 2nd Matrix : ");

r2 = s.nextInt();
c2 = s.nextInt();
System.out.println("\nEnter values for 1st matrix :");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
System.out.print("Enter a value : ");
a[i][j] = s.nextInt( );
}
}
System.out.println("\nEnter values for 2nd matrix :");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
System.out.print("Enter a value : ");
b[i][j] = s.nextInt( );
}
}

78
if(c1!=r2)
{
System.out.println("The matrices cannot multiply :");
System.exit(0);
}
else
{
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
c[i][j]=0;
for(int k=0;k<c1;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
}
System.out.println("\n1st Matrix elements are :\n\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
System.out.print("\t"+a[i][j]);
}
System.out.println("\n");
}
System.out.println("\n2nd Matrix elements are :\n\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
System.out.print("\t"+b[i][j]);
}
System.out.println("\n");
}
System.out.println("\nResult Matrix elements are :\n\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
System.out.print("\t"+c[i][j]);
}
System.out.println("\n");
}

79
}
}
Output :
Enter row and column value for 1st Matrix : 2 4
Enter row and column value for 1st Matrix : 4 1

Enter values for 1st matrix :


Enter a value : 1
Enter a value : 2
Enter a value : 3
Enter a value : 4
Enter a value : 5
Enter a value : 6
Enter a value : 7
Enter a value : 8

Enter values for 2nd matrix :


Enter a value : 1
Enter a value : 1
Enter a value : 1
Enter a value : 1
1st Matrix elements are :

1 2 3 4

5 6 7 8
2nd Matrix elements are :

1
Result Matrix elements are :

10

26

Example 5.22 Find the maximum and minimum value present in a array

import java.util.Scanner;
public class max_min
{
public static void main(String arg[ ])

80
{
int a[ ] = new int[100];
int max = 0,min = 0,i=0,n=0;
Scanner s = new Scanner(System.in);
System.out.print("Enter the size of array : ");
n = s.nextInt( );
for(i=0;i<n;i++)
{
System.out.print("Enter a value : ");
a[i]=s.nextInt( );
}
max = a[0];
min = a[0];
for(i=0;i<n;i++)
{
if(max < a[i])
max = a[i];
if(min > a[i])
min = a[ i];
}
System.out.println("Maximum value "+max+" Minimum value "+min);
}
}
Output :
Enter the size of array : 5
Enter a value : 123
Enter a value : 34
Enter a value : 12
Enter a value : 1
Enter a value : 767
Maximum value 767 Minimum value 1

Example 5.23 Write a program to sort the elements in the array.


import java.util.Scanner;
public class array_sort
{
public static void main(String arg[ ])
{
int a[ ]=new int[100];
int n=0,i=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the size of array");
n = s.nextInt( );
for(i=0;i<n;i++)
{
System.out.println("Enter a integer value :");

81
a[i] = s.nextInt( );
}
for(i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("The array value after sorting are :");
for(i=0;i<n;i++)
System.out.print(" "+a[i]);
}
}
Output :
Enter the size of array
6
Enter a integer value :
5
Enter a integer value :
15
Enter a integer value :
9
Enter a integer value :
10
Enter a integer value :
1
Enter a integer value :
2
The array value after sorting are :
1 2 5 9 10 15

82
SUMMRY
Classes, objects and methods are the basic components used in Java programming. The
concept of classes is at the root of Java‟s design. We have discussed in detail the following in
this chapter:
- How to define a class
- How to create objects
- How to add methods to class
- Recursion
- Call by value and call by reference
- Constructor, method and constructor overloading
- Simple input and output
- this, final and static keyword
- And how to use Scanner class.

83
Review Question
5.1 Give differences between constructor and method.
5.2 What is method overloading? Can we overload main method in Java?
5.3 What is the difference between call-by-value and call-by-reference?
5.4 Explain how this works?
5.5 Explain the difference between instance variable and class variable with a example.
5.6 A special number is a number in which the sum of the factorial of each digit is equal to the
number itself. For example 145 = 1! +4! + 5! = 1+24+120. Design a class „Special‟ to check if a
given number is a special number. Some of the numbers of the class are given below:

Class name : Special


Data members n : integer
Member functions
special( ) : Constructor to assign 0 to n
special(int) : Parameterized constructor to assign a value to „n‟
void sum( ) : Calculate the display the sum of the first and the
last digit of „n‟
void isSpecial( ) : Check and display if the number „n‟ is a special
number.
Specify the class Special giving the details of the constructors, void sum( ) and void isSpecial( ).
Use the Scanner class to accept a number from keyboard.
5.7 A class Telcall calculates the monthly phone bill of a consumer. Some of the members of the
class are given below:
Class name : Telcall
Data members
phno : Phone number
name : Name of consumer
n : Number of calls mode
amt : Bill amount
Member functions
Telcall( ) : Parameterized constructor to assign values to data members.

void compute( ) : To calculate the phone bill amount base on the slabs given below

Number Rate
void of calls despdata( ) : To
display the details in 1-100 Rs 500-rental change the specified format.
The calculations need 101-200 Rs 1.0 Per call + rental charge to be done as per the
slabs. Specify the 201-300 Rs 1.2 Per call + rental charge class Telcall, giving
the details of the Above 30 Rs 1.5 Per call + rental charge constructor, void
compute( ) and void dispdata( ); in the
main method, create an object of type Telcall and display the Phone bill in the following format.

Phone number Name Total calls Amount


xxxxxxxx xxx xxxxx xxxx

84
5.8 Design a class to represent a bank account. Include the following numbers:
Data members
Name of the depositor
Type of account
Account number
Balance amount in the account
Methods
To assign initial values
To deposit an amount
To withdraw an amount after checking balance
To display the name and balance
Do write proper constructor function

5.9 A class “quad” contains the following data members and member functions to find the root
of quadratic equation.
Class name : Quad
Data member : a, b, c, x1, x2 (float)
Member function
Quad (float, float, float) : Constructor to assign values to the
datamember
float discriminant( ) : To return the discreminant [b2 – 4ac ]
void root_equal( ) : To display the root if both roots are equal
void image( ) : Display roots, it roots are imaginary.
void root_real( ) : To display the two real, unequal roots
void root( ) : To call other appropriate functions to find
the solutions of the problem.

5.10 Write a program to implement a student class. Have a result method as member of the class.
This method should take marks in three subjects as parameters and display result of the student.
Use Scanner class for taking key bound input.

5.11Write a program that invokes a function satis( ) to find whether four integers a,b,c,d sent to
satis( ) satisfy the equation a3 + b3 + c3 = d3 or not. The function satis( ) return 0 if the above
equation is satisfied with given four numbers otherwise return -1.

5.12 Using recursion write a program of the following


(i) Power of a number P = xy
(ii) Reverse of a number.
(iii) Fibonacci series.
(iv) A number is prime or not.
The values should be taken from keyboard using Scanner class.

5.13 Write a function that takes an int argument and doubles it. The function does not return a
value.

85
5.14 Write a function that takes two char arguments and return 0 if both the arguments are equal.
The function returns -1 if the first argument is smaller than the second and 1 if the second
argument is smaller than the first.

5.15 What are inner classes and what‟s the practical implementation of the inner classes?

5.16 What is the difference between recursion and iteration?

5.17 What is an accessor method? What is a mutator method? What are the naming conventions
for accessor methods and mutator methods?

86
Concept of Inheritance
6.0 INTRODUCTION
You have a strong analytical ability and a good logical reasoning capability. Your
parents are at a loss. They cannot inherit any of your abilities. You are at an advantageous
position. You can inherit their traits and add a few your own. But that‟s how the world has been
all along, always partial to the generation…
Inheritance is capable of expressing the inheritance relationship of real-world models.
‟Men‟ inherit from „Person‟; ‟Women‟ inherit from „Person‟, etc etc. Inheritance facilitates the
code reusability. Additional features can be added to a class by deriving a class from it and then
by adding new features to it. Class once written and tested need not be rewritten or redefined.
Inheritance is capable of simulating the transitive nature of real-world‟s inheritance, which in
turn saves on modification time and efforts, if required.
6.1 DIFFERENT FORMS OF INHERITANCE
The mechanism of deriving a new class from an old class is called inheritance. The old
class is known as the base class or super class or parent class and the new class is called the sub-
class or derived class or child class.
The inheritance allows subclasses to inherit all the variables and methods of their parent
classes. Inheritance may take different forms:

Single Inheritance (only one Super


class) A A
Multiple Inheritance (several Super
class)
Hierarchical Inheritance (one Super B B C D
class and many sub-classes)
Multilevel Inheritance (Derived (Single Inheritance) (Hierarchical Inheritance)
classes)
- Only public, protected or
defaults are inherited, but private A A B C
members of base class cannot be
inherited. Private members of a
base class can only be access by B
its public methods/ constructors.
Hybrid Inheritance (When a sub-class D
C
inherits from multiple base classes and
(Multilevel Inheritance) (Multiple Inheritance)
all of its base classes inherit from a
single base class is known as Hybrid
Figure 6.1 Forms of Inheritance
inheritance.)

87
Java does not directly implement multiple inheritances. However, this concept is implemented
using a secondary inheritance path in the form of interfaces.

Defining a Subclass
A subclass is defined as follows:
class subclassname extends superclassname
{
variable declaration;
methods declaration;
}
The keyword “extends” signifies that the properties of the „superclassname‟ and extends to
the „subclassname‟. The subclass will now contain its own variables and methods as well those
of the superclass.
Example 6.1 Single Inheritance
class Publisher
{
String title;
float price;
public Publisher(String t,float p)
{
title = t;
price = p;
}
public void displayData( )
{
System.out.println("Title: "+title);
System.out.println("Price: "+price);
}
}
class Book extends Publisher
{
int pageCount;
public Book(String t,float p,int c)
{
super(t,p);
pageCount = c;
}
public void displayData( )
{
super.displayData( );
System.out.println("Total Pages: "+pageCount);
}
}
public class Inheritance_Demo
{
public static void main(String arg[ ])

88
{
Book b = new Book("First step to JAVA Programming",280,360);
b.displayData( );
}
}
Output:
Title: First step to JAVA Programming
Price: 280.0
Total Pages: 360

6.2 METHOD OVERRIDING


As you see in example 6.1 the displayDate( ) method is define in base and derived
class. If a method define in base class as well as redefine in derived class then that method is
known as overriding method, in our case public void displayDate( ) method. In method
overriding the prototype of overriding method in base and derived class must be same.

6.3 PREVENTING INHERITANCE


The final modifier is used to prevent derivation from a class. Some times we required a
class do not further inherit at that situation final modifier can be used.
6.3.1 Final Variable and Methods
All methods and variables can be overridden by default in subclasses. If you wish to
prevent the subclasses from overriding the members of the super class, you declare them as final
using keyword final as a modifier.
Example: final int size = 100;
final void getData(…) { …}
making a method final ensures that the functionality depend in this method will never be altered
in any way. Similarly, the value of a final variable can never be changed. Final variables, behave
like class variables and they do not take any space on individual objects of the class.
6.3.2 Final Classes
Sometimes it require to prevent a class being further subclasses for security reasons. A
class that can not be sub classed is called a final class. This is achieved in Java using the
keyword final as follows:
- final class student{…}
- final class ParmanentEmployee extend Employee{…}
Any attempt to inherit these classes will cause an error and the compiler will not allow it.
Declaring a class final prevents any unwanted extensions to the class. It also allows the compiler
to perform some optimizations when a method of a final class is invoked.
6.3.3 Finalizer Methods
We know that Java run-time is an automatic garbage collection system. It
automatically frees up the memory resources used by the objects. But objects may hold other
non-object resources such as file descriptors or window system fonts. The garbage collector
cannot free these resources. In order to free these resources you must use a finalizer method.

89
The finalizer method is simply finalize( ) and can be added to any class. The finalize
method should explicitly define the tasks to be performed. The finalize( ) method has this general
form:
protected void finalize( )
{
// finalization code here
}
Here the keyword protected is a specifier that private access to finalize( ) by code
defined outside its class. A finalize( ) method is similar to destructors in C++.

6.4 THE SUPER KEYWORD


The keyword super is used to access base class‟s data member, member function and
parameterized constructor.

6.4.1 Accessing Base Class Data member and Overridden member function
You can refer to the super class‟s variable by using the keyword super,
e.g. Super . hiddenVariable refers to the hidden variable of Super class.
Similar manner you can access the overridden method of base class by using Super
keyword as super.overridden method.
Example 6.2 Program to illustrate the concept of a hidden number variable and an Overridden
method.

class SuperClass
{
String id = "id of superclass";
void identify( )
{
System.out.println("this is identify( ) of super class");
}
}
class SubClass extends SuperClass
{
String id = "Id of subclass";
void identify( )
{
System.out.println("This is identify( ) of sub class");
}
void test( )
{
System.out.println(id+"\t"+super.id);
identify( );
super.identify( );
}
}
public class SuperDemo
{

90
public static void main(String arg[ ])
{
SubClass obj = new SubClass();
obj.test();
}
}
Output:
Id of subclass id of superclass
This is identify( ) of sub class
this is identify( ) of super class

In Example 6.2 the hidden variable “id” of super class is accessed by “super.id” and
“super.identify( )” is used for call identify( ) method of super class.

6.4.2 Inheritance and Constructors


- The object creation process of the child class involves the object creation of parent class i.e. the
child class constructor always call the null parameterized constructor of the super class from the
first line.
- A parameterized constructor of the super class can be called from the child class constructor
explicitly by using super keyword.
Example 6.3 Explicitly Calling a parameterised constructor of base class
class Parent
{
int i,j;
Parent( )
{
System.out.println("null parameterised base class constructor");
}
Parent(int a,int b)
{
i = a;
j = b;
System.out.println("i = "+i+"\t j = "+j);
}
}
class Child extends Parent
{
int k;
Child( )
{
System.out.println("The null parameterised constructor of derived class");
}
Child(int a,int b,int c)
{
super(a,b);
k = c;

91
System.out.println("i = "+i+" \tj = "+j+" \tk = "+k);
}
}
public class mainClass
{
public static void main(String arg[ ])
{
Child ch = new Child(10,20,30);
}
}

Output:
null parameterised base class constructor
i = 10 j = 20
i = 10 j = 20 k = 30

6.5 ABSTRACT CLASS


The super class contains elements and properties common to all of the subclasses. A
concrete super class is the one whose objects can be declared and created. Sometimes, we need
to define a super class having general characteristics and behavior of its subclasses, but no object
of such class should be defined as the class depicts a concept only.
For instance, consider the following code fragment:
class Shape
{
String name;
double area;
public void display( ) { }
}
class Circle extends Shape
{
.
.
.
}
class Rectangle extends Shape
{
.
.
.
}
In the above example, we definitely need to create objects of classes Circle and Rectangle but
no object of Shape class should get declared as it represents merely a concept. To ensure that no
object of such types of super classes should get declared, you can declare the super class as
abstract class.

92
An abstract class is the one that simply represents a concept and whose objects can‟t be
created. It is created through the use of keyword abstract. The general syntax is
<abstract> class <super class name>
{
Variable
Constructor
Concrete method
Abstract method
}
Example: abstract class Shape
{
String name;
double area;
public abstract display( );
}
6.5.1 Abstract Methods
Abstract methods are methods with no method statements. Sub classes must provide the
method statements for the inherited abstract methods.
Syntax: <access specifier> <abstract> <type> method name
{
.
.
.
}
Example: public abstract void display( )
{
.
.
.
}

Example 6.4 A demo program of abstract class.

abstract class Shape


{
String name;
double area;
public abstract void display( ); //abstract method
}
class Circle extends Shape
{
double radius;
double cArea( )
{
return 3.154*radius*radius;
}

93
Circle(double i)
{
radius = i;
}
public void display( )
{
System.out.println("Radius = "+radius);
System.out.println(" Area = "+cArea( ));
}
}
class Rectangle extends Shape
{
double length,breadth;
Rectangle(int i,int j)
{
length = i;
breadth = j;
}
double rArea( )
{
return length*breadth;
}
public void display( )
{
System.out.println("Length = "+length);
System.out.println("Breadth = "+breadth);
System.out.println(" Area = "+rArea( ));
}
}
public class AbstractDemo
{
public static void main(String arg[ ])
{
Circle c = new Circle(5);
c.cArea( );
c.display( );
Rectangle r = new Rectangle(10,2);
r.rArea( );
r.display( );
}
}
Output: Radius = 5.0
Area = 78.85
Length = 10.0
Breadth = 2.0
Area = 20.0

94
6.6 INTERFACES
Java does not allow multiple inheritance i.e., a sub class being the extension of more
than one super class. For instance, definitions like
class A extends B extends C
{
.
.
.
}
is not permitted. Java provides an alternate approach known as interface to support the concept
of multiple inheritances. To tie elements of different classes together Java uses an interface. An
interface defines a protocol of behavior. The aim of interfaces in Java is to dictate common
behavior among objects from diverse classes.

6.6.1 Interface Definition


The definition of interfaces is similar to the definition of classes. You just need to
replace the keyword class with another keyword interface:

interface interface_name
{
Variable declaration;
Methods declaration;
}

(i) The keyword interface beings the definition.


(ii) The interface-body can only declare two things:
- Abstract methods (methods with empty body)
- Constants (public static final)
(iii) Interface don‟t have constructors.

6.6.2 Implementation of Interface


An interface can be inherit to another interface using extends keyword where a class
can inherit from an interface by using implements keyword. The table 6.1 gives implementation
of interface.

Parent Child keyword


class class extends
interface interface extends
interface class implements
class interface Not possible
Table 6.1 Implementation of interface

Example: class class_name implements interface_name


{
Body of class_name
}

95
Example: interface interface_name extends interface_name
{
interface body
}
The implementation of interfaces can take various forms as illustrated in Figure 6.1.

Interface A class A D interface


implements extends extends

class B class B E interface


implements
extends
class
C
C
(a) (b)

Interface A interface A interface B


Extends

implements C
interface
class B C class implements

( c) (d)
Figure6.1 Various Forms of interface implementation

Example 6.5 Implementing interface


interface Vehicle
{
public static final String moves = "Water air ground";
public void parking(int x,int y);
public void property( );
}
class Car implements Vehicle
{
public void parking(int x,int y)
{
int area = x*y;
System.out.println("Parking required is "+area);
}
public void property( )
{
System.out.println("A car required four Wheels to run");
}

96
}

public class InterfaceDemo


{
public static void main(String arg[ ])
{
Car maruti = new Car( );
maruti.parking(10,20);
maruti.property( );
System.out.println("maruti.moves = "+maruti.moves);
}
}

Output: Parking required is 200


A car required four Wheels to run
maruti.moves = Water air ground
- You can access the moves variable of interface vehicle by using Vehicle.moves or
car.moves or maruti.moves

6.6.3 Difference between class and interface

class interface
(i)The members of a class can be (i) The members of an interface
constant or variable. are always declared as constant,
i.e., values are final.
(ii) Methods of a class can be (ii) The methods in an interface
abstract or non-abstract. are abstract in nature.
(iii) It can be instantiated by (iii) It can only use the public
declaring object. access specifier.

6.6.4 Difference between Interface and abstract class

interface Abstract class


(i) All variables must be public (i) No restriction.
static final.
(ii) No constructors. An interface (ii) Constructors are invoked by
cannot be instantiated using the subclass through constructor
new operator. chaining.
(iii) Interface cannot implement (iii) An abstract class comes can
any methods. have implementation.
(iv) Interface is part of the class (iv) Abstract class comes in
hierarchy. through inheritance.

97
6.7 POLYMORPHISM
Polymorphism is the capability of an action or method to do different things based on
the object that it is acting upon. There are two types of polymorphism:
(i) Method polymorphism through overloading
(ii) Object polymorphism by inheritance/ interface.
6.7.1 Method Polymorphism (overloading)
Overloading is something you‟ve already encountered. It simply refers to the ability to
define several methods to have the same name within a particular class. For example, following
are overloaded methods:
- long Math.max(long a, long b)
- int Math.max(int a, int b)
- double Math.max(double a, double b)
- float Math.max(float a, float b)
6.7.2 Object Polymorphism by Inheritance / Interface
The method polymorphism was on the method level but real worth and
implementation of polymorphism concept is by objects. Object polymorphism is possible by
inheritance or interfaces.
Example 6.6 Object Polymorphism
class Calc
{
public int Add(int a,int b)
{
return a+b;
}
}
class Simple extends Calc
{
public int Add(int a,int b)
{
int c = 10;
return a + b + c;
}
}
class Scientific extends Calc
{
public int Add(int a,int b)
{
return (a + b)/2;
}
}
public class ClsTestRun
{
public static void main(String arg[ ])
{
Calc c1 = new Calc( );
Simple s1 = new Simple( );

98
Scientific sc1 = new Scientific( );
System.out.println("Simple addition :- "+c1.Add(2,3));
c1 = s1;
System.out.println("Special addition :- "+c1.Add(2,3));
c1 = sc1;
System.out.println("Complex addition :- "+c1.Add(5,5));
}
}
Output: Simple addition :- 5
Special addition :- 15
Complex addition :- 5
You can see in the code we have set both the child object references to parent object
and called the Add method respectively. Depending on which child is referenced by the parent
object the child object method is called.
6.7.3 Dynamic Method Binding
Dynamic binding refers to the case where compiler is not able to resolve the call and
the binding is done at runtime only. Let‟s try to understand this. Suppose we have a class named
Calc and another sub classes named Simple and Scientific. Now a super class (e.g. Calc)
reference can be assigned to an object of the type sub class (e.g. Simple, Scientific) as well.
If we have a method in the super class which we override in the sub class then a call of that
method on a super class reference can only be resolved at runtime; as the compiler can‟t be sure
of what type of object this reference would be pointing to at runtime.
Example: Calc c1 = new Calc( );
Calc c2 = new Simple( );
c1.Add(2,3); // super class version is called
c2.Add(2,3); // sub class version is called
In Example 6.6 you see that even though both the object references “c1” and “c2” are of type are
“Calc” type, but at run time they refer to the objects of types “Calc” and “Simple” respectively.
Hence, at compile time the compiler can‟t be sure of the call to the method Add( ) on these
references actually refer to which version of the method (the super class version or the sub class
version). Such methods are known as Polymorphic methods. Thus dynamic binding in Java
simply binds the method calls based on the declared type of the object reference.

6.7.4 Static Binding or Early Binding


If the compiler can resolve the binding at the compile time only then such a binding is
called static binding or early binding.

Example 6.7 Static Binding


class SuperClass
{
public String str = "Java-is-presents-Super-class";
}
class SubClass extends SuperClass
{
public String str = "MyJava";
}

99
public class StaticBinding
{
public static void main(String arg[ ])
{
SuperClass sp = new SuperClass( );
SubClass sb = new SubClass( );
System.out.println(sp.str);
System.out.println(sb.str);
}
}
Output: Java-is-presents-Super-class
MyJava

Summary

In this chapter we know that

- Inheritance is the capability of one class to inherit properties from another class.
- An abstract class created using abstract keyword.
- Interface created using interface keyword.
- Uses of extends and implements keywords.
- Polymorphism is the ability of objects belonging to different types to respond to
method calls of methods of same name, each one according to the object type it is
acting upon.

100
Review Question
6.1 Why was the concept of inheritance introduced in object oriented languages? What type of
inheritance does Java have?
6.2 Can a derived class get access privilege for a private member of the base class? If yes, how?
6.3 Define abstract class.
6.4 How do you prevent a subclass from having access to a member of a super class?
6.5 How do you prevent a method from being overridden? How do you prevent a class from
being inherited?
6.6 Explain how inheritance, method overriding and abstract classes are used to support
polymorphism.
6.7 What is the difference between abstract class and interface?
6.8 How can you implement polymorphism in Java?
6.9 Can you explain finalize( ) method?
6.10 A class One with data members int a and char b inherits from another class Two with data
members float f and int x. Write definitions for One and Two for the following situations:
(i) Objects of both the classes are able to access all the data members of both the classes.
(ii) Only the members of class One can access all the data members of both the classes.
6.11 A Student class contains the following Specification
(i) Two private variables: first name, last name
(ii) Constructor with two arguments.
(ii) void Method printData( ) to print first and last name.
A Graduate class that inherits from Student class contains the following specification
(i) two private variables: Stream, Degree
(ii) Constructor with two arguments.
(iii) Method printGrad( ) to print Stream, Degree along with inherited first and last name.
6.12 A class Employee contains employee details and another class Salary calculate the
employee‟s netSalary. The details of the two classes are given below:
class name : Employee
Data members : (empNo, empName, empDesig)
empNo : Stores the employee number
empName : Stores the employee name
empDesig : Stores the employee‟s designation
Member Functions : (Employee( ), Employee(…), display( ))
Employee( ) : Default constructor
Employee(…) : Parameterized constructor to assign values to employee
numbers, name and designation.
Void display( ) : Display the employee details

class name :
Salary
Data member :
(basic)
basic :Float variable to store the basic pay.
Member functions ( Salary(…), Calculate( ))
:
Salary(…) :Parameterized constructor to assign values to data
members.
Void Calculate( ) : Calculate the employee‟s net salary according to the
following rules: DA= 40% of basic, HRA = 15% of

101
basic, salary = basic + DA + HRA, PF= 8% of salary,
Net salary = salary – PF. Display the employee details and
the Net salary.

Specify the class employee giving details of the constructors and member functions void
display( ). Using the concept of inheritance specify the class Salary giving details of constructor
and the member function void Calculate( ). The main function needs to be written.
6.12 Explain the difference between method overloading and method overriding?
6.13 What is polymorphism? What is dynamic binding? What are the advantages of dynamic
binding?
6.14 What is the difference between Static and final data members.
6.15 Suppose there is a base class B and a derived class D derived from B. B has two public
member functions b1( ) and b2( ), where as D has two member functions d1( ) and d2( ). Write
these classes for the following different situations:
(i) b1( ) should be accessible in main( ), b2( ) should not be.
(ii) Neither b1( ), nor b2( ) should be accessible in main( ).
(iii) Both b1( ) and b2( ) should be accessible in main( ).

102
Packages
7.0 INTRODUCTION
When a large program is to written, or a project is developed, it is often advantageous to
divide the program up into chunks (modules) and compile the parts separately. This option is
particularly desirable when several programmers are jointly developing a large program. Such
chunks of code are called package. Each package is stored in a directory (folder) which has the
same name as the package.

7.1 JAVA PACKAGES


Packages are Java‟s way of grouping a variety of class and/or interface together. The
grouping is usually done according to functionality. The Java packages act as “containers” for
classes. By organizing our classes into packages we achieve the following benefits:
- The class contained in the Packages can be easily reused of other programs.
- Packages provide a way to “hide” classes thus preventing other programs or
Packages from accessing classes that are meant for internal use only.
- Packages also provide a way for separating “design” from “coding”. First we can
design classes and decide their relationships, and then we can implement the Java
code needed for the methods. It is possible to change the implementation of any
method without affecting the rest of the design.
- Packages are helps to avoid clashes between class names; suppose we want to
provide mathematics related functionality in a class, we would give class name as
Math. Let there exists a class with the same name which also provides
mathematics related functions. This would result into conflict. We can avoid this
conflict by storing the classes in different packages. This is shown in the following
Example:

//Math.java file under PIET package // Math.java file under BPUT package
Package PIET; Package BPUT;
class Math class Math
{ {
// data members and method // data members and method
} }

Folder name : PIET Folder name : BPUT

Math.java Math.java

//PIET folder contains math.java file //BPUT folder contains math.java file

For most applications, we will need to use different sets of classes, one for the internal
representation of our program‟s data, and the other for external presentation purposes. We may
have to build our own classes for handling our data and use existing class libraries for designing
user interfaces. Java packages are therefore classified into two types:

103
(i) User defined packages
(ii) Java API packages
7.2 USER DEFINED PACKAGES
User defined packages are created by the user, and it created according to the following
rules:
- The keyword package must be used to create a package, and it must be the first
statement in a Java source file (except for comments and white space).
Syntax: package Package_name;
Example: package mypack;
- The package name and the folder name in which the package (mypack) is stored
must be same.
Creating Package
Step-1 Create files which contains classes and interfaces which will appear in a package.
e.g. fruit.java, mango.java
Step-2 Store file into a directory (folder) which name must match with the package name.
Example: Let in the D: drive we create a folder named as pec which contains fruit.java
and mango.java file.
D: drive
pec folder

mango.java fruit.java

eat.java

Figure 7.1 example of package

Step-3 Use the import keyword to get the package with the class/interface into which will use the
class/interface as import package_name.classname;

Example: import pec.mango;


import pec.fruit; import pec.*;
In figure 7.1 you can see
- Inside D: drive a folder names as pec is present.
- The folder pec contains two Java files (mango.java and fruit.java)
- A eat.java file is present inside D:\ drive. And it can be present any drive or any
other computer also.
Example 7.1 A demo program of package implementation.

Step-1 (i) Create a fruit.java

104
package pec;
public class fruit
{
public void test( )
{
System.out.println("SWEET");
}
}

(ii) Create a mango.java

package pec;
public class mango
{
public void shape( )
{
System.out.println("ANY SHAPE");
}
}
The two files fruit.java and mango.java are comes under the package name pec.
Step-2 Create a folder named as pec in D:\ drive and store the files fruit.java and mango.java in
side pec folder.
Step-3 Create a file eat.java inside D:\ drive but not inside the folder pec.

import pec.*;
public class eat
{
public static void main(String arg[ ])
{
fruit e1=new fruit( );
mango e2=new mango( );
e1.test( );
e2.shape( );
}
}
Compile: javac eat.java /* if the eat.java present in D:\ drive or
current directory of package directory */
Run: java eat
Output: SWEET ANY SHAPE

7.2.1 Visibility Modifiers


- The public acess specifier makes classes, method and data fields accessible from any class.
- The private acess specifier makes methods and data field accessible only from within its own
class.

105
- If public or private or protected is not used, then by default the classes, methods and data fields
are accessible by any class in the same package. This is known as package-private or package-
access.
- If a class is declared without the package statement, the class is said to be in the default
package.
Let‟s comes to discuss about visibility of data members and methods inside and outside
package.

//C1.java //C2.java
package mypack;
public class C1 package mypack;
{ {
public int x; public class C2
int y; {
private int z; void method()
public void m1( ) {
{ C1 o = new C1( );
. o.x; //can access
. o.y; //can access
} o.z; // cannot access due to private
void m2( )
{ o. m1( ); //can access
. o. m2( ); //can access
. o.m3(); //cannot access due to private
} }
private void m3( ) }
{ }
.
.
}
} /* Class C1 and C2 both are present in
same package know as mypack */

Figure 7.1 possible accessing members of class C1 in class C2

The figure 7.1 shows that

- The private data member (say z) of a file (say C1.java) cannot access by another file (say
C2.java) where C1.java and C2.java both are present in the same package.
- The private method [say m3( )] of class [say C1] cannot access in another class [say C2].
- Now let‟s come to another discussion where a class C3 which is present in another package
know as Test, where you have to access all the members (i.e.; data members and methods)
by creating an object of class C1, which is presented in Figure7.2.

106
package Test;
public class C3
{
void method( )
{
C1 obj = new C1( );
obj.x; //access
obj.y; //not access
obj.z; //not access
obj.m1( ); //access
obj.m2( ); //not access
obj.m3( ); //not access
}
}
Figure 7.2 possible Accessing methods of two packages Test and mypack
In Figure 7.2 you can see class C3 present inside Test package and it try to access members of
class C1 which is present inside package mypack.
7.2.2 Immutable Objects and classes
Normally, you create an object and allow its contents to be changed later, these
classes are known as mutable classes as discussed earlier. Occasionally, it is desirable to create
an object whose contents cannot be changed once the object is created. We call such an object an
immutable object and its class an immutable class.
For a class to be immutable, it must meet the following requirements
- Declare all data fields private.
- Provide no mutator methods.
- Provide no accessor method that returns a reference to a data field that is mutable.
Example 7.2 A demo program to implementing immutable class.
class Student
{
private int id;
private String name;
private java.util.Date dateCreated;
public Student(int sn, String name)
{
id = sn;
this.name = name;
dateCreated = new java.util.Date( );
}
public int getId( )
{
return id;
}
public String getName( )
{
return name;
}

107
public java.util.Date getDate( )
{
return dateCreated;
}
public void displayData( )
{
System.out.println(" Student-id :- "+id);
System.out.println("Student Name :- "+name);
System.out.println("Date of addmission :- "+dateCreated);
}
}
public class Test
{
public static void main(String arg[ ])
{
Student s = new Student(110121,"Nibu");
java.util.Date dc = s.getDate( );
dc.setTime(2000000);
s.displayData( );
}
}
Output: Student-id :- 110121
Student Name :- Nibu
Date of addmission :- Thu Jan 01 06:03:02 IST 1970

As shown in the Example 7.2, the data field dataCreated is returned using the getDateCreated( )
method. This is reference to a Data object. Through the content for dateCreated can changed
output.
7.2.3 Accessing a Package
The import statement can be used to search a list of Packages for a particular class.
The general form of import statement for searching a class is as follows:
import package1[.package2][.package3].class_name;
Here package1 is the name of the top level package, package2 is the name of the package that is
inside package1, and so on. You can have any number of packages in a package hierarchy.
Finally, the explicit class name is specified. Note that the statement should appear before any
class definitions in a source file. The following is an example of importing a particular class.
- import firstPackage.SecondPackage.Myclass;
After defining this statement, all the members of the class Myclass can be directly accessed using
the class name or its objects directly without using the package name. you can also use another
approach as follows:
- import packagename.*;
Here package may denote a single package or a hierarchy of packages as mentioned earlier. This
star(*) indicates that the compiler should search this entire package hierarchy when it encounters
a class name. this implies that you can access all classes contained in the above package directly.

108
7.3 JAVA API PACKAGES
Java API provides a large number of classes grouped into different packages according
to functionality. Most of the time we use the packages available with the Java API. Figure 7.3
shows the functional breakdown of packages that are frequently used in the programs. Table 7.1
shows the classes that belong to each package.

Java

lang util io applet awt net sql rmi servlet

Figure 7.3 Frequently used API packages

Package name Contents


java.lang Language supports classes. These are classes that Java
compiler itself uses and therefore they are automatically
imported. They include classes for primitive types, strings,
math functions, threads and exception.
java.util Language utility classes such as vectors, hash tables, random
numbers, date, etc.
java.io Input/output support classes. They provide facilities for the
input and output of data.
java.awt Set of classes for implementing graphical user interface. They
include classes for windows, buttons, lists, menus and so on.
java.applet Classes for creating and implementing applets.
java.net Classes for networking. They include classes for
communicating with local computers as well as with internet
servers.
java.sql Class for accessing, strong data on various data base like MS-
Access, oracle.
java.rmi This package is used for remote method invocation.
java.servlet Class for creating server side programming.
(Table 7.1 Java System used API packages)

7.4 STANDARD INPUT AND OUTPUT


Already you saw command line argument, Scanner class is used for input data from
the keyboard and Sytem.out.printf( ) method for displaying output on your console. Other
methods are present in Java for input and output which are discussed now.

109
7.4.1 Character Oriented IO
When a program is waiting for input at the console, there is sometimes a blinking
cursor in the console window indicating that the user should type some information. But, this is
not always the case. The user will only know what information in the form of a user prompt. The
user will only know what information in the form of a user prompt. The use of several of the
Java I/O classes is required to successfully receive input that is typed by the user. Although there
are 50+ classes in java in java.io package, you just need to work with three of them to
successfully retrieve input. To work with them, you need to either use the fully qualified name
shown or import the java.io package.

- java.io. InputStream stores information about the connection between an input device and the
computer or program.
- java.io. InputStreamReader translates data bytes received from InputStream objects into a
stream of characters.
- java.io.BufferedReader buffers (stores) the input received from an InputStreamReader object.
This is done to improve the efficiency. Input devices are much slower than the computer‟s
processor and buffering the data reduces the number of times the CPU has to interact with the
device itself.

The System.in is an object of InputStream type and is automatically created and connected to the
keyboard, by the System class. The System.in object is part of standard java.lang package. You
will use the System.in object to create an instance of the InputStreamReader class and then use
that object to create an instance of the BufferedReader class. For obtaining console based user
input following steps should be followed:

1. Use the System.in object to create an InputStreamReader object as:


InputStreamReader isr = new InputStreamReader(System.in);
2. Use the InputStreamReader object to create a BufferedReader object as:
BufferedReader stdin = new BufferedReader(isr);
3. Display a prompt to the user for the desired data
System.out.print (“Enter a Line”);
4. Use the BufferedReader object to read a line of text from the user using readLine( ) method;
which reads a lines of characters typed by the user.
String input = stdin.readLine( );
5. Print the value which contain by input variable as
System.out.println (“input = ” + input)

 You can also combine steps 1 & 2 and create only one instance of the BufferedReader for
use throughout their entire program e.g.

Private static BufferedReader(new InputStreamReader(System.in));

Example 7.3 Obtain some input from the user and print it on the monitor using BufferedReader
Class.
import java.io.*;
public class MyConsole

110
{
public static void main(String arg[ ])throws Exception
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter any thing");
String str = br.readLine( );
System.out.println("You entered :- "+str);
}
}
Output: Enter any thing
hi how are you ?
You entered :- hi how are you?
7.4.2 Integer Input
The readLine( ) method of BufferedReader object always returns a string like object.
You will need to parse (convert) the „String‟ object into an „int‟ value if you wish to store it in an
int variable or data member. Let us learn how you can do this:
1. Get a String of characters that is in an integer format e.g., “459”
String str = stdin.readLine( );
2. Use the Integer class to parse the string of characters into an integer.
int number = Integer.parseInt(str); // convert a string to integer value.
7.4.3 Byte Oriented IO
DataStreams are used for byte oriented I/O or binary I/O. Two DataStreams used for
I/O are:
(i) DataOutputStream for providing output.
(ii) DataInputStream for obtaining input.
A DataInputStream lets an application read primitive Java data types from an under lying input
Stream in a machine-independent way. An application uses a DataOutputStream to write data
that can later be read by a data input Stream.
DataOutputStream methods DataInputStream methods
- void writeBoolean(boolean v); - void readBoolean(boolean v);
- void writeChar(int v); - void readChar(int v);
- void writeInt(int v); - void readInt(int v);
- void writeDouble(double v); - void readDouble(double v);
- void writeFloat(float v); - void readFloat(float v);
- void writeLong(long v); - void readLong(long v);
- void writeShort(int v); - void readShort(int v);
Table 7.2 Methods of DataOutputStream and DataInputStream

- While using thses classes for console IO, make sure that DataInputStream type class is
associated with standard input i.e., System.in .
Example: DataInputStream input = new DataInputStream(System.in);
- Similarly, make sure that DataOutputStream type class is associated with standard output i.e.,
System.out .
Example: DataOutputStream output = new DataOutputStream(System.out);

111
- After instantiating a DataInputStream objcts (say input), you can read data as follows:
int n = input.readInt( );
char c = input.readChar( );
double d = input.readDouble( );
- Java makes exception handling mandatory. Therefore, you are supposed to enclose an
input reading statement in a try block as depicted below. Immediately below try block, a
catch block should follow:
try{
// input reading statement here
}
catch(Exception e){ }
For now, just follow the above guidelines. Exception handling is being covered in details in
chapter-8.
Example 7.4 Reads an integer number using DataInputStream and print it whether it is odd or
even
import java.io.*;
public class Example7_4
{
public static void main(String arg[ ])
{
DataInputStream input = new DataInputStream(System.in);
int n = 0 ;
try
{
System.out.println("Enter a digit");
n = input.readInt( );
}
catch(Exception e){ }
if(n % 2 == 0)
System.out.println("You entered an even number");
else
System.out.println("You entered an odd number");
}
}
Output: Enter a digit
7
You entered an odd number

7.4.4 Getting Input From Input Dialog Using GUI


Input dialog box can be obtained by invoking the JOptionPane.showInputDialog method
which is present in javax.swing package.
Example:
String input = JOptionPane.showInputDialog(“Enter yearly interest rate, for example
8.25:”); this statement display a graphical user interface (GUI) base input dialogs as shown in
Figure7.4 for taking user input from keyboard as a String type.

112
message

Click ok to accept & Click cancel to dismiss


dismiss the dialog the dialog with input

Figure 7.4 shows taking input from keyboard


Example:
String input = JOptionPane.showInputDialog(null, “ENTER AN INPUT”, “Input dialog
Demo”, JOptionPane.QUESTION_MESSAGE);

Name of input Dialog

Message

User input area

QUESTION_MESSAGE

- For implementing JOptionPane class you use syntax as import javax.swing.JOptionPane;


The keyword javax is used for advanced package imp[lamentation.

Example 7.5 my first GUI demo program using predefined Java API package
import javax.swing.JOptionPane;
public class InputDialog
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog(null,"ENTER AN
INPUT","Input dialog Demo",JOptionPane.QUESTION_MESSAGE);
System.out.println("You Entered :- "+input);
}
}
Output:

113
D:\JAVA20 >java InputDialog
You Entered :-123
Example 7.5 Write a program to calculate monthly payments and total payments for computer loan. The
computer loan can be calculated as follows:
Monthly_payments=

- Enter yearly interest rate (annualInterestRate double type).


Find monthlyInterestRate = annualInterestRate/1200;
- Enter number of years (year is int format)
- Enter loan amount (loanAmount is double type)
Monthly_payments =

- totalpayments = monthlyPayments * years *12;


Solution:
import javax.swing.JOptionPane;
public class InputDialog
{
public static void main(String[ ] args)
{
String annualInterestRates = JOptionPane.showInputDialog("Enter yearly interest
rate, for example 8.25:");
double annualInterestRate =Double.parseDouble(annualInterestRates);
// Obtain monthly interest rate
double monthlyInterestRate = annualInterestRate / 1200;
String Year = JOptionPane.showInputDialog("Enter number of years as an
integer, \nfor example 5:");
int Years = Integer.parseInt(Year);
String loan = JOptionPane.showInputDialog("Enter loan amount, for example
120000.95:");
double loanAmount = Double.parseDouble(loan);
double monthlyPayment = loanAmount * monthlyInterestRate / (1- 1 /
Math.pow(1 + monthlyInterestRate, Years * 12));
double totalPayment = monthlyPayment * Years * 12;
String output = "The monthly payment is " + monthlyPayment +"\nThe total
payment is "+ totalPayment;
JOptionPane.showMessageDialog(null,output);
}
}

114
Output:

(ii)
(i)

(iii) (iv)

(v)

7.4.5 Confirmation Dialogs


To implement confirmation dialogs you use the following syntax.
int option = JOptionPane.showConfirmDialog(null,”CONTINUE”);

This is used for accept repeated inputs as string type by pressing yes option. You required a loop
for continuous inputs as:

int option = 0;
while(option == JOptionPane.YES_OPTION)
{
System.out.println(“continue loop”);
option = JOptionPane.showConfirmDialog(null,"CONTINUE?");
}

115
Example 7.7 Write a program to add 'n' random numbers entered from the keyboard
import javax.swing.*;
public class Add
{
public static void main(String arg[ ])
{
int sum = 0, option = 0;
while(option == JOptionPane.YES_OPTION)
{
String s = JOptionPane.showInputDialog("Enter a Number");
int n = Integer.parseInt(s);
sum = sum + n;
option = JOptionPane.showConfirmDialog(null,"CONTINUE");
}
JOptionPane.showMessageDialog(null,"The Sum is "+sum);
}
}

7.5 STATIC IMPORT


Static import is another language feature introduced with J2SE 5.0 release. This feature
eliminates the need of qualifying a static member with the class name. We use the static import
statement to import static members from classes and use them without qualifying the class name.
The syntax for using the static import feature is:
import static package-name.subpackage-name.class-name.staticmember-name;
Or
import static package-name.subpackage-name.class-name.*;

Example 7.8 Use of Static import


import static java.lang.Math.*;
public class MathOperation
{
public void circle(double r)
{
double area = PI*r*r;
System.out.println(“Circle area is : “+area);
}
public static void main(String arg[ ])
{
MathOperation obj = new MathOperation( );
Obj.circle(2,3);
}
}
Output: Circle area is : 16.619025137490002

In the Example7.8 PI is the static member of the class Math. So the static member PI is used in
the above program with the qualified class name called Math.

116
Summary

In this chapter we saw the building blocks of coding in Java and high-level requirements
for designing applets, io and application programs. Java has several levels of hierarchy for code
organization, the highest of which is the Package. We have seen here

- How to create a package.


- How to add more classes to a package.
- How to access the contents of a package.
- How to protect a class from accidental access
- Standard input and output methods present in predefined packages.
- First GUI based input and output predefined package present in java.swing.*
- How to use Java system packages and
- How to use static import.

117
Review Questions

7.1 What is a package?


7.2 What is class name clashes?
7.3 How do you design a package?
7.4 Discuss various levels of access protection available for packages with a example.
7.5 What is immutable class and objects? Explain with a example?
7.6 Write the necessary steps to reading an string from keyboard and display it using
BufferedReader.
7.7 What is the difference byte oriented I/O and character oriented I/O?
7.8 Given a package named PIET_Student, how would you import a class named Test contained
in this package. Write one line statement.
7.9 Write a program to read the price of an item from (like 185.95) and print the output in paise
(like 18595 paise).
7.10 Write a program to convert the given temperature in Fahrenheit to Celsius using the
following conversion formula c = (F -32)/18.
7.11 Which Package is by default imported in every Java program?

118
Exception Handling
8.0 INTRODUCTION
Programming is a difficult art. No matter how much confidence you have in your
programming ability, several things may wrong during its development. This includes typing
errors, compilation errors, linking errors and if all goes well then the runtime errors. The first
three types of errors are comparatively easy to tackle. But when errors occur during execution
your program has to deal with the situation in an elegant fashion. The errors that occur at runtime
i.e.; during execution of the program are called Exception. The reasons why exceptions occur are
numerous. Some of the more common ones are:
- Falling short of memory
- Inability to open a file
- Accessing the elements of an array beyond its range
- Invalid input
- Division by zero
- Heap memory exhausted
All syntax errors will be detected and displayed by the Java compiler and therefore these errors
are known as compile-time errors. Whenever the compiler display an error, it will not create the
.class file. Some of compile-time errors are: missing semicolon, missing brackets in class and
methods, misspelling of identifiers and keywords, use of undeclared variables and so on.
Sometimes, a program may compile successfully creating .class file but may not run properly.
Such programs may produce wrong results due to wrong logic or may terminate due to errors
such as stack overflow. These type errors are known as run-time and most common run-time
errors are: dividing an integer by zero, accessing an element that is out of the bounds of an array,
attempting to use a negative size for an array and many more.
8.1 EXCEPTION AND EXCEPTION HANDLING
An exception is an abnormal condition that arises in a code sequence at run time and
way of handling anomalous situations in a program-run, is known as Exception Handling.
When to use Exception Handling:
The exception handling is ideal for:
- Processing exceptional situations.
- Processing exceptions for components that cannot handle them directly.
- Processing exceptions for widely used components (such as libraries, classes,
functions) that should not process their own exceptions.
- Large projects that require uniform error-processing.
Advantages of Exception Handling
Many reasons support the use of exception handling. The advantages of exception
handling are:
(i) Exception handling separates error-handling code from normal code.
(ii) It clarifies the code by removing error-handling code from main line of program and
enhances readability.

119
(iii) It stimulates consequences as the error-handling takes place at one place and in one manner.
(iv) It makes for clear, robust, fault-tolerant programs.
Example 8.1 A normal exception occur by dividing zero in any number as 7/0.
public class DivideByZero
{
public static void main(String arg[ ])
{
System.out.println(3/0);
System.out.println("Print JAVA");
}
}
Compile: javac DivideByZero.java
Output: Exception in thread "main" java.lang.ArithmeticException: / by zero
at DivideByZero.main(DivideByzero.java:5)
The example 8.1 generates an exception by “default exception handler” of Java.
8.1.1 What happens when an Exception Occurs?
When an exception occurs within a method, some activities take place internally.
These can be summarized in the following way:
1. The method creates an exception object and hands it off to the Java Runtime System (JRE).
Creating an exception object and handling it to the runtime system is called throwing an
Exception. The created exception object contains information about the error, including its type
and the state of the program when the error occurred.
2. The runtime system searches the call stack for a method that contains an exception handler as
show in figure 8.1 and figure 8.2.

Method where Method where


error occured Throws
exception error occured looking for
appropriate
Method without an Forward Method without an handler
exception handler exception exception handler
looking for
appropriate
Method with an Method with an handler
catches
exception handler exception exception handler

main main

Figure 8.1 runtime system Figure 8.2 runtime system searches the call stack for a
method

120
3. When an appropriate handler is found, the runtime system passes the exception to the handler.
- An exception handler is considered appropriate if the type of the exception object thrown
matches the type that can be handled by the handler.
- The exception handler is chosen, to catch the exception.
4. If the runtime system exhaustively searches all the methods on the call stack without finding
an appropriate exception handler, the runtime system terminates and uses the default exception
handler.

Error code
8.1.2 Concept of Exception Handling
The concept of Exception Handling is shown by the flow
chart.
Throw
Exception: An unexpected error that occurs during runtime. exception
Throwing: The process by which an exception is generated and
passed to the program.
Catching: Capturing an exception that has just occurred and Call error-
executing statements that try to resolve theproblem.
handling routine
Catch block: The block of code that attempts to deal with the
exception.
Stack trace: The sequence of method calls that brought control
to point where the exception occurred. Catch
exception

8.2 EXCEPTION HANDLING IN JAVA


Java treats exceptions as objects that describe any error caused by an external resource
not being available or an internal processing problem. The Exception type objects are passed to
exception handlers written by the programmer to enable graceful recovery. If the handler has not
been written, the program will terminate with a display of the Exception class. There are many
exception classes IOException (error while handling IO) and NumberFormatException (error
when invalid format of number is encountered) and a general class Exception that can catch
virtually all exceptions.
8.2.1 Exception Handling Using try{ } and Catch{ }
An exception handler consists of two core sections, called blocks.
(i) The try block encloses some code which might throw an exception (i.e.; generate an error).
(ii) The catch block contains the error handling code i.e.; determines what should be done if an
error is detected. A catch block can accept one exception only. For multiple exceptions multiple
catch blocks are to be written.

121
(iii) Java uses the try-catch-finally syntax to test a section of code and if an error occurs in that
region, to trap (i.e.; catch) the error. The finally keyword can be used to provide a block of code
that is always be executed in the last to signaled about exception.
The general syntax is
try{
// tested statement(s) If the code encounters
} an error, exception is
catch( ExceptionName e1) thrown
{
//trap handler statement(s)
} catch blocks trap
catch( ExceptionName e2) the thrown
{ exception and
// trap handler statement(s) handle them
}
finally{
//always executed block
}

Example 8.2 Rember the example7.4 which reads an integer number using DataInputStream
and print it whether it is odd or even
import java.io.*;
public class Example8_2
{
public static void main(String arg[ ])
{
DataInputStream input = new DataInputStream(System.in);
int n = 0 ;
try{
System.out.println("Enter a digit");
n = input.readInt( ); This is the code where a runtime error may
} occur, hence it is closed in try block.
catch(Exception e)
{ This is the block that will
System.out.println(“Exception occurred”); determine what to do if the
} exception of mentioned type
if(n % 2 == 0) occurs during execution
System.out.println("You entered an even number");
else
System.out.println("You entered an odd number");
}
}
Output: Enter a digit
7

122
You entered an odd number

Example 8.3 Generate exception but has no error-handlling routine.


public class DivideException
{
public static void main(String arg[ ])
{
division(200,5);
division(100,0);
System.out.println("Exit from main");
}
public static void division(int a,int b)
{
System.out.println("Result is:");
int avg = a/b;
System.out.println("Average: "+avg);
}
}
Compile: javac DivideException.java
Run: java DivideException
Output: Result is:
Average: 40
Result is:
Exception in thread "main" java.lang.ArithmeticException: / by Zero
at DivideException.division(DivideException.java:12)
at DivideException.main(DivideException.java:6)
To get solution which occurred in Example 8.3 and give a better solution to user, you have use
try and catch which shown in Example 8.4.
Example 8.4 Generate exception but has error-handling routine.
public class DivideException1
{
public static void main(String arg[ ])
{
int result = division(200,5);
System.out.println("Result = "+result);
result = division(100,0);
System.out.println("Result = "+result);
}
public static int division(int a,int b)
{
int q = -1;
System.out.println("Division Occured");
try{
q = a/b;
}

123
catch(Exception e)
{
System.out.println("EXCEPTION ---> "+e.getMessage( ) );
}
finally
{
if(q == -1)
{
System.out.println("Finally block exited");
}
else{
System.out.println("Finally block executes, Exception not occured");
}
return q;
}
}
}
Output:
Division Occured
Finally block executes, Exception not occured
Result = 40
Division Occured
EXCEPTION ---> / by zero
Finally block exited
Result = -1

8.2.2 Rules for try, catch and finally Blocks


While writing error-handling routines in your program, you must follow the following
rules:
(1) For each try block there can be zero or more catch blocks, but only one finally block.
(2) The catch blocks and finally block must always appear in conjunction with a try block.
(3) A try block must be followed by either at least one catch block or one finally block.
(4) The order exception handlers in the catch block must be from the most specific exception.
8.2.3 The finally clause of Exception Handling
The finally block is always executed whether an exception occur or not for
performing local clean-up and releasing non-object resources. The JVM follows the following
rules for the finally clause of Exception Handling.
- A try block cannot be exited without executing the corresponding finally clause.
- The code in a finally clause is executed whether or not an exception is caught.
- If a transfer of control flow occurs in the try block because of a break, continue or
return statement, then the finally clause is executed before flow transfer occurs.
Example 8.5 Program to illustrate handling of finally clause in Exception Handling Routine.

124
import java.io.*;
public class TryCatchBreak
{
public static void main(String arg[ ])
{
BufferedReader br = null;
String str;
for(int i = 0; i < 5;i++)
{
try{
br = new BufferedReader(new FileReader("DivideByZero.java"));
if( i < 4)
{
continue;
}
while( ( str = br.readLine( ) ) != null)
{
System.out.println(str);
}
}
catch(Exception e)
{
System.out.println("Exception occured");
}
finally{
System.out.println("i = "+i);
try{
br.close( ); //close file (DivisionByzero.java)
}
catch(Exception e1){}
}
} //end of for loop
} //end of main method
} Output:
i=0
i=1
i=2
i=3
public class DivideByZero
{
public static void main(String arg[ ])
{
System.out.println(3/0);
System.out.println("Print JAVA");
}
}

125
i=4

8.2.4 The throws Clause


If a method invokes code that causes an exception, then the method should provide a
catch clause to handle the exception. If a catch does not handle the exception, then the exception
must be passed out of the method and be handled by the code calling the method. If an exception
is allowed to pass through a method, a throws clause is required in the method declaration to
indicate that an exception can occur that the method itself does not handle. In general the throws
are used to transfer an exception from one block of code to another which will handle the
exception.
Example: public static void main(String arg[ ]) throws Exception
{
.
.
.
}

If a method has no throws clause, then the method cannot pass or throw any exceptions. Multiple
Exception types (comma separated) can be declared in the throws clause.
Example: public static void main(String arg[ ]) throws IOException,NumberFormatException
{
.
.
.
}
Example 8.6 Execution of throws clause.
import java.util.*;
public class throws_demo
{
public void div(int x,int y)throws ArithmeticException
{
int z = x/y;
System.out.println(z);
}
public static void main(String arg [ ])
{
Scanner s = new Scanner(System.in);
throws_demo td = new throws_demo( );
System.out.println("Enter a number");
int a = s.nextInt( );
System.out.println("Enter the 2nd number");
int b = s.nextInt( );
try{
td.div(a,b);

126
}
catch(ArithmeticException ai)
{
System.out.println("2nd number cannot be zero.....");
}
}
}
Output:
Enter a number
12
Enter the 2nd number
0
2nd number cannot be zero

8.2.5 Using throw


The throw keyword used to generate an exception explicitly or forcibly from a try
block and the current method immediately stops its execution.
Example 8.7 Exception handling using "throw" .

import java.util.*;
public class throw_demo
{
public static void main(String arg[ ])
{
Scanner s = new Scanner(System.in );
try{
System.out.println("Enter a number");
int a = s.nextInt( );
System.out.println("Enter the 2nd number");
int b = s.nextInt( );
if(b <= 0)
{
ArithmeticException ai = new ArithmeticException( );
throw ai;
}
System.out.println(a/b);
}
catch(ArithmeticException aei)
{
System.out.println("EXCEPTION: 2nd number cannot be zero or negetive");
}
}
}

127
Output:
Enter a number
12
Enter the 2nd number
0
EXCEPTION: 2nd number cannot be zero or negative

8.2.6 The Exception Class


All exceptions are subclasses of Exception class and Exception class is a subclass of
Throwable, which contains various methods that gives all kinds of information to report about
your exception.
getMessage( ): returns the error message reported by the exception in a String.
printStackTrace(): prints the stack trace of the exception to standard output, useful for debugging
proposes in locating where the exception occurred.
printStackTrace(PrintStream s): prints the stack trace to an alternative output stream.
printStackTrace(PrintWriter s): prints the stack trace to a files, this way you can log stack traces
transparent to the user or log for later reference.
toString( ): if toPrint out the exception in string format.
8.2.7 Common Exceptions
There are many different exceptions that can be thrown by a program. Some of the
common exceptions are
ArithmeticException: thrown if a program attempts to perform division by zero.
ArrayIndexOutOfBoundsException: thrown if a program attempts to access an index of an array
that does not exist.
StringIndexOutOfBoundsException: thrown of a program attempts to access a character at a non-
existent index in a string.
NullPointerException: thrown if the JVM attempts to perform an operation on an object that
points to no data, or null.
NumberFormatException: thrown if a program is attempting to convert a string to a numerical
datatype, and the String contains inappropriate characters (i.e.; „a‟ or „Q‟).
ClassNotFoundException: thrown if a program cannot find a class it depends at runtime (i.e.; the
class‟s .class file cannot be found).
IOException: thrown if the JVM failed to open an I/O Stream.
Example 8.8 The below program gives NumberFormatException for wrong number input.
import java.io.*;
public class Example8_8
{
static boolean valid;
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

128
public static void main(String arg[ ])throws IOException
{
int n = 0;
try{
System.out.println("Enter an integer number....");
int i = Integer.parseInt(br.readLine() );
valid = true;
}
catch(NumberFormatException e)
{
System.out.println(e.getMessage( )+" is not valid format for an integer");
}
}
}
Output:
Enter an integer number....
xyz
For input string: "xyz" is not valid format for an integer

8.2.8 Exception Hierarchy


The exception hierarchy is shown in Figure8.3. The Throwable class is the super class
of all Errors and Exceptions. An Error object describes internal errors, for example resource
exhaustion, inside the Java runtime system. An Exception object describes a recoverable error
that should be handled by the program.
java.lang.Object
java.lang.Throwable

java.lang.Error java.lang.Exception

java.lang.VirtualMachineError java.io.IOException

java.io.FileNotFoundException
java.lang.OutOfMemoryError
java.lang.ClassNotFoundException
java.lang.RuntimeException
java.lang.NullPointerException
java.lang.IndexOutOfBoundsException

java.lang.ArrayIndexOutOfBoundsException

(Figure 8.3 JAVA Exception hierarchy )

129
In the Figure 8.3, the exception hierarchy says the following:
- Throwable class
It is the root class of exception classes. Its immediate subclasses are
(i) Error class
(ii) Exception class
- Error class
An Error indicates that a non-recoverable error has occurred that should not be cought. The
Error class is used by the Java run-time system to handle errors occurring in the run-time
environment, which are generally beyond the control of user programs.
Example: Out of memory errors, Hard disk crash.

- Exception class
This class handles conditions that user programs can reasonably deal with. The exceptions
are usually the result of some flaws in the user program code.
Example: Division by zero error, Array out-of-bounds error.

8.2.9 Checked and Unchecked Exceptions


The Exceptions in Java belong to one of the following two categories
(i) Checked exceptions
(ii) Unchecked exceptions
(i) Checked exceptions
These represent invalid conditions in areas outside the immediate control of the program
(invalid input, database problems, and network outages, absent files).
Checked Exceptions are subclasses of Exception class. A method is required to
establish a policy for all checked exceptions thrown by its implementation.
Example 8.9 checked.java
import java.io.*;
public class checked
{
public static void main(String arg[ ])
{
try
{
FileInputStream fis=new FileInputStream("piet.txt");
int a;
while( (a=fis.read( ))!=-1)
System.out.print((char)a);
fis.close( );
}
catch(FileNotFoundException fx)

130
{
System.out.println("File not found");
}
catch(IOException io)
{
System.out.println("cannot read");
}
}
}
Output: This program generates an error message at the time of compilation
for handling “FileNotFoundException”.
(ii) Unchecked Exceptions
These exceptions are not subject to compile-time checking for exception handling.
These represent defects in the program (bugs) often invalid arguments passed to a non-private
method.
The built-in unchecked exception classes are:
- Error
- RuntimeException and their subclasses
Example 8.10 Unchecked.java
public class Unchecked
{
public static void main(String arg[ ])
{
int a = Integer.parseInt(arg[0]);
int b = Integer.parseInt(arg[1]);
int c = a / b;
System.out.println("Division value :"+c);
}
}

8.2.10 Chained Exception


The chained exception feature allows you to associate another exception with an
exception. Thus second exception describes the cause of the first exception. Consider a situation
in which you are getting null exception because of permission issue. You would like to know of
this exception is associated with some other exception. For chained exceptions there are two
constructors and two methods.
The constructors are
- Throwable (Throwable causeException);
- Throwable (String msg, Throwable causeException);
In the first form, causeException is the exception that causes the current exception.
That is, causeException is the underlying reason that an exception occurred. The second form
allows you to specify a description at the same time that you specify a causeException.

131
Example:
static void demo( ) First cause
{
NullPointerException nullerror = new NullPointerException(“First layer”);
nullerror.initCause(new ArithmeticException(“Arithmetic”));
throw nullerror;
} Set the main cause of
public static void main(String arg[ ]) exception
{
try
{
demo( );
}
catch(NullPointerException e)
{
System.out.println(“caugh:”+e);
System.out.println(“original cause:”+e.getCause( ));
}
}
Output: caugh:java.lang.NullPointerException: First layer
Original cause:java.lang.ArithmeticException: Arithmetic

The top layer exception The main cause of error

The above code shows chained exception in action. We have defined a method by name
demo( ). In demo( ) we thrown a null pointer error. But after that we set chain cause of error
using initCause( ) as arithmetic exception. You can get the main cause of error using getCause( )
method.

8.3 ASSERTION AND DESIGN BY CONTRACT


The design by contract (DBC) technique allows a programmer to provide a detailed
specification to create software according to the user requirements. The DBC technique uses
assertions to check whether the application meets the requirements specified in the defined
contract. DBC technique uses three types of assertions to check whether the software compiles
with the specification. The three types of assertions are:
(i) Precondition: An application must satisfy this specified condition before calling an external
component.
(ii) Post condition: An application must satisfy this specified condition after the execution of the
external component.
(ii)Invariant: This application must always satisfy this specified condition.
For example consider the operation stack that uses precondition, post condition, and
invariant assertions. Here
- Precondition: The stack should not empty before an element extract from a stack.
- Post condition: When elements push into the stack, you need to check whether the
element is correctly added to the specified index.
- Invariant: The number of elements in the stack is greater than or equal to zero and
should not exceed the capacity of the stack.

132
8.3.1 Implementing Assertion
An assertion is a statement, which contains a Boolean expression that the programmer
assumes to be true. If the result of the Boolean expression is true, the program execution
continues. Here the assertion ensures that the assumptions made by the programmer are correct
and free from errors. If the result of the Boolean expression is false, the AssertionError exception
will be thrown. This exception contains error information, such as file name and the line number
in which the error has occurred in the program.
We use the assert statement to implement assertions in Java programs. The assert
statement can be represented in two forms:

(i) assert Expression1;

Expression1 is Boolean expression. If the result of the Boolean expression is false, the
AssertionError exception is thrown without any information about the bugs that occurred in the
program.
Example: public void division( )
{
assert b != 0;
double c = a/b;
}
(ii)
assert Expression1: Expression2;

Expression1 is Boolean expression and Expression2 is a value, which is passed to the


constructor of the AssertionError exception.
Example: assert age > 0 : “age should no zero or –ve”
In the above example of the assertion failure occurs, the String value acts as additional
information about the errors that arise in the program.
8.3.2 Difference between Exception and Assertion
- Exception is used to test the abnormal conditions, such as division by zero,
ArrayIndexOutOfBoundsException occurred while executing the program and it does not ensure
that the program is running correctly.
- Assertion is used to test the condition assumed by the programmer, and it ensures that the
program is running correctly.
8.3.3 Assert Statement Commands
(i) Compiling the Assert Statement:
You know to compile a Java program “javac filename.java” command is used. This
command does not compile the programs that contains the assert statement. To compile a assert
statement you use the following command
javac-source 1.5 filename.java
(ii) Enabling and Disabling Assertions:
Java provides the command line parameters to enable and disable assertions.

133
-enableassertions : to enable assertion
-ea : to enable assertion
Example: java –enableassertion abc
java –ea abc
-disableassertions : to disable assertion
-da : to disable assertion
Example: java –disableassertion abc
java –da abc
Example 8.11 A demo program of Assertion
public class Division
{
void assertCheck(int a,int b)
{
assert b != 0:"The value of b cannot be ZERO";
double c = a/b;
System.out.println("Result is "+c);
}
public static void main(String arg[ ])
{
Division D = new Division();
D.assertCheck(5,0);
}
}
Compile: javac –source 1.5 division.java
Run: java –ea division
Output: The value of b cannot be ZERO

8.3.4 Assertion Rules


Assertion is used to check the validity of an assumption, which is made by a
programmer at the time of execution. There are certain rules that govern the usage of assertion in
a program. The assertion rules are
(i) Check the method arguments.
(ii) Use assertion in the default case of the switch statement.
(iii) Make use of an assertion descriptive.
(iv) Avoid processing in an assertion condition.
(v) Avoid catching assertion related exception.
(vi) Avoid the use of evaluating more than one condition in an assertion.

(i) Checking the Method Arguments


We need to check the values passed to the arguments of a method before performing
any operation on these values. We check the argument values in the methods, public or
protected, or the local package. For example, consider the following program to add two positive
numbers.
134
public void add(int x, int y )
{
int z = x + y;
}
In the above code, the user may provide a negative value of the arguments that result in an
inaccurate solution. Therefore, we need to check whether the values of the arguments are
positive before performing the addition operation. The following code satisfies this rule of
assertion:
public void add(int x, int y )
{
if(x > 0)
{
if (b > 0)
int z = x + y;
}
}
(ii) Using Assertion in the Default Case of the Switch Statement
We can use assertions in the switch statement with no default case. In such cases, we add
the default case to specify the assert statement. If none of the conditions are satisfied in the
switch case and the assertion is enable, the application causes the assertion failure and throws
AssertionError exception.
For example, consider the following example:
public String number(int number)
{
String code;
String description;
if (number < 0)
code = “negative”;
switch (code)
{
case positive:
description = “ Number is positive”;
break ;
case negative:
description = “Number is negative”;
break;
default:
assert false: “Unknown code “ + code;
}
assert(description != null): “provide description”;
return description;
}

In the above code, we use the assert statement in the default case. This statement will executed if
the variable “code” does not match with any of the specified cases.

135
(iii) Make use of an Assertion Descriptive
We need to provide a descriptive string message in an assert statement. It enables a
programmer to understand the type of error in case the assertion failure occurs. For example,
consider the following code segment, which contains an assert statement without description.
public void setName( )
{
if(name = = null)
throw new IllegalArgumentException( );
}
private void setName( )
{
assert (name != null)
.
.
.
}
In the above code, the assert statement does not contain description. When the assertion fails, the
programmer is not able to known the error against assertion. Therefore, the above code rewritten
as: public void setName( )
{
if(name = = null)
throw new IllegalArgumentException( );
}
private void setName( )
{
assert (name != null): “name cannot be null”;
.
.
.
}
(iv) Avoid Processing in an Assertion Condition
When an assertion is disable, JVM does not execute the assert statement. therefore, the
operation to be processed or performed in the assertion statements is not executed. For example,
consider the following code:
assert list.remove(“book”): “This is not in the list”;
This is an assert statement and assertion is disabled. Therefore, “Book” is not removed from the
list. We can rewrite the above code as:
boolean processed = list.remove(“Book”);
assert processed : “This is not in the list”;

(v) Avoid Catching Assertion Related Exception


The act of catching exceptions related to the assertion may discard the assertion and DBC
mechanism. Some of the assertion related exceptions are AssetError and
IllegalArgumentException. Consider the following example of catching the
IllegalArgumentException.

136
public void NameInfo( )
{
try
{
setName(null);
}
catch(IllegalArgumentException e)
{
}
}
public void setName(String name )
{
if(name = = null)
{
throw new IllegalArgumentException(“name cannot null”);
}
this.name = name;
}
The above throws the IllegalArgumentException exception when name is null.

(vi) Avoid evaluating more than one condition in an Assert Statement


We need to avoid using more than one condition in an assert statement. When we use
more than one condition in an assert statement it may be difficult to find which of the condition
is not satisfied. For example, consider the following code which uses more than one condition in
an assert statement:
public void setName(String fname, String lname )
{
if((fname = = null) || (lname = = null))
{
throw new IllegalArgumentException(“First name or Last name cannot be null”);
}
}
private void setName(String fn, String ln)
{
assert (fn != null) && ( ln != null): “First name or Last name cannot be null”;
.
.
.
}
In the above code, if one of the conditions fails, it is difficult for the programmer to identify
which of the assumptions cause failure. Therefore, the above code can be rewritten as:
public void setName(String fname, String lname )
{
if(fname = = null))
{
throw new IllegalArgumentException(“First name cannot be null”);

137
}
if(lname = = null)
{
throw new IllegalArgumentException(“Last name cannot be null”);
}
}
private void setName(String fn, String ln)
{
assert (fn != null): “First name cannot be null”;
assert (ln != null): “Last name cannot be null”;
.
.
.
}
Summary
Now we conclude this chapter that performing errors is programmer‟s birthright. A typical
programmer spends as much time in fixing errors as in programming. Different mechanisms
have evolved like exception handling and assertion to tackle these errors.

138
Review Questions
8.1 What is the purpose of declaring exceptions? How do you declare an exception, and where?
Can you declare multiple exceptions in a method declaration?
8.2 What is a checked exception, and what is an unchecked exception?
8.3 How do you throw an exception? Can you throw multiple exceptions in one throw statement?
8.4 What is the keyword throw used for? What is the keyword throws used for?
8.5 What does the JVM do when an exception occurs? How do you catch an exception?
8.6 What is the purpose of the finally clause? Give an example of how it can be used?
8.7 What are chained excveptions?
8.8 (i) What are two direct subclasses of Throwable?
(ii) What type of exceptions must be explicitly declared in a throws clause of a method?
(iii) When do you need multiple catch handlers?
(iv) Can an exception be rethrown?
(v) What is the difference between error and exception?
(vi) What is the difference between assertion and error?
8.9 What is assertion and DBC?
8.10 What are assertion rules? Explain it.

139
String
9.0 INTRODUCTION
A string a sequence of characters. In many languages, strings are treated as arrays of
characters, but in Java a String is an object. The String class has 11 constructors and more than
40 methods for manipulating String. The String class not only very useful in programming but
also is good example for learning classes and objects.

9.1 Constructing a String


In Java, Strings are class object and implemented using two classes, namely String and
StringBuffer. A Java String is an instantiated object of the String class. A Java String is not a
character array and is not NULL terminated. Strings maybe declared and created as follows:
String StringName;
stringName = new String(“string”);
Example: String firstName;
firstName = new String(“Sweet”);
You can also create a String from an array of characters. For example, the following, statements
create the String “Hello Java”.
char myArray[ ] = {„H‟, „e‟, „l‟, „l‟, „o‟, „ ‟, „J‟, „a‟, „v‟, „a‟};
String str = new String(myArray);

Example 9.1 Creating a string and sub string using an array.


public class SubString
{
public static void main(String arg[ ])
{
byte asi[ ] = {65,66,67,68,69,70};
String s1 = new String(asi);
System.out.println(s1);
String s2 = new String(asi,2,3);
System.out.println(s2);
}
}
Output: ABCDEF
CDE

The index of first character is 0, second‟s is 1, third‟s is 2, and so on.

9.2 IMMUTABLE STRINGS AND INTERNED STRINGS


A String object is immutable; its contents cannot be changed. For example
String str = “myJava”;
str = Java;
You can see the first statement creates a String object with the content “myJava” and assigns its
reference to str. The second statement creates a new String object with the content “Java” and
assigns its reference to str. The first String objects still exits after the assignment, but it can no
longer be accessed, because variable str now points to the new object, as shown in Figure 9.1.

140
str
str

myJava myJava Java


(contents cannot be changed) (This String object is now unreferenced)

Figure 9.1 Strings are immutable; once created, their contents cannot be
changed

Example 9.2 Immutable Strings.


public class MakeString
{
public static void main(String arg[ ])
{
char c[ ] = {'J','a','v','a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
Output: Java
Java

9.3 WORKING WITH STRINGS


In Java, you can work with character data i.e.; single character or group of character
i.e.; strings in three different ways. Java offers three classes to work with character data.
(i) Character class whose instances or objects can hold single character data. This class offers
many methods to manipulate or inspect single-character data.
(ii) String class whose instances or objects can hold unchanging string (immutable string) i.e.;
once initialized its contents cannot modified.
(iii) StringBuffer class whose instances or objects can hold (mutable) strings that can be changed
or modified.
We are not going to discuss character class, which is a wrapper class.

9.4 CREATING StringBuffers


StringBuffer objects are always created with new operator. But there are three ways in
which you can do so:
(i) StringBuffer sb = new StringBuffer( );
(ii) StringBuffer sb1 = new StringBuffer(“Java”);
(iii) int n = 25;
StringBuffer sb2 = new StringBuffer( n);
- The first method creates an empty StringBuffer object namely sb.

141
- The second method creates a StringBuffer object namely sb1 and initializes it with
String value “Java”.
- The third method resolves memory to hold 25 characters in StringBuffer object
named sb2.

9.5 ACCESSOR METHODS


Methods used to obtain information about an object are known as accessor methods.
The class String provides many accessor methods that may be used to perform operations on
Strings. The Table 9.1 lists some most used accessor methods of String class.

Method Prototype Description


char charAt(int index) Returns the character at the specified index.
int capacity( ) Returns maximum number of characters that
can be entered in the current String object
(this) i.e.; its capacity.
int compareTo(String1, String2) Compares two Strings lexicographically
String concat(String str) Concatenates the specified String to the end
of this String (current String object) String.
String1 + String2 Concatenation operator(i.e.; +) achieves
same as concat( ) methods
boolean endsWith(String str) Tests if the current String object ends with
the specified suffix (str).
boolean equals(String str) Compares the this String (current String
object) to the specified object str.
boolean equalsIgnoreCase(String str) Compare the this String (current String
object) to str, ignoring case considerations.
int indexOf(char ch) Returns position index of a specified
character of the this String (current String
object).
int lastIndexOf(char ch) Returns the index within the this String of
the last occurrence of the specified character.
int length( ) Returns the length of the this String.
String replace(char oldChar, char newChar) Returns a new String resulting from
replacing all occurrences of oldChar in the
this String with newChar.
boolean startsWith(String str) Tests if the this String starts with the
specified suffix (str).
String substring(int beginIndex, int endIndex) Returns a new String that is a substring of
the this String.
String toLowerCase( ) Converts all of the characters in the this
String to lower case
String to String( ) Returns the String itself.
String toUpperCase( ) Converts all of the characters in the this
String to upper case.
String trim( ) Returns white space from both ends of the
this String.

142
String valueOf(alltypes) Returns String representation of the passed
argument.
Example 9.3 length( )
public class Example9_3
{
public static void main(String arg[ ])
{
char c[ ] = {'a','b','c','d','e'};
String s = new String(c);
System.out.println("s = "+s.length( ));
}
}
Output: s = 5

Example 9.4(a) String concatenation


public class Example9_4_a
{
public static void main(String arg[ ])
{
int age = 9;
String s = "He is "+age+" years old";
System.out.println(s);
}
}
Output: He is 9 years old

Example 9.4(b) String concatenation


public class Example9_4_b
{
public static void main(String arg[ ])
{
String s = "Four = "+2+2;
String s1 = "Four = "+(2+2);
System.out.println(s);
System.out.println(s1);
}
}
Output: Four = 22
Four = 4

Example 9.4(c) String concatenation


public class Example9_4_c
{
public static void main(String arg[ ])
{
String s = "abcde";

143
char ch = s.charAt(2);
System.out.println("ch = "+ch);
}
}
Output: ch = c

Example 9.5 getChars( )


public class Example9_5
{
public static void main(String arg[ ])
{
String s = "I like java language";
int start = 8;
int end = 11;
char b[ ] = new char[end - start];
s.getChars(start,end,b,0);
System.out.println(b);
}
}
Output: ava

Example 9.6 equals( ) and equalsIgnoreCase( )


public class Example9_6
{
public static void main(String arg[ ])
{
String s1 = "Hello";
String s2 = "Hello1";
String s3 = "HELLO";
System.out.println("s1 equals s2 "+s1.equals(s2));
System.out.println("s1 equals s3 "+s1.equalsIgnoreCase(s3));
}
}
Output: s1 equals s2 false
s1 equals s3 true

Example 9.7 trim( )


public class Example9_7
{
public static void main(String arg[ ])
{
String s1 = " Hello World ";
String s2 = s1.trim();
System.out.println("s1 = "+s1);
System.out.println("s2 = "+s2);
}

144
}
Output: s1 = Hello World
s2 = Hello World */

Example 9.8 substring( )


public class Example9_8
{
public static void main(String arg[ ])
{
String original = "This is a test";
String result = original.substring(0,4);
System.out.println(result);
}
}
Output: This

Example 9.9 indexOf( )


public class Example9_9
{
public static void main(String arg[ ])
{
String str = "Now is the time for all good men";
System.out.println(str.indexOf('t') );
System.out.println(str.lastIndexOf('t') );
System.out.println(str.indexOf("the") );
}
}
Output: 7
11
7

Example 9.10 valueOf( )


public class Example9_10
{
public static void main(String arg[ ])
{
double d = 5.123456789;
String str = String.valueOf(d);
System.out.println(str);
}
}
Output: 5.123456789

Example 9.11 replace( )


public class Example9_11
{

145
public static void main(String arg[ ])
{
String str = "JAVA";
str = str.replace('A','$');
System.out.println(str);
}
}
Output: J$V$
9.6 StringBuffer class
The StringBuffer class, which is part of java.lang package, is alternative to the String
class. A StringBuffer objct contains a memory block called a buffer which may not contain a
String. The StringBuffer classes have following properties exhibits.
- The length of the String may not be same as the length of the buffer.
- The length of the buffer is referred to as the capacity of the StringBuffer object.
- You can change the length of a String in a StringBuffer object with the
setLength( ) method.
- When the StringBuffer object‟s length is longer than the String it holds, the extra
characters contain „\u0000‟.
- If you use the setLength( ) method to specify a length shorter than its String, the
String is truncated.
 Difference between length( ) and capacity method
length( ) returns total number of characters in the String where as capacity( ) returns
the maximum number of characters that can be inserted in the String.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
D o g C a t I

length( ) =9 capacity( ) =17

9.6.1 StringBuffer Object


StringBuffer objects provide more flexibility than String objects because you can
insert or append new contains into a StringBuffer. All the functions of String class can also be
used with StringBuffer class. However, there are some additional methods that you can use with
StringBuffer objects. Additional StringBuffer methods are

- append(x): add x characters to the end of a StringBuffer object.


- insert(offset, x): add x characters at a specified location offset within a
StringBuffer object.
- setCharAt(index, c): It replaces character at index with c in a StringBuffer.
- delete(beg, end): Deletes characters at index through end.
- setLength(n): Sets the length of the content to n by either truncating current
content or extending it with the null character(„\40000‟) use setLength(0) to clear a
String buffer.
- reverse( ): Reverses the contents of StringBuffer.

146
Some StringBuffer methods returns a StringBuffer value (e.g; append( ), insert( ), …). In fact,
they return the same StringBuffer that was used in the call. This allows chaining of calls.

Example 9.12 Chaining calls


public class ChainingCall
{
public static void main(String arg[ ])
{
int x = 5,y = 2;
StringBuffer sb = new StringBuffer( );
sb.append("X = ").append(x).append(" y = ").append(y);
System.out.println(sb);
}
}
Output: x = 5 y = 2

9.6.2 Efficiency of StringBuffer compared to String class


Though a StringBuffer object is mutable there is no need to allocate a new object
when modifications are desired. If a String is modified, new String object is created to hold
changes. The original String remains unchanged. For example we are now trying to solve a
problem which duplicates Strings the requested number of times using a method duplicate( ).

Example 9.13 String demo


public class StringDemo
{
public static String duplicate(String s,int time)
{
String result = s;
for(int i = 1;i <= time; i++)
result = result + s;
return result;
}
public static void main(String arg[ ])
{
StringDemo obj = new StringDemo( );
String str = obj.duplicate(" Tiger",10);
System.out.println(str);
}
}
Output: Tiger Tiger Tiger Tiger Tiger Tiger Tiger Tiger Tiger Tiger Tiger

It called to duplicate a String 10 times; it would build 10 new String objects, 9 of which it would
immediately throw away! Creating new objects is not efficient. A better solution is to use
StringBuffer which given in Example 9.14.

147
Example 9.14 StringBuffer demo
public class StringBufferDemo
{
public static String duplicate(String s, int time)
{
StringBuffer result = new StringBuffer(s);
for(int i = 1; i <= time; i++)
result.append(s);
return result.toString( );
}
public static void main(String arg[ ])
{
StringBufferDemo obj = new StringBufferDemo( );
String str = obj.duplicate(" Tiger",10);
System.out.println(str);
}
}
Output: Tiger Tiger Tiger Tiger Tiger Tiger Tiger Tiger Tiger Tiger Tiger

In Example 9.14 creates only two objects, the StringBuffer and final String that is returned.
StringBuffer will automatically expand as needed. These expansions are costly however, so it
would be better to create the StringBuffer the correct size from the start as shown in following
code fragment.
StringBuffer result = new StringBuffer (s.length( ) * time);

Example 9.15 Write a program to check whether a string is palindrome or not.


import java.io.*;
public class Palindrome
{
public static void main(String arg[ ])
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
try
{
System.out.println("Enter a word");
String str = br.readLine( );
showPalindrome(str);
}
catch(Exception e){}
}
public static void showPalindrome(String s)
{
StringBuffer sbr = (new StringBuffer(s)).reverse( );
if( s.equals(sbr.toString( ) ) )
System.out.println(s+" Is a Palindrome");

148
else
System.out.println(s+" Is not a Palindrome");
}
}
Output: Enter a word
dad
dad Is a Palindrome

Example 9.16 Enter a line and separate all the words.


import java.io.*;
public class StringProcessing
{
public static void main(String arg[ ])throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter a line:");
String str = br.readLine( );
int n = str.length( );
for(int i = 0; i < n; i++)
{
char ch = str.charAt(i);
if(ch == ' ')
System.out.println( );
else
System.out.print(ch);
}
}
}
Output: Enter a line:
Today is a hot day
Today
is
a
hot
day

9.7 STRING TOKENIZER


Usually we input values a value at a time following each vale by a carriage return. In
some cases it is nice to able to input values as a sequence. We can do this by simply entering the
sequence as a string. However, once Java has got the String, to do anything useful with it we
must be able to isolate different values within the String. A String tokenizer can identify and
parse (segregate) tokens in a String.
The StringTokenizer class which is found in the Java package util. This containing a
number of useful instance methods that can be used to isolate tokens (Figure 9.2).

149
java.lang.Object

java.util.StringTokenizer

public StringTokenizer(String str)

public StringTokenizer(String str, String delim)

public int countTokens( )

public String nextToken( )

Figure 9.2 class diagram of the StringTokenizer class

To use these methods you must create an instance of the StringTokenizer class as shown below:
StringTokenizer st = new StringTokenizer(“String”);
Where the argument is a String of text. The StringTokenizer class also provides two methods that
are immediately useful for processing Strings:
(i) countTokens( ) method which returns the number of tokens that are delimited by any white
space in a given String, thus you know how many tokens there are and therefore can use this
number as a loop parameter with which to process the String.
(ii) nextToken( ) method which returns the next token in a String from the current token. When
used for the first time the next token is first token in the String. Thus this method can be used to
pass along the string token by token.

Example 9.17 Enter a line and separate all the words using StringTokenizer class.
import java.io.*;
import java.util.*;
public class StringTokenizerDemo
{
public static void main(String arg[ ])throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter a line:");
StringTokenizer str = new StringTokenizer(br.readLine( ));
int c = str.countTokens( );
System.out.println("Number of Tokens = "+c);
for(int i=0; i < c; i++)
System.out.println(str.nextToken( ));
}
}
Output: Enter a line:
Today is a hot day
Number of Tokens = 5

150
Today
is
a
hot
day

9.7.1 Processing a Number Sequence with StringTokenizer


In the Example 9.17, we assumed that words are delimited (separated) by a space,
which is the default delimiter. What if you need to process something which has a delimiter other
than the space? Example 9.18 process a sequence of comma separated integers using the
methods found in the StringTokenizer class.

Example 9.18 Use of StringToknizer class for asequence delimited by comma ( , ).


import java.io.*;
import java.util.*;
public class Example9_18
{
public static void main(String arg[ ])throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int c = 0,total = 0;
int numberArray[ ];
System.out.println("Enter a sequence of Integer separated by comma ',' ");
StringTokenizer data = new StringTokenizer(br.readLine( ),",");
c = data.countTokens( );
System.out.println("Number of Tokens = "+c);
numberArray = new int[c];
for(int i = 0; i < c; i++)
{
numberArray[i] = new Integer(data.nextToken( )).intValue( );
System.out.println(numberArray[i]);
total = total + numberArray[i];
}
System.out.println("Average = "+(total / c));
}
}
Output : Enter a sequence of Integer separated by comma ','
1,2,3,4,5
Number of Tokens = 5
Average = 3

9.8 VECTORS
The J2SE5.0 version onwards supports the concept of variable arguments to methods.
This feature can also be achieved in Java through the use of the vector class contained in the
java.util package. This class can be used to create a generic dynamic array known as vector that

151
can hold objects of any type and any number. The objects do not have to homogeneous. Arrays
can be easily implemented as vectors. Vectors are created like arrays as follows:
Vector vect = new Vector( ); //declaring without size
Vector list = new Vector(3); //declaring with size
A vector can be declared without specifying any size explicitly. A vector without size can
accommodate an unknown number of items. Even, when a size is specified, this can be
overlooked and a different number of items may be put into the vector.
Vectors possess a number of advantages over arrays.
- It is convenient to use vectors to store objects.
- A vector can be used to store a list of objects that may vary in size.
- We can add and delete objects from the list as and when required.
A major constraint is using vectors is that you cannot directly store simple datatype in a vector,
you can only store objects. Therefore, we need to convert simple types to objects. This can be
done using the wrapper class discussed in the next section. The vector class supports a number of
methods that can be used to manipulate the vectors created. Important ones are listed in
Table 9.2.

Method call Task performed


list.addElement(item) Adds the item specified to the list at the end
list.elementAt(5) Gives the name of the 5th object.
list.size( ) Gives the number of objects present
list.removeElement(item) Removes the specified item from the list.
list.removeElementAt(n) Removes the item stored in the nth position of the
list.
list.removeElements( ) Removes all the elements in the list.
list.copyInto(array) Copies all items from list to array.
list.insertElementAt(item, n) Inserts the items at nth position.
Table 9.2 Important Vector Methods

Example 9.19 A demo for implementing Vector


import java.util.*;
public class LanguageVector
{
public static void main(String arg[ ])
{
Vector list = new Vector( );
int len = arg.length;
for(int i = 0; i < len; i++)
list.addElement(arg[i]);
list.insertElementAt("C#",2);
int size = list.size( );
String array[ ] = new String[size];
list.copyInto(array);
for(int i =0; i < size; i++)
System.out.print(" , "+array[i]);
}

152
}
Compile : javac LanguageVector.java
Run : java LanguageVector c c++ vb oracle java
Output : ,c , c++ , c# , oracle , java

9.9 WRAPPER CLASSES


Java uses simple types, such as int and char, for performance reasons. These datatypes
are not part of the object hierarchy. They are passed by value to methods and cannot be directly
passed by reference. As pointed out earlier, vectors cannot handle primitive datatypes like int,
float, long, char and double. Primitive datatypes may be converted into object types by using the
wrapper class contained in the java.lang package. Table 9.3 shows the simple datatypes and their
corresponding wrapper class types.

Simple Type Wrapper class


byte Byte
short Short
int Integer
long Long
char Character
float Float
double Double
boolean Boolean
void Void
Table 9.3 Wrapper classes for Converting Simple Types

Example 9.20 A demo program to covert primitive data types to Wrapper class object.
public class WrapperSample
{
public static void main(String arg[ ])
{
int iVal = 100;
long lVal = 2000;
float fVal = 300.5f;
double dVal = 400.1111189999;
String str = "123";

//primitive types to corresponding Wrapper objects


Integer intVal = Integer.valueOf(iVal);
Long lgVal = Long.valueOf(lVal);
Double dbVal = Double.valueOf(dVal);
Float ftVal = Float.valueOf(fVal);

//Wrapper objects to corresponding primitive type


fVal = ftVal.floatValue( );
dVal = dbVal.doubleValue( );

153
//Primitive type to String Objects
str = String.valueOf(iVal);
str = Strint.valueOf(lVal);

//String to Primitive type


iVal = Integer.parseInt(str);
lVal = Long.parseLong(str);

//String to Wrapper objects


intVal = Integer.valueOf(str);
lgVal = Long.valueOf(str);
}
}

9.10 USING clone( ) AND Cloneable INTERFACE


Object is a super class of all other classes. Object defines the methods shown in Table
9.4, which are available to every object.

Method Description Exception


Object clone( ) Creates a new object that is Throws
the same as the invoking CloneNotSupportedException
object.
boolean equals(Object object) Returns true if the
invoking object is
equivalent to object
void finalize( ) Default finalize( ) method. Throws Throwable
This is usually overridden
by subclasses.
final Class getClass( ) Obtains a class object that
describes the invoking
object.
int hashCode( ) Returns the hash code
associated with the
invoking object.
final void notify( ) Resumes execution of a
thread waiting on the
invoking object.
final void notifyAll( ) Resumes execution of all
threads waiting on the
invoking object.
String toString( ) Returns a string that
describes the object.
final void wait( ) Waits on another thread of Throws InterruptedException
execution
Table 9.4 The Methods Defined by Object

154
Most of the methods defined by Object are discussed elsewhere in this book. However, one
describes special attention: clone( ). The clone( ) method generates a duplicate copy of the
implement the Colneable interface can be cloned.
The Cloneable interface defines no members. It is used to indicate that a class allows a
bitwise copy of an object (i.e.; a clone) to be made. If you try to call clone( ) on a class that does
not implement Coneable, a ColneNotSupportedException is thrown. When a clone is made, the
constructor for the object being cloned is not called. A clone is simply an exact copy of the
original.
Cloning is a potentially dangerous action, because it can cause unintended side effects. For
example, if the object being cloned contains a reference variable and any changes made it
reflected to original object. Because cloning can cause problem, clone( ) is declared as protected
inside object. This means that it must either be called from within a method defined by the class
that implements Colneable, or it must be explicitly overridden by that class so that it is public.
Let‟s look at example of each approach.

Example 9.21 Demonstrate the clone( ) method .


class TestClone implements Cloneable
{
int a;
double b;
TestClone cloneTest( )
{
try{
return (TestClone)super.clone( );
}
catch(CloneNotSupportedException e)
{
System.out.println("Cloning is not allowed");
return this;
}
}
}
public class CloneDemo
{
public static void main(String arg[ ])
{
TestClone tc1 = new TestClone( );
TestClone tc2;
tc1.a = 100;
tc1.b = 119.56;
tc2 = tc1.cloneTest( );
System.out.println("tc1 : "+tc1.a+"\t"+tc1.b);
System.out.println("tc2 : "+tc2.a+"\t"+tc2.b);
}
}

155
Output: tc1 : 100 119.56
tc2 : 100 119.56
You can solve this problem by override the clone( ) method.

Example 9.22 Override the clone( ) method.


class TestClone implements Cloneable
{
int a;
double b;
public Object clone( )
{
try{
return super.clone( );
}
catch(CloneNotSupportedException e)
{
System.out.println("Cloning is not allowed");
return this;
}
}
}
public class CloneDemo2
{
public static void main(String arg[ ])
{
TestClone tc1 = new TestClone( );
TestClone tc2;
tc1.a = 100;
tc1.b = 119.56;
tc2 = (TestClone)tc1.clone( );
System.out.println("tc1 : "+tc1.a+"\t"+tc1.b);
System.out.println("tc2 : "+tc2.a+"\t"+tc2.b);
}
}
Output: tc1 : 100 119.56
tc2 : 100 119.56

9.10.1 Deep and Shallow Cloning


Many times in project you need to create exact copy of the object and operate on
them. To do this there two ways of doing it Shallow clone and Deep clone. When an object is
Shallow cloned the parent object or the top level object and its members are duplicated. But any
lower level objects are not duplicated. Rather references of these objects are copied. So when an
object is Shallow cloned and you modify any of it child classes it will affect the original copy.
When an object is deep cloned the entire object and its aggregated objects are also duplicated. In
order to implement shallow cloning you need to implement cloneable interface and override the
clone method with implementation.

156
Example 9.23 Shallow cloning.
import java.util.*;
class CloneExample implements Cloneable
{
int num;
Integer myArray[ ];
CloneExample(int element)
{
num = element;
myArray = new Integer[num];
Random ran = new Random( );
for(int i = 0; i < num ; i++)
myArray[i] = new Integer(ran.nextInt(1000));
}
public Object clone( )
{
try{
return super.clone( );
}
catch(CloneNotSupportedException e)
{
System.out.println("Cloning is not allowed");
return this;
}
}
}
public class ShallowCloning
{
public static void main(String arg[ ]) Gets the object
{ using the clone
CloneExample ex = new CloneExample(5); method
CloneExample copy =(CloneExample)ex.clone( );
ex.myArray[0] = new Integer(1111111);
System.out.println("Original value of myArray[0] = "+ex.myArray[0]);
System.out.println("Copy value of myArray[0] = "+copy.myArray[0]);
}
Create a new array with some value
}
Output: Original value of myArray[0] = 1111111
Copy value of myArray[0] = 1111111

9.10.2 Implementing Deep cloning


Deep cloning can be done by two ways:
(i) All objects implement a clone method
Every object is responsible for cloning itself via its clone( ) method. So when the
parent is called it makes calls to all the referenced objects inside the class and calls its clone
method.

157
(ii) Serialization
Serialization is a process by which an object instance is converted into stream of bytes.
There are much useful stuff you can do when the object instance is converted into stream of
bytes for instance you can save the object in hard disk or send it across the network. There are
three steps to do deep cloning using Serialization:
- Ensure that all classes in the object are serializable.
- Create output stream for writing the new object and input stream reading the same.
- Pass the object you want to copy the output stream.
- And finally read the object using the input stream.

Example 9.24 Deep cloning.


Example 9.24 Deep cloning
static public Object deepCopy(Object oldObj)throws Exception
{
ObjectOutputStream obj = null;
ObjectInputStream obj1 = null;
try{
//create a output stream
ByteArrayOutputStream bos = new ByteArrayOutputStream( );
obj = new ObjectOutputStream(bos);
Create a OutputStream
//Serialize original object into the output stream
obj.writeObject(oldObj);
Serialize the object using writeObject( ) method
obj.flush( );

// To read the object create a inputStream


ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray( ));
obj1 = new ObjectInputStream(bin);
Use the InputStream to read the same
// read the complete object
return obj1.readObject( );
}
catch(Exception e)
{
throw(e);
}
finally{
obj.close( );
obj1.close( );
}
}

9.10.3 Implementing Serialization


In order to implement Serialization we need to use two classes from java.io.package
“ObjectInputStream” and “ObjectOutputStream”. ObjectOutputStream has a method called
writeObject( ), while ObjectInputStream has a method called readObject( ). Using writeObject( )

158
we can write and readObject( ) can be used to read the object from the stream. The detail of
serialization is discussed in chapter-14.

Example 9.25 Implementing Serialization.


private void saveObject(myObject obj)throws IOException
{
String filepath = "C:\my.obj";
FileOutputStream fos = new FileOutputStream(filepath);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
oos.close( );
fos.close( );
fos = null;
oos = null;
}
private myObject getObject(String FullFilePath)throws IOException,ClassNotFoundException
{
myObject obj = null;
FileInputStream fis = new FileInputStream(FullFilePath);
ObjectInputStream ois = new ObjectInputStream(fis);
obj = (myObject)ois.readObject( );
ois.close( );
fis.close( );
return obj;
}

9.11 CLASS LOADER


Java was designed thinking platform independency in mind. So from loading libraries
point of view it should not rely on file systems. In short it‟s not necessary that you should be able
to load libraries which are in only file systems but also from other sources like FTP,HTTP etc.
So Java went one step further you can load classes from across network or from other source like
FTP, HTTP etc. in order to attain this class loaders came in to picture. ClassLoader is the class
responsible for finding and loading classes at runtime. You can either use different class loaders
or you can make a custom one.
There are three types of class loaders:
- BootStrap class loader also called primordial class loader
- Extension class loader
- System class loader
(i) BootStrap class loader
BootStrap class loader loads those classes which are essential for JVM to function
properly. BootStrap class loader is responsible for loading all core java classes for instance
java.lang.*, java.io.* etc. BootStrap class loader finds these necessary classes from
jdk/jre/lib/rt.jar. BootStrap class loader cannot be instantiated from Java code and is
implemented natively inside JVM.

159
(ii) Extension class loader
The Extension class loader also termed as the standard extension class loader is a child
of the BootStrap class loader. Its primary responsibility is to load classes from extension
directories, normally located the jre/lib/ext directory. This provides the ability to simply drop in
new extensions, such as various security extensions without requiring modification to the user‟s
class path.

(iii) System class loader


The System class loader also termed application class loader is the class loader
responsible for loading code from the path specified by the CLASSPATH environment variable.
It is also used to load an application‟s entry point class that is static void main( ) method in a
class.

9.11.1 Flow between BootStrap, extension and System class loader


To explain flow between BootStrap, extension and System class loader let‟s consider
the below given code.
import java20.*;
public class Simple
{
public static void main(String arg[ ])
{
String mystr = “I am a Student”;
System.out.println(mystr);
}
}
The above class uses String class that means it has
reference to java.lang.String. JVM will request the system BootStrap class loader
class loader to load java.lang.String. But before it tries to
load it will delegate to extension class loader. Extension
class loader will pass it to BootStrap class loader. Now Extension class loader
BootStrap class loader does not have any parent so it will
try to load java.lang.String using rt.jar. Now the
BootStrap will return the class back using the same chain System class loader
to the application.
How import java20.* is loaded using class loader.
For the import statement JVM will make a call to the Application requests a class
system class loader who will delegate the same to the
extension class loader which will delegate the same to the Figure 9.3 Flow between class
BootStrap class loader. BootStrap loader will not find loader
java20.* and return nothing to the extension class loader.
Extension class loader will also check the same in its path and will not find anything thus
returning nothing to the system class loader. System class loader will use its class path and load
the class and return the same to the JVM who will then return it to the application.

160
9.11.2 Difference between Static and Dynamic class loading
In static loading we use the new keyword to create object. For example
myclass obj = new myclass( ).
In static loading we need to know from the start what type of object we will be creating. While in
dynamic class loading we need to know the string name of the class and then everything else will
be dynamically loaded. Dynamic class loading is only possible due to Reflection API interfaces.
Reflection API is a member of core java.lang package. The methods provided by the Reflection
API obtain information about a class, such as the fields, constructors, methods, and super classes
of the class. In addition, you can obtain the interfaces implemented by the class.

Example 9.26 Implementing dynamic loading.


public class DynamicLoading
{
public static void main(String arg[ ])throws Exception
{ 1
Class toRun = Class.forName("java20.piet.java"); //load the class
Method mainMethod = findMain(toRun); // call the findMain method of the class
2 3
mainMethod.invoke(null,new Object[ ]{toRun}); //This method finds the mainMethod of the
class
}
private static Method findMain(Class z)throws Exception
{
Method m[ ] = z.getMethods( );
for(int i = 0; i < m.length ; i++)
{
if(m[i].getName( ).equals("main"))
return m[i];
}
return null;
}
}

In the example 9.24 implement dynamic class loading, in this example some steps are marked.
First thing we need to do is load the class which is done by using Class.forName( ). In the second
step we just try to find out the main method and get the method reference using getMethod( )
collection. Finally invoke the method invoke( ).

9.12 Autoboxing and Unboxing


This is a newly added feature in J2SE 5.0. Auto boxing is the process in which
primitive type is automatically boxed (convert) into equivalent type wrapper. There is no need to
explicitly do casting for the same. The compiler generates a code implicitly to convert primitive
type to the corresponding wrapper class type and vice-versa.
For example, consider the following statements:
- Double dobj = 19.42;
This will auto box a double to a Double object automatically.

161
- double pobj = dobj
This will auto box a double object to a primitive data type.

9.13 ENUMERATED TYPES


J2SE 5.0 allows us to use the enumerated type in Java using the enum keyword. This
keyword is used to replace static final constants. For example, consider the following code:
public class Day
{
public static final int SUNDAY = 0;
public static final int MONDAY = 1;
public static final int TUESDAY = 2;
public static final int WEDNESDAY = 3;
public static final int THURSDAY = 4;
public static final int FRIDAY = 5;
public static final int SATURDAY = 6;
}
Using the enumerated type the above code can be rewritten as:
public enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY}
Example 9.27 Use of enum type data .
public class WorkingDay
{
enum Day{SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY}
public static void main(String arg[ ])
{
for (Day d : Day.values( ))
{
weekend(d);
}
}
public static void weekend(Day k)
{
if(k.equals(Day.SUNDAY))
System.out.println("Value = "+k+" is a HoliDay");
else
System.out.println("Value = "+k+" is a WorkingDay");
}
}
Output: Value = SUNDAY is a HoliDay
Value = MONDAY is a WorkingDay
Value = TUESDAY is a WorkingDay
Value = WEDNESDAY is a WorkingDay
Value = THURSDAY is a WorkingDay
Value = FRIDAY is a WorkingDay
Value = SATURDAY is a WorkingDay

162
9.14 ANNOTATIONS
The annotations feature, introduced by J2SE 5.0, is also known as metadata. We can
use this feature to merge additional Java elements with the programming elements, such as
classes, methods, parameters, local variable, packages, and fields.
Metadata is stored in java class files by the compiler and these class files are used by
the JVM or by the program to find the metadata for interacting elements. For example, the
following code that contains the declaration of an annotation:
package mypack.annotation;
import java.lang.annotation.*;
@Retention(Retentionpolicy.RUNTIME)
@Target((ElementType.METHOD))
public @interface UnitTest
{
String value( );
}
Here @Retention is a meta-annotation, which declares that the @UnitTest annotation must be
stored in a class file.
The @Target meta-annotation is used to declare the @UnitTest annotation, which
annotates the methods in the Java class files. The @interface meta-annotation is used to declare
the @UnitTest annotation with the member called value, which returns String as an object.
An annotation can also be applied to programming elements. For example, consider the
code in which an annotation is applied to the methods, positive( ) and negative( ) of a class,
Checking:
import mypack. Annotation.*;
public class Checking
{
@UnitTest(value = “This test will positive”);
public void positive(int no)
{
assert no > 0;
}
@UnitTest(value = “This test will negative”);
public void negative(int no)
{
assert no < 0;
}
}
After merging the annotation with the programming element, we can use the methods available
in the interface, Java.lang.reflect. Annotated Element to query about the existence of
programming element and get their values. The methods of the AnnotatedElement interface are
- IsAnnotationPresent( )
- getAnnotations( )
- getAnnotation( )
- getDeclaredAnnotations( )
The class that implement the AnnotatedElement interface are:
- java.lang.reflect.accessibleobject

163
- java.lang.class
- java.lang.reflect.constructor
- java.lang..reflect.field
- java.lang.reflect.method
- java.lang.package

Example 9.28 Use of annotations.


import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@interface MySingle
{
int value( );
}
public class Single
{
@MySingle(200)
public static void myMethod( )
{
Single obj = new Single( );
try{
Method m = obj.getClass( ).getMethod("myMethod");
MySingle anno = m.getAnnotation(MySingle.class);
System.out.println("The value is : "+anno.value( ));
}
catch(NoSuchMethodException e)
{
System.out.println("Method not found");
}
}
public static void main(String arg[ ])
{
myMethod( );
}
}
Output: The value is : 200

164
Summary
In this chapter we learned the following:
How does Java handle strings.
How to use the String and StringBuffer classes.
How important StringTokenizer class.
What is a vector in Java.
How are wrapper classes useful.
How Cloneable interface is used to copy object‟s content.
What is class loader.
What is autoboxing and unboxing.
Enumerated type
Annotations introduced by J2SE 5.0 version.

165
Review Question
9.1 Write a program to extract a portion of a character string and print the extracted string.
Assume that m characters are extracted, starting with the nth character.
9.2 Write a program, which will read a text and count all occurrences of a particular word.
9.3(i) What is the difference between equals( ) and equalsIgnorecase( ) string functions?
(ii) What is the difference between length( ) and capacity( ) string functions?
(iii) What is the difference between String class and StringBuffer class?
9.4 Write a program, which will read a string and rewrite it in the alphabetical order. For
example, the word STRING should be written as GINRST.
9.5 Write a program that accepts a shopping list of five items from the command line and stores
them in a vector.
9.6 What are the applications of wrapper class?
9.7 What is Serialization? How do you implement Serialization actually?
9.8 What is autoboxing and unboxing?
9.9 How do you implement deep cloning?
9.10 Can you explain the fundamentals of deep and shallow cloning?
9.11 What is the difference between static and dynamic class loading?
9.12 What are class loader‟s?
9.13 Write a program to delete all vowels from a sentence. Assume that the sentence is not more
than 80 characters long.
9.14 Write a program that takes a set of names of individuals and abbreviates the first, middle
and other names except the last name by their first letter.
9.15 Write a program that will read a line and delete from it all occurrences of the word the.
9.16 How do you convert a char, an array of characters, or a number to a string?
9.17 Write a program that passes integers from the command line and displays them in
increasing order.
9.18 Write a program that parses a binary number as string and convert it to decimal number.

166
Multithreading
10.0 INTRODUCTION
In the modern operating systems such Windows Xp, Windows Vista, Windows 7 and
8, Red Hat Linux etc may recognize that they can execute several programs simultaneously. This
ability is known as multitasking. In system‟s terminology, it is called multithreading. One of the
powerful feature of Java is its built-in support for multithreading-the concurrent running of
multiple tasks within a program. In many programming language, you have to invoke system-
dependent procedures and functions to implement multithreading. This chapter introduces the
concepts of threads and how to develop multithreading programs in Java.

10.1 THREAD CONCEPTS


When a program executes with a separate memory allocation, the execution time
between starting and ending of the program is known as Process.
When a single environment can execute multiple processes in a single instance of time
then that environment is known as multiprocess environment.
Thread is a single sequential flow of control from one line to another in a program
which can execute independently inside the process‟s memory location. That‟s why thread is
known as light weight process. Since they do not occupy their own memory location, they use
the process‟s memory location.
When more than one thread execute simultaneously without depending upon other
execution then that program is known as multithreaded program. These threads can be executed
simultaneously in multiprocessor systems, as shown in Figure 10.1(a).
Thread 1 Thread 1

Thread 2 Thread 2

Thread 3 Thread 3

(a) (b)
Figure10.1 (a) Here multiple threads are running on multiple CPUs. (b) Here multiple
threads share a single CPU.

In single-processor systems, as shown in Figure 10.1(b), the multiple threads share CPU time,
and the operating system is responsible for scheduling and allocating resources to them. This
arrangement is practical, because most of the time the CPU is idle. It does nothing, for example
while waiting for the user to enter data.
A unique property of Java is its support for multithreading. That is java enables us to use
multiple flows of control in developing programs. Each flow of control may be thought of as a
separate tiny program (or module) known as a thread that runs in parallel to others as shown in
Figure 10.2. A program that contains multiple flows of control is known as multithreaded
program. Figure 10.2 illustrates a Java program with four threads, one main and three others. The
main thread is actually the main method module, which is designed to create and start the other
three threads, namely A, B and C. Once initiated by the main thread, the threads A, B and C run

167
concurrently and share the resources jointly. The ability of a language to support multithreads is
referred to as concurrency.

Main Thread
--------
Main method
-------- module

--------
start start start
--------
-
------- switching ------- switching -------
------- ------- -------
------- ------- -------
Thread A -
Thread B Thread C

Figure 10.2 A Multithreaded Program

10.2 CREATING MULTITHREADED PROGRAM


A multithreaded program can be created two ways:
- By extending.java.lang.Thread class (By using Thread class)
- By implementing java.lang.Runnable interface (By using Runnable interface)

10.2.1 Using Thread Class


It includes the following steps:
(i) Create a class by inheriting (or extending) Thread class.
(ii) Override run( ) method available in Thread class to provide implementation logic or body of
the thread.
(iii) Initialize the class created in step-i (the subclass of thread) and call the start( ) method upon
it to start the execution of Thread.

Example10.1 Creating a thread using Thread class.


class MyThread extends Thread
{
public void run( )
{
System.out.println("This is a child class thread");
}
}
public class ThreadDemo
{
public static void main(String arg[ ])
{
MyThread mt=new MyThread( );

168
mt.start( );
System.out.println("Parent thread running");
}
}
Output: Parent thread running
This is a child class thread

10.2.2 Using Runnable Interface


It includes the following steps:
(i) Create a class which must implements Runnable interface. If required provide constructor to
this class.
(ii) Override the run( ) method available in Runnable interface & provide implementation logic
for the thread.
(iii) Create an instance(object) of the class which inherits Runnable and provide this instance to
the constructor of the Thread as:
MyThread mt = new MyThread( );
Thread th = new Thread(mt);
This class which
implements Runnable
(iv) Call the start( ) method upon the Thread class instance to start the Thread‟s execution as:
th.start( );

Example10.2 Creating a thread using Runnable interface.


class MyThread implements Runnable
{
public void run( )
{
System.out.println("This is a child class thread");
}
}
public class ThreadDemo2
{
public static void main(String arg[ ])
{
MyThread mt=new MyThread( );
Thread th=new Thread(mt);
th.start( );
System.out.println("Parent thread running");
}
}
Output: Parent thread running
This is a child class thread
 If a class is already extending another class you cannot extend Thread class because java
doesn‟t support multiple inheritances; so you have left only one choice i.e.; implementing
Runnable interface. When you extend a thread each of your threads has a unique object
associated with it, where as with Runnable, many threads share the same object instance.
169
10.2.3 Process of Setting Priority
Priority setting is a method in which you can execute various threads one after
another. The setPriority( ) method of Thread class to change the priority which accept an int
value available as constants in Thread class. Priority constants vary from 1 to 10.
MIN_PRIORITY its numeric value 1
MAX_PRIORITY its numeric value 10
NORM_PRIORITY [default] its numeric value 5
e.g. (i) th.setPriority(Thread.MAX_PRIORITY)
(ii) th.setPriority(10);
(iii) th.setPriority(5);

Example 10.3(a) Priority setting (to Runnable interface).


class MyThread implements Runnable
{
public void run( )
{
System.out.println("CHILD............");
}
}
public class PriorityDemo1
{
public static void main(String arg[ ])
{
MyThread mt=new MyThread( );
Thread th = new Thread(mt);
th.setPriority(3);
th.start( );
System.out.println("Parent---------");
}
}
Output: Parent---------
CHILD............

Example 10.3(b) Priority setting (to Thread class).


class MyThread extends Thread
{
public void run( )
{
System.out.println("CHILD............");
}
}
public class PriorityDemo2
{
public static void main(String arg[ ])
{
MyThread mt=new MyThread( );

170
mt.setPriority(9);
mt.start( );
System.out.println("Parent---------");
}
}
Output: Parent---------
CHILD............

10.3 LIFE CYCLE OF THREAD


The process of execution of a thread (starting and ending time of a thread execution) is
known as life cycle of a thread which is shown in Figure 10.3.

Thread start( ) Ready to run( ) Running Death


Creation run

resume( ) time
exprires for sleep Sleep( )/join( )/suspend( )
makes thread stop for
child
Suspended

Figure 10.3 State diagram of life cycle of thread

Thread Creation:
In this state the instance of the thread is being created and required resources will be
allocated to the Thread.
Ready to Run:
After instantiation of the thread start( ) method can be called to make the Thread ready to
run, not running since at that moment the processor might be busy with other threads.
Running:
In this state the thread starts its execution by using run( ) method. In this state the thread
stays with the processor.
Suspended:
From the running state the thread can be suspended to stop its execution temporarily or
permanently. The thread can restart its execution from its previous step of instruction of the
run( ) method without executing the entire run( ) method again. The thread cannot enter into
running state from suspension directly.
Death:
In this state the thread finishes its execution and goes for making the resources free which
has been occupied by the thread.
To handle the life cycle of thread Java provides various methods which are given in
Table 10.1.

171
public static Thread currentThread( ) Returns a reference to the currently
executing thread object.
public static void yield( ) Causes the currently executing thread object
to temporarily pause and allow other threads
to execute.
public static void sleep(long millis) Causes the currently executing thread to
sleep. This method throws
InterruptedException.
public void start( ) Causes this thread to begin execution; the
JVM calls the run( ) method of this thread.
This start( ) method throws
IllegalThreadStateException started.
public void run( ) If this (current) thread was constructed
using a separate Runnable run object then
that Runnable object‟s run( ) method is
called; otherwise, this method does nothing
and returns.
public void stop( ) It forces the thread to stop executing, this
method is inherently unsafe. Stopping a
thread with Thread.stop( ) causes it to
unlock all the of the monitors that it has
locked.
public void destroy( ) Destroys this thread, without any cleanup.
Any monitors it has locked remain locked.
public final boolean isAlive( ) Tests if this thread is alive. A thread is alive
if it has been started and has not yet died. It
returns true if thread is alive and false
otherwise.
public final void suspend( ) If the thread is alive, it is suspended and
makes no further progress unless and until it
is resume.
public final void resume( ) If the thread is alive but suspended, it is
resumed and is permitted to make progress
in its execution.
public final void join(long millis) Waits at-most milliseconds for this thread to
die. A timeout of „0‟ (zero) means to wait
forever.
public final void join(long millis, int nanos) Waits at most millis milliseconds plus nanos
nanoseconds for this thread to die. This
method throws InterruptedException.
final void notify( ) Resumes the first threads that went into the
sleep mode.
final void notifyall( ) Resumes all the threads that are in sleep
mode. The execution of these threads
happens as per priority.

172
final void wait( ) Sends the calling thread into the sleep
mode. This thread can now be activated
only notify( ) or notifyall( ) and wait( ) all
the methods throw InterruptedException.
The wait( ) and notify( ) methods generally
used in situations where we need to
communicate between two threads.

10.3.1 Knowing the Current Thread


The currentThread( ) method of thread class can be used to find the thread in execution.
Thread t = Thread.currentThread( );

Example 10.4 Knowing the current thread.


class MyThread extends Thread
{
public void run( )
{
System.out.println("CHILD............");
}
}
public class CurrentThread
{
public static void main(String arg[ ])
{
Thread th = Thread.currentThread( );
MyThread mt=new MyThread( );
th.setPriority(1);
mt.start( );
System.out.println("Parent---------");
}
}
Output: Parent---------
CHILD............

10.3.2 Suspending Thread using sleep( ) method


The sleep( ) method accepts a long value specifying the number of milliseconds the
thread will be suspended. After finishing of the suspension duration the thread will be eligible for
running. e.g. Thread.sleep(3000);

Example 10.5 Suspending a thread using sleep( ) method.


class MyThread extends Thread
{
public void run( )
{
System.out.println("CHILD............");
}

173
}
public class SleepDemo
{
public static void main(String arg[ ])throws InterruptedException
{
MyThread mt=new MyThread( );
mt.start( );
System.out.println("Parent---------1");
Thread.sleep(1000);
System.out.println("Parent---------2");
}
}
Output: Parent---------1
CHILD............
Parent---------2

10.4 SYNCRONIZATION (LOCKING)


This is a mechanism to avoid multiple accesses of threads to a method asynchronsly or
at-a-time as shown in figure 10.4.
myMethod1 myMethod2
{ {
-------- --------
-------- Writing abc Reads --------
-------- --------
} }
Figure 10.4 Two methods try to access same memory location
When more than one thread try to access a method which is synchronized then the
method will be locked until the one thread is not finished the method call.
The locking state of the method is known as monitor. The synchronized method
occupies this state when a thread called it. The monitor can be object based monitor or class
based monitor.

10.4.1 Object Based Monitor


If the method which is used by many threads is nonstatic, then a separate of this
method is available to each and every objects which cause multiple threads can access the
method. But multiple threads cannot access the method simultaneously by using one object of
the method. For example, one printer multiple user can used one by one in LAN (Local Area
Network).
Example 10.6 Object based monitor.
class Computer
{
synchronized public void printer(String s)
{
System.out.println(s);

174
try{
System.out.println("Wait for .......1000 miliseconds");
Thread.sleep(4000);
}
catch(Exception e){}
}
}
class Job extends Thread
{
String line;
Computer c;
Job(String I, Computer p)
{
line = I;
c = p;
}
public void run( )
{
c.printer(line);
}
}
public class SysDemo1
{
public static void main(String arg[ ])
{
Computer c1 = new Computer( );
Computer c2 = new Computer( );
Computer c3 = new Computer( );
Job ie = new Job("IEXPLORER",c1);
Job pad = new Job("NOTEPAD",c2);
Job word = new Job("MSWORD",c3);
ie.start( );
pad.start( );
word.start( );
}
}
Output: IEXPLORER
NOTEPAD
MSWORD
Wait for .......1000 miliseconds
Wait for .......1000 miliseconds
Wait for .......1000 miliseconds

10.4.2 Class Based Monitor


If the synchronized method is a static method then by using multiple threads we
cannot access the method at a time by any object. For example, one printer in LAN.

175
Example 10.7 Object based monitor.
class Computer
{
static synchronized public void printer(String s)
{
System.out.println(s);
try{
System.out.println("Wait for .......1000 miliseconds");
Thread.sleep(4000);
}
catch(Exception e){}
}
}
class Job extends Thread
{
String line;
Computer c;
Job(String I, Computer p)
{
line = I;
c = p;
}
public void run( )
{
c.printer(line);
}
}
public class SysDemo2
{
public static void main(String arg[ ])
{
Computer c1 = new Computer( );
Computer c2 = new Computer( );
Computer c3 = new Computer( );
Job ie = new Job("IEXPLORER",c1);
Job pad = new Job("NOTEPAD",c2);
Job word = new Job("MSWORD",c3);
ie.start( );
pad.start( );
word.start( );
}
}
Output: IEXPLORER
Wait for .......1000 miliseconds
NOTEPAD
Wait for .......1000 miliseconds

176
MSWORD
Wait for .......1000 miliseconds

10.4.3 wait( ) and notify( ) Method


The synchronized keyword can be used to mark a statement or block of code so that
only one thread may execute an instance of the code at a time. Entry to the code is protected by a
monitor lock around it. A lock is assigned to the object and ensures only one thread at a time can
access the code and no other thread will not be able to execute the code until the first thread has
finished and released the lock.
In addition to having a lock that can be grabbed and released, each object has a
system that allows it to pause or wait and allows another thread takes over the lock. A call to
wait from within synchronized code causes the thread to give up its lock and goto sleep. This
normally happens to allow another thread to obtain the lock and continue some processing. The
wait( ) method is meaningless without the use of notify( ) or notifyAll( ) method which allows
code that is waiting to be notified that it can wake up and continue executing.
The idea behind the mechanism is simple: one thread needs a certain condition to exist and
assumes that another thread will create that condition. When another thread creates the condition,
it notifies the first thread that has been waiting for the condition. This is performed with the
following methods of the object class.

//producing code
while(true)
{
try
{
wait( );
}
catch(InterruptedException e) { }
}
//some producing code(action goes here)
notifyAll( );

Using wait( ) and notify( ) method we can solve the famous producer and consumer
problem which is a inter thread communication process. In producer consumer problem; unless
the producer not produce, the consumer cannot consume the product. This problem can be solved
in Example 10.8. Before starting inter threaded communication at first we have to understand
why inter threaded communication is needed. Using the concept of multithreaded programming
we have divided the task into discrete logical units. But if we consider a thread is producing a
data and another thread is consuming that data then the consumer thread have to wait until the
data is produced by the producing thread.The consumer thread checks this condition by using a
loop, this process is know as pooling. Similarly the producer has to wait till the data is consumed
by the consumer thread. This the wastage of CPU cycles.
The wait( ) method enables the currently running thread to be wait until another thread
calls the notify( ) method. The notify( ) method wakes up a thread that is waiting for the current
monitor( ), if more than one thread is waiting, one of them chosen arbitrarily.

177
Example 10.8 Producer-Consumer problem.
class Q
{
int n;
boolean valueSet = false;
synchronized int get( )
{
if(!valueSet)
{
try {
wait( );
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
}
System.out.println("Got: " + n);
valueSet = false;
notify( );
return n;
}
synchronized void put(int n)
{
if(valueSet)
{
try{
wait( );
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify( );
}
}
class Producer extends Thread
{
Q q;
Producer(Q obj1)
{
q = obj1;

178
}
public void run( )
{
int i = 0;
while(i <= 5)
{
q.put(i++);
}
}
}
class Consumer extends Thread
{
Q q;
Consumer(Q obj)
{
q = obj;
}
public void run( )
{
while(true)
{
q.get( );
}
}
}
public class PCFixed
{
public static void main(String args[ ])
{
Q q = new Q( );
Producer P1= new Producer(q);
Consumer Q1= new Consumer(q);
Q1.start( );
P1.start( );
System.out.println("Press Control-C to stop.");
}
}
Output: Put: 0
Got: 0
Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
Put: 4

179
Got: 4
Put: 5
Got: 5
The wait( ), notify( ) and notifyAll( ) methods are used for inter thread communication.

10.4.4 Deadlock and System Thread Starvation


Deadlock occurs when threads are waiting for each other forever. This happens when
several threads are suspended until it can gain control of the same object, and each one has a lock
on another resource that they need in order to proceed with processing. Two or more threads wait
for locks in a circular chain such that the locks can never be acquired.
System thread starvation occurs in GUI-based applications and applets, when user
communication and screen updates are handled by a system thread may not get to the running
state often and long enough, so user interactions suffer slowdowns. To prevent the occurrence of
dead situations and system failures in multithreaded environment, suspend( ), resume( ) and
stop( ) methods are used. e.g. Thread.stop( ) is used to stop a thread execution.

10.4.5 Using isAlive( ) and join( ) method


The main thread which starts firstly when the program is started should ideally end
also in the last; thus making sure that all the other child threads have finished their execution,
before the main thread has ended its execution and this made possible normally with the sleep( )
method within main( ) but this not ideal solution. Java provides us with a better solution in
threads by which we can find out whether all other child threads have finished executing before
the main thread and it is done in two ways as mentioned:
(i) We can call the isAlive( ) method which will return the value as true on which it is called else
will give false as its running value.
(ii) Another method is to implement join( ) method, this method will wait until the thread on
which it is called is terminated.

Example 10.9 Using isAlive( ) method.


class MyOwnThread extends Thread
{
private String threadName;
public MyOwnThread(String name)
{
threadName = name;
}
public void run( )
{
for(int i = 0; i < 5; i++)
{
System.out.println("Thread " + threadName + " : " + i);
}
}
}
public class IsAliveExample
{

180
public static void main(String[ ] args)
{
Thread th = new MyOwnThread("A");
th.start( );
// wait till the thread is alive
while(th.isAlive( ));
System.out.println("Thread is not alive any more.");
}
}

Output: Thread A : 0
Thread A : 1
Thread A : 2
Thread A : 3
Thread A : 4
Thread is not alive any more.

Example 10.10 Using join( ) method.


class MyOwnThread extends Thread
{
private String threadName;
public MyOwnThread(String name)
{
threadName = name;
}
public void run( )
{
for (int i = 0; i <= 5; i++)
{
System.out.println("Thread " + threadName + " : " + i);
}
}
}
public class JoinExample
{
public static void main(String[ ] args)
{
Thread th1 = new MyOwnThread("A");
Thread th2 = new MyOwnThread("B");
try {
th1.start( );
th1.join( );
th2.start( );
}
catch (InterruptedException e){}
}

181
}
Output: Thread A : 0
Thread A : 1
Thread A : 2
Thread A : 3

10.4.6 The transient and volatile Modifiers


Java defines two interesting type modifiers: transient and volatile. When an instance
variable is declared as transient, then its value need not persist when an object is stored.

For example:
class T
{
transient int a; // will not persist
int b; // will persist
}
Here, if an object of type T is written to a persistent storage area, the contents of „a‟ would not be
saved, but the contents of „b‟ would.
The volatile modifier tells the compiler that the variable modified by volatile can be
changed unexpectedly by other parts of your program. In a multithreaded program, sometimes,
two or more threads share the same instance variable. For efficiency considerations, each thread
can keep its own, private copy of such a shared variable. The real (or master) copy of the
variable is updated at various times, such as when synchronized method is entered. In some
cases, all that really matters is that the master copy of a variable always reflects its current state.
To ensure this, simply specify the variable as volatile, which tells the compiler that it must
always use the master copy of a volatile.

Example 10.11 Using volatile modifier in multithreaded program.


class X
{
volatile int a;
int b;
public void increase( )
{
a++;
b++;
System.out.println("a = "+a+"\tb = "+b);
}
}
class Process extends Thread
{
X x;
Process(X x)
{
this.x = x;
}

182
public void run( )
{
while(true)
{
try{
Thread.sleep(2000);
}
catch(Exception e){}
x.increase( );
}
}
}
public class VolatileDemo
{
public static void main(String arg[ ])throws Exception
{
X x = new X( );
Thread th = Thread.currentThread( );
th.setPriority(7);
while(true)
{
Process p = new Process(x);
p.start( );
System.out.println("Thread sleep for 1000 millisecond...");
Thread.sleep(1000);
System.out.println("x.a = "+x.a+"\tx.b = "+x.b);
System.out.println("Press ctrl+c to break.....");
}
}
}

Output:
Thread sleep for 1000 millisecond...
x.a = 0 x.b = 0
Press ctrl+c to break.....
Thread sleep for 1000 millisecond...
a=1 b=1
x.a = 1 x.b = 1
Press ctrl+c to break.....
Thread sleep for 1000 millisecond...
a=2 b=2
x.a = 2 x.b = 2
Press ctrl+c to break.....
Thread sleep for 1000 millisecond...
a=3 b=3
a=4 b=4

183
x.a = 4 x.b = 4
Press ctrl+c to break.....
Thread sleep for 1000 millisecond...
a=5 b=5
a=6 b=6
x.a = 6 x.b = 6
Press ctrl+c to break.....
Thread sleep for 1000 millisecond...
a=7 b=7
a=8 b=8
a=9 b=9
x.a = 9 x.b = 9
Press ctrl+c to break.....
Thread sleep for 1000 millisecond...

10.4.7 Difference between multithreading and multitasking

Multithreading Multitasking
- It is a programming concept in which a - It is an operating system concept in
program or a process is divided into two which multiple tasks are performed
or more subprograms or threads that are simultaneously.
executed at the same time in parallel.

- It supports execution of multiple parts - It supports execution of multiple


of a single program simultaneously. programs simultaneously.

- The processor has to switch between - The processor has to switch between
different parts or threads of a program. different programs or process.

- It is highly efficient. - It is less efficient in comparision to


multithreading.
- A thread is the smallest unit in - A program or process is the smallest
multithreading. unit in a multitasking environment.

- It helps in developing efficient - It helps in developing efficient


programs. operating system.

- It is cost-effective in case of context - It is expensive in case of context


switching. switching.

184
Summary

In this chapter we known


- A thread is a program unit that is executed independently of other parts of the
program.
- A thread can be created using Thread class or Runnable interface.
- A thread start using start( ) method and terminate when its run method terminates.
- By calling the lock method, a thread acquires a lock object. Then no other thread
can acquire the lock until the first thread releases the lock.
- A deadlock occurs if no thread can proceed because each thread is waiting for
another to do some work first.
- The wait( ), notify( ), notifyAll( ) methods are used for interthread communication.
- Also we know how isAlive( ) and join( ) methods work in a thread.

185
Review Question
10.1 What is a thread? How to create threads?
10.2 Explain life cycle of thread.
10.3 What is the difference between multitasking and multithreading?
10.4 What is synchronization? Give difference between class based monitor and object based
monitor?
10.5 What is the function of wait( ), notify( ) and notifyAll( ) method in thread class? Give a
example.
10.6 How isAlive( ) and join( ) method work?
10.7 What is the use of volatile modifier in multithreaded program?
10.8 What is deadlock and starvation? Which methods are used to prevent deadlock?
10.9 How to know which thread is currently running?
10.10 What is the difference to create a thread using Thread class or using Runnable interface?
10.11 Can you explain how scheduling and priority works in threads?
10.12 What is the difference between process and thread ?
10.13 Why inter threaded communication is needed ?
10.14 What is deadlock ? Implement the concept of deadlock using a program.
10.15 What are daemon threads?
Answer: Daemon threads are designed run in background. One example of a daemon thread is
the garbage collection thread. You can use setDaemon( ) to mark a thread as daemon.

186
Applets
11.0 INTRODUCTION
Applets are small applications that are accessed on an Internet server, transported
over the Internet, automatically installed, and run as part of a web document. After an applet
arrives on the client, it has limited access to resources, so that it can produce an arbitrary
multimedia user interface and run complex computations without indroducing the risk of viruses
or breaching data integrity. Java has revolutionized the way the Internet users retrieve and use
documents on the world wide network. Java has enabled them to create and use fully interactive
multimedia Web documents. A web page can now contain not only a simple text or a static
image but also a Java applet which, when run, can produce graphics, sounds and moving images.
Java applets therefore have begun to make a significant impact on the World Wide Web.

11.1 APPLET FUNDAMENTAL


You can embed applets into Web pages in two ways: one, you can write your own
applets and embed them into Web pages. Second, you download an applet from a remote
computer system and then embed into a Web page.

11.1.1 Local Applet


An applet developed locally and stored in a local system is known as a local applet.
When a Web page is trying to find a local applet, it does not need to use the Internet and
therefore the local system does not require the Internet connection. It simply searches the
directories in the local system and locates and loads the specified applet as shown in Figure11.1.

Local
applet

Local Computer
Figure 11.1 Loading local applets

11.1.2 Remote Applet


A remote applet is that which is developed by someone else and stored on a remote
computer connected to the Internet. If our system is connected to the Internet, you can
downloaded the remote applet on to our system via at the Internet and run it as shown in Figure
11.2. Inorder to locate and load a remote applet, you must known the applet‟s address on the
Web. This address is known as Uniform Resource Locator(URL) and must be specified in the
applet‟s HTML document as the value of the CODEBASE attribute. For example,

CODEBASE = http://www.ticon.com/applets

187
Internet

Local Computer (Client) Remote Computer (Server)

Remote Applet
Figure 11.2 Loading a Remote applets

11.1.3 How Applets differ from Applications


Although both the applets and stand-alone applications are Java programs, there are
significant differences between them which are
- Applets do not use the main( ) method for initiating the execution of the code.
Applets, when loaded automatically call certain methods of Applet class to start
and execute the applet code.
- Unlike stand-alone applications, applets cannot be run independently. They are run
from inside a Web page using a special feature known as HTML tag.
- Applets cannot read from or write to the files in the local computer.
- Applets cannot run any program from the local computer.
- Applets cannot communicate with other servers on the network.

11.2 CREATING A SIMPLE WEBPAGE


From the previous discussion we conclude that applet is embedded into a web page.
So we have to know how to create a web page. Generally a web page is created by HTML, the
Table 11.1 provides various HTML tags to create a web page.

Tag name Purpose


<HTML>…</HTML> Signifies the beginning and end of a HTML file.
<HEAD>…</HEAD> Creating a web page‟s Head.
<TITLE>…</TITLE> Giving a web page a Title.
<BODY>…</BODY> Creating a web page‟s Body.
<H1>Through <H6> Creating web page Headings.
<B> Creating Bold text.
<I> Creating Italic Text.
<P> Creating Paragraphs.
<IMG> Adding an Image to a web page.
<A> Creating a Hyperlink.
<TABLE> Creating a Table.
<TR> Creating Table Row.
<TH> Creating Table Headings.

188
<TD> Creating a Table caption.
<CAPTION> Creating a Table caption.
<FRAME> Creating Frames.
<FROM> Creating HTML Forms.
<BUTTON> Creating a customizable Button.
Table 11.1 Various HTML tags

- A HTML page must begin with <HTML> and end with </HTML>.
- Every tag must be ended with „/‟ e.g. <Body>…</Body>.
- Open your notepad and design a web page using HTML tags.
- After designing, you must save the file with extension name .html e.g., first.html.

Example 11.1 Creating a Webpage.


First.html
<html>
<head>
<title> MY FIRST WEB PAGE </title>
</head>
<body>
<h1> Welcome to HTML!</h1>
</body>
</html>

HTML is not a case sensitive; you can use lower case or upper case letter. The structure HTML
page is shown is Figure 11.3.

189
<HTML>
<! ………….
Comment section
………… >

<HEAD>
Title Tag
</HEAD>
<BODY>
Applet Tag
</BODY>
</HTML>

Figure 11.3 Structure of HTML page.

11.3 CREATION PROCEDURE OF APPLET PROGRAMS


The following steps are given to create an applet.
Step1: import the required packages in your program like
(i) java.applet.* → This class is required to create applet.
(ii) java.awt.* → This class is required to create different components (button, text-
field, etc) into applet.
(iii) java.awt.event.* → To make the applet event driven.
Step2: Create a class which must inherit(extends) for (i) java.applet.Applet class.
Step3: Override the required methods of the class to provide components to appear and to start
the execution of the applet. Methods available as the life cycle methods of applet are
- init( )
- start( )
- paint( )
- stop( )
- destroy( )
Step4: After compilation of the applet class, create a HTML file which will be shown into the
web browser with the applet. This file must contain the <Applet> tag with height and
width attribute of a applet as:
<applet code = “class name”height= “400”width= “300”>
</applet>

Example 11.2 My first applet program.


MyApplet.java
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
public void init( )
{

190
setBackground(Color.blue);
Label l=new Label("OK it's Execute….");
l.setBackground(Color.white);
add(l);
}
}
Test.html
<html>
<body>
<h5 align="center">THIS IS A WEB-PAGE </h5>
<Applet code = "MyApplet.class" height=200 width=300 >
</Applet>
</body>
</html>
After creation of MyApplet.java and Test.html save both files in the same folder
(say D:\java20\applet), then compile and run the program as:

D:\java20\applet> javac MyApplet.java


D:\java20\applet> appletviewer Test.html

The steps involved in developing and testing in applet are:


(i) Bulding an applet code (.java)
(ii) Creating an executable applet (.class file)
(iii) Designing a web using HTML tags.
(iv) Preparing <Applet> tag.
(v) Incorporating <Applet> tag into the web page.
(vi) Creating .HTML file (.html file).
(vii) Testing the applet code (appletviewer).
The appletviewer is tool to test the applet without using Web server. This supports only
<applet> tag but not any other HTML tag. This can be used by using a command known as
appletviewer in the command prompt.
Suppose in the Example 11.2 MyApplet.java is present in c:drive, pet. folder and your
test.html file present in D:drive then you use CODEBASE in the <applet> tag as:
<Applet code = “MyApplet.class”CODEBASE = “C:\pet” height= “200” width= “300” >
</Applet>

191
Example 11.3 Creating moving banner.
Banner1.java
import java.awt.*;
import java.applet.*;
public class Banner1 extends Applet
{
String str1 = "COMPUTER";
String str2 = "SCIENCE";
int x, y = 80, x1=240;
public void init( )
{
setBackground(Color.white);
setFont(new Font("sanarit",Font.BOLD,20));
}
public void paint(Graphics g)
{
g.drawString(str1,x,80);
g.setColor(Color.black);
g.drawString(str2,x1,80);
g.setColor(Color.black);
x = x + 20;
x1 = x1 - 20;
if(x1 == x )
{
x = 0;
x1 = 240;
}
try{
Thread.sleep(500);
}
catch(Exception e){}
repaint( );
}
}
Test2.html
<html>
<body>
<h5 align="center">THIS IS A WEB-PAGE </h5>
<Applet code = "Banner1.class" height=400 width=300 >
</Applet>
</body>
</html>

D:\java20\applet>javac Banner1.java
D:\java20\applet>appletviewer Test2.html

192
11.4 APPLET LIFE CYCLE
Every Java applet inherits a set of default behaviours from the Applet class. As a result,
when an applet is loaded, it undergoes a series of changes in its state as shown in Figure 11.4.

init( ) start( ) stop( ) destroy( )

paint( )

Figure 11.4 Life cycle of applet

The Applet class consists of five methods which is executed sequentially. The working
principles of these methods are:
- init( ) : This method execute at the time of applet initialization and executes only
once in the life cycle of the applet. This is known as born state of applet.
- start( ) : This method execute the code to activate the applet and it may execute
more than once in the life cycle of the applet. This is known as running state of
applet.
- paint( ) : This execute a block of code to draw or paint different shapes into the
applet. This is known as display state of applet.
- stop( ) : This method deactivate the applet. If the browser containing the applet
will be minimized or back or forward button will be pressed then the applet goes
for deactivation or calls stop( ) method. this is known as idle state of applet.

193
- destroy( ) : This method executes a block of code to make the resources free
which is occupied by the applet. This executes only once in the life cycle of applet.
This is known as dead state of applet.

Example 11.4 Life cycle of applet.


LifeCycle.java
import java.awt.*;
import java.applet.*;
public class LifeCycle extends Applet
{
public void init( )
{
setBackground(Color.green);
System.out.println("init...");
}
public void start( )
{
System.out.println("start...");
}
public void paint(Graphics g)
{
System.out.println("paint...");
}
public void stop( )
{
System.out.println("stop...");
}
public void destroy( )
{
System.out.println("destroy...");
}
}

Test3.html
<html>
<body bgcolor="cyan">
<h1 >Engg. Material</h1>
<applet code="LifeCycle.class" height="800",width="700">
</applet>
</body>
</html>

D:\java20\applet>javac LifeCycle.java
D:\java20\applet>appletviewer Test3.html
init...
start...

194
paint...
stop...
destroy...

The class hierarchy of Applet class is given in the Figure 11.5.


java.lang.Object

java.awt.Component

java.awt.Container

java.awt.Panel

java.awt.Applet

Figure 11.5 Applet class hierarchy

11.5 PASSING PARAMETERS TO APPLETS


You can supply user-defined parameters to an applet using <PARAM> tag in between
<Applet> tags. For example

<Applet code = “MyApplet.class” height = “400” width = “400”>


<Param name = “P1” value = “India”>
</Applet>
The param tag has a name attribute (e.g.color) and a value attributes (e.g. red), the
parameters are passed on an applet when it is loaded. You can define the init( ) method in the
applet to get hold of the parameters defined in the <PARAM> tags. This is done using the
getParameter( ) method, which takes one string argument representing the name of the parameter
and returns a string containing the value of that parameter.
For example, String str = getParameter(“p1”);

Example 11.5 Parameter passing to an applet from html file.

ParameterPass.java

import java.awt.*;
import java.applet.*;
public class ParameterPass extends Applet
{
String str;

195
public void init( )
{
setBackground(Color.white);
setFont(new Font("sanarit",Font.BOLD,20));
str = getParameter("kp");
if(str == null)
str = "No parameter";
str = "World is a - " + str;
}
public void paint(Graphics g)
{
g.drawString(str,5,50);
}
}
Test4.html
<html>
<body>
<h1>This is a web Page</h1>
<Applet code="ParameterPass.class"height="100"width="300">
<param name="kp" value="STAGE">
</Applet>
</body>
</html>
D:\java20\applet>javac ParameterPass.java
D:\java20\applet>appletviewer Test4.html

The various attributes present in <APPLET> tag is given in the table 11.2.

Attribute Purpose
CODE = AppletFilename.class Specifies the name of the applet class to be
loaded. That is, the name of the already
compiled .class file in which the executable Java
byte code for the applet is stored.
CODEBASE = URL Specifies the URL of the directory in which the
applet resides. If the applet resides in the
different directory then CODEBASE is required.
WIDTH = pixels This attributes specifies the width of an applet.

196
HEIGHT = pixels This attributes specifies height of an applet.
NAME This facilitates inter-applet communication.
ALIGN Specifies where on the page the applet will
appear.
Table 11.2 Attributes of <APPLET> tag
11.6 THE GRAPHICS CLASS
Java‟s Graphics class includes methods for drawing many different types of shapes.
To draw a shape on the screen, you may call one of the methods available in the Graphics class.
All the drawing methods have arguments representing end points, corners, or starting location of
a shape as value in the applet‟s coordinate system. To draw a shape, you only need to use the
appropriate method with the required arguments. Table 11.3 shows the most commonly used
drawing methods in the Graphics class.
Method Description
drawArc( ) Draw a hallow arc.
drawstring(“text”,int x, int y) Displays a text string at (x, y).
drawOval(int x, int y, int width, int height) Draws a hallow oval.
drawPolygon(int x[ ], int y[ ], int points) Draws a hollow polygon.
drawRect(int x, int y, int width, int height) Draws a hollow rectangle.
drawRoundRect(int x, int y, int width, Draws a hollow rectangle with rounded
int height,int arc-width,int arc-height) corners.
drawLine(int x1, int y1, int x2, int y2) Draws a straight line.
fillOval(int x, int y, int width, int height) Draws a filled oval.
fillPolygon(int x[ ], int y[ ], int points) Draws a filled polygon.
fillRoundRect(int x, int y, int width, int height, Draws a filled rectangle with rounded
int arc-width,int arc-height) corners.
fillRect(int x, int y, int width, int height) Draws a filled rectangle.
fillArc( ) Draws a filled arc.
setColor(color c) Sets the drawing color.
setFont(Font f) Sets the font.
getColor( ) Retrieves the current drawing color.
getFont( ) Retrieves the currently used font.
clearRect( ) Erases a rectangle area of the covas.
Table 11.3 Drawing Methods of the Graphics class
Example: g.drawRect(20,30,100,50)

width
(0,0)

h
e
i (20,30)
g
h
t

( JAVA Coordinate system)

197
Example 11.6 Create a face.
Face.java
import java.awt.*;
import java.applet.*;
public class Face extends Applet
{
public void paint(Graphics g)
{
g.drawOval(40,40,120,150); //Head
g.drawOval(57,75,30,20); //Left Eye
g.drawOval(110,75,30,20); //Right Eye
g.fillOval(68,81,10,10); //Left Pupil
g.fillOval(121,81,10,10); //Right Pupil
g.drawOval(85,100,30,30); //Nose
g.fillArc(60,125,80,40,180,180); //Mouth
g.drawOval(25,91,15,30); //Left Ear
g.drawOval(160,92,15,30); //Right Ear
}
}
Test5.html
<html>
<body>
<h5 align="center">THIS IS A WEB-PAGE </h5>
<Applet code = "Face.class" height=200 width=300 >
</Applet>
</body>
</html>

D:\java20\applet>javac Face.java
D:\java20\applet>appletviewer test5.html

198
Example 11.7 Creating second banner.
Banner2.java
import java.awt.*;
import java.applet.*;
public class Banner2 extends Applet
{
String str = "WELCOME";
int x, y = 80;
public void init( )
{
setBackground(Color.gray);
setFont(new Font("sanarit",Font.BOLD,20));
}
public void paint(Graphics g)
{
g.setColor(Color.white);
g.drawString(str,x,100);
x=x+10;
if(x > 400)
{
x = 0;
}
try{
Thread.sleep(500);
}
catch(Exception e){}
repaint( );
}
}

Test6.html
<html>
<body>
<h5 align="center">THIS IS A WEB-PAGE </h5>
<Applet code = "Banner2.class" height=200 width=400 >
</Applet>
</body>
</html>

D:\java20\applet>javac Banner2.java
D:\java20\applet>appletviewer test6.html

199
11.7 DISPLAYING NUMERICAL VALUES
You can display numerical values by first converting them into strings and then using
the drawString( ) method of Graphics class. You can do this easily by calling the valueOf( )
method of String class. Example 11.8 illustrates how an applet handles numerical values.

Example 11.8 Displaying numerical values into a applet.


Numvalue.java
import java.applet.*;
import java.awt.*;
public class Numvalue extends Applet
{
public void paint(Graphics g)
{
int x = 10;
int y = 20;
int sum = x+y;
String s = "SUM : " + String.valueOf(sum);
setBackground(Color.gray);
g.setColor(Color.white);
g.drawString(s,100,100);
}
}
Test7.html
<html>
<body>
<h5 align="center">THIS IS A WEB-PAGE </h5>
<Applet code = "Numvalue.class" height=150 width=200 >
</Applet>
</body>
</html>

200
D:\java20\applet>javac Numvalue.java
D:\java20\applet>appletviewer test7.html

Summary
Applets are Java programs developed for use on the Internet. They provide a means to
distribute interesting, dynamic, and interactive applications over the World Wide Web. We have
learned the following about applets in this chapter:
- Types of applet.
- How do applets differ from applications?
- How to design Web page?
- How to design applets and
- How to execute applets.

201
Review Question
11.1 Write applets to draw the following shapes.
(i) Cone
(ii) Cylinder
(iii) Cube
(iv) Square inside a circle
(v) Circle inside a square.
11.2 What is an applet? Explain types of applet?
11.3 How do applets differ from application programs?
11.4 Discuss the lifecycle of applet. Write a Java program to demonstrate the life cycle.
11.5 Discuss the steps involved in loading and running a remote applet.
11.6 Describe the various sections of Web page.
11.7 How many arguments can be passed to anapplet using <PARAM> tags?
11.8 What are the constraints of an applet program ?
11.9 What is the use of CODE and CODEBASE attribute ?
11.10 How can we pass a parameter to an applet ?
11.11 Give an example for passing parameter to an applet ?

202
GUI Basics
12.0 INTRODUCTION
The design of the API for Java GUI programming is an excellent example of how the
object-oriented principle is applied. In the chapter7, we discussed simple GUI examples to
demonstrate OOP. In this chapter that follow, you will learn the framework of Java GUI API and
use the GUI components to develop user friendly interface like Java Beans for application and
applets. Specifically, it discusses GUI components and their relationships, containers and layout
managers, colors, fonts, borders, image icons and tool tips applied on frames.

12.1 AWT (Abstract Window Tool Kit)


The Abstract Window Toolkit (AWT) package in Java enables the programmers to
create GUI-based applications. It contains a number of classes that help to implement common
Windows-based tasks, such as manipulating windows, adding scroll bars, buttons, list items, text
boxes, etc; all the classes are contained in the java.awt packages. These classes are hierarchically
arranged inside the awt package in such a manner that each successive lebel in the hierarchy adds
certain attributes to the GUI application. AWT provides support for both standard and applet
windows. Figure12.1 shows how their corresponding classes are hierchically arranged in the awt
package.

Component

Container

Window Panel

Frame Dialog Applet

(Figure 12.1 AWT Hierachy )

Component:
Component class is the super class to all the other classes from which various GUI
elements are realized. It is primarily responsible for affecting the display of a graphic object on
the screen. It also handles the various keyboard and mouse events of the GUI application.
Container:
As the name suggests, the container object contains the other awt components. It
manages the layout and placement of the various awt components within the container. A
container object can contain other containers objects as well; thus allowing nesting of containers.

203
Window:
The Window object realizes a top-level Window but without any border or menu bar. It
just specifies the lay out of the Window. A typical Window that you would want to create in
your application is not normally derived from the Window but from its subclass, i.e., Frame.
Panel:
The super class of applet, Panel represents a Window space on which the application‟s
output is displayed. It is just like a normal Window having no border, title bar, menu bar, etc. a
panel can contain within itself other panels as well.
Frame:
The Frame object realizes a top-level Window complete with border and menu bar. It
supports common Window-related events such as close, open, active, deactivate etc.

12.2 AWT Classes


Now let‟s know how the various classes can be implemented in java to create GUI
applications.

12.2.1 Frame
This is a Java application which creates GUI to execute as a stand-alone application.
Unlike applet this does not execute in Web browsers. This contains main method to start
execution.
Creation Procedure:
(i) Create the subclass of java.awt.Frame and provide the constructor which may initiate the
components to appear with the frame.
(ii) If required to draw shapes into Frame then provide paint( ) method.
(iii) Provide main( ) method which must initialise the class (subclass of Frame) and specify
size and visibility property.
(iv) Before adding any component into the frame change the layout of the frame using
setLayout( ) method.

Example 12.1 Creating a Frame program.


import java.awt.*;
public class MyFrame extends Frame
{
MyFrame( )
{
setBackground(Color.gray);
Button b1=new Button("Submit");
setLayout(new FlowLayout( ));
add(b1);
}
public static void main(String arg[ ])
{
System.out.println(“Press ctrl+c to close MyFrame”);
MyFrame mf=new MyFrame( );
mf.setSize(200,400);
mf.setVisible(true);

204
}
}
D:\java20\awt>javac MyFrame.java
D:\java20\awt>java MyFrame

12.2.2 Layout Managers


Layout Managers specifies how components are arranged in a container. Layout
manager are set in the container using the setLayout(LayoutManager) method. Three basic
layout managers:
(i) FlowLayout
(ii) GridLayout
(iii) BorderLayout
FlowLayout:
In the FlowLayout manager the components are arranged in the container from left to
right in the order in which they are added. When a row is filled, a new row is started. You can
specify the way the components are aligned by using one of the three constants.
FlowLayout.RIGHT
FlowLayout.CENTER
FlowLayout.LEFT
Example:
FlowLayout l = new FlowLayout(FlowLayout.LEFT, 10,20)
setLayout(l);
or
setLayout(new FlowLayout(FlowLayout.LEFT, 10,20));
The constructors of FlowLayout manager are
FlowLayout( ) : Creates a default FlowLayout manager.
FlowLayout(int alignment) : Creates a FlowLayout manager with a specified alignment.
FlowLayout(int alignment, int hgap, int vgap) : Creates a FlowLayout manager with a
specified alignment, horizontal gap, and vertical gap.

GridLayout:
The GridLayout manager arranges components in a grid(matrix) formation with the
number of rows and columns defined by the constructor. The components are placed in the grid
from left to right, with the first row then second and so on, in the order in which they are added.
The constructors available for GridLayout manager are:
205
GridLayout( ) : Creates a default GridLayout manager.
GridLayout(int rows, int columns) : Creates a GridLayout with a specified number of rows
and columns.
GridLayout(int rows, int columns, int hgap, int vgap) : Creates a GridLayout manager with a
specified number of rows and columns, horizontal gap and vertical gap.
Example:
setLayout(new GridLayout(3,2,5,5));
It sets GridLayout, 3 rows, 2 columns and gaps 5 between components horizontally and
vertically. The Figure 12.2(a) and Figure 12.2(b) shows the GridBagLayout manager.

0 1 2 3

0 Label 0

Text
1 1
Text Area 2
Area JPanel
Text
1
2 Field 2

3 Button 1 Button 2 3

0 1 2 3

Figure 12.2(a) A GridBagLayout manager divides Figure 12.2(b)The components are


the container into cells. placed in the frame of GridBagLayout.

BorderLayout:
The BorderLayout manager divides the Window into five areas: East, South, West,
North and Center. The North and South components can stretch
horizontally. NORTH
The East and West components can stretch vertically. Components are
added to a BorderLayout by using - add(component, index);
Where index is a constant as
BorderLayout.EAST, BorderLayout.SOUTH WEST EAST
The constructors available for BorderLayout manager are:
BorderLayout( ) : Creates a default BorderLayout manager.
BorderLayout(int hgap, int vgap) : Creates a BorderLayout manager SOUTH
with a specified number of horizontal gap and vertical gap.
Example: setLayout(new BorderLayout(5,10));
Button b1 = new Button( );
add(b1, BorderLayout.EAST);

12.2.3 AWT Components


There are so many components are present in the awt package. These are Label,
Button, TextField, TextArea, MenuItem, CheckBox.

12.2.3.1 Label
A label component used to make appear single line text. The constructors and
methods available in Label class are

206
Constructor
- Label( )
- Label(String text)
Methods
- void setText(String text) : To change the text of a Label.
- String getText( ) : To fetch the text available to the label.
- void addMouseListener(MouseListener ms) : To register the Label with
MouseListener.
- void setFont(Font f) : To change the font of the label.
- void setBackground(Color c) : To change the background color of the label.

12.2.3.2 Button
A push button is used to display a caption over it. The constructors and methods
available in Button class are given as:
Constructor
- Button( )
- Button(String caption)
Methods
- void setLabel(String caption) : To change the caption of the Button.
- String getLabel( ) : To fetch the label of the Button.
- void setActioncommand(String command) : To assign a string as a action command to
identify the button uniquely at the time of event handling.
- void addActionListener(ActionListener) : To register the button with ActionListners.
- Void addMouseListener(mouseListener me) : To register the button with the
MouseListener.
Example: Button b1 = new Button(“click me”);
b1.setFont(new Font(“courian”,Font.BOLD,20));
b1.setBackground(Color.yellow);
setLayout(new FlowLayout( ));
add(b1);

12.2.3.3 TextField
A single line text box which can accept input as text or string type from the user.
The constructors and methods available in TextField class are given as:
Constructor
- TextField( )
- TextField(int column-size)
Methods
- void setText(String text) : To replace the text available in the text field.
- void getText( ) : To fetch a text available in the text field.
- void append(String text) : To add the text into the field‟s available data.
- void addTextListener(TextListener( )) : To add the TextListener to the text field.
Example: TextField tf = new TextField(30);
tf.setText(“Hello”);
tf.setFont(new Font(“courian”,Font.BOLD,20));

207
Example 12.2 Creating a Frame with a Button and TextField.
import java.awt.*;
public class MyFrame2 extends Frame
{
MyFrame2( )
{
setBackground(Color.gray);
Button b1=new Button("OK");
TextField tf=new TextField(30);
tf.setText("Hello HOW ARE U SIR?");
tf.setFont(new Font("courian",Font.ITALIC,20));
b1.setFont(new Font("courian",Font.BOLD,20));
b1.setBackground(Color.LIGHT_GRAY);
setLayout(new FlowLayout( ));
add(tf);
add(b1);
}
public static void main(String arg[ ])
{
System.out.println("Press ctrl+c for close MyFrame2");
MyFrame2 mf=new MyFrame2( );
mf.setSize(400,200);
mf.setVisible(true);
}
}
D:\java20\awt>javac MyFrame2.java
D:\java20\awt>java MyFrame2

Text Field

Button

12.2.3.4 CheckBox
CheckBox is used to take multiple predefined inputs from the user. The constructors
available for CheckBox are
- Checkbox( )
- Checkbox(String label, boolean state)
- Checkbox(String label)

208
- Checkbox(String label, CheckboxGroup ch, boolean state: To form a radio button.
Example: Checkbox ch1 = new Checkbox(“J2SE”);
Checkbox ch2 = new Checkbox(“J2SE”);
Checkbox ch3 = new Checkbox(“J2ME”);
add(ch1);
add(ch2);
add(ch3);

Radio Button:
Radio button is used to select one value from a group of predefined values.
Example: CheckboxGroup c = new CheckboxGroup( );
Checkbox m = new Checkbox(“male”, c, false);
Checkbox f = new Checkbox(“female”, c, true);

12.2.3.5 ComboBox
It is used to select one item from the list. The available constructors and methods
are:
Constructors:
- Choice( )
- Choice(String item[ ])
Methods:
- void add(String item) : To add an item to the combo box.
- String getSelectedItem( ) : To get the selected item of the combo box.
- int getSelectedIndex( ) : To get the item selected in index wise of combo box.
- void selected(int index) : To select an item by using it‟s index.
- void replace(int index, String new-item) : To replace an item by using the index.
Example: Choice ch = new Choice( );
ch.add(“Hydrabad”);
ch.add(“Chenni”);
ch.add(“Bhubaneswar”);
ch.add(“Delhi”);
add(ch);

12.2.3.6 List
The listbox is used to display a list of item where more than one item can be visible
at a time. The available constructors and methods are
Constructors:
- List( )
- List(String items[ ])
Methods:
- void add(String item) : To add an item to the list.
- String getSelectedItem( ) : To get the selected item of the list.
- int getSelectedIndex( ) : To get the item selected in index wise of list.
- void selected(int index) : To select an item by using its index.
- void replace(int index, String new_String) : To replace an item by using the index.

209
Example: List l1 = new List(3);
l1.add(“Kolkota”);
l1.add(“Mumbai”);
l1.add(“Chennai”);
l1.add(“Delhi”);
l1.add(“Hydrabad”);
add(l1);

Example 12.3 Creating a list in a Frame.


import java.awt.*;
public class MyFrame3 extends Frame
{
MyFrame3( )
{
String str[ ] = {"Kolkota","Hydrabad","Bhubaneswar","Delhi","Pune"};
List l1 = new List(3);
setLayout(new FlowLayout( ));
for(int k = 0; k < str.length; k++)
l1.add(str[k]);
add(l1);
}
public static void main(String arg[ ])
{
System.out.println("Press ctrl+c to close the MyFrame3....");
MyFrame3 mf3 = new MyFrame3( );
mf3.setSize(400,200);
mf3.setVisible(true);
}
}
D:\java20\awt>javac MyFrame3.java
D:\java20\awt>java MyFrame3

210
12.2.3.7 MenuBar
It is used to represent menu and represent menubar of the Window.
Constructor:
- MenuBar( )
Method:
- void add(Menu) : To add a menu to the menubar.
Menu: To represent each indivisual menu of the menubar.
Constructors:
- Menu( )
- Menu(String Label)
Methods:
- void add(MenuItem mi) : To add a menu item inside menu.
- void addSeparator( ) : To add a line between items.
MenuItem: To represent each item of the menu. The constructors and methods available for
MenuItem class are;
Constructors:
- MenuItem( )
- MenuItem(String item)
- MenuItem(String item, MenuShortcut sck)
Methods:
- void setShortcut(MenuShortcut ms) : To give a shortcut key to the menu item.
- void setLabel(String label) : To set a label to menu item.
- void addActionListener(ActionListener al) : To add action listener to menu.

Example 12.4 Creating Menu based program.


import java.awt.event.*;
import java.awt.*;
public class MenuFarme extends Frame
{
MenuFarme( )
{
MenuBar mb=new MenuBar( );
setMenuBar(mb);
setLayout(new FlowLayout( ));
Menu f=new Menu("FILE");
Menu e=new Menu("EDIT");
mb.add(f);
mb.add(e);

MenuItem mi1=new MenuItem("Open");


MenuItem mi2=new MenuItem("Exit");
MenuItem mi3=new MenuItem("Copy");
MenuItem mi4=new MenuItem("Paste");
f.add(mi1);
f.addSeparator( );
f.add(mi2);

211
e.add(mi3);
e.add(mi4);
Label l1=new Label("A menu based frame");
add(l1);
}
public static void main(String arg[ ])
{
System.out.println("Press ctrl+c to close MenuFarme");
MenuFarme mf=new MenuFarme( );
mf.setSize(400,200);
mf.setVisible(true);
}
}

D:\java20\awt>javac MenuFarme.java
D:\java20\awt>java MenuFarme
Press ctrl+c to close MenuFarme

12.3 INTRDUCTION TO SWING


When Java was introduced, the GUI classes are bundled in a library known as AWT.
For every platform on which Java runs, the AWT components are automatically mapped to the
platform-specific components through their respective agents, known as peers. AWT is fine for
developing simple graphical user interface, but not for developing comprehensive GUI projects.
In Java, the AWT user interface components were placed in a flexible library known as swing
components. Swing components are less dependent on the target platform and don‟t rely on
native GUI are reffered to as light weight because it is fully implemented in Java, without calling
the native operating system for drawing the graphical user interface components. On the other
hand, AWT is heavy weight toolkit, as it merely makes calls to the operating system in order to
produce its GUI components. As you know API (Application Programming Interface) is the
definition of how a programmer can access the functionality contained within a code library.
Swing‟s API provides to access to the graphical components in swing.
The GUI classes for swing can be classified into three groups.
- Container Classes(JFrame, JApplet, Jpanel) :
Container class are used to contain other components.
- Component classes(JButton, JTextField, JTextArea, JComboBox, JList,
JRadioButton, JMenu ) :
Component classes are subclasses of JComponent.

212
- Helper classes(Graphics, Color, Font, FontMatrices, Dimension) :
Helper classes are used to support GUI components.
 The JFrame, JApplet, JDialog and JComponent classes and their subclasses are grouped in the
javax.swing package.
Java Foundation Classes (JFS)
Java Foundation Class is an extened version of AWT released in the year 1997. It
provides a rich set of class libraries.Main properties of JFS:
- We can create GUI component (Swing, Drag and Drop, Accessiblity, 2D Graphics).
- The components are cross platform independent.
Swing provides a Model-view-controller (MVC) architecture. The MVC based
architecture allows swing components to be replaced with several data models and views.

12.3.1 Container Classes


The Container classes contain the following subclasses:
javax.awt.Container : It is used to group components. Frames, Panels and Applets
are its subclasses.
javax.swing.JFrame : It is a Window not contained inside another Window. It is
the container that holds other swing user interface
components in Java GUI applications.
javax.swing.JPanel : It is an invisible container that holds user interface
components. Panels can be nested, you can place panels
inside a container that holds a panel.
javax.swing.JDialog : It is a popup Window or message box generally used as a
temporary window to receive additional information from
the user or to provide notification that an event has occurred.
javax.swing.JApplet : It is a subclass of Applet. You must extend JApplet to create
a swing based java applet.

Top level Container: JFrame, JApplet, JDialog


General purpose Container: JPanel

12.3.2 GUI Helper Classes


The Helper classes consists of the following classes:
java.awt.Graphics : For drawing Strings, lines, simple shapes etc.
java.awt.Color : Deals with the color of GUI components.
java.awt.Font : Specifies fonts for the text.
java.awt.LayoutManager : To manages components for container class.

12.3.3 LookAndFeel class


This is the class that is passed into UIManager.setLookAndFeel( ) method. This class
is the center of your look and feel. It contains the UIDefaults class like JComponents, list of the
colors, icons etc.

12.4 JApplet
The JApplet class can be used to create an applet.
package : javax.swing

213
class : javax.swing.JApplet
The available constructors and methods for JApplet class are given below
Constructor : public JApplet( ) to crate a blank JApplet instance.
Methods:
- Container getContentPane( ) : Returns the ContentPane object for this applet.
- int getHeight( ) : Returns the vertical size of applet.
- int getWidth( ) : Returns the Horizontal size of applet.
- void paint(Graphics g) : The point method is called every time the applet is to be
redrawn.
- void start( ) : The start method is called when the Web page or appletviewer is
redisplayed.
- void setBackground(Color Bgcolor) : Sets the background color of the text for the
applet argument (say Bgcolor).
- Void setForeground(Color Fgcolor) : Sets the foreground color of the Applet.

Example 12.5 Creating JApplet.


SMyApplet.java
import java.applet.*;
import java.awt.*;
public class SMyApplet extends Applet
{
public void init( )
{
setBackground(Color.LIGHT_GRAY);
Label l=new Label("OK it's Execute");
l.setBackground(Color.white);
add(l);
}
}
ST.html
<html>
<body>
<h5 align="center">THIS IS A WEB-PAGE </h5>
<Applet code = "SMyApplet.class" height=200 width=300 >
</Applet>
</body>
</html>
D:\java20\awt>javac SMyApplet.java
D:\java20\awt>appletviewer ST.html

214
12.5 JFrame
A JFrame is a top-level window with a title and a border. It is normally used as the
main window of a standlone application.
Package: javax.swing
Class : javax.swing.JFrame
The available constructors and methods for JFrame class are
Constructors:
- JFrame( ) : Creates default frame.
- JFrame(String text) : Creates a frame instance with the specified text in the title
bar.
Methods:
- void addWindowListener(WindowListener Handler) : Configure a window event
handler for the frame.
- Container getContentPane( ) : Returns the ContentPane object for this frame.
- void setBackground(Color bg) : Sets the background color of the frame.
- void setFont(Font TextFont) : Sets the font for this component.
- void setForeground(Color TextColor) : Sets color of the text of the frame.
- void setSize(int Width, int Height) : Resides the window.
- void setTitle(String Text) : Sets the texty for the title bar.
- void show( ) : Makes the window visible.

12.6 JPanel
JPanel is a generic light weight container. With Java GUI programming, you can divide
a window into panels. Panels acts as sub-containers to group to Panels, then Panels are added to
Frame. JPanel is a subclass of JComponent. So all the other swing components except top-level
container you can add a border and a tool-tip.
Example: JFrame f = new JFrame( );
JPanel p = new JPanel( );
p.add(new JButton(“ok”));
p.setToolTipText(“I am a JPanel”);
p.setBorder(BorderFactory.createLineBorder(Color red));
f.add(p);

215
12.6.1 JSplitPane
The JSplitPane divide the panel into multiple sub-panels.
Example: JSplitPane p = new JSplitPane( );
p.setOpaque(true);
p.setDividerLocation(150);
JPanel right = new JPanel( );
right.setBackground(color.gray);
JPanel left = new JPanel( );
left.setBackground(Color.black);
p.setRightComponent(right);
p.setLeftComponent(left);

12.6.2 JScrollPane
The JScrollPane gives the option to scroll the panel horizontally and vertically.
Example: JTextArea tf = new JTextArea(5,20);
JScrollPane p = new JScrollPane(tf);
frame.setContentPane(p);

12.6.3 TabbedPane
A TabbedPane displays a component from a group of components when one of
Pane‟s tabs is selected. It is a space saving component.

Example 12.6 A demo program TabbedPane.


import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class TabbedPane extends JFrame
{
public TabbedPane( )
{
setTitle("Tabbed Pane");
JTabbedPane jtp = new JTabbedPane( );
getContentPane( ).add(jtp);
JPanel jp1 = new JPanel( );
JPanel jp2 = new JPanel( );
JLabel label1 = new JLabel( );
label1.setText("PANEL-1");
JLabel label2 = new JLabel( );
label2.setText("PANEL-2");
jp1.add(label1);
jp2.add(label2);
jtp.addTab("Tab1", jp1);
jtp.addTab("Tab2", jp2);
}
public static void main(String[ ] args)

216
{
TabbedPane tp = new TabbedPane( );
tp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tp.setVisible(true);
tp.setSize(400,200);
}
}
D:\java20\awt>javac TabbedPane.java
D:\java20\awt>java TabbedPane

12.7 JTree
The JTree is a special type of graph that designed for displaying data with the
hierarchical properties by adding nodes to nodes and keeps the concept of parent and child node.

Example 12.7 A demo program to Tree class.


import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
public class treeDemo extends JFrame implements TreeSelectionListener
{
public static void main(String[ ] args)
{
new treeDemo( );
}
private JTree tree;
private JTextField currentSelectionField;
public treeDemo( )
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = getContentPane( );
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode child;
DefaultMutableTreeNode grandChild;
for(int i=1; i<4; i++)
{

217
child = new DefaultMutableTreeNode("Child " + i);
root.add(child);
for(int j=1; j<4; j++)
{
grandChild = new DefaultMutableTreeNode("Grandchild " + i + "." + j);
child.add(grandChild);
}
}
tree = new JTree(root);
tree.addTreeSelectionListener(this);
content.add(new JScrollPane(tree), BorderLayout.CENTER);
currentSelectionField = new JTextField("Current Selection: NONE");
content.add(currentSelectionField, BorderLayout.SOUTH);
setSize(250, 275);
setVisible(true);
}
public void valueChanged(TreeSelectionEvent event)
{
currentSelectionField.setText("Current Selection: " +
tree.getLastSelectedPathComponent( ).toString( ));
}
}

12.8 JTable
Swing component that allows the user to store, show and edit data in tabular format.

Example 12.8 Creating a table and inserting values in various position.


import javax.swing.*;
import javax.swing.table.*;
public class TableDemo
{
public static void main(String[ ] args)
{
new TableDemo( );
}
public TableDemo( )
{
JFrame frame = new JFrame("Inserting rows in the table!");

218
JPanel panel = new JPanel();
String data[ ][ ] = {{"Vinod","100"},{"Raju","200"},{"Monali","300"}};
String col[ ] = {"Name","code"};
DefaultTableModel model = new DefaultTableModel(data,col);
JTable table = new JTable(model);
//Insert first position
model.insertRow(0,new Object[ ]{"Moti","50"});
//Insert 4 position
model.insertRow(3,new Object[ ]{"Amar","600"});
//Insert last position
model.insertRow(table.getRowCount( ),new Object[ ]{"Sasmita","600"});
panel.add(table);
frame.add(panel);
frame.setSize(300,150);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
D:\java20\awt>javac TableDemo.java
D:\java20\awt>java TableDemo

12.9 JImage
It is used to display an image into the component.
Example: ImageIcon i1 = new ImageIcon(“C:/ Image.gif);
JLabel l = new JLabel(i1);
JButton b1 = new JButton(i1);

Example 12.9 Creating a JFrame with image icon.

import javax.swing.*;
import java.awt.*;
public class TestImageIcon extends JFrame
{
ImageIcon i1 = new ImageIcon("D://java20/awt/india.gif");
ImageIcon i2 = new ImageIcon("D://java20/awt/france.gif");
ImageIcon i3 = new ImageIcon("D://java20/awt/germany.gif");
TestImageIcon( )

219
{
setLayout(new GridLayout(1,3,5,5));
add(new JLabel(i1));
add(new JLabel(i2));
add(new JLabel(i3));
}
public static void main(String arg[ ])
{
TestImageIcon frame = new TestImageIcon( );
frame.setTitle("TESTimageICON");
frame.setSize(450,150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //to close the frame
frame.setVisible(true);
}
}

D:\java20\awt>javac TestImageIcon.java
D:\java20\awt>java TestImageIcon

Example 12.10 A demo program to swing component.


import java.awt.*;
import javax.swing.*;
public class Controls extends JFrame
{
private JButton DemoButton;
private JCheckBox DemoCheckBox;
private JComboBox DemoComboBox;
private JLabel DemoLabel;
private JList DemoList;
private JPasswordField DemoPassword;
private JRadioButton DemoRadioButton;
private JScrollBar DemoScrollbar;
private JSlider DemoSlider;
private JTextArea DemoTextArea;
private JTextField DemoTextField;
private LayoutManager Layout;

220
public Controls ( )
{
Container Panel;
String [ ] ListData;
DemoButton = new JButton( );
DemoCheckBox = new JCheckBox( );
DemoComboBox = new JComboBox( );
DemoLabel = new JLabel( );
DemoList = new JList( );
DemoPassword = new JPasswordField( );
DemoRadioButton = new JRadioButton( );
DemoScrollbar = new JScrollBar( );
DemoSlider = new JSlider( );
DemoTextArea = new JTextArea (3, 15);
DemoTextField = new JTextField( );
Layout = new FlowLayout ( );
ListData = new String [2];

Panel = getContentPane( );
Panel.setLayout (Layout);
Panel.setBackground (Color.LIGHT_GRAY);

ListData [0] = "JList";


ListData [1] = "Selection";

Panel.add (DemoLabel);
Panel.add (DemoButton);
Panel.add (DemoRadioButton);
Panel.add (DemoCheckBox);
Panel.add (DemoTextField);
Panel.add (DemoPassword);
Panel.add (DemoTextArea);
Panel.add (DemoComboBox);
Panel.add (DemoList);
Panel.add (DemoSlider);
Panel.add (DemoScrollbar);

DemoLabel.setText ("JLabel");
DemoButton.setText ("JButton");
DemoCheckBox.setText ("JCheckbox");
DemoComboBox.addItem ("JComboBox");
DemoComboBox.addItem ("Selection");
DemoList.setListData (ListData);
DemoPassword.setText ("JPasswordField");
DemoRadioButton.setText ("JRadioButton");

221
DemoTextArea.setText ("JTextArea");
DemoTextField.setText ("JTextField");
}
public static void main(String[ ] args)
{
Controls tp = new Controls( );
tp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tp.setVisible(true);
tp.setSize(500,200);
}
}
D:\java20\awt>javac Controls.java
D:\java20\awt>java Controls

Summary

In this chapter we know the following


- Every container has a layout manager that is used to position and place
components in the container in the desired location.
- The difference between AWT and Swing.
- Every Swing GUI component is a subclass of javax.swing.JComponent, and
JComponent is a subclass of java.awt.Component. The properties font,
background, forgound, height, width, and preferredSize in component are inherited
in these subclasses, as are toolTipText and border in JComponent.
- We can use borders on way Swing components. We can create an image icon
using the ImageIcon class and display it in a label and a button. Icons and borders
can be shared.
- The syntax to create a Color object is Color c = new Color(r, g, b) in which r, g
and b specify a color by its red, green, and blue components. Alternatively, you
can use or the 13 standard colors(BLACK, BLUE, CYAN, DARK_GRAY,
GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE,
YELLOW) defined as constants in java.awt.Color.

222
Review Question
12.1 Which class is the root of the Java GUI component classes?
12.2 Why do you need to use layout managers?
12.3 What is the difference between AWT and Swing?
12.4 Create Frame having following components which are
1. label (User name)
2. textfield
3. label (password)
4. password textfield
5. button(caption login)
As shown in FigureQ12.4.
FigureQ12.4

12.5 Create a Frame which contains 15 buttons having captions (0,1,2,3,4,5,6,7,8,9,+,-,*, /,=) and
a text area.
12.6 Draw a car using Graphics class on a Frame.
12.7 What is JFC ?
12.8 What are components of JFC ?
12.9 Write a swing program having textboxes for entering name and roll of students.
12.10 Write a program to create an user interface that accepts the details of students.

223
Event Handling
13.0 INTRODUCTION
To make a graphical user interface functional in a Java program, you must make the
interface receptive to user events. In the applications that you have written so far, user input was
under control of the program. The program asked the user for input in a specific order. For
example, a program might ask the user to supply first a name, then a amount. But the programs
that you use every day on your computer don‟t work like that. In a program with a modern
graphical user interface, the user is in control. The user can use both the mouse and the keyboard
and can manipulate many parts of the user interface in any desired order. For example, the user
can enter information into text fields, pull down menus, click buttons, and drag scroll bars in any
order. The program must react to the user commands, in whatever order they arrive. To deal with
many possible inputs in a random order is quite a bit harder than simply forcing the user to
supply input in a fixed order. In this chapter you will learn how to write Java programs that can
react to user interface events, such as button pushes and mouse clicks. The Java window toolkit
has a very sophisticated mechanism that allows a program to specify the events in which it is
interested and which objects to notify when one of these events occurs.

13.1 THE EVENT MODEL


The morden approach to handling events is based on Events, Event Sources and Event Listeners.
Events: An event is an object that describes a state change in a source. When ever change
in the state to a GUI happens on interaction of the user then it is known as event. In a Java
program each type of event can be represented.
Event Source: A source is an object that generates an event. This occurs when the internal state
of that object changes in some way. A source must register listeners in order for the listeners to
receive notifications about a specific type of event. Each type of event has its own registration
method. Here is the general form:
- public void addTypeListener(TypeListener d)
Example: addKeyListener( ), addMouseMotionListener( )

According to event source the event can be classified into two type.
Multicasting Event:
When an event occurs, all registered Listeners are notified and receive a copy of the
event object. This is known as multicasting the event; in all cases notifications are sent only to
listeners that register to receive them.
Unicasting Event:
Some sources may allow only one Listener to register. The general form of such a
method is this:
- public void addTypeListener(TypeListener d) throwsj ava.util.TooManyListenersException
Here, Type is the name of the event and d is a reference to the event listener. When such an event
occurs, the registered listener is notified. This is known as unicasting the event.
A source must also provide a method that allows a listener to unregister an interest in
a specific type of event. the general form of such a method is this:
- public void removeTypeListener(TypeListener d)
Example: removeKeyListener( )

224
Event Listeners: A Listener is an object that is notified when an event occurs. It has two major
requirements. First, it must have been registered with one or more sources to receive
notifications about specific type of events. Second, it must implement methods to receive and
process these notifications. The methods that receive and process events are defined in a set of
interfaces found in java .awt.event .
calls
Event EventListeners
 The mechanism to provide code or execution at the time of event occurance is known as event
handling. In a Java program event is known as source and the code for handling the event is
known as Listener. The source is predefined class and Listeners are predefined interfaces.
13.2 EVENT CLASSES
At the root of the Java event class hierarchy is EventObject, which is in java.util.
EventObject is a superclass for all events. Its one constructor is shown here:
- EventObject(Object src)
Here, src is the object that generates this event.
EventObject contains two methods: getSource( ) and toString( ) .The getSource( )
method returns the source of the event. its general form is
- Object getSource( )
The toString( ) method returns the string equivalent of the event.
The class AWTEvent is subclass of EventObject class which is defined java.awt
package. Its getID( ) method can be used to determine the type of the event, the signature of this
method is int getID( ).
The package java.awt.event defines several types of events that are generated by
various user interface elements. Table 13.1 enumerates the most important of these event classes
and provides a brief description of when they are generated.
Event Class Description Listener/Interface
Executed
ActionEvent Generates when a button or menu item will be ActionListener
clicked.
ItemEvent When a checkbox/choce/list will be selected/ ItemListener
unselected.
AdjustmentEvent When a scrollbar scrolls AdjustmentListener
TextEvent When a text field/textarea will changed its TextListener
text.
MouseEvent When mouse moves/clicks on a component. MouseListener or
MouseMotionListener
KeyEvent When the key will be pressed/ released/ typed KeyListener
on any component.
ComponentEvent When a component will be shown/ hidden/ ComponentListener
released.
ContainerEvent When a component will be added/removed ContainerListener
from the container.
FocusEvent When the components gets/loses focus. Focus Listener
WindowEvent When the frame will opened/ closed/ WindowListener
minimized/ restored
Table 13.1 Event classes in java.awt.event

225
13.3 PROCESS OF EVENT HANDLING
The following steps are followed to implement event handling into your program.
(i) Create the required GUI (Frame, Applet) with the required component.
(ii) Depending upon the type of event generated by the component implement the corresponding
Listener interface to create a class.
(iii) Override all the methods available to the Listener interface and provide implementation
logic i.e; the code to execute at the time of event occurance.
(iv) Register the component which will generate event with the Listen by using addXXX( )
method (XXX is the appropriate Listener)

Example: Button b1 = new Button(“ok”);


b1.addActionListener(MyListener);
Here MyListener is the class which inherit from ActionListener which calls
actionPerformed( ) method.

Example 13.1 (a) Applet is in action.

AppletAction.java
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class AppletAction extends Applet implements ActionListener
{
public void init( )
{
setBackground(Color.LIGHT_GRAY);
setFont(new Font("sansarif",Font.BOLD,25));
Button b1=new Button("Change");
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
setBackground(Color.black);
}
}

testApplet.html
<html>
<body bgcolor="cyan">
<h1 align="center">Web Page Running</h1>
<applet code="AppletAction.class" height="100",width="200"
name="applet1">
</applet>
</body>
</html>

226
D:\java20\eventhandling>javac AppletAction.java
D:\java20\eventhandling>appletviewer testApplet.html

Before pressing button (Change) the After pressing button (Change) the
color of applet (AppletAction) is color of applet (AppletAction) is
LIGHT_GRAY Black
Example 13.1 ( b) Frame is in action.
import java.awt.*;
import java.awt.event.*;
public class MyframeAction extends Frame implements ActionListener
{
MyframeAction( )
{
setBackground(Color.gray);
Button b1=new Button("Change");
b1.addActionListener(this);
setLayout(new FlowLayout( ));
add(b1);
}
public void actionPerformed(ActionEvent ae)
{
setBackground(Color.black);
}
public static void main(String arg[ ])
{
MyframeAction mf=new MyframeAction();
mf.setSize(200,100);
mf.setVisible(true);
}
}

D:\java20\eventhandling>javac MyframeAction.java
D:\java20\eventhandling>java MyframeAction

227
. When button (Change) is pressed
Frame when created its color is Gray
.
its Color changed to black

13.4 METHODS OF LISTENER CLASS


Before you procede more to event handling, you must know various Listener
interfaces and its methods. The Table13.2 provides various Listener interfaces and method
descriptions.
Listener Method Description
ActionListener actionPerformed(ActionEvent ae) When a button/menu item is
clicked.
ItemListener itemStateChanged(ItemEvent ic) When a checkbox/
radiobutton / child list will
be selected.
AdjustmentListener adjustmentValueChanged When the scroll bar scrolls.
(AdjustmentEvent ac)
TextListener textValueChanged(TextEvent te) When the textfield/ textarea
changes its text.
(i) mousePressed(MouseEvent me) When the mouse will be
pressed on any component.
(ii) mouseReleased(MouseEvent me) When the mouse will be
released from any
component.
MouseListener (iii) mouseClicked(MouseEvent me) When the mouse pointer
clicked from any
component.
(iv) mouseEntered(MouseEvent me) When the mouse pointer
enters into a component.
(v) mouseExited(MouseEvent me) When the mouse pointer
goes out of the component.
(i) MouseMoved(MouseEvent me) When the mouse moves on
MouseMotionListener a component.
(ii) MouseDragged(MouseEvent me) When the mouse drags on a
component.
(i)keyPressed(KeyEvent ke) When key will be pressed
on the component.

KeyListener (ii) keyReleased(KeyEvent ke) When the key will be


released after the press on a
component.
(iii) keyTyped(KeyEvent ke) When the key will be typed
on a component.

228
(i) windowOpened(WindowEvent we) When the frame will be
shown.
(ii) windowActivated(WindowEvent we) When the frame activated
or ready to use.
(iii) windowIconified(WindowEvent we) When the frame will be
restored.
WindowListener (iv) windowDeactivated(WindowEvent we) When the frame will be
deactivated before closing.
(v) windowClosing(WindowEvent we) When the frame will on the
operation closing or „x‟
button will click.
(vi) windowClosed(WindowEvent we) When the window is
already disposed or
destroyed.
Table 13.2 Various Listener interfaces and its methods

Example 13.2 (a) Write a program to close a frame using WindowListener.


import java.awt.*;
import java.awt.event.*;
public class FrameClose extends Frame implements WindowListener
{
FrameClose( )
{
setBackground(Color.red);
setSize(200,200);
setVisible(true);
addWindowListener(this);
}
public void windowClosing( )
{
System.exit(0); //this.dispose( );
}
public void windowOpened(WindowEvent we){}
public void windowActivated(WindowEvent we){}
public void windowIconified(WindowEvent we){}
public void windowDeiconified(WindowEvent we){}
public void windowDeactivated(WindowEvent we){}
public void windowClosed(WindowEvent we){}
public static void main(String arg[ ])
{
FrameClose mc = new FrameClose( );
}
}

229
13.4.1 Adapter Class
This is a type of class which inherits an interface and overrides all the methods available in
the interface to create a subclass which need not to override all the methods of the interface.
In the Example 13.2(b) you can see the frame can be closed without override all the methods
present in the WindowListener class. This is possible only by the Adapter class or AdapterListener.

Example 13.2 (b) Closing a frame using adapter listener.


import java.awt.*;
import java.awt.event.*;
public class Frameclose1 extends Frame
{
Frameclose1( )
{
setBackground(Color.red);
setSize(200,200);
setVisible(true);
addWindowListener(new MyListener( ));
}
public static void main(String arg[ ])
{
Frameclose1 mf = new Frameclose1( );
}
}
class MyListener extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}

The Table13.3 gives commonly used Listener Interfaces implemented by Adapter classes.
Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener

Table13.3 Commonly used Listener Interfaces implemented by Adapter classes.

13.4.2 Anonymous Inner Classes


An anonymous inner class is one that is not assigned a name. This section illustrates how an
anonymous inner class can facilitate the writing of event handler.
Example 13.2 (c) A demo program to Anonymous Inner Classes.

230
import java.awt.*;
import java.awt.event.*;
public class AnonymousDemo extends Frame
{
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}); // Anonymous classimplementation.
public static void main(String arg[ ])
{
AnonymousDemo ad = new AnonymousDemo( );
ad.setSize(200,200);
ad.setVisible(true);
}
}
13.5 Applet-Applet Communication
This is a mechanism to communicate between different applets in the web browser. To
communicate between applets we required java.applet.AppletContext class.
Creation Procedure
(i) In the applet(both) create the instance of AppletContext class, using getAppletContext( ) method of
Applet class.
Example: AppletContext ac = getAppletContext( );
(ii) Use getApplet( ) method of AppletContext which accept a String parameter, specifying name of the
applet provided in HTML page‟s <Applet> tag as name attribute.
Example: <Applet code = “Applet1.class” height = “100” width= “300” name= “a1”>
(iii) Fetch the fields available in other applet by using the instance provided by getApplet( ) method of
AppletContext class.
Example: In the second applet (Applet2)
Applet1 ap1 = (Applet1) ac.getApplet(“a1”);

Example 13.3 Applet-Applet Communication. In this example Applet1 and Applet2 are sending
and receiving message from one another.
Applet1.java
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Applet1 extends Applet implements ActionListener
{
TextField tf;
TextArea ta;
public void init( )
{
setBackground(Color.gray);
setFont(new Font("sansarif",Font.BOLD,10));
Button b1=new Button("SEND");
tf= new TextField(20);
231
ta=new TextArea(4,20);
add(tf);
add(b1);
add(ta);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
AppletContext ac=getAppletContext( );
Applet2 a2=(Applet2)ac.getApplet("applet2");
String text=tf.getText( );
a2.ta.append(text +"\n");
tf.setText(" ");
}
}

Applet2.java

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Applet2 extends Applet implements ActionListener
{
TextField tf;
TextArea ta;
public void init()
{
setBackground(Color.red);
setFont(new Font("sansarif",Font.BOLD,10));
Button b1=new Button("SEND");
tf= new TextField(20);
ta=new TextArea(4,20);
add(tf);
add(b1);
add(ta);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
AppletContext ac=getAppletContext();
Applet1 a1=(Applet1)ac.getApplet("applet1");
String text=tf.getText();
a1.ta.append(text +"\n");
tf.setText(" ");
}
}

232
Applet_Applet_Communication.html
<html>
<body bgcolor="cyan">
<h1 align="center">ROURKELA</h1>
<applet code="Applet1.class" height="200",width="200" name="applet1">
</applet>
<applet code="Applet2.class" height="200",width="200" name="applet2">
</applet>
</body>
</html>
D:\java20\eventhandling>javac Applet1.java
D:\java20\eventhandling>javac Applet2.java
D:\java20\eventhandling>appletviewer Applet_Applet_Communication.html

Preparing message by Applet1 in its text Applet2 class is waiting for message.
area.

Applet1 sent its message by pressing send Applet2 receives message sent by
button Applet1

Applet1 is waiting for message. Appet2 preparing a message

Applet2 sends message by pressing send


Applet1 receives the message.
button.

233
Example 13.4 Passing parameters between two frames.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class Adminpage extends JFrame implements ActionListener
{
JLabel l1,l2,l3;
String uid="",pwd="";
Font f;
JTextField t1;
JPasswordField p1;
JPanel pn1;
JButton bn;
Container cn;
Adminpage( )
{
super("Adminpage");
cn=getContentPane( );
cn.setLayout(null);
f=new Font("arial",Font.BOLD,20);
addWindowListener(new WindowAdapter( )
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
pn1=new JPanel( );
pn1.setBounds(100,100,800,100);
cn.add(pn1);
l3 = new JLabel("USER LOGIN INFORMATION");
l3.setFont(new Font("arial",Font.BOLD,40));
pn1.add(l3);
l1=new JLabel("USER NAME");
l1.setBounds(100,250,150,20);
cn.add(l1);
l1.setFont(f);
l1.setForeground(Color.WHITE);
t1=new JTextField();
t1.setBounds(250,250,100,20);
cn.add(t1);
l2=new JLabel("PASSWORD");
l2.setBounds(100,300,150,20);
cn.add(l2);

234
l2.setFont(f);
l2.setForeground(Color.WHITE);
p1=new JPasswordField();
p1.setBounds(250,300,100,20);
cn.add(p1);
bn=new JButton("login");
bn.setBounds(150,350,100,20);
cn.add(bn);
bn.addActionListener(this);
cn.setBackground(Color.gray);
setSize(900,450);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource( )==bn)
{
uid=t1.getText( );
pwd=p1.getText( ).toString( );
new Login(uid,pwd);
this.setVisible(false);
}
}
public static void main(String ar[ ])
{
new Adminpage( );
}
}
class Login extends JFrame
{
JLabel l1,l2;
Login( ){}
Login(String u,String p)
{
super("LOGINPAGE");
l1 = new JLabel("User name is ---> "+u);
l2 = new JLabel("Password is --- >"+p);
setLayout(new FlowLayout( ));
add(l1);
add(l2);
setVisible(true);
setSize(400,200);
addWindowListener(new WindowAdapter( )
{
public void windowClosing(WindowEvent we)
{

235
System.exit(0);
}
});
}
}

13.6 PLAYING SOUND


To play a sound we required java.lang.AudioClip class. The java.applet.Applet class has some
methods which returns instance of AudioClip class by accepting path of the second file as an instance of
java.net.URL class.
Example: For Frame
URL u1 = new URL(“music.au”);
AudioClip ac = Applet.newAudioClip(u1);
Example: For Applet
URL u1 = new URL(getCodeBase( ),”/music.au”);
AudioClip ac = getAudioClip(u1);
After initializing AudioClip class use play( ) or loop( ) method to start music or use stop( ) method to stop
music.
Example: ac.play( );
ac.stop( );

Example 13.5 Playing sounds.


import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class Soundfrm extends Frame implements ActionListener
{
AudioClip ac;
Soundfrm( )
{
setLayout(new FlowLayout( ));
Button b1=new Button("PLAY");
Button b2=new Button("STOP");
try{
ac = Applet.newAudioClip(new URL("file:///E:/game/audio/yahoo1.au"));
b1.setBackground(Color.yellow);
b2.setBackground(Color.orange);
b1.addActionListener(this);
b2.addActionListener(this);
add(b1);

236
add(b2);
}
catch(Exception e)
{
System.out.println(e);
}
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand ( );
if(str.equals("PLAY"))
{
ac.play( );
}
else{
ac.stop( );
}
}
public static void main(String arg[ ])
{
Soundfrm cf=new soundfrm( );
cf.setSize(400,400);
cf.setVisible(true);
}
}
Example 13.6 Shrink or enlarge a ball using buttons.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ControlBall extends Frame
{
private Button Enlarge = new Button("Enlarge");
private Button Shrink = new Button("Shrink");
private BallCanvas canvas = new BallCanvas( );
public ControlBall( )
{
Panel panel = new Panel( );
panel.add(Enlarge);
panel.add(Shrink);
this.add(canvas, BorderLayout.CENTER);
this.add(panel, BorderLayout.SOUTH);
Enlarge.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent e)
{
canvas.enlarge( );
}

237
});
Shrink.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent e)
{
canvas.shrink( );
}
});
}
public static void main(String[ ] args)
{
Frame frame = new ControlBall( );
frame.setTitle("ControlBall");
frame.setSize(200, 200);
frame.setVisible(true);
}
public static class BallCanvas extends Panel
{
private int radius = 5;
public void enlarge( )
{
radius += 1;
repaint( );
}
public void shrink( )
{
radius -= 1;
repaint( );
}
public void paint(Graphics g)
{
g.drawOval(50, 50,2*radius, 2*radius);
}
}
}

Frame started After 20 clicks of Enlarge After 4 clicks of Shrink

238
13.7 KEY EVENT

Key events enable the use of the keys to control and perform actions or get input from
the keyboard. A key event fired whenever a key is pressed, released, or typed on a component.
The KeyEvent object describes the nature of the event (pressed, released or typed key) and the
value of the key. The KeyEvent class consists of two methods.
char getKeyChar( ) : Returns the character associated with the key in this event.
int getKeyCode( ) : Returns the integer key code associated with the key in this event.
The KeyListener interface consists of the following methods:
void KeyPressed(KeyEvent e) : Invoked after a key is pressed on the source component.
void KeyReleased(KeyEvent e) : Invoked after a key is released on the source component.
void KeyTyped(KeyEvent e) : Invoked after a key is pressed and then released on the source
component.
The KeyPressed handler is invoked when a key is pressed, the KeyReleased handler is
invoked when a key is released, and the KeyTyped handler is invoked when a Unicode character
is entered. Every key evevt has an associated key character or key code that is returned by
getKeycode( ) or getKeyChar( ) method in KeyEvent. The Keycodes are constants defined in
Table13.4.

Constant Description
VK_HOME The Home key.
VK_END The End key.
VK_PGUP The Page Up key.
VK_PGDN The Page Down key.
VK_UP The Up-arrow key.
VK_DOWN The down-arrow key.
VK_LEFT The left-arrow key.
VK_RIGHT The right-arrow key.
VK_ESCAPE The Esc key.
VK_Tab The Tab key.
VK_Control The Control key.
VK_SHIFT The Shift key.
VK_BACK_SPACE The Backspace key.
VK_CAPS_LOCK The Caps Lock key.
VK_NUM_LOCK The Num Lock key.
VK_ENTER The Enter key.
VK_UNDEFINED The key code unknown.
VK_F1 to VK_F12 The function keys from F1 to F12.
VK_0 to VK_9 The number keys from 0 to 9.
VK_A to VK_Z The letter keys from A to Z.

Table13.4 Key Constants

Example 13.7 Moving a letter ‘J’ in a frame by using key event.

239
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyEventDemo extends JFrame
{
KeyboardPanel kp = new KeyboardPanel( );
KeyEventDemo( )
{
add(kp);
kp.setFocusable(true);
}
public static void main(String arg[ ])
{
KeyEventDemo frame = new KeyEventDemo( );
frame.setTitle("KeyEventDemo");
frame.setSize(500,200);
frame.setLocationRelativeTo(null); //Ceter the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
static class KeyboardPanel extends JPanel
{
int x = 100;
int y = 100;
char keychar = 'J';
KeyboardPanel( )
{
addKeyListener(new KeyAdapter( )
{
public void keyPressed(KeyEvent e)
{
switch(e.getKeyCode( ))
{
case KeyEvent.VK_DOWN: y+=10;break;
case KeyEvent.VK_UP: y-=10;break;
case KeyEvent.VK_LEFT: x-=10;break;
case KeyEvent.VK_RIGHT: x+=10;break;
default:keychar=e.getKeyChar( );
}
repaint( );
}
});
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);

240
g.setFont(new Font("TimesRoman",Font.BOLD,30));
g.drawString(String.valueOf(keychar),x,y);
}
}
}

13.8 THE EVENT HANDLING PROCESS AND EVENT-DELEGATION MODEL


In Java every event is an object of class of java.awt.event package. For example
when the user clicks on a particular button an instance of ActionEvent is generated. The
popularly accepted technique is the delegate the event to some other object called event listeners.
Suppose a button is clicked then it will create an object of the ActionEvent class and this object
contains the total information about the event and its source and this object will send as an
argument of the actionPerformed method. The actionPerformed method is a member of the
ActionListener interface. The event object is passed to a listener object means the event sources
calls a particular method of the listener object and pass the event object to the method as an
argument.

JButton b1 = new JButton(“OK”); Click Event


b1.addActionListener(this);
This is an object of Button class on the user
JButton b2 = new JButton(“Cancel”); interface.
b2.addActionListener(this);
Generates
public void actionPerformed(ActionEvent e)
{
An object of ActionEvent
if( e.getSource( ) = b1)
label.setText(“You pressed OK button”);
else
label.setText(“Cancel is pressed”); actionPerformed() method of actionListener
} interface.

Figure 13.1 Source code for Button click Figure 13.2 Button click event handled.

Example 13.8 Creating a simple calculator.


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class calculator extends JFrame implements ActionListener
{
private boolean newNumber = true;
private int result = 0;
private String op ="=";

241
JButton bt;
JTextField jtf;
calculator( )
{
Panel p1=new JPanel( );
p1.setLayout(new GridLayout(4,3));
for(int i=0;i<=9;i++)
{
p1.add(bt=new JButton(""+i));
bt.addActionListener(this);
}
p1.add(bt=new JButton("+"));
bt.addActionListener(this);
p1.add(bt=new JButton("-"));
bt.addActionListener(this);
p1.add(bt=new JButton("*"));
bt.addActionListener(this);
p1.add(bt=new JButton("/"));
bt.addActionListener(this);
p1.add(bt=new JButton("%"));
bt.addActionListener(this);
p1.add(bt=new JButton("="));
bt.addActionListener(this);
JPanel p2=new JPanel( );
p2.setLayout(new BorderLayout( ));
p2.add(p1,BorderLayout.CENTER);
add(p2,BorderLayout.CENTER);
add(jtf=new JTextField(30),BorderLayout.NORTH);
}
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand( );
if ('0' <= actionCommand.charAt(0) && actionCommand.charAt(0) <= '9')
{
if (newNumber)
{
jtf.setText(actionCommand);
newNumber = false;
}
else
{
jtf.setText(jtf.getText( ) + actionCommand);
}
}
else
{

242
execute( );
op = actionCommand;
}
}
void execute( )
{
int number = new Integer(jtf.getText( )).intValue( );
switch (op.charAt(0))
{
case '+': result += number; break;
case '-': result -= number; break;
case '*': result *= number; break;
case '/': result /= number; break;
case '%': result %= number; break;
case '=': result = number;
}
jtf.setText(new Integer(result).toString( ));
newNumber = true;
}
public static void main(String arg[ ])
{
calculator mf=new calculator( );
mf.setTitle("**calculator**");
mf.setSize(300,300);
mf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mf.setVisible(true);
}
}

13.9 Introduction to MVC Architecture


To provide higher degree of code re-usability, it is important to separate an interface
design from the actual program logic part. This is due to the fact that the user interface code can
easily be used directly else where whenever it is needed. In this context we should understand an
important architecture called Model-View-Control (so called MVC). It comprises of three
building blocks namely Model, View and Control. MVC is quite evident from the Swing widgets
of Java where the interesting points converge at a single task of user interactive interface design.
Let‟s know about these three objects briefly.

243
Model:
Model refers to the data on which the computations are carried out. Model maintains the
state information pertaining to the application. It also provides utility methods to access and
update this state information and notifies its view objects about these updations as and when the
change takes place. So a model object is responsible to register its viewers and notify such
registered viewer objects when the state change occurs in it.
View:
A view object provides visual effects to the data by displaying the state of the Model
object. The model and view objects interact with each other in such a way that the view object
registers with the model object so that the updations carried on the data are notified to them.
Controller:
The user is abstracted from the direct interaction with the Model and View objects. This
abstraction is provided by an interface called Controller. The controller enable the user to
interact with Model and View through well-defined mechanism defined by this interface.

Enter Inform
model
User Data Controller Model

Notify all
views

Request for new state


Display to the View
user

Repaint the view after the

Change of model state


Figure 13.3 MVC Architecture and its functionality

In Figure 13.3 the user enters the data through any of input components of Controller.
The Controller informs the Model to update this information. The model holds appropriate data
structure support to handle such messages. The model in turn notifies all of its views about such
state updations. The views send a request to the model for the updated state information before
repainting itself. Hence this architecture minimizes the direct coupling among Model,View and
Controller objects. Hence MVC provides abstraction between the model and views. The primary
responsibility of a model is to notify its registered views about the updations.
In Java, the views are built with AWT or Swing components. The interaction of
user with the application program is through an action, say clicking a button or checkbox or
moving the mouse etc. In each of these cases, whenever , the user interacts with such objects, an
event occurs. To ensures this aspect by providing a wide variety of interfaces called Listeners.
For example, when a button is pressed using a mouse, an event is generated and is passed to an
interface called ActionListener so that when you press a button on a window, an appropriate
action takes place depending on the functionality inherited from the ActionListener interface.
The behavior of this action is captured by suitable methods provided by the Listeners. Hence the
GUI programming is also known as event-driven programming.

244
SUMMARY
In this chapter we know the following:
- The root class of the event classes is java.util.EventObject. The subclasses of
EventObject deals with special types of events, such as action events, window
events, mouse events and key events.
- The listener object‟s class must implement the corresponding event-listener
interface. Java provides a listener interface for every event class.
- The listener object must be registered by the source object. Registration methods
are dependent on the event type.
- Java provides convenience listener adapters for every AWT listener interface with
multiple handlers.
- A source object may fire several types of events. For each event, the source object
maintains a list of listeners and notifies all the registered listeners by invoking the
handler on the listener object to process the event.

245
Review Questions
13.1 Write a program that will change the color of a circle from one color to another when the
circle is clicked but will not change the color of the circle if somewhere else is clicked.

13.2 Write a program that displays the background color of a Panel to red when the mouse is
clicked, blue when the mouse is pressed, green when the mouse exits and yellow when the
mouse enters.

13.3 Write a program that receives a string from the keyboard and displays it on a Panel. The
Enter key signals the end of a string. Whenwver a new string is entered; it is displayed on the
Panel.

13.4 Write a program to get a character input from the keyboard and display the character where
the mouse points.

13.5 Write a program that draws line segments using the arrow keys. The line starts from the
center of the frame and draws towards east, north, west or south when the right-arrow key, up-
arrow key, left-arrow key or down-arrow key is clicked.

13.6 Write a program that moves a circle up, down, left or right using the arrow keys.

13.7 Create Form named as Student_Form having attributes Name, Regd_No, Age, Branch, and
Semester with two buttons login and Cancel. When login button is pressed it opens another
Frame named as loged_info which displays all the attributes values given in Student_Form.
When cancel button is clicked it closed all the form.

13.8 Create a simple calculator having all options.

13.9 What is event delegation model ?

13.10 Write a small program to implement the concept of event delegation model.

246
Input/Output: Exploring java.io
14.0 INTRODUCTION
This chapter explores java.io, which provides support for I/O operations. As all
programmers learn early on, most programs cannot accomplish their goals without accessing
external data. Data is retrieved from an input source. The results of a program are sent to an
output destination. In Java, these sources or destinations are defined very broadly. For example, a
network connection, a memory buffer, or disk file can be manipulated by the Java I/O classes.
Although physically different, these devices are all handled by the same abstraction: the Stream.
A stream is a logical entity that either produces or consumes information. A stream is linked to a
physical device by the Java I/O system. All streams behave in the same manner, even if the
actual physical devices they are linked to differ.

14.1 THE JAVA I/O CLASSES AND INTERFACES


The I/O classes defined by java.co. are listed on Table 14.1.
BufferedInputStream FileWriter PipedInputStream
BufferedOutputStream FilterInputStream PipedOutputStream
BufferedReader FilterOutputStream PipedReader
BufferedWriter FilterReader PipedWriter
ByteArrayInputStream FilterWriter PrintStream
ByteArrayOutputStream InputStream PrintWriter
CharArrayReader InputStreamReader PushbackInputStream
CharArrayWriter LineNumberReader PushbackReader
DataInputStream ObjectInputStream RandomAccessFile
DataOutputStream ObjectInputStream.GetField Reader
File ObjectOutputStream SequenceInputStream
FileDescriptor ObjectOutputStream.PutField SerializablePermission
FileInputStream ObjectStreamClass StreamTokenizer
FileOutputStream ObjectStreamField StringReader
FilePermission OutputStream StringWriter
FileReader OutputStreamWriter Writer
Table 14.1 java.io package

14.2 FILE
So far we have used variables and arrays for storing data inside the programs. This
approach poses the following problems:
- The data is lost either when a variable goes out of scope or when the program is
terminated. That is, the storage is temporary.
- It is difficult to handle large volumes of data using variables and arrays.
We can overcome these problems by storing data on secondary storage devices such as
pendrives or hard disks. The data is stored in these devices using the concept of files. Data stored
in file is often called persistent data.
A file is a collection of related records placed in a particular area on the disk. Storing
and managing data using files is known as file processing which includes tasks such as creating
files and manipulation of data. In file processing, input refers to the flow of data in a program
and output means the flow of data out of a program. Input to a program may come from the
keyboard, the mouse, the memory, the disk, a network, or another program. Similarly, output

247
from a program may go to the screen, the printer, the memory, the disk, a network, or another
program. This illustrated in Figure 14.1
Sources Destinations
Keyboard Screen

Mouse Printer
.Java
Memory Program Memory

Disk Disk

Network Network
Input Output
Figure 14.1 Relationship of Java program with I/O devices.

Java Streams are classified into two basic types, namely input stream and output stream.
An input stream extracts or reads data from the source (file) and sends it to program. Similarly,
an output stream takes data from the program and sends (i.e.; writes) it to the destination (file).

14.3 STREAM CLASSES


The java.io package contains a large number of stream classes that provide capabilities
for processing all types of data. These classes may be categorized into two groups based on the
data type on which they operate.
- Byte stream classes that provide for handling I/O operations on bytes.
- Character stream classes that provide support for managing I/O operations on
bytes.
These two groups may further classified on their purpose. Figure 14.2 shows how
stream classes are grouped based on their functions. Byte stream and character stream classes
contain specialized classes to deal with input and output operations independently on various
types of devices.

Example 14.1 How println( ) works.


System.out.println( )

class Object of PrintStream which is a subclass of output stream, it accepts an object of


OutputStream and to initialize.
import java.io.*;
public class Print
{
public static void main(String arg[])throws Exception
{
PrintStream p = new PrintStream(System.out);
p.println("kanta");
}
}
Output: kanta

248
Java Stream classes

ByteStream Character
classes Stream classes

Reader Writer
InputStream OutputStream
classes classes
classes classes

Memory Memory File Pipe


File Pipe

Figure 14.2 Classification of Java stream classes

ByteStream Class CharacterStream Class


- This is a stream which transfers data - This is a type of stream which can transf-
from source to destination in the format er data from source to destination in the
of byte data. It can transfer any type of format of character data.
data source to destination.
- Object/text data will be converted into - It cannot carry non-textual data.
byte format, text data will be converted
into corresponding ASCII value.
- For input it required InputStream class. - For input it required Reader class.
- For output it required OutputStream - For output it required Writer class.
class.

14.4 BYTE STREAM CLASSES


Byte Stream classes have been designed to provide functional features for creating and
manipulating streams and files for reading and writing bytes. Java provides two kinds of byte
stream classes: Inputstream and Outputstream classes.

14.4.1 InputStream classes


Input stream class that is used to read 8-bit bytes includes a number of subclasses as
shown in Figure14.3. The InputSream class is an abstract class and we cannot create instances of
this class.

249
Object

InputStream

FileInputStream SequenceInputStream

PipeInputStream ObjectInputStream

ByteArrayInputStream StringBufferInputStream

FileInputStream

BufferedInputStream DataInputStream PushbackInputStream

Figure 14.3 Hierarchy of InputStream classes

The InputStream class defines various methods for performing input functions are given in
Table14.2.
Method Description
read( ) Reads a byte from the input stream.
read(byte b[ ] ) Reads an array of bytes into b.
read(byte b[ ], int n, int m) Reads m bytes into b starting from n+m byte.
available( ) Gives number of bytes available in the input.
skip( ) Skips over n bytes from the input stream.
reset( ) Goes back to the beginning of the stream.
close( ) Closes the input stream.
Table 14.2 InputStream methods

The class DataInputStream extends FilterInputStream and implements the interface


DataInput. The DataInput interface contains the following methods:
readShort( ) readFloat( ) readLine( )
readInt( ) readUTF( ) readChar( )
readLong( ) readDouble( ) readBoolean( )

14.4.2 Output Stream Classes


Output stream class is used to write. It includes a super class known as OutputStream.
The OutputStream class is an abstract class and therefore we cannot instantiate it. The various
subclasses present in Outputstream class is shown in Figure 14.4.

250
Object

OutputStream

FileOutputStream ObjectOutputStream

PipedOutputStream ByteArrayOutputStream

FileOutputStream

BufferedOutputStream DataOutputStream PushbackOutputStream

Figure 14.4 Hierarchy of OutputStream classes

The various methods present in OutputStream class are given in Table 14.3.

Method Description
write( ) Writes a byte to the output stream.
write(byte b[ ]) Writes all bytes in the array „b‟ to the output stream.
write(byte b[ ], int n, int m ) Writes „m‟ bytes from array b starting nth byte
close( ) Closes the output stream.

Table 14.3 various methods of Output Stream.

The DataOutputStream class extends from FilterOutputStream and implements


DataOutput interface. The following methods contained in DataOutput interface.

writeShort( ) writeFloat( ) writeBytes( )


writeInt( ) writeUTF( ) writeChar( )
writeLong( ) writeDouble( ) writeBoolean( )

14.4.3 File Operation Using ByteStream classes


To read a file we can use FileInputStream class and it must be call inside the try block
or throws block, since it throws Filenotfound Exception. Similar manner a file can be write using
FileOutputStream.

Example14.2 Reading file using FileInputStream.


import java.io.*;
public class ReadFile

251
{
public static void main(String arg[ ])throws Exception
{
FileInputStream fis=new
FileInputStream("D://java20/operator/operator5.java");
int i;
while((i = fis.read( ))!=-1)
{
if(i=='\n')
System.out.println( );
else
System.out.print((char)i);
}
}
}
D:\java20\file>javac ReadFile.java
D:\java20\file>java ReadFile
public class operator5
{
public static void main(String arg[ ])
{
int a=10;
System.out.println(" "+(++a * a++));
}
}

Example 14.3 Writing data using FileOutputStream.


import java.io.*;
import java.util.*;
public class FileDemo
{
public static void main(String arg[ ])throws Exception
{
FileOutputStream fos = new FileOutputStream("data.txt");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter a line");
String str = br.readLine( );
fos.write(Byte.parseByte(str));
fos.close( );
}
}

14.5 CHARACTER STREAM CLASS


Character streams can be used to read and write 16-bit Unicode characters. Like byte
streams, there are two kinds of character stream classes, reader stream classes and writer stream.

252
14.5.1 Reader Stream Classes
Reader Stream classes are designed to read character from the files. Reader class is the
base class and consists of number of subclasses as shown in Figure 14.5.
Object

Reader

BufferedReader StringReader

CharArrayReader PipeReader

InputStreamReader FilterReader

FileReader PushbackReader
Figure 14.5 Hierarchy of ReaderStream classes
The methods of Reader class are:
read( ) : Reads a single character as its integer equivalent.
read(char ch[ ] ) : Reads an array of bytes into b.
read(char ch[ ], int start, int length): Reads a piece of data as the character array from
the starting position till length.
14.5.2 Writer Stream Classes
The writer stream classes are designed to write characters. These classes are designed to
perform all output operations on files. The Writer class is an abstract class which acts as a base
class for all the other writer stream classes as shown in Figure 14.6.

Object

Writer

BufferedWriter PrintWriter

CharArrayWriter StringWriter

FilterWriter OutputStreamWriter PipeWriter

FileWriter
Figure 14.6 Hierarchy of WriterStream classes

253
The methods of Writerclass are
write( int d) : Writes an integer data to the output stream.
write(char ch[ ]) : Writes an array of characters to the output
stream.
write(char ch[ ],int start,int length) : Writes an array of characters from the starting
index to the length to the output stream.
write(String str) : Writes a string to the output stream.

14.5.3 File Operation using Character Stream class


For reading a file we required FileReader class and writing we required FileWriter
class.
Example 14.4 Copy the contents of a file to another file.
import java.io.*;
public class FileCopy
{
public static void main(String arg[ ])
{
FileReader ins = null ;
FileWriter out = null;
int ch;
try{
ins = new FileReader("input.txt");
out = new FileWriter("output.txt");
while( ( ch = ins.read( ))!=-1)
{
out.write(ch);
}
}
catch(IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally{
try{
ins.close( );
out.close( );
}
catch(IOException e){}
}
}
}

14.6 BUFFERING
A Buffer is a temporary storage used to hold data until enough has been collected that it
is worth transferring. Buffering can be used for both input and output. Accessing any input or

254
output device usually requires some processing, independent of the amount of data being
transferred. The overhead of the accessing the device can be become significant if very small
amounts of data are being transferred very often. It is usually more efficient to transfer large
amounts less often. This can be achieved through the use of buffering. An input buffer is used for
reading a large chunk of data from a stream. The buffer is then accessed as needed and, when
emptied, another chunk of data is read from the stream into the buffer. An output buffer is used
to store up data to be wriiten to a stream. Once the buffer is full the data is sent to the stream all
at once and the buffer is emptied to receive more data.
Sometimes we wish to guarantee that some data has actually been written to the stream
and that is not waiting around in the output buffer. At such times, we execute a flush operation,
which forces the buffer to be written to the stream as soon as possible.
The BufferedInputStream and BufferedOutputStream filters may be used to add buffering
to any byte-oriented stream. The BufferedReader and BufferedWriter filters may be used to add
buffering to any character-oriented Stream.

Checking for File EOF:

Checking for a binary file‟s end-of-file condition is a tricky task because reading does
not return -1 or null as in the case of text files. It only throws EOFException and closes the input
file stream.
boolean eof = false;
while(!eof)
{
try{
// read data from file here
}
Catch(EOFException e) {
// print message if any
Eof = true; // set eof as true
}
}

14.7 PRINTING IN JAVA


Apart from providing various classes for obtaining input, Java also provides classes for
printing on printer through Java 2D printing API. The Java 2D printing API is not limited to
printing graphics. It enables you to print the content of an applications user interface as the
content can be printed by sending row data to the printer under formatting control of Java 2D
printing API. The main classes and interfaces invoved in printing are represented in the
java.awt.print package.

14.7.1 Java Printing API


Printing involves deciding what to print and then readying printer for it; in other words,
we can say that printing invoves creation of print jobs. A print job is a unit of work to be run on
a printer and can consists of printing one or more files. The system assigns a unique job number
to each job as it is received.

255
In the Java Printing API, the programs have a contract with the printing subsystem to
supply a given page at a given time. The printing subsystem may request that your application
render a page more than once, or render pages out of sequence. This model provides several
advantages:
1. By sending strips of the page instead of whole page to the printer, it allows the application to
print complex documents that would require more printer memory than is available. The
application does not have to know how to print each strip; it only needs to know how to render a
given page. The API will take care of the rest. In this case, the printing subsystem might request
that a page be rendered several times depending on the number of strips required to completely
print the page.
2. If the paper tray on a particular printer outputs the pages in reverse order, then your
application might be asked to print the document in reverse order, so it will appear in the right
order in the output tray.

14.7.2 Rendering Models


There are two printing models in Java: Printable jobs and Pageable jobs.
Printables:
Printables jobs are the simpler of the two printing models. This model only uses one
PagePrinter for the entire document. Pages are rendered in sequence, starting with page zero.
When the last page prints, your PagePrinter must return the NO_SUCH_PAGE value. The print
subsystem will always request that the application render the pages in sequence. For example, if
your application is asked to render pages five through seven, the print subsystem will ask for all
pages up to seventh page, but will only print pages five, six, and seven.
Pageables:
Pageable jobs offer more flexibility than Printable jobs, as each page in a Pageable job can
feature a different layout. Pageable jobs are most often used with books, a collection of pages
that can have different formats. A pageable job has the following characteristics:
- Each page can have its own painter. For example, you could have a painter
implemented to print the cover page, another painter to print the table of contents,
and a third to print the entire document.
- You can set a different page format for each page in the book. In a Pageable job
you can max portrait and landscape pages.
- The Pageable job doesn‟t need to know how many pages are in the document.
All of the classes required to print are located in the java.awt.print package, which is
composed of three interfaces and four classes. The following tables define the classes and
interfaces of the print package.
Name Type Description
Paper Class This class defines the page‟s physical characteristics.
PageFormat Class PageFormat defines the page‟s size and orientation. It
also defines which paper to use when rendering a
page.
PrinterJob Class This class manages the print job. Its responsibilities
include creating a print job, displaying a print dialog
box when necessary and printing the document.
Book Class Book represents a document. A Book object acts as a
collection of pages. Pages included in the Book can

256
have identical or differing formats and can use
different painters.
Pageable Interface A Pageable implementation represents a set of pages
to be printed. The Pageable object returns the total
number of pages in the set as well as the PageFormat
and Printable for a specified page. The Book class
implements this interface.
Printable Interface A page painter must implements the Printable
interface. There is only one method in this interface,
print( ) .
PrinterGraphics Interface The Graphics object implements this interface.
PrinterGraphics provides the getPrinterjob( ) method
to obtain the printer job that instatiated the print
process.

Pageable Interface:
The Pageable interface includes following three methods:

Method Name Dsecription


int getNumberOfPages( ) Returns the number of pages in the docu-
ment.
PageFormat getPageFormat(int index) Returns the page‟s PageFormat as specified
by pageIndex.
Printable getPrintable(int pageIndex) Returns the Printable instance responsible for
rendering the page specified by pageIndex.

Printable Interface:
The Printable interface features one method and two values which are given below:

Name Type Description


int print(Graphics g,PageFormat pf, method Requests that the graphics handle using the
int pageIndex) given page format render the specified page.
NO_SUCH_PAGE value This is a constant. Return this value to indicate
that there are no more pages to print.
PAGE_EXITS value The print( ) method returns PAGE_EXISTS. It
indicates that the page passed as a parameter to
print( ) has been rendered and does exists.

PrinterGraphics Interface:
The PrinterGraphics interface consists of one method getPrinterJob( ) that returns
PrinterJob.
PrinterJob getPrinterJob( )
14.7.3 Units of Measurement
When working with the Graphics 2D class, it is important to understand the difference
between device space and user space. In the device space, you work in pixels using the resolution
of the device. A square or image of 100 pixels by 100 pixels drawn on a device that has a
resolution of 1,024 pixels by 768 pixels will not be the same size as it is when rendered on a
257
device that has a resolution of 1,600 pixels by 1,400 pixels. The reason is simple because the
second device features more pixels per inch, the square will appear samaller.
User space, on the other hand, allows us to think in terms of measurement units, regar-
dless of the device‟s resolution. When you create a 2D object for a given resource (printer or
screen), a default mapping is generated to map the user space to the device space. When using
the print API, you must set your mind to work with units because all the classes work in the user
space. Java provides PageFormat for the units of measurement, and it consists of 12 methods
which are shown in Table 14.4.
Method Name Description
double getHeight( ) This method returns the page‟s physical height in
points (let 1inch = 72 points). If an image 8.5X11
inches, then this method returns 792 points or 11
inches.
double getImageableHeight( ) This method returns the page‟s imageable height,
which is the height of the print area on which you
may draw.
double getImageableWidth( ) This method returns the page‟s imageable width on
which you may draw.
double getImageableX( ) This method returns the „X‟ origin of the imageable
area.
double getImageableY( ) This method returns the „Y‟ origin.
double getWidth( ) This method gives the image‟s physical width in
points.
double getHeight( ) This method returns the image‟s physical height in
pixels.
double[ ] getMatrix( ) This method returns a transformation matrix that tra-
nslates user space into the required page orientation.
The return value is in the format required by the
AffineTransform constructor.
int getOrientation( ) This method returns the orientation of the page as
either PORTRAIT or LANDSCAPE.
void setOrientation(int ori) This method sets the orientation of the page, using
the constants PORTRAIT and LANDSCAPE.
Paper getPaper( ) This method returns the Paper object associated with
the page format.
void setPaper(Paper p) This method sets the Paper object that will be used
by the PageFormat class, which access to the physic-
cal page characteristics to complete this task.

Table 14.4 Methods PageFormat class

14.7.4 PrinterJob Class


The PrinterJob class controls the printing process. It can both instantiate and control a
print job. The Table14.5 contains various methods present in PrinterJob class.

258
Method Name Description
abstract void cancel( ) This method cancels the current print job. You can
validate the cancellation with the isCancel( ) meth-
od.
abstract boolean isCancelled( ) This method returns true if the job is cancelled.
PageFormat defaultPage( ) This method returns the default page format for the
PrinterJob.
abstract PageFormatdefaultPage This methods clones the PageFormat passed in
(PageFormat page) parameters and modifies the clone to create the
default PageFormat.
abstract int getCopies( ) This method returns the number of copies that the
print job will print.
abstract int getCpoies(int Copies) This method returns the number of copies that the
job will print.
abstract String getJobName( ) This method returns the job name.
static PrinterJob getPrinterJob( ) This method creates and returns a new PrinterJob.
abstract String getUserName( ) This method returns the user name associated with
the print job.
abstract PageFormat pageDialog This method displays a dialog that allows the user
(PageFormat page) to modify the PageFormat.
abstract void setPageable(Pageable This method queries the document to obtain the
document) total number of pages. The Pageable will return the
PageFormat and the printable object for each page.
abstract void setPrintable(printable This method sets the painter object that will render
painter) the pages to be printed. A painter object is an object
that implements the printable class and its print( )
method.
abstract void setPrintable(printable This method complete the same tasks as abstract
painter, PageFormat format) void setPrintable(Printable painter), except that you
supply the PageFormat that the Painter will use. As
indicated in the definition of the Printable interface,
the print( ) method passes a PageFormat object as t-
he first parameter.
abstract void print( ) This method prints the document.
abstract void setJobName(String This method sets the name of the print job.
JobName)
abstract boolean printDialog( ) This method displays a print dialog box that allows
the user to change the print parameters.
abstract PageFormat validatePage This method will validate the PageFormat passed in
(PageFormat page) parameters. If the printer cannot use the
PageFormat that you supplied, then a new one that
conforms to the printer will be returned.
Table14.5 various methods present in PrinterJob class.
14.7.5 The Printing Sequence
In Java printing task is usually carried out in two parts:

259
Job control – Creating a print job, associating it with a printer, specifying the number of copies,
and user print dialog interaction.
Page Imaging – Drawing content to a page, and managing content that spans pages.
(1) Creating Print Job
You need to write following code to create the print Job.
PrinterJob pJob = PrinterJob.getPrinterJob( );
To create the print job, you need to create an object or PrinterJob class by invoking its
getPrinterJob( ) method via the object of PrinterJob type.

(2) Render Content to Page for Printing


Provide code that renders the content to the page by implementing the Printable
interface.
Class MyPrinter implements Printable
{
.
.
.
}
pJob.setPrintable(new MyPrinter( ));
or you could set the PageFormat along with the Painter:
pJob.setPrintable(Painter, pageFormat);
Finally, the painter object must implement the print( ) method:
public int print(Graphics g, PageFormat pageFormat, int page)
Here the first parameter is the graphics handle that you will use to render the page, the
PageFormat is the format that will be used for the current page,and the last parameter is the page
number that must be rendered.

(3) Displaying Print Dialog


An application typically displays a print dialog, so that the user can adjust various
options such as number of copies, page orientation, or the destination printer. This is done by
invoking printDialog( ) method via the pJob object.
boolean doPrint = pJob.printDialog( );
This dialog appears until the user either approves or cancels printing. The doPrint variable will
be true if the user gave a command to go ahead and print. If the doPrint variable is false, the user
cancelled the print job. If the doPrint variable is true, then the application will request that the
job be printed by calling the PrinterJob.print( ) method.
if(doPrint)
{
try{
pJob.print( );
}
catch(PrinterException e){ }
}
The PrinterJob.print( ) method returns as soon as the job is sent to the printer, the user
application cannot detect paper jams or paper out problems. The Printable interface has only one
method:

260
public int print(Graphics g,PageFormat pf,intpage)throws PrinterException;
The PageFormat class describes the page orientation (portrait or landscape) and its size and ima-
geable area in units of 1/72 nd of an inch. Imageable area accounts for the margin limits of most
printers. The imageable area is the space inside these margins, and in practice if is often further
limited to leave space for headers or footers.
14.7.6 PrintYour First Page
The print system in Java has two distinct models: the Printable and the Pageable.
Though Printable can print simple documents, it features several limitations, the major one being
that all pages must share the same format. The Pageable model, on the other hand offers more
flexibility.
Example14.5 Write a program to print 1/2' X 1/2' inch grid.
import java.awt.*;
import java.awt.print.*;
import java.awt.geom.*;
public class MyPrinter implements Printable
{
private final double INCH = 72;
public MyPrinter( )
{
PrinterJob pJob = PrinterJob.getPrinterJob( );
pJob.setPrintable(this);
if(pJob.printDialog( ))
{
try{
pJob.print( );
}
catch(Exception e)
{
e.printStackTrace( );
}
}
}
public int print(Graphics g,PageFormat pf, int page)
{
double i;
Graphics2D g2d;
Line2D.Double line = new Line2D.Double( );
if(page == 0)
{
g2d = (Graphics2D)g;
g2d.setColor(Color.black);
g2d.translate(pf.getImageableX( ),pf.getImageableY( ));
//PRINT THE VERTICAL LINE
for(i = 0; i<pf.getWidth() ;i = i + INCH/2)
{
line.setLine(i,0,i,pf.getHeight( ));

261
g2d.draw(line);
}
//PRINTING THE HORIZONTAL LINE
for(i = 0; i<pf.getHeight( );i = i + INCH/2)
{
line.setLine(0,i,pf.getWidth( ),i);
g2d.draw(line);
}
return (PAGE_EXISTS);
}
else{
return (NO_SUCH_PAGE);
}
}
public static void main(String arg[ ])
{
MyPrinter mp = new MyPrinter( );
}
}
The Example14.5 prints the grids on a paper by a printer below shown.

Thus for printing you required the following steps:


- Create a PrinterJob object. This object controls the print process by displaying
page and print dialogs,and initiating the print action.
- Display the proper dialogs, either print or page dialogs.
- Create a class that implements the Printable interface‟s print( ) method.
- Validate the page number to be rendered.
- Render your page using the Graphics parameter.
- If the page render, return the PAGE_EXISTS value; if the page does not render,
return the NO_SUCH_PAGE value.

262
14.8 RANDOM ACCESS FILES
The files which are read or write only sequentially is known as sequential files. The
RandomAccessFile class supported by the java.io package allows us to create files that can be
used for reading and writing data with random access. We can use one of the following two
mode strings:
“r” for reading only
“rw” for both reading and writing

RandomAccessFile Methods:
read( ) write(int d)
readChar( ) writeChar(char ch)
readChars( ) writeChars(String str )
readFloat( ) writeFloat(float f )
readDouble( ) writeDouble(double d)
readLine( )

You first create an object of randomAccessFile which points to a file and using seek( ) method
the file pointer is moved to data present on the file.
RandomAccessFile f = new RandomAccessFile(“data.txt”, “rw”);

Example 14.6 Creating a RandomAcess file.


import java.io.*;
public class RandomFile
{
public static void main(String arg[ ])
{
try{
RandomAccessFile f = new RandomAccessFile("data.txt","rw");
f.writeChar('X');
f.writeInt(786);
f.writeDouble(3.14);
f.seek(0); //Go to begining
System.out.println(f.readChar( ));
System.out.println(f.readInt( ));
System.out.println(f.readDouble( ));
f.close( );
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Output:
D:\java20\file>javac RandomFile.java
D:\java20\file>java RandomFile

263
X
786
3.14

14.9 READING AND WRITING OBJECTS


You can read or write to files as object basis. To read an object you required
ObjectInputStream which is a subclass of InputStream. The objectInputStream consists of a
constructor which takes a argument of type InputStream.
ObjectInputStream(InputStream is);
Similar manner you can write the content of an object by using ObjectOutputSrtream
which is a subclass of OutputStream. ObjectOutputSrtream consists of one constructor which
takes an argument of type OutputStream.
ObjectOutputStream(OutputStream os);
The various methods present in ObjectInputStream and ObjectOutputStream are given in
Table 14.6.

ObjectInputStream ObjectOutputStream
Object readObject( ) void writeObject(Object obs)
Object read( ) void write(int x)
Object readChar( ) void writeChar(char ch )
Object readFloat( ) void writeFloat(float ft)
Object readDouble( ) void writeDouble(double db)
Object readBoolean( ) void writeBoolean(boolean b)
Figure14.6 methods of ObjectInputStream and ObjectOutputStream

Example 14.7 Reading and Writing Object.


import java.io.*;
public class WriteObj
{
public static void main(String arg[ ])throws Exception
{
Integer myint = new Integer(50);
FileOutputStream fos = new FileOutputStream("data.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(myint);
os.close( );
FileInputStream fis = new FileInputStream("data.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Integer i = (Integer)ois.readObject( );
System.out.println("Data is "+i);
}
}
Output:
D:\java20\file>javac WriteObj.java
D:\java20\file>java WriteObj
Data is 50

264
14.10 SERIALIZATION
Serialization is a mechanism which can be used to store and retrieve state of an object
from any storage place (File). State of an object means the value of the variable to the objects.
Implementing Serialization:
The class which object has to be written or read from the file must inherit
java.io.Serializable interface. Serializable is an interface which does not contain any method and
it is known as marks or null interface.

Example 14.8 Implementing Serialization.


import java.io.*;
class Student implements Serializable
{
public int rollno;
public String name;
Student(int r,String n)
{
rollno = r;
name = n;
}
public void Attendance( )
{
System.out.println("Roll-No : "+rollno);
System.out.println("Name : "+name);
}
}
public class SerialDemo
{
public static void main(String arg[ ])throws Exception
{
Student s1 = new Student(10,"Rizi");
FileOutputStream fos = new FileOutputStream("data.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(s1);
os.close( );
FileInputStream fis = new FileInputStream("data.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Student s2 = (Student)ois.readObject( );
s2.Attendance( );
}
}
D:\java20\file>javac SerialDemo.java
D:\java20\file>java SerialDemo
Output:
Roll-No : 10
Name : Rizi

265
Serialization is a technique of writing the state of an object to a byte stream. The class
that implements Serializable (which contains no methods) interface can be saved and restored by
using the technique of serialization. If a class that implements Serializable interface its
subclasses are also serializable.
14.11 TRANSIENT VARIABLES
When creating an object that can be serialized, one design consideration is whether all
the object‟s instance variables should be saved. In some cases, an instance variable must be
created from scratch each time the object is restored. A good example is an object referring to a
file or input stream. Such an object must be created a new when it is part of a serialized object
loaded from an object stream, so it doesn‟t make sense to save this information when serializing
the object. It‟s a good idea to exclude from serialization a variable that contains sensitive
information. If an object stores the password needed to gain access to a resource, that password
is more at risk if serialized into a file. The password also might be detected if it is part of an
object restored over a stream that exists on a network. A third reason not to serialize a variable is
to save space on the storage file that holds the object. If its values can be established without
serialization, you might want to omit the variable from the process.
To prevent an instance variable from being included in serialization, the transient
modifier is used. This modifier is included in the statement that creates the variable, preceding
the class or data type of the variable. The following statement creates a transient variable called
balance:
public transient int balance = 0;

14.12 GRAPHICAL INPUT AND OUTPUT


The combination of awt and file can create small applications for user like Employee
Information, Student Information etc, where user can store or fetch data from a Frame consists of
text fields; the user can give input in a graphical window and that input will store in a file. When
the user wants to retrieve data which will store permanently in a file that data again comes one
after another on the graphical window. This is given in the Example14.9 and 14.10.
Example 14.9 Graphical input created by using java.awt package for taking input from the user
and store the values in a file.

ENTER Button is used Exit Button is used


to store data in a file. to close the frame.

266
import java.io.*;

import java.awt.*;

import java.awt.event.*;

public class studentFile extends Frame implements ActionListener


{
TextField number,name,marks;
Button enter,exit;
Label num_l,name_l,marks_l;
DataOutputStream dos;
public studentFile( )
{
setLayout(new GridLayout(4,2));
number = new TextField(25);
num_l = new Label("ROOL_Number");
name = new TextField(25);
name_l = new Label("NAME");
marks = new TextField(25);
marks_l = new Label("MARKS");
enter = new Button("ENTER");
enter.addActionListener(this);
exit = new Button("EXIT");
exit.addActionListener(this);
add(num_l);
add(number);
add(name_l);
add(name);
add(marks_l);
add(marks);
add(enter);
add(exit);
try
{
FileOutputStream fos= new FileOutputStream("student.txt");
dos= new DataOutputStream(fos);
}
catch(IOException e)
{
System.out.println(e.toString( ));
System.exit(1);
}
}

267
public void actionPerformed(ActionEvent e)
{
if(e.getSource( )==enter)
{
addRecord( );
}
else
{
closed( );
}
}
public void addRecord( )
{
int num;
Double d;
num = (new Integer(number.getText( ))).intValue( );
d = (new Double(marks.getText( ))).doubleValue( );
try
{
dos.writeInt(num);
dos.writeUTF(name.getText( ));
dos.writeDouble(d);
}
catch(IOException e) { }
number.setText("");
name.setText("");
marks.setText("");
}

public void closed( )


{
System.exit(0);
}

public static void main(String arg[ ])


{
studentFile s = new studentFile();
s.setSize(400,200);
s.setVisible(true);
}
}

Example 14.10 In above example (Example 14.9) we can retrieve values present in a file by
using a frame. We can traverse one student’s data to another student’s data by using NEXT
button and by pressing EXIT button we can close the frame.

268
NEXT button is used for dis- EXIT button is used to
play Student‟s information closed the frame.
import java.io.*; one by one.
import java.awt.*;
import java.awt.event.*;
public class studentFile1 extends Frame implements ActionListener
{
boolean moreRecord = true;
TextField number,name,marks;
Button next,exit;
Label num_l,name_l,marks_l;
DataInputStream dis;
public studentFile1( )
{
setLayout(new GridLayout(4,2));
number = new TextField(25);
num_l = new Label("ROOL_Number");
name = new TextField(25);
name_l = new Label("NAME");
marks = new TextField(25);
marks_l = new Label("MARKS");
next = new Button("NEXT");
next.addActionListener(this);
exit = new Button("EXIT");
exit.addActionListener(this);
add(num_l);
add(number);
add(name_l);
add(name);
add(marks_l);
add(marks);
add(next);
add(exit);
try{

269
FileInputStream fis= new FileInputStream("student.txt");
dis= new DataInputStream(fis);
}
catch(IOException e)
{
System.out.println(e.toString( ));
System.exit(1);
}
}
public void actionPerformed(ActionEvent e)
{
if((e.getSource( )==next) && moreRecord == true)
{
readRecord( );
}
else
{
closed( );
}
}
public void readRecord( )
{
int n;
Double d;
String s;
try{
n = dis.readInt( );
s = dis.readUTF( );
d = dis.readDouble( );
number.setText(String.valueOf(n));
name.setText(String.valueOf(s));
marks.setText(String.valueOf(d));
}
catch(EOFException eof)
{
moreRecord = false;
}
catch(IOException e) { }
}
public void closed( )
{
System.exit(0);
}
public static void main(String arg[ ])
{
studentFile1 s = new studentFile1( );

270
s.setSize(400,200);
s.setVisible(true);
}
}

Summary

In this chapter we know the following:


- A stream is an abstraction that either produces or consumes information. It is
basically unidirectional flow of data in the form of byte or character.
- InputStream: Information flow to the program from some source.
- OutputStream: Information flow from to program to some device on file or some
destination.
- ByteStreams: To read and write 8 bit bytes, a program should use the byte Stream.
The InputStream and OutputStream classes provide API and partial implement-
ation for input streams and output stream (streams that read/write 8 bits/ 1 bytes).
- CharacterStreams: Readers and Writers are the abstract super classes for character
streams in java.io.
- How to create a code for printing.
- Object Serialization and Deserialization.

271
Review Question

14.1 What do you mean by Stream?


14.2 Write the difference between input and output stream.
14.3 Write the difference between ByteStream and Character Stream.
14.4 Write a program to read data from a file?
14.5 What is object serialization?
14.6 Write a program to implement the concept of object Serialization.
14.7 Write a program to print a JFrame consists of JTextField, JLabel etc.
14.8 Read rollno and marks of 5 students and write them on a file namely “stu.dat”.
14.9 Copy contents of a text file on to another text file.
14.10 (i) Which streams are used for performing IO in (a) text files (b) binary files
(ii) What is the difference between text files and binary files?
(iii) Create a DataInputStream for the file named “student.dat”.
(iv) How are Pageable and Printable printing mechanisms different?
14.11 Write a program to count number of tokens present in a file.
14.12 Write a program to print an image.
14.13 What is the use of transient modifier in serialization process?

272
Util
15.0 INTRODUCTION
The java.util package contains the collection frame work, event model and several
utility classes like StringTokenizer; random number generator etc. A collection is a group of
objects. The addition of collections caused fundamental alterations in the structure and
architecture of many elements in java.util package. Collections are a state-of-the-art technology
that merits close attention by all Java programmers. The java.util package contains a set of utility
classes and these are implementations of Datastructure. A set of useful classes implementing
standard data structure are BitSet, Dictionary, Hashtable, Stack and vector. The java.util pack-
ages also contain the Enumeration interfaces which provide a protocol for classes to count thro-
ugh a set of values.

15.1 Collection FrameWork


This is a framework which helps a program to store different types of elements with
the help of various data structures and dynamic size. The collections framework contains many
interfaces such as Collection, Map and Iterator. Other interfaces of the framework extend these
interfaces.
Interface Description
Collection Collection of elements
List It is extended from collection in which each elements is associated
with index.
Queue It is extended from Collection and is a special type of list.
Set It is extended from Collection having unique elements.
Sorted Set It is extended from set for sorted collection of unique elements.
Map Collection of key and value pairs which must be unique.
SortedMap It is extended from Map for sorted collection of unique key value
pairs.
Iterator Object used to traverse through a collection.
ListIterator It is extended from Iterator. Object used to traverse through the
sequence.
Table15.1 java.util package

15.1.1 Collection
This is an interface which provides facility to store different types of elements without
fixing size of collection. This does not have any direct subclass but has the sub interface to
provide the same functionality.
Methods of Collection interface are:
void add(Object element) To add an element into a collection by increasing the size
of collection.
void addAll(Collection c) One collection can be added into another one by using
addAll( ) method.
int size( ) Returns the number of elements available to the
collection.
Iterator.iterator( ) To traverse through the collection for fetching elements
from the reference of Iterator interface.

273
15.1.2 Iterator
This is an interface which helps to fetch data from a collection.
Methods of Iterator interface are:
boolean hasNext( ) Returns true or false by specifying the next
element is present or absent.
Object next( ) This returns the object (element) in current
position and also makes the control of
iterator indicate to next element.
Object privous( ) Returns object available in current position
and also makes the control of iterator
indicate to previous element.

15.1.3 List
This is an interface which provides facility to store element in indexing order. Each
elements available to this type of collection must have an index associated with its starting from
0 to size( )-1.
Methods of List interface are:
void add(int index, Object Obj)- Adds the element, Obj in the specified index of list.
Object get(int index)- Its returns the element available to the list in specified index.
List interface consists of two subclasses
- ArrayList
- LinkedList
Methods available for sub List interface are:
void addFirst(Object element) – Adds an element in first position.
void addLast(Object element) – Adds an element in last position.
Object getFirst( ) – Returns the first element.
Object getLast( ) – Returns the last element.

Example 15.1 Creating a ArrayList.


import java.util.*;
public class ArraylistDemo
{
public static void main(String arg[ ])
{
ArrayList name = new ArrayList( );
for(int i = 0; i<arg.length; i++)
{
name.add(i,arg[i]);
}
System.out.println("ArrayList Contain :");
for(int i = 0; i<name.size( ); i++)
{
System.out.println(name.get(i));
}
}
}

274
D:\java20\util>javac ArraylistDemo.java
D:\java20\util>java ArraylistDemo Pabitra Sunita Dulal J.Prusty
ArrayList Contain :
Pabitra
Sunita
Dulal
J.Prusty

Example 15.2 Creating a LinkedList.

import java.util.*;
public class LinkedlistDemo
{
public static void main(String arg[ ])
{
LinkedList node = new LinkedList( );
for(int i = 0; i<arg.length; i++)
{
node.add(i,arg[i]);
}
System.out.println("LinkedList Contain :");
for(int i = 0; i<node.size( ); i++)
{
System.out.println(node.get(i));
}
}
}

D:\java20\util>javac LinkedlistDemo.java
D:\java20\util>java LinkedlistDemo java c c++ c# cobol
ArrayList Contain :
java
c
c++
c#
cobol

15.1.4 Set

This is an interface which provides facility to store any number of elements which will
be unique. The uniqueness of the elements can be decided by using hash code of the object. Hash
code is a number which is being generated by JRE and it is always unique for each and every
object. This interface does not contain any extra other than its super interface collection. The Set
interface can implement by HashSet. The object having larger hashcode that will appear at the
last and the object having less hashcode will be displayed first. The method hashcde ( ) is
available in Object class which returns an integer value.

275
Example 15.3 Creating a hash set.
import java.util.*;
public class SetDemo
{
public static void main(String arg[ ])
{
HashSet name = new HashSet( );
for(int i = 0; i<arg.length;i++)
{
name.add(arg[i]);
}
Iterator it = name.iterator( );
while(it.hasNext( ))
{
System.out.println(it.next( ));
}
}
}
D:\java20\util>java SetDemo cat apple book hat xerox book
xerox
cat
book
apple
hat
Note: For duplicate value the hashcode remains same like book

15.1.5 SortedSet
This is an interface which provides facility to store element in unique and assending
order. The methods present in SortedSet are:
Set headset(Object to) – returns a set of element upto the object specified.
Set tailSet(Object from) – returns a set of elements containing element from the object
specified tail end.
Set subset(Object from, Object to) – returns a set elements from the object specified to
the object.
The interface SortedSet is implemented through TreeSet class.
Example 15.4 Using SortedSet in TreeSet.
import java.util.*;
public class SortedSetDemo
{
public static void main(String arg[ ])
{
TreeSet name = new TreeSet( );
for(int i = 0; i<arg.length;i++)
{
name.add(arg[i]); //Storing data
}

276
Iterator it = name.iterator( );
while(it.hasNext( ))
{
System.out.println(it.next( ));
}
//Fetching a sub set
System.out.println("Creating a Sublist........\n\n");
Set s1 = name.tailSet(arg[1]);
Iterator it1 = s1.iterator( );
while(it1.hasNext( ))
{
System.out.println(it1.next( ));
}
}
}
D:\java20\util>java SortedSetDemo abc defg hijkl mnopqr stuvwxyz
abc
defg
hijkl
mnopqr
stuvwxyz
Creating a Sublist........

defg
hijkl
mnopqr
stuvwxyz

15.1.6 MAP
This is an interface which provides facility to store element with key associated with it.
Each key available in map are going to be unique and the uniqueness of the keys can be decided
by hashcode.
a001 10
a002 12
Object key a003 14 value
b001 12
c003 13

The available methods present Map interfaces are:


void put(Object key, Object value) – Stores a element with a key.
Object get(Object key) – returns the element available for the key.
Set keyset( ) – returns the keys available in Map as a reference of Map.
int Size( ) – returns the number of elements available in Map.

The Map interface can be implanted by HashMap class.

277
Example 15.5 Map demo.
import java.util.*;
import java.io.*;
public class MapDemo
{
public static void main(String arg[ ])throws Exception
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
HashMap Student = new HashMap( );
//TreeMap Student = new TreeMap( );
for(int i = 0; i<3 ; i++)
{
System.out.println("Enter a Name :");
String name = br.readLine( );
System.out.println("Enter Mark :");
String mark = br.readLine( );
Student.put(name,mark);
}
Set s = Student.keySet( );
Iterator it = s.iterator( );
System.out.println("***** STUDENT's DATA AVAILABLE :");
while(it.hasNext( ))
{
String n = (String)it.next( );
String m = (String)Student.get(n);
System.out.println(" Name : "+n+"\t Mark : "+m);
}
}
}
Output :
D:\java20\util>java MapDemo
Enter a Name :
Nabin Nanda
Enter Mark :
7.9
Enter a Name :
Tikan Pati
Enter Mark :
8.3
Enter a Name :
Debabrata Kar
Enter Mark :
6.7
***** STUDENT's DATA AVAILABLE :
Name : Tikan Pati Mark : 8.3

278
Name : Nabin Nanda Mark : 7.9
Name : Debabrata Kar Mark : 6.7

15.1.7 SortedMap
It is a interface which provide facility to store element with unique keys and the keys are
going to be in sorted order. The methods available in SortedMap are:
Set headset(Object to) - Returns the keys available upto the object specified.
Set tailSet(Object from) - Returns the keys available from the object specified
till the end.
Set subset(Object from, Object to)- Returns the keys available in between the form
object and to object.
The SortedMap interface can implemented through TreeMap class.

Example 15.6 Write a program to read all lines from a file and arrange the line in sorted order,
and display it in console.
import java.io.*;
import java.util.*;
public class ReadFile
{
public static void main(String arg[ ]) throws Exception
{
FileReader fr = new FileReader("data.txt");
BufferedReader br = new BufferedReader(fr);
TreeSet line = new TreeSet( );
String str;
while((str = br.readLine( ))!=null)
{
line.add(str.trim( ));
}
Iterator it = line.iterator( );
while(it.hasNext( ))
{
System.out.println(it.next( ));
}
}
}

15.1.8 Vector
This is a class which provides facility to store elements of any amount and any type
with index associated for each elements.
Constructor of Vector class:
vector( ) – Creates a vector of initial size(10) and increment as (10).
vector(initial size) – Creates a vector of specified initial size and increments as 10.
vector(initial size, increment) – Creates a vector of specified initialize and increments.

279
Methods of Vector class :
void add(Object element)- add an element into the specified index.
void addAll(Collection elements) – Total collection is added.
void remove(Object element) – Remove the particular element.
int size( ) – To find size of vector.
Objcet get(int index) – To read an element.
void addElement(Object element) – Add an element in the last position.
void replace(int index, Object element) – To replace an element.
int indexOf(Object element) – To search an element.
Example: Vector v = new Vector( );
v.add(1, “Hello”);
v.add(“Hello”);

Example 15.7 A demo program to Vector class.


import java.util.*;
import java.io.*;
public class VectorDemo
{
public static void main(String arg[ ])throws Exception
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
Vector Student = new Vector(10,3);
for(int i = 0; i<2; i++)
{
System.out.println("Enter a Student Name :");
String k = br.readLine( );
Student.add(i,k);
}
for(int i = 0; i<Student.size( );i++)
{
String v = (String)Student.get(i);
System.out.println("Name : "+v);
}
}
}
D:\java20\util>java VectorDemo
Enter a Student Name :
Tikan Pati
Enter a Student Name :
Paradeep Mishra
Name : Tikan Pati
Name : Paradeep Mishra

280
15.1.9 Using System’s Date and Time
For using System‟s date and time various classes are provided by java.util package.
The Calender class and GregorianCalender are used for finding System‟s current date and time
where as Calender class is a abstract class. The available constructors for GregorianCalender are:
Constructor:
GregorianCalender( ) – System‟s current date and time.
GregorianCalender(int year,int month,int day);
GregorianCalender(int year,int month,int day,int hour);
GregorianCalender(int year,int month,int day,int hour,int minute,int second);
Methods of GregorianCalender are:
int get(int Calender_Constant)
Example: GregorianCalender gc = new GregorianCalender( );
int y = gc.get(Calender.YEAR);
Calender Constant:
Calender.YEAR
Calender.MONTH
Calender.HOUR
Calender.MINUTE
Calender.DAY-OF-WEEK [0 – SUNDAY, 6 – SATERDAY]
Date Class:
Use the Date class to create and manipulates calendar dates by using system-independent
technique. The Date class consists of two constructors.
- Date( )
- Date(“YY/mm/dd)

Example 15.8 Reading System date.


import java.util.*;
public class Timer1
{
public static void main(String arg[ ])
{
Date d = new Date();
System.out.println(d);
}
}
Output: Fri Jul 20 20:25:40 IST 2012

Example 15.9 Alternate approach to finding System date.


import java.util.*;
public class Timer2
{
public static void main(String arg[ ])
{
GregorianCalendar gc = new GregorianCalendar( );
int h = gc.get(Calendar.HOUR);
int m = gc.get(Calendar.MINUTE);

281
int s = gc.get(Calendar.SECOND);
System.out.println(h+" : "+m+" : "+s);
}
}
D:\java20\util>javac Timer2.java
D:\java20\util>java Timer2
7 : 20 : 3

15.1.10 Random
The Random class is used for generating random number.

Summary

The java.util package contains the collection framework, event model and several utility
classes. Classes in java.util are: Dictionary, Hashtable, Stack and Vector. A collection is an
object that represents a group of objects such as vector class. The advantage of collection frame
work (i) to reduce programming effort (ii) increase performance in implementation. There are six
collection interfaces like List, Set, Map etc. List is an ordered collection of elements and where
these elements can be accessed using the index. This can provide facility to insert duplicate
element. Set is a collection that contains no duplicate element. It performs the operations like the
list. Although the Set can not contain duplicate element but it contains null value. A map can not
contain duplicate keys. The Map interface provides three collection views Arrays, Hashtable,
Vector etc. HashTable is a datastructure; it stores the key and the associated values in a hash
table. Vector is basically a growable array of objects. It is similar to an array. The components
can be accessed using an integer index. The size of the vector can be grown or can be shrinking
according to the user need.

282
Review Question

15.1 What is collection framework?


15.2 Name three classes of java.util package.
15.3 What are the advantages of collection framework?
15.4 What are the interfaces in the collection framework?
15.5 What is vector class?
15.6 Which classes supports data structures?
15.7 How do you create an instance of Set? How do you insert a new element in a set?
15.8 Suppose that Set1 is a Set that contains the Strings “red”, “yellow”, “green” and that Set2 is
another set that contains the Strings “red”, “yellow”, “blue”. Answer the following questions:
(i) What are Set1 and Set2 after executing Set1.addAll(Set2)?
(ii) What are Set1 and Set2 after executing Set1.add(Set2)?
(iii) What are Set1 and Set2 after executing Set1.removeAll(Set2)?
(iv) What are Set1 and Set2 after executing Set1.remove(Set2)?
15.9 What are the difference between ArrayList and LinkedList? Are all the methods in ArrayList
also in LinkedList? What methods are in LInkedList but not in ArrayList?
15.10 How do you create a set or list from an array of objects?
15.11 How do you create an instance of Vector? How do you add or insert a new element into a
vector? How do you remove an element from a vector? How do you find the size of a vector?
15.12 How do you create an instance of Map? How do you add an entry consisting of an element
and a key into a map? How do you remove an entry from a map? How do you find the size of a
map? How do you traverse entries in a map?
15.13 Write a program that reads word from a text file and displays all the nonduplicate words in
ascending order. The text file is passed as a command-line argument.
15.14 Write a program that lets the user enter number from a graphical user interface and display
them in a text area. Use a linkedlist to store the numbers. Do not store duplicate numbers. Add
the buttons Sort, Shuffle, and Reverse to sort, shuffle, and reverse the list.
15.15 Which method can you use to sort the elements in an ArrayList or a LinkedList? Which
method can you use to sort an array of Strings?
15.16 Which method can you use to perform binary search for elements in an ArrayList or
LinkedList? Which method can you use to perform binary search for an array of Strings?

283
Networking
16.0 INTRODUCTION
Data communications between remote parties can be achived through a process call,
networking, involving the connection of computers, media, and networking devices. When we
talk about networks, we need to keep in mind three concepts: distributed processing, network
criteria, and network structure. To communicate between two computer the Open Systems
Interconnection (OSI) model was designed by the International Organization for Standardization
(ISO). It has seven-layer model as shown in Figure 16.1.

USES OSI-LAYER EXAMPLE

Facilities 7. Application HTTP, FTP,…,telnet

Data transformation 6. Presentation SSL, XDR

Recovery, Synchronize 5. Session RPC, RMI, …

Reliability, multiplex 4. Transport TCP, UDP

Routing 3. Network IP, ICMP, …

Error/Flow Control 2. Data link Device Driver, HDLC,


LLC, …..

Connection, volts, wire 1. Physical RJ45, …

Figure 16.1 OSI Model


- The physical layer is the user connected computers having network devices.
- The data link layer is responsible for delivering data units from station to the next
without errors.
- The network layer is responsible for the source-to-destination delivery of a packet across
multiple network links.
- The transport layer is responsible for the process-to-process delivery of the entire
message.
- The session layer is designed to establish, maintain and synchronize the interaction bet-
ween communicating systems.

284
- The presentation layer was designed to handle the syntax and semantrics of the inform-
ation exchanged between the two systems.
- The application layer enables the users to access the network.
The physical, data link, and network layers are the network support layers. The
application layer is the user support layer. The transport layer links the network support layer and
user support layer. Computers running on the Internet, communicate to each other using either
the Transmission Control Protocol (TCP) or User Datagram Protocol (UDP). When we write
Java programs that communicate over the network, our programming is present at the application
la-yer.

16.1 PROCESS-TO-PROCESS DELIVERY


The data link layer is responsible for delivery of frames between two neighboring nodes
over a link. This is called node-to-node delivery. The network layer is responsible for delivery of
datagrams between two hosts. This is called host-to-host delivery. Communication on the Inter-
net is not defined as the exchange of data between two nodes or between two hosts. Real
communication takes place between two processes (application programs). We need process-to-
process delivery. However, at any moment, several processes may be running on the source host
and several on the destination host. To complete the delivery, we need a mechanism to deliver
data from one of these processes running on the source host to the corresponding running on the
destination host.
The transport layer is responsible for process-to-process delivery, the delivery of a packet,
part of a massage, from one process to another. Two processes communicate in a client-server
relationship. Figure16.2 shows three types of deliveries and their domains.
Processes Processes
… … … …
… … … …
●●●● ●● ●●●●
… … … …

Node-to-Node Node-to-Node Node-to-Node

Host-to-Host

Process-to-Process

Figure 16.2 Types of deliveries

There are two widely used transport-layer protocol in the Internet:


TCP (Transmission Control Protocol)
Connection Oriented (see Figure 16.3)

285
Reliable due to
Error and flow control
Order guaranted
Delivery guaranted
UDP (User Datagram Protocol)
Connection less Packet/datagram based (see Figure 16.4)
Not reliable due to
Losses, duplicates,… etc
Order of arrival not guaranted.
Delivery not guaranted.

Server Client

bind( )
Socket
listen

connect
accept

Blocks until connection from client


Write( )

read
Connection establishment
Process request

Write( ) read( )

Figure 16.3 Connection Oriented Protocol

16.2 CLIENT-SERVER PARADIGM


Although there are several ways to achieve process-to-process communication, the
most common one is the client-server paradigm. A process on the local host, called a client,
needs services from a process usually on the remote host, called a server.

16.2.1 Ports
Whenever we need to deliver something to one specific destination among many, we
need an address. At the data link layer, we need MAC address to choose one node among several
nodes, if the connection is not point-to-point. At the network layer, we need an IP address to
choose one host among millions. At the transport layer, we need a transport layer address, called
a port number, to chose among multiple process running on the destination host.

286
Server Client

Socket( )
bind( )

Bind( )

Sendto( )

Recvfrom( )

Recv from
Blocks until data
Data (reply)
Receive from client

Process request

Write( )

Figure 16.4 Connection less protocol


In the Internet model, the port numbers are 16 bit integers between 0 and 65,535. Standardized
ports are reserved for some application as:
HTTP (port 80) DNS (port 53) RPC (port 111)
Echo (port 7) Telnet (port 23) TFTP (port 69)
Daytime (port 13) POP3 (port 110) SNMP (port 162)
SMTP (port 25) SNMP (port 161)
So we can use ports in between 1024-65,535 for our own applications. Administrator privileges
are required for working with ports in the range 0-1023.

Sockets:
Process-to-process delivery needs two identifiers, IP address and port number, at each end
to make a connection. The combination of an IP address and port number is called a socket
address as shown in figure16.5.
IP address Port number
192.168.10.3 . 69

192.168.10.3 69

Socket address
Figure 16.5 Socket address

287
- A socket is an end point of a communication link which determined by local remote host
address and port as shown Figure 16.6.
- A computer is identified by its 32 bit IP address, which IP uses to deliver data to the right
computer on the network.
Example: 192.1.1.1
docs. rin.edu
- Ports are identified by a 16 bit number, which TCP and UDP use to deliver the data to the
right application on the computer.

TCP

or

UDP

Port# Data
ports packet

Figure 16.6 End point connection

16.3 TCP BASED COMMUNICATION


The reliable, but complex transport-layer protocol in the Internet is called Transmission
Control Protocol (TCP). TCP is called a stream connection-oriented and reliable transport proto-
col. It adds connection-oriented and reliability features to the services of IP. TCP allows the
sending process to deliver data as a stream of bytes and the receiving process to obtain data as a
stream of bytes. TCP creates an environment in which the two processes seem to be connected
by an imaginary tube that carries their data across the Internet. The sending process produces the
stream of bytes, and the receiving process consumes it.

java.net.ServerSocket (required for only Server end)


This class provides facility to open a port or create Socket on the specified port.
java.net.Socket (required for both Server and Client end)
This class provides facility to communicate with the destination by using InputStream or
OutputStream.
Both these classes are presents java.net package.
Java Server Creation Process
(1) Create an instance of java.net.ServerSocket by using a port number of the Server‟s
machine.
Example: ServerSocket ss = new ServerSocket(2000);
(2) Create an instance of java.net.Socket class by using accept( ) method of ServerSocket
instance.
Example: Socket sc = ss.accept( );

288
(3) If Server needs writing then use OutputStream of the Socket instance. If server needs
reading then use InputStream of Socket instance.
For Reading
InputStream is = sc.getInputstream( );
For Writting
OutputStream os = sc.getOutputStream( );
(4) Reading or Writing data to the client using appropriate read( )/write( ) method of the
InputStream/OutputStream.
(5) Close the Socket using close( ) method of the Socket class.
All the above said steps throws SocketException and IOException.

Example16.1(a) Creating a Server.


import java.net.*;
import java.io.*;
public class Server
{
public static void main(String arg[ ])throws Exception
{
ServerSocket soc = new ServerSocket(5000);
Socket sc=soc.accept( );
OutputStream os = sc.getOutputStream( );
PrintStream out = new PrintStream(os);
out.println(arg[0]);
sc.close( );
}
}

Client Creation Process


(1) Locate the server‟s socket using the Socket class instance. The Socket class constructor
accepts two parameters as Server‟s IP address and its port number as its first and second
parameter.
Example: Socket sc1 = new Socket(“192.168.10.2”,5000);
Socket sc2 = new Socket(“localhost”,5000);
(2) Get the InputStream of Socket‟s instance to read from Server or get the OutputStream of
the Socket‟s instance to write the server.
(To know the IP address of Server you use the command ipconfig as c:\>ipconfig )
For Reading
InputStream is = sc.getInputStream( );
For Writing
OutputStream os = sc.getOutputStream( );
(3) Use appropriate read( )/write( ) method of InputStream or OutputStream to read/write
from server.
(4) Close the Socket by using close( ) method of Socket instance.

289
Figure 16.7 ServerSoket and Socket Communication

Example 16.1(b) Create a Client Socket connected to the appropiate server's port and get a
acknowl-edgement form it.
import java.net.*;
import java.io.*;
public class Client
{
public static void main(String arg[])throws Exception
{
Socket sc=new Socket("localhost",5000);
InputStream is = sc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String str = br.readLine();
System.out.println("Server sends..."+str);
sc.close();
}
}

Server Command Prompt Client Command Prompt

16.3.1 InetAddress class


The InetAddress class finds the host name and IP address. The java.net package
provides the following addressing related classes:
InetAddress
for IP address, which is either is 32 bits or 128 bits unsigned numb-
Inet4Address .
er used by IP, the lower-level protocol like TCP and UDP are built.
Inet6Address
290
SocketAddress
InetSocketAddress

InetAddress

Inet4Address Inet6Address
Figure 16.8 InetAdress class
You cannot create InetAddress objects by invoking the InetAddress constructor, instead invoke
static methods of the InetAddress class. The static methods of InetAddress class are:
getInetAddress( )
getHostName( )
getHostAddress( )
getByName( )

Example 16.2 Finding host name of a Web page present in the Internet.
import java.net.*;
public class Hostname
{
public static void main(String arg[ ])throws Exception
{
InetAddress ip = InetAddress.getByName(arg[0]);
System.out.println("Host : "+ip.getHostName( ));
System.out.println("IP : "+ip.getHostAddress( ));
}
}

16.4 UDP SOCKETS


The simple unreliable transport-layer protocol in the Internet is called the User
Datagram Protocol (UDP). It does not add anything to the services of IP except for providing
process-to-process communication instead host-to-host communication. UDP is a connection,
unreliable protocol that has no flow and error control. It uses port numbers to multiple data from
the application layer as shown in Figure 16.9.

Server Client

Application 5000 7000 Application

Datagram
Figure 16.9 UDP Sockets Communication

291
Creating UDP Server:
(1) Create the instance of java.net.DatagramSocket by using a port number of Server‟s
machine as:
DatagramSocket ds = new DatagramSocket(5000);
(2) Create an array of bytes to provide it for the instance of java.net.DatagramPacket. The
DatagramPacket have a constructor which takes 4 arguments as:
DatagramPacket(byte b[ ],int b.length,InetAddress client_IP, long port_number)
Example:
byte m[ ] = arg[0].getBytes( );
DatagramPacket dp= new DatagramPacket(b,b.length,InetAddress.getLocalHost( ) ,7000);
(3) Send the Datagram to the client by using send( ) method of DatagramSocket instance as:
ds.send(dp)

Example 16.3(a) Creating UDP Server.


import java.net.*;
import java.util.*;
public class UdpServer
{
public static void main(String arg[ ])throws Exception
{
DatagramSocket ds = new DatagramSocket(5000);
GregorianCalendar gc = new GregorianCalendar( );
String str = " "+gc.get(Calendar.YEAR);
str = str+"/"+gc.get(Calendar.MONTH);
str = str+"/"+gc.get(Calendar.DATE);
byte b[ ] = str.getBytes( );
DatagramPacket dp=new DatagramPacket(b,b.length,InetAddress.getLocalHost( ),7000);
ds.send(dp);
System.out.println("Data Sent ......");
}
}
Creating UDP client:
(1) Create the instance of DatagramSocket by providing port number of client‟s machine as:
DatagramSocket ds = new DatagramSocket(7000);
(2) Create an empty array of bytes to receive data from the Server through an instance of
DatagramPacket as
byte b[ ]= new byte[1000];
DatagramPacket dp = new DatagramPacket(b,b.length);
(3) Receive the datagram from the server by using receive( ) method of DatagramSocket
instance as:
ds.receive(dp);

Example 16.3(b) Creating UDP Client.


import java.net.*;
import java.util.*;
public class UdpClient

292
{
public static void main(String arg[ ])throws Exception
{
DatagramSocket ds = new DatagramSocket(7000);
byte b[ ] = new byte[1000];
DatagramPacket dp = new DatagramPacket(b,b.length);
ds.receive(dp);
String str = new String(b,0,b.length);
System.out.println("Server Sendes : "+str);
}
}

UDP Sever Command Prompt UDP Client Command Prompt

16.5 LOCATING NETWORK RESOURCES


Java provides various classes to locating or identifying network resources on the
Internet. These classes are
URI URLClassLoader HttpURLConnection
URL URLConnection JarURLConnection
URLStreamHandler
The most commonly used classes are URI, URL, URLConnection and HttpURLConnection.
(i)URI (Uniform Resources Identifier)
URI identifies a resource but not necessarily a locator for that resource.
(ii)URL (Uniform Resource Locator)
It is subclass of URI. URL tells how to access the resource, while a URI may or may
not. The URN (Uniform Resource Name) is another subset of URI, but no java class exits for it.
URL Syntax:- protocol://host:port/file
Example: http://www.gmail.com/index.html
The Constructors of URL class are:
(a) URL (full URL)
Example: URL (http://www.king.com/welcome.html);
(b) URL (base-URL,relative-URL)
Example: URL burl = new URL(http://www.king.com);
URL rurl = new (burl, “welcome.html”);
(c) URL (protocol,base-URL,relative-URL)
Example: URL(“http”, www.king.com, “welcome.html”);
(d) URL (protocol,baseURL,port,relativeURL)
Example: URL(“http”, www.king.com, 80, “index.html”);
All the above four constructors throws MalformedURLException.
The methods of URL class are:
- getProtocol( )

293
- getHost( )
- getPort( )
- getFile( )
- URLConnection OpenConnection( )
(iii) URLConnection class
This is a class which can read or write data to a remote path. Once you make a
connection to a remote Server, you can use URLConnection to use the properties of remote
object.

Example 16.4 Finding URL of remote webpage.


import java.net.*;
import java.io.*;
import java.util.Date;
class UCDemo
{
public static void main(String arg[ ])throws Exception
{
int c;
URL hp = new URL(arg[0]);
URLConnection hpcon = hp.openConnection( );
long d = hpcon.getDate( );
if(d==0)
System.out.println("No date info");
else
System.out.println("Date:"+new Date(d));
int len = hpcon.getContentLength( );
if(len==-1)
System.out.println("Content length unavailable");
else
System.out.println("Content length : "+len);
//Displaying the contents of web page
if(len != 0)
{
System.out.println("= = = = = CONTENTS OF WEB PAGE = = = = = ");
InputStream input = hpcon.getInputStream( );
while((( c = input.read( ))!=-1))
{
if(c =='\n')
System.out.println( );
else
System.out.print((char)c);
}
}
else
{
System.out.println("No Content available");

294
}
}
}
D:\java20\networking>javac UCDemo.java
D:\java20\networking>java UCDemo file:///c:/test.html
No date info
Content length : 135
= = = = = CONTENTS OF WEB PAGE = = = = =
<html>
<body bgcolor="cyan">
<h1 >ROURKELA</h1>
</applet>
</body>
</html>

16.6 Whois
To opens a connection to a “whois” port on the InterNIC server, sends the command-
line argument down the socket, and then prints the data that is returned. InterNIC will try to look
up the argument as registered Internet domain name, then send back the IP address and contact
information for the site.

Example 16.5 Demonstrate Sockets.


import java.net.*;
import java.io.*;
public class Whois
{
public static void main(String arg[ ])throws Exception
{
int c;
Socket s = new Socket("internic.net",43);
InputStream in = s.getInputStream( );
OutputStream out = s.getOutputStream( );
String str = (arg.length == 0 ?"google.com":arg[0])+"\n";
byte buf[ ] = str.getBytes( );
out.write(buf);
while(( c = in.read( ))!=-1)
{
System.out.println((char)c);
}
s.close( );
}
}
The above example gives information google.com if no data supply as command line.

295
16.7 A CLIENT AND SERVER EXAMPLE

This example presents a client programs and a server program. The client sends data to a server.
The Server receives the data, uses it to produce a result, and then sends the result back to the
client. The client displays the result on the console. In this example, the data sent from the client
comprise the radius of a circle and the result produced by the server is the area of the circle see
Figure 16.10.

area
Server Client

Radius
Figure 16.10 The Client sends the radius to the server;
The Server computes the area and sends it to the client.

Figure 16.10 the client sends the radius to the server; the server computes the area and sends it to
the client.The client sends the radius through a DataOutputStream on the output stream socket
and the server receives the radius through the DataInputStream on the input stream socket, as
shown in Figure 16.11(a). The server computes the area and sends it to the client through a
DataOutputStream on the output stream socket, and the client receives the area through a
DataInputStream on the input stream socket, as shown in Figure 16.11(b). The server and client
are given in Example 16.6(a) and 16.6(b).

Server Client
radius radius

DataInputStream DataOutputStream

Socket.getInputStream Socket.getOutputStream

socket socket

Network

Figure 16.11(a) The Client sends the radius to the server

296
Server Client
area area

DataOutputStream DataInputStream

Socket.getOutputStream Socket.getInputStream

socket
socket

Network

Figure 16.11(b) The Server sends the area to the Client

Example 16.6(a) Creating a Server frame.


import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;

public class Server extends JFrame


{
// Text area for displaying contents
private JTextArea jta = new JTextArea( );
public static void main(String[ ] args)
{
new Server( );
}

public Server( )
{
// Place text area on the frame
setLayout(new BorderLayout( ));
add(new JScrollPane(jta), BorderLayout.CENTER);
setTitle("Server");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // It is necessary to show the frame here!
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
jta.append("Server started at " + new Date( ) + '\n');

297
// Listen for a connection request
Socket socket = serverSocket.accept( );
// Create data input and output streams
DataInputStream inputFromClient = new
DataInputStream(socket.getInputStream( ));
DataOutputStream outputToClient = new
DataOutputStream(socket.getOutputStream( ));
while (true)
{
// Receive radius from the client
double radius = inputFromClient.readDouble( );
// Compute area
double area = radius * radius * Math.PI;
// Send area back to the client
outputToClient.writeDouble(area);
jta.append("Radius received from client: " + radius + '\n');
jta.append("Area found: " + area + '\n');
}
}
catch(IOException ex) {
System.err.println(ex);
}
}
}

Example 16.6(b) Creating Client frame.


import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client extends JFrame
{
// Text field for receiving radius
private JTextField jtf = new JTextField( );
// Text area to display contents
private JTextArea jta = new JTextArea( );
// IO streams
private DataOutputStream toServer;
private DataInputStream fromServer;
public static void main(String[ ] args)
{
new Client( );
}
public Client( )
{

298
// Panel p to hold the label and text field
JPanel p = new JPanel( );
p.setLayout(new BorderLayout( ));
p.add(new JLabel("Enter radius"), BorderLayout.WEST);
p.add(jtf, BorderLayout.CENTER);
jtf.setHorizontalAlignment(JTextField.RIGHT);
setLayout(new BorderLayout( ));
add(p, BorderLayout.NORTH);
add(new JScrollPane(jta), BorderLayout.CENTER);
jtf.addActionListener(new ButtonListener( )); // Register listener
setTitle("Client");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // It is necessary to show the frame here!
try {
// Create a socket to connect to the server
Socket socket = new Socket("localhost", 8000);
// Create an input stream to receive data from the server
fromServer = new DataInputStream(socket.getInputStream( ));
// Create an output stream to send data to the server
toServer = new DataOutputStream(socket.getOutputStream( ));
}
catch (IOException ex)
{
jta.append(ex.toString() + '\n');
}
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
try {
// Get the radius from the text field
double radius = Double.parseDouble(jtf.getText( ).trim( ));
// Send the radius to the server
toServer.writeDouble(radius);
toServer.flush( );
// Get area from the server
double area = fromServer.readDouble( );
// Display to the text area
jta.append("Radius is " + radius + "\n");
jta.append("Area received from the server is "+ area + '\n');
}
catch (IOException ex)
{
System.err.println(ex);

299
}
}
}
}

(Server Frame) (Client Frame)

Summary

- Java supports stream sockets and datagram sockets. Stream Sockets use TCP for data
transmission, where as datagram sockets use UDP.

- To create a server, you must first obtain a server socket, using new SeverSocket (port).
After a server socket is created, the server can start to listen for connections. Using the
accept( ) method on the server socket. The client requests a connection to a server by
using new Socket(ServerName, port) to create a client socket.

- In java.net package the URL class is used to access information in the web.

300
Review Question
16.1 Where to use TCP and UDP protocols?
16.2 Define port, IP and Sockets.
16.3 Write a TCP base java program for client-server paradigm.
16.4 Write a graphical (awt) client-server paradigm.
16.5 How InetAddress class can be used?
16.6 Write a UDP based java program for client-server paradigm.
16.7 How TCP is differing from UDP?
16.8 In which layer TCP and UDP work? And how they are work?
16.9 What is the use of URL class?
16.10 Write a program and use InetAddress class to obtain IP address?

301
JDBC
17.0 INTRODUCTION
In today‟s scenario, many enterprise level applications need to interact with for storing
application specific information. We can store applications in file or a data base like Oracle,
MySQL, Sybase, etc. The advantages of database over file system are:
- In database we can be removed data redundancy (repeation of data) and inconsistency
(inaccuracy) problems.
- In database we can easily access the data from the database.
- Data isolation problem can be removed by using database. Data are scattered in various
files and files may be in different formats. So writing the new application program to
retrieve the appropriate data is so difficult in file system.
- Integrity (restriction/rules/conditions) problem can be removed using database.
- Atomicity problem can be removed. If any system failure occurs but the data should be in
consistent state.
- Concerned access anomalies can be removed. For the faster response many systems
permit the users to update the data simultaneously. In file system, the concurrent update
may result inconsistent data but in database it does not occur.
- Security problems can be removed. Not every user of the database should be able to
access the data. Only the authorized users can access the database.

JDBC is a technology to communicate with DBMS from a Java program. JDK provides a
set of API to communicate with DBMS (Database Management System) with the help of
Drivers. Drivers are an application which makes available DBMS for the external applications
like the Java programs. All DBMS venders provide drivers and as well as operating system
contains default drivers for some of the DBMS. Before you proceeding JDBC, you must have
sufficient knowledge in SQL and DBMS.

17.1 JDBC (JAVA DATA-BASE CONNECTIVITY)


The Java API for developing Java database applications is called JDBC. JDBC is the
trademarked name of a Java API that supports Java programs that access relational databases.
JDBC provides Java programmers with a uniform interface for accessing and manipulating a
wide range of relational databases. Using the JDBC API, applications written in the Java
programming language can execute SQL statements, retrieve results, present data in a user-
friendly interface, and propagate changes back to the database. The JDBC API can also be used
to interact with multiple data sources in a distributed, heterogeneous environment. The
relationships between Java programs, JDBC API, JDBC drivers, and relational databases are
shown in Figure 17.1. The JDBC API is a set of Java interfaces and classes used to write Java
programs for accessing and manipulating relational database.
Since a JDBC driver servers as the interface to facilitate communications between JDBC and a
proprietary database, JDBC drivers are database specific and are normally provided by the
database vendors. You need MySQL database, and Oracle JDBC drivers to access the Oracle
database. For the Microsoft Access database, use the JDBC-ODBC bridge driver included in
JDK. ODBC is a technology developed by Microsoft for accessing databases on the Window
platform. An ODBC driver is preinstalled on windows. The JDBC-ODBC bridge driver allows a
Java program to access any ODBC data source.

302
Java Programs

JDBC API

JDBC-ODBC
MySQL JDBC Oracle JDBC
Bridge Driver
Driver Driver
Microsoft ODBC
Driver

Local or Remote Local or Remote


Microsoft
MySQL DB Oracle DB
Access DB

Figure 17.1 Java Programs access and manipulate databases through JDBC Drivers.

17.1.1 Components of JDBC


JDBC has four main components through which it communicates effectively with the
database. These components are:
(i) The JDBC API
The JDBC API provides the methods and interfaces for an easy and effective
communication with databases. It provides a standard for connecting the database to the
application. The application user processes the SQL commands according to its need and
sends back the result to the user. The JDBC API provides two main packages, java.sql
(for J2SE application) and javax.sql (for J2EE application), to interact with the databases.

(ii) The JDBC DriverManager


The DriverManager is one of the most important components of JDBC. It
manages the different types of database drivers used for Java application. The main
objective of the DriverManager is to load database specific drivers in the application. It is
also used to select the most appropriate database specific driver from the previously
loaded drivers when a new connection to a database is established. DriverManager is also
used to make database specific calls to the database to process the user requests.

(iii) The JDBC Test Suite


The JDBC test suite is used to ensure proper functioning of the JDBC driver.
The Suite tests the JDBC driver based on the JDBC technology. It also ensures the
compliance of JDBC driver with the Java application.

(iv) The JDBC-ODBC Bridge


The JDBC-ODBC Bridge is used to connect the database drivers to the specific
databases. This driver translates JDBC method calls to ODBC function calls. The bridge
is used to implement JDBC for any database that uses on ODBC driver, you can import.

303
17.2 TYPES OF JDBC DRIVERS
The JDBC driver (third party vender implementation) has to be plugged in to the drive,
which can be done dynamically at runtime. This ensures that the Java application is vender
independent. Therefore, if we want to communicate with any data store through JDBC, we need
a JDBC driver, which intelligently communicates with the respective data store. Currently, we
have 220 plus JDBC drivers available in the market, which are designed to communicate with
different data stores. Some of these drivers are Pure Java drivers and are portable for all the
environments where as others are partly Java drivers and require some libraries to communicate
with the database. The different types of drivers available in JDBC are listed in Table 17.1.

JDBC Driver Description


Type-1 Driver This type of drivers are Bridge Driver (JDBC-ODBC bridge)
Type-2 Driver This driver is partly Java and partly Native code driver.
Type-3 Driver It is a pure Java driver that uses a middleware driver for connect to a
database.
Type-4 Driver It is a Pure Java driver and is directly connected to a database.
Table 17.1 types of JDBC drivers

17.2.1 The Type-1 Driver (JDBC-ODBC Bridge)


The Type-1 driver acts as a bridge between JDBC and other database connectivity mechanisms,
such as ODBC. An example of this type of driver is the Sun JDBC-ODBC bridge driver. The
JDBC-ODBC bridge allows you to access database using the ODBC drivers. This driver helps
the Java programmers to use JDBC and program. Java applications used to communicate with
exiting data stores that support ODBC. It converts JDBC calls into ODBC calls and redirects the
request to the ODBC driver. The architecture of the Type-1 driver is shown in Figure 17.2.
As shown in Figure 17.2, Java application is programmed to JDBC API and will make a
request to the JDBC-ODBC bridge driver, that is, JDBC call, where the JDBC-ODBC bridge
driver is responsible to resolve the JDBC call and make an equivalent ODBC calls to the ODBC
driver. To do this JDBC-ODBC bridge driver uses ODBC API. Later, the ODBC driver
completes the request and sends the response to the JDBC-ODBC bridge driver. Now, the JDBC-
ODBC bridge driver converts the response and sends it to the requesting Java application in
JDBC standards. The Type-1 driver is generally used in the development and testing phases of
Java applications.
Native DBMS specific call
JDBC call Native ODBC call

SP API Oracle
JDBC API ODBC API
Java JDBC- ODBC
ODBC
Application Bridge SP API SQL Server
Driver
Driver

SP API Sybase

igure 17.2 JDBC Type-1 Architecture

304
Advantages of the Type-1 Driver
- Serves as single driver that can be used to interact with different data stores.
- Allows you to communicate with all the databases supported by the ODBC driver.
- Represents as a vender independent driver and is available along with (built-in) JDK.

Disadvantages of the Type-1 Driver


- Decreases the execution speed due to a more number of translations (includes
JDBC→ODBC →DB Native call).
- Depends on the ODBC driver due to which Java applications indirectly become
dependent on ODBC drivers.
- Requires ODBC binary code (or ODBC client library) that must be installed on every
client to access data from the database.
- The Type1 driver is not recommended for use when Java applications are required with
auto-installation applications, such as applets.

17.2.2 The Type-2 Driver (Java to native API)


The Type-2 driver converts JDBC calls in a client machine. The Type-2 driver follows a
2-tier architecture model, as shown in Figure 17.3.

JDBC call
Native call

JDBC API
DBMS Specific Native API Database
Java Type -2
Driver Server
Application

Client Side

Figure 17.3 JDBC Type-2 Architecture

Type-2 driver resides on the client along with the Java application. This driver
communicates directly with the database server. It requires the driver binary code to be present
on the JAVA client application. They do offer very much significant performance improvement
than JDBC-ODBC Bridge but again the main drawback is the driver must be installed on the
client machine.
Example:
OCI (Oracle Call Interface) – Allows you to communicate with the Oracle database server.
This driver converts JDBC calls into Oracle native libraries (OCI) calls.

17.2.3 The Type-3 Driver (Java to Network Protocol/All Java Driver)


Type-3 drivers are the right choice for three-tiered approach and they can only be
implemented with three-tier architecture. There are two portions of Type-3 drivers one is the
small JDBC driver who is responsible to pass the SQL commands to the application server.

305
Second section is the middle ware or so called the application server which passes the request to
database. Middle ware section can be type1 JDBC driver or a native code.

JDBC Call Server specific Native DBMS

Middleware SP API Oracle


JDBC Server
Java
SP API SQL Server
Appli- Type-3 Server Driver
cation
Driver
SP API
Client side Sybase

Figure 17.4 Type-3 Driver Architecture

Advantages of the Type-3 Driver


- Serves as pure Java drives and are auto downloadable.
- Does not require native libraries on the client machine.
- Allows a single driver to access multiple databases, implying that this driver is database
independent.
- Configures the database details in the middleware server; instead of providing these
details to the client.
- Allows to switch from one database to another without changing the client-side driver
classes.
- Follows the 3-tier model; thereby, allows you to access the database between the
networks and manage the database resources accurately.

Disadvantages of the Type-3 Driver

- Provides slow communication due to the increased number of network calls.


- Are more costly as compared to the other drivers.
Example: (i) IDS Driver - Listens for JDBC calls and converts them into IDS (Intrusion
Detection System) sever specific understandable network calls. The Type-3 driver communicates
over a socket to IDS server, which acts as a middleware server.
(ii) Weblogic RMI Driver – Listens for JDBC calls and sends the request from the client to the
middleware server by using the Remote Method Invocation (RMI) protocol. The middleware
server uses a suitable JDBC driver to communicate with a database.

17.2.4 The Type-4 Driver (Java to Database Protocol)


The Type-4 driver is a pure Java driver, which implements the database protocol to
interact directly with a database. It does not require any native database libraries to retrieve the
records from the database. The Type-4 driver translates JDBC calls into database specific
network calls. Type-4 drivers follow the 2-tier architecture model, as shown in Figure 17.5.

306
DB Specific
JDBC Call

DBMS Specific
JDBC API Network protocol
Java Type-4
Database
Application Driver
Server

Client Side

Figure 17.5 JDBC Type-4 Driver

As shown in Figure 17.5, the Type-4 driver prepares a DBMS specific network message and then
communicates with a database server over a socket. This type of driver is lightweight and is
generally known as thin driver.

Advantages of the Type-4 Driver


- Serves as a pure Java driver and are auto downloadable.
- Does not require native libraries to be installed on the client machine.
- Uses the database server specific protocol and thereby it is secure to use this driver.
- Does not require a middleware server.

Disadvantage:
The main disadvantage of the Type-4 driver is that it uses database specific proprietary
protocol and is DBMS vender dependent.
Examples:
- Thin Driver for Oracle from Oracle Corporation.
- Weblogic, mssqlserver4 for MSSQL server from BEA Systems.

Figure17.6 shows basic JDBC Architecture Diagram where the above four drivers are
implemented to communicate with the database. Depending upon the availability the
programmer can use one of the drivers among the four drivers as descrive above.

17.3 Developing Database Applications Using JDBC


The JDBC API consists of classes and interfaces for establishing connection with
databases, sending SQL statements to databases, processing the results of the SQL statements to
databases, and obtaining database metadata. Four key interfaces are needed to develop any
database.
(1) Loading Drivers
An appropriate driver must be loaded using the statement below before connecting to
a database.
Class.forName(“JDBC Driver class”);

307
JDBC-ODBC Bridge ODBC

JDBC-Native Native vendor


Driver
Data
Java
API Base
Program/ Manager Middle-
JDBC Net ware
Client

Pure Java Driver

Java Client Drivers Application Database


Server/ Server
Middle Tier

Figure17.6 JDBC Architecture Diagram

The various JDBC DRIVER classes are given in Table 17.2.

Database Driver class Source


Access Sun.jdbc.odbc.JdbcOdbcDriver Already in JDK
MySQL com.mysql.jdbc.Driver Companion website
Oracle Oracle.jdbc.driver.OracleDriver Companion website
Table 17.2 JDBC DRIVER classes

Example: Class.forName(“oracle.jdbc.driver.OracleDriver”);
For Oracle10g, the Oracle JDBC driver is contained in classes12.zip or objbc14.jar for
using type-4 drivers. So you must set path of oracle server as:
Variable name: CLASSPATH
Variable value: .;c\oracle\product\10.2.0\OraHome10\jdbc\lib\classes12.zip

(2) Establishing Connections


After the leading driver (step1) you must to connect to a database using the static
method getConnection(Database URL) in the DriverManager class as follows:
Connection con = DriverManager.getConnection(database-URL);
Where database-URL is the unique identifier of the database on the Internet. Some of the
JDBC URL are given in Table 17.3.
Database URL Pattern
Access jdbc:odbc:datasource
MySQL jdbc:mysql://hostname/dbname
Oracle jdbc:oracle:thin:@hostname:port#:OracleDBSID

Table 17.3 JDBC URLs

308
Example:
Connection con = DriverManager.getConnection(“jdbc:oracle:thin:@127.0.0.1:1521:DB1”,
“scott”, “tiger”);
- 127.0.0.1 is the local system IP where oracle is installed or you can give the server name
or localhost.
- 1521 is the port number.
- DB1 is SID (global Database name), given by administrator when Oracle Server is
configure and it can be any name, here it is DB1.
(3) Creating Statements
Create a statement to execute SQL by using createStatement( ) method of
Connection class (created at step-2) as:
Statement stmt = con.createStatement( );
(4) Executing Statements
Execute the required SQL by using appropriate method of Statement class. If
DML/DDL then use executeUpdate( ) method. If select then use executeQuery( ) method
which returns the records using “ResultSet”.
Example:
ResultSet rs = stmt.executequery(“select * from dept”);
(5) Processing ResultSet
The ResultSet maintains a table whose current row can be retrieved. The initial row
position is null. You can use next( ) method to move to the next row and the various
getxxx( ) method is used to retrieve values from a current row, for example getInt( ),
getString etc.
Example: System.out.println(getInt(“DEPTNO”));
Using the five steps now you can connect to a database say Oracle10g. The Example
17.1 shows how to connect Oracle Server using Type-4 driver.

Example 17.1 Connecting Oracle database using Type -4 driver


import java.sql.*;
public class Testconnection1
{
public static void main(String arg[ ])throws SQLException,ClassNotFoundException
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("Jdbc:Oracle:thin:@127.0.0.1:1521:DB1","scott","tiger");
Statement stmt=con.createStatement( );
ResultSet rs=stmt.executeQuery("select *from DEPT");
while(rs.next( ))
{
System.out.println(rs.getInt("DEPTNO")+" "+rs.getString("DNAME"));
}
con.close( );
}
}
D:\java20\jdbc>javac Testconnection1.java
D:\java20\jdbc>java Testconnection1
67 fog

309
45 mech
60 mech
10 ACCOUNTING
20 RESEARCH
30 SALES
40 OPERATIONS

In the previous section, we discussed about JDBC and its APIs. Figure 17.7 discuss how to
use JDBC to obtain a connection and communicate with the database:

Class.forName(driverClassName)

Connection con=DriverManager.getConnection(url,username,password)

Statement stmt=con.createStatement( )

rs=stmt.executeUpdate();

con.close()

Figure 17.7 Creating and using connection

17.3.1 Exploring the Methods of Statement


The following are some of the methods supported by the Statement object:

(1) executeUpdate(String sqlStatement)


This method executes the SQL Statement that creates, inserts, updates, and deletes
the database. The executeUpdate( ) method returns the int value that specifies the number
of records affected by the executed SQL statements.
Example: Statement stmt = con.createStatement( );
String sql = “insert into dept values(50, „CSE‟, „Rourkela‟)”;
try{
int count = stmt.executeUpdate(sql);
}
catch(SQLException e){ }

(2) executeQuery(String sqlStatement)


The executeQuery(String) method is used to execute the Sql statement to query the
database. For example, if you execute SELECT statement to retrieve the records from the
database. This method returns the query results in the form of ResultSet object. The

310
ResultSet object contains the group of results generated after executing the specified SQL
query.
Example: Statement stmt = con.createStatement( );
String query = “SELECT * from dept”;
ResultSet rs = stmt.executeQuery(query);

(3) execute(String sqlStatement)


The execute( ) method executes any SQL statement used to update or query the
database. This method returns a boolean value indicating whether or not the given SQL
statement has generated a ResultSet. If the boolean value evaluates to true, the ResultSet
is generated, otherwise it implies that the SQL statement has not generated a ResultSet.
(4) getResultSet( )
The getResultset( ) method returns the current ResultSet associated with a Statement
object. This method is used along with the execute( ) method.
Example: Statement stmt = con.createStatement( );
String sql = “SELECT * from dept”;
if(stmt.execute(sql))
{
ResultSet rs = stmt.getResultSet( );
}
(5) getUpdateCount( )
The getUpdateCount( ) method returns the number of records affected after executing
an SQL statement using the execute method.
17.3.2 Creating DSN
For using Type-1 driver you must follow the given steps
(i) Create a table in a database as per your requirement.
(ii) Configure the Data Source Name(DSN) of the database for using any Java application
to connect to the database.
Configuring DSN:
The Type-1 driver requires a DSN to connect to the database. You need to follow the
following steps to create DSN:
(i) Select Control Panel→ Administrative tools→ Data Source(ODBC).
The ODBC Data Source Administrator dialog box appears, as shown in Figure 17.8(a).

Figure 17.8 (a)

311
(ii) Click the Add button to add the data source to which the driver is to be connected.
The create New Data Source dialog box appears, as shown in Figure 17.8(b).

Figure 17.8(b)

(iii) Select the required driver. In this case, you have selected Microsoft ODBC for
Oracle, because you want to connect to the Oracle database.
(iv) Click the Finish button (Figure 17.8(b)) to open the Microsoft ODBC for Oracle
Setup dialog box, as shown in Figure 17.8(c ).

Figure 17.8(c)
(v) Enter the details (Figure 17.8(c )) in the following fields:
Data Source Name – Enter the name that your application uses within the JDBC
URL.
Description – Enter a brief description about DSN. This field is optional.
User Name – Enter the database user name (Optional).
Server – Enter the host string of the database server. The Server field is required if
oracle database server is installed on a different computer.
(vi) Click the ok button (Figure 18(c ))to finalize the setup.
Example 17.2 Connecting Oracle database using DSN

import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.*;

312
public class TestConnection2
{
public static void main(String[ ] args) throws Exception
{
String sql=null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("Jdbc:Odbc:jkm","scott","tiger");
sql = "select * from DEPT";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery( );
while(rs.next( ))
{
System.out.println("deptno:"+rs.getInt("DEPTNO"));
}
}
catch(SQLException e)
{
e.printStackTrace( );
}
catch(Exception ex)
{
ex.printStackTrace( );
}
finally{
if(rs != null)
rs.close( );
if(pstmt != null)
pstmt.close( );
if(con != null)
con.close( );
}
}
}
D:\java20\jdbc>javac TestConnection2.java
D:\java20\jdbc>java TestConnection2
deptno:67
deptno:45
deptno:60
deptno:10
deptno:20
deptno:30
deptno:40

313
17.3.3 Working with the ResultSet Interface
A ResultSet is an interface packaged in the java.sql package and provided under the
JDBC core API. The java.sql.ResultSet interface is defined to describe an object, known as
ResultSet object, implemented by third-party vendor as a part of JDBC driver. The ResultSet
object represents the data in a tabular form that is retrieved by executing an SQL query. It
implies that a ResultSet object represents a table of data that is CURSOR returned by executing
an SQL query. The DBCURSOR is a buffer (cache) where the query result can be saved (it
means DBCURSOR is a place in the DB). A ResultSet object encapsulates the resultant tabular
data obtained when a query is executed. A ResultSet object holds zero or more objects, where
each of the objects represents one row that may span over one or more table columns. We can
obtain a ResultSet object by using the executeQuery( ) or getResultSet( ) method of a JDBC
statement object.
A. Describing the Methods of ResultSet:
The java.sql.ResultSet interface provides certain methods to work with the ResultSet
object. The ResultSet object supports various methods that include moving the cursor through
the rows represented by this object and read the data. Table 17.4 shows some of the most
commonly used methods in ResultSet.
Methods Description
absolute(int row) Moves the cursor to the given number of rows in a
ResultSet Object.
afterLast( ) Moves the cursor just after the last row in a
ResultSet object.
beforeFirst( ) Moves the cursor before the first row in a ResultSet
object.
cancelRowUpdates( ) Cancels all the changes made to the rows in a
ResultSet object.
clearWarnings( ) Clears all warning message on a ResultSet object.
close( ) Closes a ResultSet object and releases all the JDBC
resources connected to it.
deleteRow( ) Deletes the specified row from a ResultSet object, as
well as from the database.
first( ) Moves the cursor to the first row in a ResultSet
object.
getArray( ) Retrieves the value of the specified column from the
ResultSet object.
getAsciiStream( ) Retrieves a specified column in the current row as a
stream of ASCII characters.
getxxx( ) Retrieves the column values of the specified types
from the current row. The type can be any of the
Java pre-defined data types, such as int, Long, Byte,
character, String, double, or large object types.
getDate( ) Retrieves the specified column from the current row
in ResultSet and uses the given calendar to construct
the time in milliseconds. The object retrieved is of
the java.sql.Date type in the Java programming
langue.

314
getDate(String columnName, Retrives the specified column from the current row
Calender cal) in the ResultSet and uses the given calendar to
construct the time in milliseconds. The object
retrieved is of the java.sql.Date type in the Java
programming language.
getFetchDirection( ) Retrives the direction(forward or reverse) in which
the ResultSet retrieves the row from a database.
getFetchSize( ) Retrieves the size of the associated ResultSet object.
getMetaDate( ) Retrieves the number, type, and properties of the
ResultSet object.
getObject(int columnIndex) Retrieves a specified column in the current row as
an object in the Java programming language.
getObject(int i, Map map) Retrieves a specified column in the current row as
an object in the Java programming language and
also uses the Map object that contains mapping of
the SQL structured or distinct type.
getObject(String Retrieves a specified column or the basis of the
columnName) given column name in the current row as an object.
getObject(String colName, Retrieves a specified column on the basis of the
Map map) given column name as an object in the Java
programming language and also uses the Map object
that contains mapping of the SQL structured or
distinct type.
getRow( ) Retrieves the current row number associated with
the ResultSet object.
getStatement( ) Retrieves the statement object associated with the
ResultSet object.
getTime(int columnIndex) Retrieves the column values as java.sql.Time object.
getTime(int columnIndex, Retrieves the column values as a java.sql.Time
Calendar cal) object and uses the given calendar to construct the
time in milliseconds.
getTime(String columnName) Retrieves column values as a java.sql.Time object
on the basis of specified column name.
getTime(String columnName, Retrieves the column values as a java.sql.Time
Calendar cal) object on the basis of the specified column name and
uses the given calendar to construct the time in
milliseconds.
getTimestamp(int Retrieves the column values as a java.sql.Timestamp
columnIndex) object.
getTimestamp(int Retrieves the column values as a java.sql.Timestamp
columnIndex, Calendar cal) object on the basis of the specified column name.
getType( ) Retrieves the type of the ResultSet object used in a
connection.
getWarnings( ) Retrieves the warning reported on the ResultSet
object.
insertRow( ) Inserts the specified row and the contents into the

315
ResultSet object as well as into the database.
isAfterLast( ) Moves the cursor of the ResultSet object to the end
of the last row.
isBeforeFirst( ) Retrieves whether the cursor is before the first row
in the ResultSet or not.
isFirst( ) Retrieves whether the cursor is on the first row or
not.
isLast( ) Detects whether the cursor is on the last row of the
ResultSet object or not.
last( ) Moves the cursor to the first row in the ResultSet
object. It returns true if the cursor is positioned on
first row, and false if the ResultSet object does not
contain any rows.
moveToCurrentRow( ) Moves the cursor to the current row in the ResultSet
object.
moveToInsertRow( ) Moves the cursor to the inserted row in the
ResultSet object.
next( ) Moves the cursor forward one row. It returns true if
the cursor is now positioned on a row and false if the
cursor is positioned after the last row.
previous( ) Moves the cursor backward one row. It returns true
if the cursor is now positioned on a row and false if
the cursor is positioned before the first row.
refreshRow( ) Refreshes the current row associated with the
ResultSet object with the recent updates.
relative(int rows) Moves the cursor to a relative number of rows or
columns specified in the method.
rowDeleted( ) Retrieves whether the row has already been deleted
or not.
rowInserted( ) Determines whether the current row has an insertion
or not.
rowUpdated( ) Retrieves whether the current row has been updated
or not.
setFetchDirection(int Sets the direction of the ResultSet object.
direction)
setFetchSize(int rows) Sets the size of the ResultSet object.
updateArray( ) Updates the column in the ResultSet object with a
java.sql.Array value.
updatexxx( ) Updates the column values of the current row of the
specified types. The type can be any of the Java
predefined data types, such as int, long, Byte,
character, String, double( ), and the large object
types.
updateRow( ) Updates the current row with the new contents.
wasNull( ) Reports whether the last column has an SQL NULL
value or not.

316
updateNull(String Updates a specific column with a NULL value.
columnName)
updateObject(int Updates the specific column with an object value.
columnIndex, object x)
updateTime(int columnIndex, Updates the time value with a java.sql.Time value.
Time x)
updateTimestamp(int Updates the time value with a java.sql.Timpstamp
columnIndex,Timestamp x) value.

getConcurrency( ) Retrieves the concurrency mode of the ResultSet


object.
getCursorName( ) Retrieves the SQL cursor name used by the
ResultSet object.
Table 17.4 Methods of the java.sql. ResultSet interface
B. Data Fetching Methods of ResultSet
You can retrieve data from a ResultSet in two simple ways.
- Move the cursor position to the required row.
- Read the column data using getxxx( ) methods.
Let‟s discuss these steps in detail.
Moving the Cursor Position
When you obtain a ResultSet, initially the cursor is positioned before the first row, that is,
beforeFirst. You can use the next( ) method of ResultSet to move the cursor position to the next
record in ResultSet. When the cursor is moved to the next record, it returns a Boolean value that
indicates whether or not the cursor has moved after last record. The next( ) method returns true if
it successfully positions the cursor on the next row. If the cursor is positioned after last row, then
the next( ) method returns false.
Reading the Column values
After moving the cursor to the respective row, you can use the getter methods of ResultSet
to retrieve the data from the row where the cursor is positioned. The getter methods of ResultSet
are overloaded to support the navigation of the column by using its index or name. The ResultSet
object supports two versions of getter methods for each of the JDBC type. One of these two
methods takes column index of type int as input, where column index starts with 1; and other
method takes column name of the java.lang.String. Column names passed into getter methods are
not case sensitive. If a select list contains the same column more than once, the first instance of
the column returns.
When the getter methods of ResultSet are invoked, the JDBC driver attempts to convert the
requested column value into the respective Java type and returns the Java value. However, if it
fails to convert the column value into its respective Java type, it throws SQLException and
describes it as a conversion error. The allowable mapping for the various SQL types to Java
types under the JDBC specification are described in Table 17.5.
JDBC Type Java Type
CHAR String
VARCHAR String
LONGVARCHAR String
NUMERIC java.math.BigDecimal
DECIMAL java.math.BigDecimal

317
BIT Boolean
BOOLEAN Boolean
TINYINT Byte
SMALLINT Short
INTEGER Int
Table 17.5 JDBC and Java Data Types
 - getxxx( ) methods are used for data fetching.
Example getInt( ), getString( ), getChar( ), getFloat( )
- next( ), previous( ), last( ), first( ),absolute( ), relative( ), isFirst( ), isLast( ),… etc are
used for traversing.
Updation Methods
The following methods are used for updation data in the database.
- void moveToInsertRow( )
- void updatexxx(String column-name, xxx value)
- void updatexxx(int column-number, xxx value)
- void insertRow( )
- void deleteRow( )
- void update( )
Example:
(i) rs.moveToInsertRow( );
rs.updateInt(1,70);
rs.updateString(2, “abcd”);
rs.updateString(3, “RKL”);
(ii) rs.absolute(20);
rs.updateint(1,200);
(iii) while(rs.next( ))
{
if(rs.getString(“Loc”.equals(“RKL”))
{
Rs.deleteRow( );
}
}

In Example (i),(ii) and (iii) rs is the object of ResultSet.


Example 17.3(a) Creating a table Student having attributes SLNO, Name and Mark.
public class CreateTable
{
public static void main(String arg[])throws SQLException,ClassNotFoundException
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("Jdbc:Odbc:jkm","scott","tiger");
Statement stmt=con.createStatement();
String sql = "create table student (SLNO number,Name varchar2 (20), Mark number (5,2))";
stmt.executeUpdate(sql);
System.out.println("TABLE CREATED .......");
con.close();

318
}
}
D:\java20\jdbc>javac CreateTable.java
D:\java20\jdbc>java CreateTable
TABLE CREATED .......

Example 17.3(b) Inserting values in a table


import java.sql.*;
public class InsertTable
{
public static void main(String arg[])throws SQLException,ClassNotFoundException
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("Jdbc:Odbc:jkm","scott","tiger");
Statement stmt=con.createStatement();
String sql = "insert into student values (' "+arg[0]+" ',' "+arg[1]+" ',' "+arg[2]+" ')";
int count = stmt.executeUpdate(sql);
System.out.println("Number of Rows affected is ......."+count);
con.close();
}
}
D:\java20\jdbc>javac InsertTable.java
D:\java20\jdbc>java InsertTable 101 Amar 6.9
Number of Rows affected is .......1
D:\java20\jdbc>java InsertTable 102 Kriti 7.9
Number of Rows affected is .......1

17.3.4 Handling NULL Values


In a database, when a column contains a NULL value, it means that the column‟s value
is unknown(unassigned/unavailable/inapplicable). In Java, NULL means that an object type
variable has not been initialized with reference to an instance. Java primitive types cannot hold
NULL values. For example, consider a table with a column name col1 of type number. Suppose
the col1 value of one row is NULL and of the other row is 0. In this case, if we try to get the
values of these columns by using the getInt( ) method in Java, the value returned in both cases
would be 0 for both the rows; however, 0 and NULL both are different. In this context, 0 is a
value and NULL indicates that the value is unknown.

319
Similarly, when we use the getString( ) method in the previous example, it returns a
NULL value; and when we use the getDouble( ) method, it returns 0.
In addition, we can use the ResultSet.wasNull( ) method to realize whether the value
retrieved using the ResultSet object is NULL. The ResultSet.wasNull( ) method returns a
Boolean value; if it is true; For example a “emp” table in Oracle, the “mgr” column holds the
manager id of the employees; and “mgr” column shows NULL for the employee who are not
under the control of any manager, we can realize the NULL values by using the below code.
ResultSet rs = st.executeQuery(“select ename,mgr from emp”);
while(rs.next( ))
{
String name = rs.getstring(1);
int mgr = rs.getInt(2);
if(rs.wasNull( ))
{
System.out.println(“Employee,”+ename+ “ is not under any manager”);
}
else
{
System.out.println(“Employee,”+ename+ “is working under the manager with an employee ID” +mgr);
}
}

17.4 WORKING WITH PREPARED STATEMENT INTERFACE


The PreparedStatement object is used to execute the parameterized SQL statement. It
is important to note that when the parameterized SQL statement is used with the
PreparedStatement object, it supports zero or more parameters. The PreparedStatement object
represents a precompiled query that can be executed multiple times without compiling it again
and again.
The java.sql.PreparedStatement interface is a part of JDBC API that describes the
PreparedStatement object, which is implemented by a third-party vendor as a part of JDBC
driver. Some of the important points with respect to PreparedStatement are as follows:
- A PreparedStatement object is associated with a Connection object.
- A PreparedStatement object represents the execution plan of an SQL statement saved into
the database that is passed as a parameter while creating the PreparedStatement object.
- The SQL statement used with PreparedStatement can be a parameterized SQL statement,
that is, it can take Parameters whose values can be set while executing.
- A PreparedStatement is implicitly closed after the Connection object on which the
PreparedStatement object was created is closed.
The following operations are performed to create and execute the PreparedStatement object:
- The PreparedStatement( ) method of the Connection object is used to get the object of
PreparedStatement.
- The Connection object submits the given SQL statement to database.
- The database compiles the given SQL statement.
- An execution plan is prepared by the database to execute the SQL statement.
- Database stores the execution plan with a unique ID and returns the identity to the
Connection object.

320
- The Connection object prepares a PreparedStatement object, initializes it with the
execution plan identity, and returns the reference of PreparedStatement object to the Java
application.
- The setxxx( ) method of PreparedStatement object is invoked to execute the SQL
statement with the parameters set for the PreparedStatement object.
- The PreparedStatement object delegates the request to database.
- The database locates and executes the execution plan with the given parameters.
- Finally the result of the SQL statement is sent to the Java application in the form of
ResultSet.
Example:
PreparedStatement pstmt = con. PreparedStatement(“select * from dept DNO>?andDNAME=?”);

Using PreparedStatement( ) method of Connection interface to create a reference of


PreparedStatement. This method accepts a parameter as the required SQL with. You need to
perform the following broad-level steps to use PreparedStatement:
- Create a PreparedStatement object.
- Set the values for the parameters
- Execute the PreparedStatement
The advantages and Disadvantages of PreparedStatement

(i) It improves the performance of an application, in comparison to the Statement object,


where the same query is required to be executed multiple number of times; therefore,
PreparedStatement performs faster by avoiding compilation of multiple queries and
preparing them.

(ii) It provides a programmatic approach to set the values of parameters in a more descriptive
way as compared to the Statement object.
(a) It can represent only one SQL statement. Therefore, we cannot execute more than one
statement by a single PreparedStatement.
(b) It supports to add only a single SQL statement to be executed for multiple times with
different set of values.

Example 17.4 Insert records into a table (say dept) using PreparedStatement.
import java.sql.*;
public class PrepareStamentDemo
{
public static void main(String arg[])throws Exception
{
String value1,value2,value3;
value1=arg[0];
value2=arg[1];
value3=arg[2];
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("Jdbc:Oracle:thin:@127.0.0.1:1521:DB1","scott","tiger");
PreparedStatement pstmt= con.prepareStatement("insert into dept(DEPTNO,DNAME,LOC) values(?,?,?)");
pstmt.setString(1,value1);
pstmt.setString(2,value2);

321
pstmt.setString(3,value3);
pstmt.executeUpdate();
con.close();
}
}

D:\java20\jdbc>javac PrepareStamentDemo.java
D:\java20\jdbc>java PrepareStamentDemo 90 CSE ROURKELA
D:\java20\jdbc>java PrepareStamentDemo 80 EEE CUTTACK

Methods Available in PreparedStatement:

setArray(int i,Array x) Sets the values of parameters to the given


array object.
setAsciiStream(int parameterIndex, Sets the value of the PreparedStatement
InputStream x, int length) parameter according to the given input
stream, specified in the method.

setBigDecimal(int parameterIndex, Sets the value of theparameter by using the


BigDecimal x) values specified in the java.math.BigDecimal
value.
setBinarystream(int parameterIndex, Sets the binary values for the parameters used
InputStream x, int length) in the PreparedStatement object.
setBoolean(int parameterIndex, boolean Sets the Boolean values for the parameters
x) used in PreparedStatements.
setByte(int parameterIndex, byte[ ] x) Sets the byte values for the parameters used
in PreparedStatements.

322
setBytes(int parameterIndex, byte[ ] x) Sets the byte values in an array for the
parameters used in PreparedStatements
setCharacterStream(int parameterIndex, Sets the character values for the
Reader reader, int length) PreparedStatement parameters and also
specifies the length of the character stream.
setDate(int parameterIndex, Date x) Sets the PreparedStatement parameter with a
java.sql.Date value.
setDate(int parameterIndex, Date x, Sets the PreparedStatement parameter with a
Calendar cal) java.sql.Date value and also uses the calendar
object to set the value of the parameter.
setDouble(int parameterIndex, double x) Sets the value of the parameter to the Java
double value.
setFloat(int parameterIndex, float x) Sets the value of the parameter to the Java
float value.
setInt(int parameterIndex, int x) Sets the value of the parameter to the Java int
value.
setLong(int parameterIndex, long x) Sets the value of the parameter to the Java
long value.
setNull(int parameterIndex, int sqlType) Sets the NULL values for the parameters.
setNull(int parameterIndex, int sqlType, Sets the NULL values for the parameters and
String typeName) also specifies the SQL user-defined type.
setObject(int parameterIndex, Object x) Sets the value of the parameter by using the
given object value.
setObject(int parameterIndex, Object x, Sets the value of the parameter by using the
int targetSqlType) given object value and also sets the SQL
type.
setShort(int parameterIndex, short x) Sets the value of the parameter to the Java
short value.
setString(int parameterIndex, string x) Sets the value of the parameter to the Java
String value.
setTime(int parameterIndex, Time x) Sets the value of the parameter to the
java.sql.Time value.
setTime(int parameterIndex, Time x, Sets the value of the parameter to the
Calendar cal) java.sql.Time value using the Calendar
object.
setURL(int parameterIndex, URL x) Sets the value of the parameter to the
java.net.URL value.

Example 17.5 Deleting a record using PreparedStatement

import java.sql.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class DeleteDemo
{

323
public static void main(String[] arg) throws Exception
{
String sql=null;
Connection con = null;
PreparedStatement stmt = null;
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:DB1","scott","tiger");
sql="select * from DEPT";
stmt = con.prepareStatement(sql);
int i;
i= stmt.executeUpdate("delete from dept where DEPTNO="+arg[0]);
if(i>=1)
System.out.println("Data DELETED......");
else
System.out.println("Data not DELETED......");
con.close();
}
}
D:\java20\jdbc>javac DeleteDemo.java
D:\java20\jdbc>java DeleteDemo 80
Data DELETED......

After deleting the record (80) the table “dept” contain these records
17.5 WORKING WITH THE CALLABLESTATEMENT INTERFACE
The CallableStatement object executes an SQL statement to invoke the database
procedure or function. The java.sql.CallableStatement interface is a part of JDBC API that
describes a standard abstraction for the CallableStatement object, implemented by third party
vendor as a part of JDBC driver. The java.sql.CallableStatement interface extends the
java.sql.PreparedStatement interface. The CallableStatement object provides support for both
input and output parameters. CallableStatement provides a standard abstraction for the data
stores to call stored procedures and functions in a vendor independent way. The SQL-stored
procedures may have IN, OUT or IN OUT parameters. An IN parameter receives a value passed
to the procedure when it is called. An OUT parameter returns a value after the procedure is
completed, but it contains no value when the procedure is called. An IN OUT parameter contains
a value passed to the procedure when it is called, and returns a value after it is completed.

324
17.5.1 Using CallableStatement
In Java, CallableStatement is used to call the stored procedures and functions by using
an object of the CallableStatement interface. The following steps are included to use
CallableStatement in an application.
(i) Creating the CallableStatement object.
(ii) Setting the values of parameters.
(iii) Registering the OUT parameter type.
(iv) Executing the stored procedure or function.
(v) Retrieving the parameter values.
(i) Creating the CallableStatement object:
The CallableStatement object can be created by invoking the prepareCall
(String) method of the Connection object. The syntax to call the prepareCall method
in an application is as follows:
{ call procedure_name(?,?,…)} //calling the procedure method with parameters.
{call procedure_name} // with no parameter.
(ii) Setting the values of the parameters:
After creating the CallableStatement object, you need to set the values for the
IN and IN OUT type parameters of the stored procedure. The values of these
parameters can be set by calling the setXXX( ) methods of the CallableStatement
object. These methods are used to pass the values to the IN and IN OUT parameters.
The values for the parameter can be set by using the following syntax:
setXXX(int index, xxx value);
(iii) Registering the OUT parameter Type:
The OUT or IN OUT parameter, which are used in a procedure and represented
by CallableStatement, must be registered to collect the values of the parameters after
the stored procedure is executed. You can register the parameters by invoking the
registerOutparameter( ) method of the CallableStatement object. The parameter can
be registered by using the following syntax:
registerOutParameter(int index, int type)
(iv) Executing the stored Procedure or Function:
After registering the OUT parameter type, you need to execute the procedure by
using the execute( ) method of the CallableStatement object. The execute( ) method of
CallableStatement does not take any argument.
(v) Retrieving the parameter values:
After executing the stored procedure, you can retrieve it OUT or IN OUT type
parameter values. You can use the getter methods of the CallableStatement object to
retrieve the parameter values of the procedure. The close( ) method on the
CallableStatement object is invoke to release the resources that it holds.
17.5.2 Executing a Stored Procedure with IN Parameter
Let‟s try to insert a record into two tables, such as bank and personal_details, as a part
of creating a new account. First you create two tables called bank and personal_details by using
the following SQL queries:

Create table bank ( Accno number,Name varchar2(20), Bal number(10,2),


Acctype number
);

325
Create table personal_details ( Accno number, Address varchar2(20),
Phno number
);
After creating the tables, we want to create the createAccount procedure; that can insert a record
into both the tables. The code snippet of the createAccount procedure is as follows:
Create or replace procedure createAccount(accnumber number, actype number,
acname varchar2, amt number, addr varchar2, phno number) is
begin
insert into bank values(accnumber,acname,amt,actype)
insert into personal_details values(accnumber,addr,phno);
end;

Figure 17.8 showing the creation of Tables and a procedure in Oracle-10g.

The Figure 17.8 showing the creation of Tables and a procedure in a database.
326
Example 17.6 A demo program to callable statemet.
import java.sql.*;
public class CallableStatementDemo
{
public static void main(String arg[])throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("Jdbc:Oracle:thin:@127.0.0.1:1521:DB1","scott","tiger");
CallableStatement cs = con.prepareCall("{call createAccount(?,?,?,?,?,?)}");
cs.setInt(1,101);
cs.setInt(2,102);
cs.setString(3,"Anup");
cs.setDouble(4,20000);
cs.setString(5,"PARADIP");
cs.setInt(6,987654321);
cs.execute();
System.out.println("Account Created .................");
con.close();
}
}
D:\java20\jdbc>javac CallableStatementDemo.java
D:\java20\jdbc>java CallableStatementDemo
Account Created .................

Data inserted simultaneously in bank and personal_details table using callable statement

17.5.3 Executing a Stored Procedure with OUT parameters


We create an application that calls a stored procedure named getBalance( ) by using
CallableStatement. First create a procedure named getBalance( ) as:
create or replace procedure getBalance(acno number, amt OUT number) is
begin
select bal into amt from bank where accno = acno;

327
end;

Figure 17.9 Creating a procedure by using the OUT parameter in Oracle-10g

Example 17.7 A demo program to callable statement using OUT parameter.


import java.sql.*;
public class CallableStatementDemo1
{
public static void main(String arg[])throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("Jdbc:Oracle:thin:@127.0.0.1:1521:DB1","scott","tiger");
CallableStatement cs = con.prepareCall("{call getBalance(?,?)}");
cs.setInt(1,Integer.parseInt(arg[0]));
cs.registerOutParameter(2,Types.DOUBLE);
cs.execute();
System.out.println("Balance : "+cs.getDouble(2));
con.close();
}
}
D:\java20\jdbc>javac CallableStatementDemo1.java
D:\java20\jdbc>java CallableStatementDemo1 101
Balance : 20000.0

17.5.4 Calling Functions by Using CallableStatement


The procedure to call a function in an application is same as it is in case of stored
procedures. The syntax to invoke a function in JDBC is as follows:
{ call ?:= function_name(?,?,…)} //with string parameters.
{call ?:= function_name} // with no parameter.

Example 17.8
import java.sql.*;
public class CallableStatementDemo2
{
public static void main(String arg[])throws Exception
{

328
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("Jdbc:Oracle:thin:@127.0.0.1:1521:DB1","scott","tiger");
CallableStatement cs = con.prepareCall("{call ?:= getBalanceFt(?)}");
cs.registerOutParameter(1,Types.DOUBLE);
cs.setInt(2,Integer.parseInt(arg[0]));
cs.execute();
System.out.println("Balance : "+cs.getDouble(1));
con.close();
}
}

D:\java20\jdbc>javac CallableStatementDemo2.java
D:\java20\jdbc>java CallableStatementDemo2 101
Balance : 20000.0

Figure 17.10 Creating a User-Defined Function


(creating a Functinon named as getBalanceFt in Oracle-10g)

17.6 WORKING WITH THE RESULTSETMETADATA INTERFACE


JDBC API provides the feature of MetaData that contains descriptive information about
the data available in a database. JDBC MetaData provides information about tables, views,
column names, column datatypes, stored procedure, and databases. JDBC API provides two
interfaces, such as ResultSetMetaData and DatabaseMetaData, to provide the metadata
information of a database.

17.6.1 Describing ResultSetMetaData


The java.sql.ResultSetMetaData interface is used to describe a JDBC Driver object that
encapsulates the metadata of the cursor. The ResultSetMetaData object is used to retrieve
information about the columns in a ResultSet. It can also be used to get the information, such as
column names, column datatypes, and column length, related to a particular result. The most
commonly used methods of the ResultSetMetaData interface are given in Table 17.6.

329
Methods Descriptions
getColumnCount( ) Returns an integer value and retrieves the
number of columns in the ResultSet object.
getColumnName(int index) Takes the column index and returns the
column name.
getColumnTypeName(int index) Takes the column index and returns the
database specific type name.
getColumnType(int index) Takes the column index and returns the
integer value that indicates the columns
SQL type. It also compares this value with
the java.sql.Types constants.
isAutoIncrement(int index) Returns the Boolean value indicating
whether the column at the given index is
auto incremented or not.
isNullable(int index) Indicates whether the column at the given
index accepts NULL value or not.
getCatalogName(int index) Accesses the catalog name of the column
of a table associated with the ResultSet
object.
getColumnClassName(int index) Retrieves the java class name associated
with the ResultSet object.
getColumnDisplaySize(int index) Retrieves the width of the columns
associated with the ResultSet object.
getColumnLabel(int index) Retrieves the title of the specified column
in the ResultSet object.
getPrecision(int column) Retrieves the precision value (number of
digits after the decimal point) of the
decimal digits of the particular column in
the ResultSet object.
getScale(int column) Retrieves the number of decimal digits
present to the right of the decimal point for
a designated column in the ResultSet
object.
getSchemaName(int column) Retrieves the schema name of the specified
column in the ResultSet object.
getTableName(int column) Retrieves the table name of the specified
column in the ResultSet object.
isCaseSensitive(int column) Indicates whether the case of a column
matters in context with the associated
ResultSet object or not.
isCurrency(int column) Indicates whether the specified column
indicates a cash value or not.
isDefinitelyWritable(int column) Indicates that a column is writable.
isReadOnly(int column) Indicates that the specified column is read
only; and write operations cannot be
performed in the column values.

330
isSearchable(int column) Indicates whether a column value can be
used as a condition in the WHERE clause
or not.
isSigned(int column) Indicates whether a column value in a
particular column are signed or not.
isWritable(int column) Indicates whether a write operation is
possible on a column value or not.

Table 17.6 Methods of ResultSetMetaData


17.6.2 Using ResultsetMetaData
The information for the ResultSet object can be retrieved by using the
ResultSetMetaData object. The following code snippet shows how to create an object of
ResultSetMetaData:
Statement stmt = con.createStatement( );
ResultSet rs = stmt.executeQuery( );
ResultSetMetaData rsmd = rs.getMetaData( );
Example 17.9 A demo program to ResultSetMetaData
import java.sql.*;
import java.util.*;
public class ResultSetMetaDataDemo
{
public static void main(String arg[])throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("Jdbc:Oracle:thin:@127.0.0.1:1521:DB1","scott","tiger");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from "+arg[0]);
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println("Table Name : "+arg[0]);
int colcount = rsmd.getColumnCount();
for(int i = 1; i<=colcount;i++)
{
System.out.print(rsmd.getColumnName(i)+"\t");
System.out.println(rsmd.getColumnTypeName(i));
}
con.close();
}
}

D:\java20\jdbc>javac ResultSetMetaDataDemo.java
D:\java20\jdbc>java ResultSetMetaDataDemo dept

Table Name : dept


DEPTNO NUMBER
DNAME VARCHAR2
LOC VARCHAR2

331
17.7 Using DatabaseMetaData
JDBC provides the DatabaseMetaData interface for obtaining database wide
information. The Connection interface establishes a connection to a database. It is within the
context of a connection that SQL statements are executed and results are returned. A connection
also provides access to database metadata information that descrives the capabilities of the
database, supported SQL grammar, stored procedures, and so on. To obtain an instance of
DataBaseMetaData for a database, use the getMetaData( ) method on a Connection object like
this:
DatabaseMetaData dmd = Connection.getMetadata( );
Example 17.10 A demo program to DatabaseMetaData.
import java.sql.*;
import java.util.*;
public class DatabaseMetaDataDemo
{
public static void main(String arg[])throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("Jdbc:Oracle:thin:@127.0.0.1:1521:DB1","scott","tiger");
System.out.println("Data Base Connected..........");
DatabaseMetaData dmd = con.getMetaData();
// ResultSet rs = dmd.getTables(null,null,null,new String[] {"TABLE"});
System.out.println("Database URL : "+dmd.getURL());
System.out.println("Database UserName : "+dmd.getUserName());
System.out.println("Database Product Name : "+dmd.getDatabaseProductName());
System.out.println("Database Product Version : "+dmd.getDatabaseProductVersion());
System.out.println("JDBC Driver Name : "+dmd.getDriverName());
System.out.println("JDBC Driver Version : "+dmd.getDriverVersion());
System.out.println("JDBC Driver Major Version : "+dmd.getDriverMajorVersion());
System.out.println("JDBC Driver Minor Version : "+dmd.getDriverMinorVersion());
System.out.println("Maximum number of connection : "+dmd.getMaxConnections());
System.out.println("Max Table Length : "+dmd.getMaxTableNameLength());
System.out.println("Max Columns in Table : "+dmd.getMaxColumnsInTable());
//System.out.print("user tables are : ");
// while(rs.next())
// {
// System.out.print(rs.getString("TABLE_NAME")+" , ");
// }
con.close();
}
}
D:\java20\jdbc>javac DatabaseMetaDataDemo.java
D:\java20\jdbc>java DatabaseMetaDataDemo
Data Base Connected..........
Database URL : Jdbc:Oracle:thin:@127.0.0.1:1521:DB1
Database UserName : SCOTT
Database Product Name : Oracle
Database Product Version : Personal Oracle Database 10g Release 10.2.0.1.0 - Production

332
With the Partitioning, OLAP and Data Mining options
JDBC Driver Name : Oracle JDBC driver
JDBC Driver Version : 10.2.0.1.0
JDBC Driver Major Version : 10
JDBC Driver Minor Version : 2
Maximum number of connection : 0
Max Table Length : 30
Max Columns in Table : 1000

Summary

In this chapter we known the following


- JDBC generally referred as Java Data Base Connectivity is one of the service APIs of
Java platform that includes Java Standard and Enterprise Editions.
- JDBC defines a standard protocol for Java application to access tabular data stores.
- JDBC API needs to be supported by JDBC driver to communicate with the respective da-
tabase.
- JDBC driver is responsible to drive the queries prepared by Java applications to DBMS.
- ODBC provides a standard abstraction to communicate with different databases vendor
independently.
- JDBC Statement object is used to represent the DB CURSOR (buufer) to Java application
using JDBC to read database. The ResultSet object follows the iteration pattern. We can
obtain any number of ResultSet by using JDBC Statement, but at a time only one
ResultSet can be opened.
- The PreparedStatement object is used to execute SQL statements with IN parameters.
This supports positional parameters, represented using „ ? `.
- The CallableStatement object is used to execute the Database stored procedure that
support IN and OUT parameters.
- The DatabaseMetaData object is used to get the database and JDBC driver details.

333
REVIEW QUESTIONS
17.1 What is ODBC?
17.2 What is JDBC?
17.3 Explain the different types of JDBC drivers.
17.4 What is java.sql.Connection?
17.5 What is java.sql.Statement?
17.6 Write the syntax of JDBC URL.
17.7 Give one example JDBC URL to connect to Oracle database by using JDBC Type-4 driver.
17.8 Which method of the Connection interface is used to get a basic JDBC statement object?
17.9 What is the return type of the executeUpdate( ) method and what does it describe?
17.10 Which method of the statement interface is used to execute data retrieval SQL ststements?
17.11 What is java.sql.PreparedStatement?
17.12 Give advantages and disadvantages of PreparedStatement.
17.13 What are the steps involved in using PreparedStatement?
17.14 What is java.sql.CallableStatement?
17.15 Which package provides the ResultSet interface?
17.16 Which version of getxxx( ) method of ResultSet is preferred to get the result and why?
17.17 Which method of ResultSet is used to find whether a column contains the NULL value in a
database or not?
17.18 What is ResultSetMetaData?
17.19 What are the advantages of developing database applications using Java?
17.20 Describe Driver, Connection, Statement and ResultSet.
17.21 How do you create a Statement and execute an SQL statement?
17.22 Describe prepared Statements. How do you create instances of PreparedStatement? How
do you execute a PreparedStatement? How do you set parameter values in a PreparedStatement?
17.23 Describe CallableStatement. How do you create instances of CallableStatement? How do
you execute a CallableStatement? How do you register OUT parameters in a CallableStatement?
17.24 What is DatabaseMetaData for? Describe the methods in DatabaseMetaData. How do you
get an instance of DatabaseMetaData?
17.25 What is ResultSetmetaData for? Describe the methods in ResultSetMetaData. How do you
get an instance of ResultSetMetaData?
17.26 How do you find the number of columns in a ResultSet? How do you find the column
names in a ResultSet?
17.27 Create frame for Employee which store, edit and delete records for employees. Employee
frame contains three tabbed panes named as Add record, Edit Record, Delete Record as shown in
figure Q17-a. The three tabbed panes contain three panels for add, edit and delete records.

Figure Q17-a

334
In Figure Q17-a displays a panel (When Add Record tabbed pane is selected) in a frame having
(i) Three labels (DEPTNO:, DName:, loc:)
(ii) Three text fileds
(iii) Two button (Add, Reset)
When Add button is pressed then the Employee‟s Department Number, Department Name and
Location value present in the textfields are added to the database. When Reset button is clicked
then text fields are cleared. In Figure Q17-a if you pressed Edit Record tabbed pane then it show
the below frame as shown in Figure Q17-b

Figure Q17-b
Figure Q17-b displays a panel in the previous frame, which activated when Edit Record tabbed
pane is clicked. This panel contains two buttons Edit and Save. For editing a record you have to
supply DEPTNO value which is act as a primary key and Save button is used to save the
modified record. The third tabbed pane Delete Record when click it activated another panel in
the same frame which shown in Figure Q17-c.

Figure Q17-c
In this panel it consists of one label (i.e.; Enter DEPT-NO:), a textfield for accepting user input
and a button (i.e.; Delete).User have to supply Department number of a employee and the
corresponding record for that employee is deleted from the database when Delete button is
pressed.

335
RMI
18.0 INTRODUCTION
The RMI (Remote Method Invocation) systems allow an object running in one Java
virtual machine to invoke methods on an object running in another Java virtual machine. This
technique is known as distributed object application. RMI provides for remote communication
between programs written in Java programming language. Java‟s RMI approach is organized
into client and server framework. A typical server program obtains a remote reference to one or
more remote objects on a server and then invokes methods on them. RMI provides the
mechanism by which the server and the client communicate and pass information back and forth.
The Java programming language‟s RMI system assumes the homogeneous environment of the
Java Virtual Machine (JVM), and the system can therefore take advantage of the Java platform‟s
object model whenever possible.

18.1 SYSTEM GOALS


The goals for supporting distributed objects in the Java programming language are:
- Support seamless remote invocation on objects in different virtual machines.
- Supports callbacks from servers to applets.
- Integrate the distributed object model into the Java programming language in a natural
way while retaining most of the Java programming language‟s object semantics.
- Make differences between the distributed object model and local java platform‟s object
model apparent.
- Make writing reliable distributed applications as simple as possible.
- Preserve the type-safety provided by the Java platform‟s runtime environment.
- Support various reference semantics for remote objects; for example live (nonpersistent)
references, persistent references, and lazy activation.
- Maints the safe environment of the Java platform provided by security managers and
class loaders.
Underlying all these goals is a general requirement that the RMI model be both simple
(easy to use) and natural (fits well in the language).

18.2 DISTRIBUTED OBJECT MODEL


The Distributed object model can be described using following topics
- Distributed Object Application
- Defination of Terms
- The Distributed and Nondistributed Models Constrasted
- Overview of RMI interfaces and classes
- Implementing a Remote Interface
- Parameter Passing in RMI
- Locating Remote Objects

18.2.1 Distributed Object Application


RMI applications are often comprised of two separate programs: a server and a client.
A typical server application creates a number of remote objects, makes references to those
remote objects accessible, and waits for clients to invoke methods on those objects. A typical
client application gets a remote reference to one or more remote objects in the server and then
invokes methods on them. Distributed object applications need to:

336
Locate remote objects
Applications can use one of two mechanisms to obtain references on remote
objects with RMI‟s simple naming facility, the rmiregistry, or the application can pass and return
object references as part of its normal operation.
Communicate with remote objects
Details of communication between remote objects are handled by RMI; to the
programmer, remote communication looks like a standard method invocation.
Load class bytecodes for objects that are passed as parameters or return value
Because RMI allows a caller to pass objects to remote objects, RMI provides the
necessary mechanisms for loading an object‟s code as well as transmitting its data.
The Figure18.1 depicts an distributed application that uses the registry to obtain
references to a remote object. The Server calls the registry to associate a neme with a remote
object. The client looks up the remote object by its name in the server‟s registry and then invokes
a method on it. The Figure 18.1 also shows that the RMI system uses an existing web server to
load bytecodes, from objects when needed. RMI can load class bytecodes using any URL
protocol (e.g.; HTTP, FTP, file, etc) that is supported by the Java platform.

RMI registry
RMI
client
RMI
URL
URL Protocol
Server
Protocol

Web server Web Server

Figure 18.1 Distributed Object application

18.2.2 Defination of Terms


In the Java platform‟s distributed object model, a remote object is one whose methods
can be invoked from another Java virtual machine, potentially on a different host. An object of
this type is described by one or more remote interfaces, which interfaces are written in the Java
programming language that declare the methods of the remote object. RMI is the action of
invoking a method of a remote interface on a remote object. Most importantly, a method
invocation on a remote object has the same syntax as a method invocation on a local object.

18.2.3 The Distributed and Nondistributed Model Constrasted


The Java platform‟s distributed object model is similar to the Java platform‟s object model in the
following ways:
- A reference to a remote object can be passed as an argument or returned as a result in any
method invocation (local or remote).

337
- A remote object can be cast to any of the set of remote interfaces supported by the
implementation using the syntax for casting built into the Java programming language.
- The built-in instanceof operator can be used to test the remote interfaces supported by a
remote object.
The Java platform‟s distributed object model differs from the Java platform‟s object model in
these ways:
- Clients of remote objects interact with remote interfaces, never with the implementation
classes of those interfaces.
- Non-remote arguments to, and results from, a remote invocation are passed by copy,
rather than by reference. This is because references to objects are only useful within a
single virtual machine.
- A remote object is passed by reference, not by copying the actual remote implementation.
- The semantics of some of the methods defined by class java.lang.Object are specialized
for remote objects.
- Since the failure modes of invoking remote objects are inherently more complicated than
the failure modes of invoking local objects, clients must deal with additional exceptions
that can occur during a remote method invocation.

18.2.4 Overview of RMI Interface and Classes


The interfaces and classes that are responsible for specifying the remote behavior of the
RMI system are defined in the java.rmi package hierarchy. The Figure 18.2 shows the
relationship between interfaces and classes:

Interfaces Classes

Remote extends Remote Object IOException

RemoteException
RemoteServer

Activatable UnicastRemoteObject

Figure 18.2 java.rmi package hierarchy


The java.rmi.Remote Interface
In RMI, a remote interface is an interface that declares a set of methods that may be
invoked from a remote Java virtual machine. A remote interface must satisfy the following
requirements:
- A remote interface must at least extend, either directly or indirectly, the interface
java.rmi.Remote
- Each method declaration in a remote interface or its super-interfaces must satisfy the
requirements of a remote method declaration as follows:

338
 A remote method declaration must include the exception java.rmi.RemoteException
(or one of its superclasses such as java.io.IOException or java.lang.Exception) in its
clause, in addition to any application specific exceptions (java.rmi.RemoteException).
 In a remote method declaration, a remote object declared as a parameter or return
value (either declared directly in the parameter list or embedded within a non-remote
object in a parameter) must be declared as the remote interface, not the
implementation class of that interface.
The interface java.rmi.Remote is a marker interface that defines no methods:
public interface Remote( ){ }
A remote interface must at least extend the interface java.rmi.Remote (or another
remote interface that extends java.rmi.Remote). However, a remote interface may extend a non-
remote interface under following condition:
- A remote interface may also extend another non-remote interface, as long as all of the
methods (if any) of the extended interface satisfy the requirements of a remote method
declaration. For example, the following interface “BankAccount” defines a remote
interface for accessing a bank account. It contains remote methods to deposit to the
account, to get the balance, and to withdraw from the account:

public interface BankAccount extends java.rmi.Remote


{
public void deposit(float amount)throws java.rmi.RemoteException;
public void withdraw(float amount)throws java.rmi.RemoteException;
public float getBalance( )throws java.rmi.RemoteException;
}

The next example shows a valid remote interface Branch2 that extends a nonremote
interface Branch1, which has remote methods, and the interface java.rmi.Remote:

public void deposit(float amount)throws java.rmi.RemoteException;


public interface Branch1
{
public final Strig = “Delhi”;
public Object foo(Object obj)throws java.rmi.RemoteException;
public void info( )throws java.rmi.RemoteException;
public int ministstement( )throws java.rmi.RemoteException;
}
public interface Branch2 extends Branch, java.rmi.Remote
{
public void access( )throws java.rmi.RemoteException;
}

The Remote Exception Class


The java.rmi.RemoteException class is the superclass of exceptions thrown by the
RMI runtime during a remote invocation. To ensure the robustness of applications using the RMI
system, each remote method declared in a remote interface must specify java.rmi.RemoteExcep-
tion (or one of its super classes such as java.io.IOException or java.lang.Exception) in its throws

339
clause. The exception java.rmi.RemoteExcveption is thrown when a remote method invocation
failure includes:
- Communication failure (the remote server is unreachable or is refusing connections; the
connection is closed by the server, etc.)
- Failure during parameter or return value marshalling or unmarshalling.
- Protocol errors.
The class RemoteException is a checked exception (one that must be handled by the caller of a
remote method and is checked by the compiler), not a RuntimeException.

The RemoteObject class and its Subclasses


RMI server functions are provided by java.rmi.server.RemoteObject and its subclasses,
java.rmi.server.UnicastRemoteObject and java.rmi.activation.Activatable.
- The class java.rmi.server.RemoteObject provides implementations for the java.lang.Ob-
ject methods, hashCode, equals, and toString that are sensible for remote objects.
- The UnicastRemoteObject and Activatable class identifies the semantics of the remote
reference, for example whether the server is a simple remote object or is an activatable
remote object.
- The java.rmi.server.UnicastRemoteObject class defines a unicast remote object whose
references are valid only while the server process is alive.
- The class java.rmi.activation.Activatable is an abstract class that defines an activatable
remote object that starts executing when its remote methods are invoked and can shut
itself down when necessary.

18.2.5 Implementing a Remote Interface


The general rules for a class that implements a remote interface are as follows:
- The class must extends java.rmi.server.UnicastRemoteObject, thereby inheriting the
remote behavior provided by the classes java.rmi.server.RemoteObject and
java.rmi.server.RemoteServer.
- The class can implement any number of remote interfaces.
- The class can extend another remote implementation class.
- The class can define methods that donot appear in the remote interface, but those
methods can only be used locally and are not available remotely.
For example, the following class BankAcctImpI implements the BankAccount remote interface
and extends the java.rmi.server.UnicastRemoteObject class:

Package mypack;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class BankAcctImpI extends UnicastRemoteObject implements BankAccount
{
private double balance = 0.0;
public BankAcctImpI(double initialBal) throws RemoteException
{
balance = initialBal;
}
public void deposit(double amount)throws RemoteException

340
{
balance + = amount;
}
public void withdraw(double amount)throws RemoteException
{
balance - = amount;
}
public double getBalance( )throws RemoteException
{
return balance;
}
}
18.2.6 Parameter Passing in RMI
An argument to, or a return value from, a remote object can be any object that is serial-
izeable. This includes primitive types, remote objects, and non-remote objects that implement the
java.io.Serializable interface.
Passing Non-remote Objects:
A non-remote object, that is passed as a para