First Step in JAVA Programming
First Step in JAVA Programming
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 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
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.
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
(state 1) (state 2)
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)
4
1,0
Machine Language
Assembly language (ADD,MOVE)
Procedure Oriented Laguage(C,BASIC,COBOL)
Object Oriented Language (C++,JAVA,C#)
Main program
Funn-1 Funn-2
Local Data Local Data
n n
Fun -4 Fun -5
Funn-3
Funn-6 Funn-7 Funn-8
Local Data
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
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.
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
Text Editor
Ex:Notpad,wordpad
Javac
Java Jdb
Java Program
output
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.
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
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)
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.
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.
2.7 Summary
Java Libraries
JDK
JVM
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.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.
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
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
3.2.5 Operators
Operators are symbols that initiate an action. The following tokens are the operators
formed from ASCII characters:
= > < ! ~ ?:
== <= >= != && || ++ --
+ - * / & | ^ %
+= -= *= /= &= |= ^= %=
<< >> >>> <<= >>= >>>=
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.
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.
(2) obj1
301
age name
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;
- 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.
(c ) Multiplication operator * :
Example: 3*9 =27
22
Example: int a =10, s = 10;
s=s+ ++a; //now s value become 21 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.
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 :
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);
}
}
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)
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
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
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);
}
}
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
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 )
double
double
double
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.
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
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.
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.
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.
if (expression)
{statement1;
.
.
Statement n;
}
Example 4.1 A demo program to if statement functionality.
35
Example 4.2
Note: If multiple statements are present in if body then must use { }. Otherwise “if” take the
statement1 as its body part.
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.
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
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.
41
Example 4.5 Write a program to find out factorial of a number.
Example 4.7 Write a program to reverse a number using command line argument.
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
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
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();
}
}
}
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);
}
}
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:
47
Example 4.13 A demo program of break and continue.
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];
- 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
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);
}
}
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.
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.
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.
59
Example 5.1 accessing a data member by an object
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!
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;
}
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
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
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
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.
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
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.
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
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>)
- 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;
5.14.3 this
“this” is a keyword which returns the reference to the current objects.
74
Explanation: The statements - cl.x
- cl.me( ).x
- cl.me( ).me( ).x
all are same to accessing a data member by an object.
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.
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
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;
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
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
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:
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.
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.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.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:
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
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.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.
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
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( )
{
.
.
.
}
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.
interface interface_name
{
Variable declaration;
Methods declaration;
}
95
Example: interface interface_name extends interface_name
{
interface body
}
The implementation of interfaces can take various forms as illustrated in Figure 6.1.
implements C
interface
class B C class implements
( c) (d)
Figure6.1 Various Forms of interface implementation
96
}
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.
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.
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
- 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.
//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
} }
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
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;
104
package pec;
public class fruit
{
public void test( )
{
System.out.println("SWEET");
}
}
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
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 */
- 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
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:
You can also combine steps 1 & 2 and create only one instance of the BufferedReader for
use throughout their entire program e.g.
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
112
message
Message
QUESTION_MESSAGE
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=
114
Output:
(ii)
(i)
(iii) (iv)
(v)
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);
}
}
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
117
Review Questions
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.
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
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
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
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
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
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
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
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
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.
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);
}
}
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 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.
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:
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;
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
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”;
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.
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.
140
str
str
Figure 9.1 Strings are immutable; once created, their contents cannot be
changed
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.
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
143
char ch = s.charAt(2);
System.out.println("ch = "+ch);
}
}
Output: ch = c
144
}
Output: s1 = Hello World
s2 = Hello World */
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
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.
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);
148
else
System.out.println(s+" Is not a Palindrome");
}
}
Output: Enter a word
dad
dad Is a Palindrome
149
java.lang.Object
java.util.StringTokenizer
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.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.
152
}
Compile : javac LanguageVector.java
Run : java LanguageVector c c++ vb oracle java
Output : ,c , c++ , c# , oracle , java
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";
153
//Primitive type to String Objects
str = String.valueOf(iVal);
str = Strint.valueOf(lVal);
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.
155
Output: tc1 : 100 119.56
tc2 : 100 119.56
You can solve this problem by override the clone( ) method.
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
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.
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.
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.
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.
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( ).
161
- double pobj = dobj
This will auto box a double object to a primitive data type.
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
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.
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
168
mt.start( );
System.out.println("Parent thread running");
}
}
Output: Parent thread running
This is a child class thread
170
mt.setPriority(9);
mt.start( );
System.out.println("Parent---------");
}
}
Output: Parent---------
CHILD............
resume( ) time
exprires for sleep Sleep( )/join( )/suspend( )
makes thread stop for
child
Suspended
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.
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
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
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
//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.
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.
181
}
Output: Thread A : 0
Thread A : 1
Thread A : 2
Thread A : 3
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.
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...
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.
- The processor has to switch between - The processor has to switch between
different parts or threads of a program. different programs or process.
184
Summary
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.
Local
applet
Local Computer
Figure 11.1 Loading local applets
CODEBASE = http://www.ticon.com/applets
187
Internet
Remote Applet
Figure 11.2 Loading a Remote applets
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.
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>
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:
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.
paint( )
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.
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...
java.awt.Component
java.awt.Container
java.awt.Panel
java.awt.Applet
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
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.
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.
Component
Container
Window Panel
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.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.
204
}
}
D:\java20\awt>javac MyFrame.java
D:\java20\awt>java MyFrame
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
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.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);
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.
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
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.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.
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.
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.
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.
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);
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
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);
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
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.
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)
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
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
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.
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
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
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);
}
});
}
}
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);
}
}
}
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.
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);
}
}
}
Figure 13.1 Source code for Button click Figure 13.2 Button click event handled.
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);
}
}
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
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.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.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).
248
Java Stream classes
ByteStream Character
classes Stream classes
Reader Writer
InputStream OutputStream
classes classes
classes classes
249
Object
InputStream
FileInputStream SequenceInputStream
PipeInputStream ObjectInputStream
ByteArrayInputStream StringBufferInputStream
FileInputStream
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
250
Object
OutputStream
FileOutputStream ObjectOutputStream
PipedOutputStream ByteArrayOutputStream
FileOutputStream
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.
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++));
}
}
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
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.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 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
}
}
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.
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:
Printable Interface:
The Printable interface features one method and two values which are given below:
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.
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.
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.
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”);
263
X
786
3.14
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
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.
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;
266
import java.io.*;
import java.awt.*;
import java.awt.event.*;
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("");
}
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
271
Review Question
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.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.
274
D:\java20\util>javac ArraylistDemo.java
D:\java20\util>java ArraylistDemo Pabitra Sunita Dulal J.Prusty
ArrayList Contain :
Pabitra
Sunita
Dulal
J.Prusty
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
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”);
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)
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
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.
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.
Host-to-Host
Process-to-Process
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
read
Connection establishment
Process request
Write( ) read( )
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( )
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
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.
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();
}
}
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( ));
}
}
Server Client
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)
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);
}
}
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.
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.
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
296
Server Client
area area
DataOutputStream DataInputStream
Socket.getOutputStream Socket.getInputStream
socket
socket
Network
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);
}
}
}
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
}
}
}
}
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.
302
Java Programs
JDBC API
JDBC-ODBC
MySQL JDBC Oracle JDBC
Bridge Driver
Driver Driver
Microsoft ODBC
Driver
Figure 17.1 Java Programs access and manipulate databases through JDBC Drivers.
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.
SP API Oracle
JDBC API ODBC API
Java JDBC- ODBC
ODBC
Application Bridge SP API SQL Server
Driver
Driver
SP API Sybase
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.
JDBC call
Native call
JDBC API
DBMS Specific Native API Database
Java Type -2
Driver Server
Application
Client Side
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.
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.
306
DB Specific
JDBC Call
DBMS Specific
JDBC API Network protocol
Java Type-4
Database
Application Driver
Server
Client Side
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.
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.
307
JDBC-ODBC Bridge ODBC
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
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.
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()
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);
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.
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( );
}
}
318
}
}
D:\java20\jdbc>javac CreateTable.java
D:\java20\jdbc>java CreateTable
TABLE CREATED .......
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);
}
}
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=?”);
(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
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.
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:
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;
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
327
end;
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
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.
D:\java20\jdbc>javac ResultSetMetaDataDemo.java
D:\java20\jdbc>java ResultSetMetaDataDemo dept
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
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.
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
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.
Interfaces Classes
RemoteException
RemoteServer
Activatable UnicastRemoteObject
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:
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:
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.
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 parameter of a remote method invocation or
returned as a result of a remote method invocation, is passed by copy; that is, the object is
serialized using the object serialization mechanism of the java platform. So, when a non-remote
object is passed as an argument or return value in a remote method invocation, the content of the
non-remote object is copied before invoking the call on the remote object. When a non-remote
object is returned from a remote method invocation, a new object is created in the calling virtual
machine.
Passing Remote Objects:
When passing an exported remote object as a parameter or return valuer in a remote
method call, the stub for that remote object is passed instead. Remote objects that are not
exported will not be replaced with a stub instance. A remote object passed as a parameter can
only implement remote interfaces.
Referential Integrity:
If two references to an object are passed from one JVM to another JVM in parameters
(or in the return value) in a single remote method call and those references refer to the same
object in the sending JVM, those references will refer to a single copy of the object in the
receiving JVM. So within a single remote method call, the RMI System maintains referential
integrity among the objects passed as parameters or as a return value in the call.
Class Annotation:
When an object is sent from one JVM to another in a remote method call, the RMI
system annotates the class descriptor in the call stream with information (the URL) of the class
so that the class can be loaded at the receiver. It is a requirement that classes be downloaded on
demand during remote method invocation.
Parameter Transmission:
Parameters in an RMI call are written to a stream that is asubclass of the class
java.io.ObjectOutputStream in order to serialize the parameters to the destination of the remote
call. The ObjectOutputStream subclass overrides the replaceObject( ) method to replace each ex-
ported remote object with its corresponding subinstance. Parameters that are objects are written
to the stream using the ObjectOutputstream‟s writeObject( ) method. The ObjectOutputStream
341
calls the replaceObject( ) method for each object written to the stream via the writeObject( )
method. The replaceObject( ) method of RMI‟s subclass of ObjectOutputStream returns the
following:
- If the object passed to replaceObject( ) is an instance of java.rmi.Remote and that object
is exported to the RMI runtime, then it returns the stub for the remote object. If the object
is an instance java.rmi.Remote and object is not exported to the RMI runtime, then
replaceObject( ) reurns the object itself. A stub for a remote object is obtained via a call
to the method java.rmi.server.RemoteObject.tostub.
- If the object passed to replaceObject( ) is not an instance of java.rmi.Remote, then the
object is simply returned.
RMI‟s subclass of ObjectOutputStream also implements the annotateClass method that
annotates the call stream with the location of the class so that it can be downloaded at the
receiver. Any other default behavior of ObjectOutputStream for writing objects is maintained in
parameter passing. For example, the calling of writeReplace when writing objects and
readResolve when reading objects is honored by RMI‟s parameter marshal and unmarshal
stream.
The stub hides the serialization of parameters and the network-level communication in order to
present a simple invocation mechanism to the caller.
In the remote JVM, each remote object may have a corresponding skeleton (in java2
platform-only environments, skeletons are not required). The skeleton is responsible for dispatc-
hing the call to the actual remote object implementation. When a skeleton receives an incoming
method invocation it does the following:
342
- Unmarhshals (reads) the parameter for the remote method,
- invokes the method on the actual remote object implementation, and
- marshals (writes and transmits) the result (return value or exception) to the caller.
Stubs skeleton
Remote Remote
Virtual Connection
Reference Reference
Layer Layer
Transport Transport
Network Connection
Layer Layer
The architecture of RMI is designed with the goal to create a Java distributed object
model. It creates a system that extends the safety and robustness of the Java architecture to the
distributed computing world. The RMI architecture is divided into client-side and server-side
layers, as shown in Figure 18.3. RMI system works on “rmi” protocol, but how this system is
worked in OSI layers given in Figure 18.4.
Remote object
Presentation stub Skeleton
layer
Remote reference Remote Reference RMI
Session layer
layer layer
System
Trasport layeer TCP TCP
Network layer IP IP
343
Where RMI does not eliminate the concept of sockets, rather, it uses sockets internally over
TCP/IP to exchange input and output between client and server machines. RMI represent a
higher level view of networking than sockets. Java RMI is a purly Java-based implementation
RMI uses Java Remote Method Protocol (JRMP) on top of TCP/IP . JRMP is a wire-level
protocol. It also defined as a proprietary, stream-based protocol, which is only partially specified
in two versions of RMI. The first version was released with the Java 1 version of RMI and
required using skeleton classes on the server. The second version was released with Java 2 SDK.
This version has been optimized for performance and does not eliminate the concept socket. In
other words, RMI provides object-to-object communication between Java Virtual Machines
(JVMs) in a network. There are many distributed object systems, such as Distributed Component
Object Model (DCOM) , Common Object Request Borker Architecture (CORBA), and RMI
DCOM facilitates distributed computing on the the .Net platform.
rmiregistry
This is an application available in JDK to register server application into a part or client‟s
request. It can be used by the command rmiregistry. In command prompt use start
rmiregistry[port number], the default port number is 1099.
Example:
start rmiregistry 5000
The java.rmi.Naming class contain the following methods.
bind( ) : It is used to bind a remote object name to a specified URL.
rebind( ) : Same as bind( ).
unbind( ) : It is used to remove binding between the URL and the object name.
lookup( ) : It is mainly used by the client to get remote object specified by the URL.
Example18.1(a) Creating a Remote Interface
message.java
import java.rmi.*;
public interface message extends Remote
{
public String showMessage(String str)throws RemoteException;
}
344
Example 18.1(b) Creating Implementation class.
import java.rmi.*;
import java.rmi.server.*;
public class msgImpl extends UnicastRemoteObject implements message
{
public msgImpl()throws RemoteException
{
}
public static void main(String arg[])throws Exception
{
msgImpl mi = new msgImpl();
Naming.rebind("msg",mi);
System.out.println("Server started.........");
}
public String showMessage(String str)
{
String s = "Welcome to Server and you send the message --- "+str;
return s;
}
}
import java.rmi.*;
public class msgClient
{
public static void main(String arg[])throws Exception
{
message m1 = (message)Naming.lookup("rmi://192.168.10.1:1099/msg");
String str = m1.showMessage(arg[0]);
System.out.println(str);
}
}
After creating three files message.java, msgImpl.java and msgClient.java store these files
in two folders named as „A‟ and „B‟. The A folder contains the files message.java and
msgImpl.java and the folder B contains message.java and msgClient.java. Now store folder A in
345
C drive and folder B in D drive. The A folder is used for server and B folder is used for client.
Now compile and execute the A folder as :
C:\A> javac *.java
C:\A>rmic msgImpl
C:\A>start rmiregistry 1099
C:\A>java msgImpl
Server started……..
After compilation of A folder, you copy the msgImpl_stub.class file in A folder and paste
it in B folder. Now compile the B folder in a new command prompt as:
D:\B> javac *.java
D:\B> java msgClient hello
D:\B> Welcome to Server and you send the message --- hello
Figure 18.4 (a) Server Command prompt running for server program
Figure 18.4(b) rmiregistry command prompt running on port 1099 after pressing the command
“start rmiregistry 1099”
Figure 18.4 (c) Client Command prompt running and responding the server‟s message
346
18.3.2 Implicity Starting Registry
In the previous section you know how to create and run RMI application. You can also
implicity starting rmiregistry, for this you required java.rmi.registry package. Which contains
java.rmi.registry. Registry and java.rmi.registry.LocateRegistry class. Let‟s know how these
classes and packages are used to implicity starting registry.
In server
(i) Create the instance of registry by using createRegistry( ) method of LocateRegistry class.
Example:
Registry reg = LocateRegistry.createRegistry(5000);
(ii) Bind the server application into the registry by using bind( )/rebind( ) method of Registry
class.
Example:
reg.rebind(“rmi://localhost:5000/myserver”,mi);
In Client
(i) Create the instance of the registry by using getRegistry( ) method of LocateRegistry class.
This method accepts two parameters as IP address of server and port number of server‟s registry.
Example:
Registry reg = LocateRegistry.getregistry(“localhost”,5000);
(ii) Search the server application by using lookup( ) method of Registry class.
Example:
message m = (message)reg.lookup(“rmi://localhost:5000/myserver”);
347
2. Name collision with class of same name
as skeleton causes one of these errors:
(i) Skeleton can‟t be instantiated.
(ii) Skeleton not of correct class.
3. Bad URL due to wrong codebase.
4.Skeleton not of correct class.
java.rmi.Server.ExportException The port is in use by another virtual
machine.
Exception Occurs
java.rmi.UnknownHostException Unknown host.
java.rmi.ConnectException Connection refused to host.
java.rmi.ConnectIOException I/O error creating connection.
java.rmi.MarshalException I/O error marshaling transport header, marsh-
aling call header, or marshaling arguments.
java.rmi.NoSuchObjectException Attempt to invoke a method on an object that is
no longer available.
java.rmi.StubNotFoundException Remote object not exported.
Exception Occurs
java.rmi.UnmarshalException 1.Corrupted stream leads to either an I/O or protocol
error when:
(i) Marshaling return header.
(ii) Checking return type.
(iii) Checking return code.
(iv) Unmarshaling return.
2. Return value class not found.
java.rmi.UnexpectedException An exception not mentioned in the method signature
occurred. The UnexpectedException exception
object contains the underlying exception that was
thrown by the server.
java.rmi.ServerError Any error that occurs while the server is executing a
remote method. The ServerError exception object
contains the underlying error that was thrown by the
server.
java.rmi.ServerException This exception is thrown as a result of a remote
method invocation when a RemoteException is
thrown while processing the invocation on the
server, either while unmarshalling the arguments or
executing the remote method it set.
java.rmi.ServerRuntimeException A RuntimeException is propagated to clients intact.
348
18.4.3.1 Possible Causes of java.rmi.ServerException
These are some of the underlying exceptions which can occur on the server when the
server is itself executing a remote method invocation. These exceptions are wrapped in a
java.rmi.serverException; that is the java.rmi.ServerException contains the original exception for
the client to extract. These exceptions are wrapped by ServerException so that the client will
know that its own remote method invocation on the server did not fail, but that a secondary
remote method invocation made by the server failed.
Exception Occur
java.rmi.server.SkeletonMismatchException Hash mismatch of stub and skeleton.
java.rmi.UnmarshalException (i) I/O error unmarshaling call header.
(ii) I/O error unmarshaling arguments.
(iii) Invalid method number or method
hash.
java.rmi.RemoteException A RemoteException occurring as a result
of a remote invocation by the server.
18.4.4 Naming Exceptions
The following table lists the exceptions specified in methods of the java.rmi.Naming
class and the java.rmi.registry.Registry interface.
Exception Occur
java.rmi.AccessException Operation disallowed. The registry restricts bind,
rebind, and unbind to the same host. The lookup
operation can originate from any host.
java.rmi.AlreadyBoundException Attempt to bind a name that is already bound.
java.rmi.NotBoundException Attempt to lookup a name that is not bound.
java.rmi.UnknownHostException Attempt to contact a registry on an unknown
host.
Exception Occur
java.rmi.RMISecurityException A security exception that is thrown by
the RMISecurityManager.
java.rmi.Server.ServerCloneException Clone failed.
java.rmi.Server.SocketSecurityException Attempts to export object on an illegal
port.
18.5 BOOTSTRAPPING IN RMI
Bootstrapping technique provides the usuage of a special class loader (such as RMI‟s
class loader) instead of the default class loader to download all the classes and interfaces by a
client application during the RMI runtime. The Bootstrapping program needs to:
(i) Create an instance of the RMISecurityManager class or a user defined security manager.
RMISecurityManager, in turn, extends java.lang.SecurityManager. The security manager
ensures that loaded classes adhere to the standard Java safety gurantees, for example that
classes are loaded from trusted sources. Applications must either define their own security
manager or use the restrictive RMISecurityManager. If no security manager is in place, an
application cannot load classes from network sources. A security manager is set using
349
System.setSecurityManager. The security manager is obtained by the
System.setSecurityManager method. The SecurityManager class contains many methods
with names that begin with the word check.
Example:
public void checkRead(FileDescriptor fd){ }
public void checkRead(String filename){ }
public void checkRead(String filename,Object excutionContext){ }
public void checkWrite(FileDescriptor fd)
{
throw new SecurityException(“NoAccess”);
}
public void checkWrite(String filename)
{
throw new SecurityException(“NoAcess”);
}
(ii) Use the method RMIClassLoader.loadClass to load the class file for the client.
Otherwise, the default class loader will try to load the client class file from the local
CLASSPATH. Once a class is loaded by the RMIClassLoader, any classes used
directly by that class are also loaded by the RMIClassLoader and thus are subject to
the security manager restrictions. If an application defines it own security manager
which disallows the creation of a class loader, classes will be loaeded using the
default Class.forName mechanism.
(iii) Use the newInstance( ) method to create an instance of the client and it to Runnable.
Thus the client must implement the java.lang.Runnable interface. The Runnable
interface provides a well-defined interface for starting a thread execution
(iv) Start the client by calling the run( ) method of the Runnable interface. The bootst-
rapping the RMI client is illustrated as:
import java.rmi.RMISecurityManager;
import java.rmi.server.RMIClassLoader;
public class BootStrapClient
{
public static void main(String arg[ ])throws Exception
{
System.setSecurityManager(new RMISecurityManager( ));
URL url = new URL(http://host/myclient);
Class c = RMIClassloader.loadClass(url);
Runnable client = (Runnable)c.newInstance( );
}
}
350
SUMMARY
RMI is used in distributed system, which uses remote procedure calls to remotely invoke
Java methods of the objects stored over a network. In other words, RMI provides object-to-object
communication between different Java Virtual Machines (JVMs) in a network. There are many
distributed object systems, such as Distributed Component Object Model (DCOM), Common
Object Request Borker Architecture (CORBA), and RMI DCOM facilitates distributed compu-
ting on the .NET platform. CORBA is a standard that allows distributed computing between
heterogeneous objects. Java RMI is a purely Java-based implementation. RMI uses Java Remote
Method Protocol (JRMP) on top of TCP/IP. JRMP is a wire-level protocol. It is also defined as a
proprietary, stream-based protocol, which is only partially specified in two versions of RMI. The
first version was released with the JDK1.1 version of RMI and required using skeleton classes on
the server. The second version was released with Java2 SDK. This version has been optimized
for performance and doesnot require skeleton classes. RMI does not eliminate the concept of
sockets; rather, it uses sockets internally over TCP/IP to exchange input and output between
client and server machines. RMI represents a higher level view of networking than sockets.
351
REVIEW QUESTIONS
18.1 What is distributed processing?
18.7 What is the difference between Java Networking and Java RMI?
(a) Write the server interface by extending java.rmi.Remote interface and declare remote
methods for clients.
(b) To make the client as remote object, write an interface which extends java.rmi.Remote and
declare remote methods which are called by a server.
352
APPENDDIX
353
APPENDIX A
Internationalization
Many web sites maintain several versions of web pages, so that readers can choose one written in
a language they understand. Because there are so many languages in the world, it would be
highly problematic to create and maintain enough different versions to meet the needs of all
clients everywhere. Globalization of web applications can be accomplished through the process
of Internationalization and Localization. Internationalization can be defined as the process of
enabling a web application to present different country and region specific formats without
making any changes in the source code of the web application or recompiling the application.
The process of customizing a software or web application for a specific region or language, by
introducing locale-specific components, is known as localization. It enables web applications to
adopt message, number and date formats according to a given locale. Java Standard Edition
(Java SE) provides a rich set of APIs to support Internationalization and Localization of an
application. This section gives a brief introduction about how to use the APIs provided with the
core Java platform to implement Internationalization and Localization. The Internationalization
APIs provided with Java SE can easily adopt different messages, number, date and currency
formats according to different country and region conventions. Java also provides support for
Unicode character sets and a rich set of APIs to manage locale-specific formats. Java SE
provides two common classes to implement Internationalization, Locale and ResourceBundle.
Lets‟s explore these two classes one by one.
354
CODE LANGUAGE CODE LANGUAGE
da Danish ja Japanese
De German ko Korean
el Greek nl Dutch
en English no Norwegian
es Spanish pt Portuguese
fi Finnish sw Swedish
fr French tr Turkish
it Italian zh Chinese
Table A-1 Common Language codes
The constructors of the Locale class can use to create object as:
- Locale myobj = new Locale(“en”, “US”);
- Locale myobj1 = new Locale(“en”, “US”, “VENTURA”);
355
String getDisplayVariant() : Returns the name for lacale‟s variant if it exists.
Locale[ ] getAvailableLocales() : Returns the available locales in an array.
356
The getBundle() method of ResourceBundle class automatically looks for the property file,
provided as a parameter. Then a PropertyResourceBundle is created that refers to the specified
property file. A call to the
ResourceBundle.getBoundle(“ApplicationResouces”, new Locale(“en”, “US”))
method attempts to retrieve the object of the PropertyResourceBoundle class for the file with the
name “ApplicationResouces_en_US.properties”.
The ResourceBundle object can be obtained by using any one of its static getBundle()
methods according to the requirements. These methods use the PropertyResourceBundle class as
a reference to the specified property class. The signature of the getBundle() methods are shown
here:
- getBundle(String baseName) : Returns a resource bundle by using the specified base name, the
default locale and the caller‟s class loader.
- getBundle(String baseName, Locale locale) : Returns a resource bundle by using the specified
base name and locale, and the caller‟s class loader.
- getBundle(String baseName, Locale locale, ClassLoader loader) : Returns a resource bundle by
using the specified base name, locale and class loader.
By default , the getBundle() method searches for the .class file, but uses the .properties
file, if it exists, instead of the .class file.
357
APPENDIX B
MODEL QUESTION PAPER
B. Tech.
Fifth Semester Examination - 2010
JAVA PROGRAMMING
Time: 3 Hours Max. Marks: 70
Answer Question No. f which is compulsory and any five from the rest The figures in the right-
hand margin indicate marks.
358
B. Tech
Fifth Semester Examination - 2011
JAVA PROGRAMMING
Full Marks-70 Time : 3 – Hours
Answer Question No. 1 which is compulsory and any five from the rest.
The figures in the right-hand margin indicate marks.
359
8.(a) Differentiate between Swing and AWT. Explain any two special components in Swing.
5
(b) What is object cloning ? Why is it needed ?
Explain how objects are cloned. 5
********************
B. Tech
Fifth Semester Examination - 2012
JAVA PROGRAMMING
Full Marks-70 Time: 3 Hours
Answer Question No. 1 which is compulsory and any five from the rest. The figures in the right-
hand margin indicate marks.
360
(ii) When invoking a constructor from a subclass, its superclass's no-arg constructor
is always invoked.
(iii) You can override a private method defined in a superclass,
(iv) You can override a static method defined in a superclass.
6.(a) State the differences between Swing and AWT. Explain important components and
container in AWT. 7
(b) What are the advantages of RMI over socket-level programming ? 3
7.(a) What is the layout manager used in JToolBar ? Can you change the layout manager ?
Explain your answer. 4
(b) Write a Java program to find out factorial of a number using I/O Exception. 6
Answer Question No. 1 which is compulsory and any five from the rest.
The figures in the right-hand margin indicate marks.
361
4.(a) WAP to accept five integers from user & and arrange in ascending order. 5
(b) Implement an abstract class Figure which has data members dim1 and dim2 and an
abstract method area(). Two subclasses Triangle and Rectangle are subclassed from
Figure. Write a Java program where the dynamic method dispatch is achieved.
5
5.(a) Write a program in Java to determine the sum of the series for given value of n.
1 + 1/2 + 1/3 + ...... + 1/n 5
(b) Create a class employee with data members employee ID, employee name, designation
and salary .write methods get employeeQ- To take user input, show Grade ( ) - to display
grade of employee based on salary.show employee ( ) to display employee details.
5
6.(a) What is thread? Explain the thread life-cycle with suitable diagram. 5
(b) Explain the various types of JDBC- drivers. 5
7.(a) What is Event ? Explain at least two types of event classes and their corresponding event
listeners. 5
(b) What is an applet ? Write a Java program to create an applet which display your name by
clicking a button. 5
8. Write notes on any two: 5x2
(a) Interface
(b) Java swing
(c) Exception Handling in Java.
*******************
B. Tech
Fifth Semester Examination - 2013
JAVA PROGRAMMING
BRANCH : IT, CSE
QUESTION CODE :C-378
Full Marks -70 Time : 3 Hours
Answer Question No. 1 which is compulsory and any five from the rest. The figures in the right-
hand margin indicate marks.
362
(g) Differentiate between a Java application and an applet.
(h) List two properties of JScrollBar and JSIider.
(i) Which methods in the Thread class are deprecated ?
(j) What are the two use of the keyword super ?
2.(a) What is function overloading ? What are the various ways of overloading a
constructor? Explain. 5
(b) Define inheritance. How the access specifiers modify the behavior of Java program
implementing Inheritance ? Explain. 5
3.(a) How a class is related to a package ? What are the categories of visibility for class
members in a package hierarchy ? 5
(b) What is the difference between an abstract class and an interface and when should you
use them ? 5
4.(a) How can threads communicate with each other ? How would you implement a producer
(one thread) and a consumer (another thread) passing data (via stack)?
5
(b) How errors are handled in Java ? What is a user defined exception ? 5
5.(a) Explain different ways of creating a thread. 5
(b) What is the difference between AWT and Swing ? Explain with an example. 5
6.(a) Draw a Smiley using Java applet to represent on a browser. 5
(b) Write down a Java program to get X and Y coordinates of JTextField. 5
7.(a) Write down a Java program using wrapper classes to convert a hexadecimal
number into a decimal number. 5
(b) What is the order of method invocation in an applet ? 5
8. Write short notes on any two: 5x2
(a) TCP/IP Server Socket
(b) Layout Managers
(c) Remote Method Invocation(RMI)
(d) JDBC.
***************
363
Index
A D
abstract class 92 Data abstraction 2
access specifer 2 Data binding 4
pubic 2,87 Data types 19
private 2,87 Premitve data type 19
protected 2,87 Reference data type 20
default 2,87 DataOutputStream 111
accessing package 108 DataInputStream 111
adapter class 230 DatabaseMetaData interface 332
applet 187 DBC 132
appletviewer 191 deadlock 180
applet life cycle 193 Deep cloning 156
Annotation 163 Distributed object model 336
Array 48 do-while 45
One-dimensional array 49 dynamic method binding 99
Multi-dimensional array 49
Anonymous arrays 50 E
ASCII 17 Encapsulation 2
assertion 132 Enumerated 162
Auto boxing 167 Error class 130
awt 203 Event 224
awt components 206 Unicasting Event 224
Multicasting Event 224
B Event source 224
BootStrap class loader 159 Event handling 224
Break 47 Event handling process 241
Buffering 254 Event delegation model 241
BufferedReader 111 Exception 119
Byte oriented I/O 111 extends 88
ByteStream class 249 Extension class loader 160
C F
Call by reference 63 file 247
Call by value 63 finding array size 51
Chained exception 131 final 74,89
Checked exception 130 finalizer 89
Class 01,57 for 40
Class variable 57 frame 204
Class loader 159
Clone 154 G
Cloneable 154 Graphics class 197
Command line argument 13 GreorianCalendar 281
Compiled language 10 GUI helper class 213
Concrete supper class 92
Conformation dialogs 115 H
Connection oriented protocol 286 HTML 189
Connection less protocol 287 Hungarian Notation 12
Constants 22
Constructor 65
Continue 47 I
Identifier 18
IDS Driver 306
364
if 35 M
if-else 36 method 58
Immutable String setter method 63
InetAddress 290 getter method 62
Infinite loop 46 method overloading 89
Inheritance 3,87 monitor 174
InputStream 110 Multiline comments 13
InputStreamReader 110 MVC 213,243
Inner class 71
Instance variable 57 N
Interpreted language 10 nested switch 39
Integer Literals 18 notify() 177
Interface 96 notifyall() 177
Internationalization
Interned String 140
isAlive() 180 O
Iteration 40 Object 01, 59
Object behavior 4
Operators 19,22
J Arithmetic operator 22
Java 1 Relational operator 25
Java features 8 Logical operator 25
Java program structure 11 Bitwise operator 25
Java Character set 17 Instanceof operator 28
Java key words 17 Dot (.) operator 28
Java Printing API 255 Ternary operator
JDK 8 Operator precedence and associativity 29
JDBC 302 OOP 1,4
JDBC API 303
JDBC Driver Manager 303
JDBC Architecture 308 P
JFrame 215 Polymorphism 4,68
JPanel 215 POP 4
JSplitpane Process 167
JScrollPane 216 Producer-Consumer problem 177
JTree 217 Punctuators 19
JOptionPane 113
JTable 218 R
JImage 219 Random access file 263
JFS 43 Recursion 70
JIT 10 Remote Interface 340
join() 180 ResultSet 314
JRE 9 ResultSet Interface 314
Jump statement 46 ResultSetMetaData 329
JVM 10 ResourceBundl;e class 356
return 64
L RMI 336
Layers of software 4 RMI Architecture 343
Layout manager 205 rmiregistry 356
Literals 18 Runnable Interface 169
Integer literal 18 Runtime class libraries 9
Floating Literal 18
Boolean literal 18 S
Character literal 19 Scanner 77
Selection statement 35
Serialization 158,160,265
Shallow cloning 156
365
Single line comments 13 vector 152,279
Sleep() void 65
Sockets 287 volatile 182
Static 72
Static binding 99 W
Static and dynamic class loading 161 wait() 174
static import 116 weblogic RMI driver 306
String 140 while 45
String Buffer 141,146 whois 295
String Tokenizer 149 wrapper class 153
Super 90
Swing 212
Switch statement 38
Syncronization 174
System class loader 159
System date and time 281
System thread starvation 180
T
TabbedPane 216
TCP 285
TCP based communication 288
this 74
Thin driver 307
thread 167
lifecycle of thread 171
Tokens 17
transient 182,266
TreeMap class 279
Type conversion 28
Implicit type conversion 29
Explicit type conversion 29
Wedening and narrowing conversion 30
Type casting 29
U
UDP 285,291
Unchecked exception 130
URI 293
URL 293
URLConnection class 294
User interface toolkits 9
Util 273
Collection 273
Iterator 274
List 274
Set 275
SortedSet 276
Map 277
SortedMap 274
V
Variables 21
Variable scope 21
Variable default value 58
366