JAVA. Object Oriented Programming with. M.T. Somashekara D.S.Guru K.S. Manjunatha

Similar documents
GUI Event Handling 11. GUI Event Handling. Objectives. What is an Event? Hierarchical Model (JDK1.0) Delegation Model (JDK1.1)

Contents. iii Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services August 1998, Revision B

Advanced Java Programming (17625) Event Handling. 20 Marks

Table of Contents. Chapter 1 Getting Started with Java SE 7 1. Chapter 2 Exploring Class Members in Java 15. iii. Introduction of Java SE 7...

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently.

Unit 1- Java Applets. Applet Programming. Local Applet and Remote Applet ** Applet and Application

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

The AWT Event Model 9

Core JAVA Training Syllabus FEE: RS. 8000/-

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

SIMPLE APPLET PROGRAM

Core Java SYLLABUS COVERAGE SYLLABUS IN DETAILS

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

SCHEME OF COURSE WORK

Introduction to Programming Using Java (98-388)

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

Mobile MOUSe JAVA2 FOR PROGRAMMERS ONLINE COURSE OUTLINE

SELF-STUDY. Glossary

OBJECT ORIENTED PROGRAMMING. Course 8 Loredana STANCIU Room B613

1 OBJECT-ORIENTED PROGRAMMING 1

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming

Introduction to Java Applets 12

Supporting Materials

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

G51PRG: Introduction to Programming Second semester Applets and graphics

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

Road Map. Introduction to Java Applets Review applets that ship with JDK Make our own simple applets

Dr. Hikmat A. M. AbdelJaber

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

COMPSCI 230. Software Design and Construction. Swing

Packages: Putting Classes Together

(2½ hours) Total Marks: 75

ощ 'ршорвшэш! цвн-эориэу ощ 'sajbpossv # PIPG DUJ 'ssjmoossv ^ PIPG pipa w н OX ЛЮН VAV

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

VALLIAMMAI ENGINEERING COLLEGE

Contents 8-1. Copyright (c) N. Afshartous

10/16/2008. CSG 170 Round 5. Prof. Timothy Bickmore. User Analysis Task Analysis (6) Problem Scenarios (3)

John Cowell. Essential Java Fast. How to write object oriented software for the Internet. with 64 figures. Jp Springer

Module 5 Applets About Applets Hierarchy of Applet Life Cycle of an Applet

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

GUI Software Architecture

15CS45 : OBJECT ORIENTED CONCEPTS

PESIT Bangalore South Campus

SNS COLLEGE OF ENGINEERING, Coimbatore

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

Chapter 1 GUI Applications

Which of the following syntax used to attach an input stream to console?

Overloading Example. Overloading. When to Overload. Overloading Example (cont'd) (class Point continued.)

PESIT Bangalore South Campus

Murach s Beginning Java with Eclipse

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

SD Module-1 Advanced JAVA

Object Oriented Programming with Java. Unit-1

SD Module-1 Advanced JAVA. Assignment No. 4

UNIT-2: CLASSES, INHERITANCE, EXCEPTIONS, APPLETS. To define a class, use the class keyword and the name of the class:

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

(Refer Slide Time: 02:01)

Get Unique study materials from

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

Essential Series. Springer-Verlag London Ltd.

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

Assignment No 2. Year: Dept.: ComputerTech. Sanjivani Rural Education Society s Sanjivani KBP Polytechnic, Kopargaon

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA

Java Application Development

Come & Join Us at VUSTUDENTS.net

UNIT -1 JAVA APPLETS

DHANALAKSHMI SRINIVASAN COLLEGE OF ENGINEERING AND TECHNOLOGY ACADEMIC YEAR (ODD SEM)

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1

9. APPLETS AND APPLICATIONS

Java TM Applets. Rex Jaeschke

Compaq Interview Questions And Answers

COP 3330 Final Exam Review

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

Java Applets / Flash

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

S.No Question Blooms Level Course Outcome UNIT I. Programming Language Syntax and semantics

Objective Questions. BCA Part III Paper XIX (Java Programming) page 1 of 5

Module 4 Multi threaded Programming, Event Handling. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

5/23/2015. Core Java Syllabus. VikRam ShaRma

1 Shyam sir JAVA Notes

An applet is called from within an HTML script with the APPLET tag, such as: <applet code="test.class" width=200 height=300></applet>

Java 1.8 Programming

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 9: Writing Java Applets. Introduction

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

CS Exam 1 Review Suggestions

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

CS201 - Introduction to Programming Glossary By

"Charting the Course... Java Programming Language. Course Summary

Contents Introduction 1

Java - Applets. C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1,

A- Core Java Audience Prerequisites Approach Objectives 1. Introduction

Transcription:

PH IL ea rn in g C op yr ig ht ed JAVA M at er ia l Object Oriented Programming with M.T. Somashekara D.S.Guru K.S. Manjunatha

Object Oriented Programming with JAVA M.T. SOMASHEKARA Department of Computer Science and Applications Bangalore University, Bengaluru D.S. GURU Department of Studies in Computer Science University of Mysore, Mysuru K.S. MANJUNATHA Department of Computer Science Maharani s Science College for Women, Mysuru Delhi-110092 2017

Foreword xv Preface xvii Acknowledgements xix v Contents 1. Introduction to Object Oriented Programming Paradigm... 1 14 1.1 Introduction 1 1.2 Evolution of Higher Level Languages 1 1.2.1 The General Topology of Object Based and Objects Oriented Language 4 1.3 Complexity of Softwares and their Attributes 5 1.4 Object Orientated Programming Paradigm 7 1.4.1 Basic Principles of Object Oriented Programming 8 1.4.2 Advantages of Object Oriented Programming 12 1.4.3 Applications of Object Oriented Programming 12 1.4.4 Object Oriented Programming Languages 13 Summary 13 Review Questions 14 2. Introduction to the JAVA Language...15 20 2.1 Introduction 15 2.2 Evolution of Java 15 2.3 Salient Features of Java Language 16 2.4 Java, Internet and World Wide Web 19 2.5 The Java Environment 19 Summary 20 Review Questions 20

vi Contents 3. The JAVA Language Preliminaries...21 34 3.1 Introduction 21 3.2 Keywords and Identifiers 22 3.3 Constants 23 3.3.1 Numeric Constants 23 3.3.2 Character Constants 26 3.4 Variables 27 3.5 Data Types 27 3.6 Console I/O 28 3.7 Structure of a Java Program 31 3.8 Sample Program 31 3.9 Executing a Java Program 32 3.10 Errors 32 Summary 33 Review Questions 34 4. Operators and Expressions... 35 74 4.1 Introduction 35 4.2 The Assignment Operator [=] 36 4.3 The Arithmetic Operators [unary +, unary, +,, *, /, %] 37 4.3.1 Types of Arithmetic Expressions 40 4.3.2 Precedence of Arithmetic Operators and Associativity 41 4.4 The Relational Operators [<, <=, >, >=, ==,!=] 44 4.5 The Short Circuit Logical Operators [&&,,!] 46 4.6 The Arithmetic Assignment Operators [+=, =, *=, /=, %=] 49 4.7 The Increment/Decrement Operators [++, ] 51 4.8 The Conditional Operator [?:] 53 4.8.1 Nesting of Conditional Operators 54 4.9 The InstanceOf() Operator 55 4.10 The Dot Operator [.] 56 4.11 The Bitwise Operators [&,, ^, ~, <<, >>, >>>] 56 4.11.1 Application of Bitwise Operators 62 4.12 Type Conversion 64 4.13 Precedence Levels and Associativity among all the Operators 69 Summary 70 Review Questions 70 True/False Questions 73 Programming Exercises 73

Contents vii 5. Selection...75 101 5.1 Introduction 75 5.2 The Simple if Statement 76 5.3 The If-Else Statement 78 5.4 The Nested If-Else Statement 80 5.5 The else-if Ladder 82 5.6 The Switch Statement 88 5.7 Nested Switch Statement 96 Summary 98 Review Questions 98 True/False Questions 99 Programming Exercises 100 6. Iteration...102 135 6.1 Introduction 102 6.2 The while loop 103 6.3 The for loop 109 6.3.1 Variations of for Loop 112 6.4 The Do-While loop 114 6.5 Which Loop to Use When? 119 6.6 Jumps in Loops 119 6.7 Nesting of Loops 124 6.7.1 Jumps in Nested Loops 127 6.8 Labeled Loops 132 Summary 133 Review Questions 133 True/False Questions 134 Programming Exercises 134 7. Classes, Objects and Methods...136 193 7.1 Introduction 136 7.2 Class Definition Instance Variables and Member Methods 136 7.3 Declaration and Creation of Objects, Accessing Members 137 7.4 Classification of Member Methods 139 7.5 Constructors 147 7.5.1 Constructors without Arguments 147 7.5.2 Constructors with Arguments 149 7.5.3 Copy Constructors 151 7.6 The this Keyword 153 7.7 Passing Objects to Methods as Arguments 154 7.8 Methods Returning an Object 157

viii Contents 7.9 Static Member Data 162 7.10 Static Member Methods 167 7.11 Static Blocks 169 7.12 Nesting of Member Methods 170 7.13 Recursion 172 7.14 Nested Classes 176 7.14.1 Non-static Nested Classes or Inner Classes 176 7.14.2 Static Nested Classes 178 7.15 Local Classes 179 7.16 Anonymous Classes 181 7.17 Final Members 182 7.18 Variable Arguments 184 7.19 Objects of One Class as Instance Variables of Another Class (Containment) 187 7.20 Garbage Collection and Finalise Method 189 Summary 189 Review Questions 190 True/False Questions 191 Programming Exercises 192 8. Inheritance...194 234 8.1 Introduction 194 8.2 Types of Inheritance 198 8.2.1 Single Level Inheritance 198 8.2.2 Multilevel Inheritance 201 8.2.3 Multiple Inheritance 206 8.2.4 Hierarchical Inheritance 207 8.2.5 Hybrid Inheritance 212 8.3 Constructors and Inheritance 213 8.4 Abstract Classes and Methods 217 8.5 Dynamic Method Dispatch 222 8.6 Object Slicing 226 8.7 Object Typecasting 228 8.8 The Final Keyword 230 Summary 231 Review Questions 232 True/False Questions 233 Programming Exercises 233 9. Interfaces...235 254 9.1 Introduction 235 9.2 Defining Interfaces 235 9.3 Implementing Interfaces 236

Contents ix 9.4 Polymorphism through Interfaces 239 9.5 Implementing an Interface Partially 240 9.6 Extending Interfaces 242 9.7 Implementing Multiple Interfaces 245 9.8 Multiple Inheritance through Interfaces 248 Summary 253 Review Questions 253 True/False Questions 254 Programming Exercises 254 10. Packages...255 288 10.1 Introduction 255 10.2 Classification of Packages 255 10.3 Creating and Using a Package 256 10.4 To Create a Package Spread across Multiple Files 258 10.5 Importing Classes from a Package (Hiding Classes in a Package) 260 10.6 Nested Packages 263 10.7 Extending Imported Classes 266 10.8 Classes and Interfaces in a Package and Using Them 267 10.9 Static Importing 269 10.10 Access Control 274 10.10.1 Private Access 274 10.10.2 Default Access 276 10.10.3 Protected Access 278 10.10.4 Public Access 282 Summary 287 Review Questions 287 True/False Questions 287 Programming Exercises 288 11. Arrays...289 339 11.1 Introduction 289 11.2 One-dimensional Arrays 290 11.3 Multi-dimensional Arrays 306 11.3.1 Two-dimensional Arrays (2-D arrays) 307 11.3.2 Three-dimensional Arrays 313 11.4 Arrays and Methods 318 11.4.1 One-dimensional Arrays as Arguments to Methods 318 11.4.2 Passing Two-dimensional Arrays to Methods 322 11.5 Arrays within Class 325 11.5.1 One-dimensional Array within Class 325 11.5.2 Two-dimensional Array within Class 329

x Contents 11.6 Arrays of Objects 332 Summary 335 Review Questions 335 True/False Questions 336 Programming Exercises 336 12. String Handling...340 356 12.1 Introduction 340 12.2 The String Class 340 12.2.1 The Constructors of the String Class 340 12.2.2 The Member Methods of the String Class 342 12.3 The StringBuffer Class 350 12.3.1 The Constructors of the StringBuffer Class 350 12.3.2 The Member Methods of the StringBuffer Class 351 Summary 354 Review Questions 354 True/False Questions 355 Programming Exercises 355 13. Exception Handling...357 387 13.1 Introduction 357 13.2 Types of Exceptions 357 13.2.1 Built-in Exceptions 358 13.2.2 Custom Exceptions 359 13.3 Default Exception Handling Mechanism 359 13.4 User-Defined Exception Handling Mechanism 360 13.5 Single Try Block and Multiple Catch Blocks 365 13.6 Catching Multiple Exceptions with a Single Catch Block 367 13.7 Nested Try Blocks 369 13.8 Stack Unwinding 374 13.9 Chained Exceptions 376 13.10 Throw Statement 377 13.11 Throws Statement 378 13.12 Finally Statement 379 13.13 Try with Resources Statement 383 13.14 Custom Exceptions 384 Summary 386 Review Questions 386 True/False Questions 387 Programming Exercises 387

Contents xi 14. Multithreaded Programming...388 437 14.1 Introduction 388 14.2 The Java Thread Model 389 14.3 The Life Cycle of a Thread 389 14.4 The Thread Class 390 14.5 The Main Thread 392 14.6 Creating Our Own Threads 393 14.6.1 Extending the Thread Class 393 14.6.2 Implementing Runnable Interface 395 14.7 Creating Multiple Children Threads 397 14.8 Forming Groups of Threads 401 14.9 Thread Priorities 403 14.10 Synchronisation 406 14.10.1 Synchronised Method 409 14.10.2 The Synchronised Statement 412 14.11 Deadlock 415 14.12 Suspending and Resuming Threads 418 14.13 Producer-Consumer Relationship between Threads 426 14.14 Daemon Threads 433 Summary 435 Review Questions 436 True/False Questions 436 Programming Exercises 437 15. File Handling...438 472 15.1 Introduction 438 15.2 The File Class 439 15.3 I/O Stream Classes Related to File Handling 447 15.4 The Character Stream Classes 449 15.5 The Byte Stream Classes 458 15.6 Mixed Data I/O Streams 463 15.7 Object I/O Streams 466 15.8 Random Access File 469 Summary 470 Review Questions 471 True/False Questions 472 Programming Exercises 472 16. Applets...473 494 16.1 Introduction 473 16.2 Types of Applets 474

xii Contents 16.3 The Life Cycle of an Applet 476 16.4 Creating and Executing an Applet 478 16.5 The Attributes in the <applet> Tag 483 16.6 Passing Parameters to Applets 484 Summary 492 Review Questions 493 True/False Questions 493 Programming Exercises 494 17. Introduction to AWT...495 554 17.1 Introduction 495 17.2 AWT Hierarchy 495 17.3 Event Handling 496 17.4 AWT Controls 499 17.4.1 Labels 499 17.4.2 Buttons 501 17.4.3 Checkbox 503 17.4.4 CheckboxGroup 506 17.4.5 Lists 509 17.4.6 Choice Control 512 17.4.7 Scrollbar Control 514 17.4.8 TextField 519 17.4.9 TextArea 521 17.5 Layout Managers 523 17.5.1 Flow Layout 523 17.5.2 Border Layout 525 17.5.3 Grid Layout 526 17.5.4 Card Layout 528 17.5.5 GridbagLayout 531 17.5.6 Panels 531 17.6 AWT Window-Level Controls 534 17.6.1 Windows 534 17.7 Handling Keyboard Events 541 17.8 Handling Mouse Events 543 17.9 Handling Events with Specialised Classes 545 17.9.1 Handling MouseEvents through MouseAdapter Class 546 17.9.2 Inner Classes 548 17.9.3 Anonymous Inner Classes 549 Summary 551 Review Questions 552 True/False Questions 552 Programming Exercises 553

Contents xiii 18. Basic Utility Classes [java.lang Package]...555 582 18.1 Introduction 555 18.2 The Wrapper Classes 555 18.2.1 The Number Class 555 18.2.2 The Byte Class 556 18.2.3 The Short Class 558 18.2.4 The Integer Class 559 18.2.5 The Long Class 562 18.2.6 The Float Class 565 18.2.7 The Double Class 567 18.2.8 The Character Class 569 18.2.9 The Boolean Class 571 18.3 The System Class 572 18.4 The Object Class 574 18.5 The Class Class 575 18.6 The Runtime Class 577 18.7 The Process Class 579 18.8 The Void class 579 18.9 The Math Class 579 Summary 581 Review Questions 581 True/False Questions 582 Bibliography...583 583 Index...585 590

Foreword Computer programming has evolved over the last six decades, starting from assembly language programming and progressing through simple procedural languages, block structured procedural languages, object oriented languages, functional languages, and scripting languages. Each evolution was started by the prevailing hardware and the demand for applications. One major evolution was the emergence of object oriented languages, which were later adapted to be applicable in this era of the Internet in which diverse computers distributed all over the world are interconnected. Java, which was initially developed as a small object oriented language to program embedded systems, evolved as a general purpose programming language to meet the needs of programmers who were required to write programs which could be executed on the Internet. Currently, Java is the programming language of choice in many industries, particularly those involved in creating large-scale applications using the Internet. This book by Dr. M.T. Somashekara, Dr. D.S. Guru, and Mr. K.S. Manjunatha is a very useful addition to the library of books on Java programming. The main merit of this book is that it starts from basics and builds gradually to a substantially high level to enable students to write programs for Internet applications. All important concepts are illustrated with Java programs, an important pedagogical tool. The book is well written with a number of learning aids such as summary, review questions, true-false questions, and programming exercises. This book has been classroom tested by the experienced authors Dr. Somashekara, Dr. Guru, and Mr. Manjunatha. The book is suitable for the undergraduate students of Computer Science. I am sure students as well as working professionals will find this book an invaluable aid in learning how to program using Java. xv V. Rajaraman Indian Institute of Science Bengaluru

Preface The Java language is a general purpose and a purely object oriented language invented by a group of computer scientists at Sun Micro Systems during 1990s to meet the varied needs of embedded world. The fascinating and principal features of the language such as object oriented, platform independence, architectural neutral, robust and security were needed to support the development of embedded software for various electronic devices like TVs, refrigerators, etc. Incidentally the same features were required to be supported for computing in the internet world and also considering the heterogeneous nature of the computing devices employed in the internet world. As a result, the Java language became very close to the internet computing world. Because of its affinity to the internet, the language is referred to as the language of the internet. The book is expected to cater to the needs of both undergraduate and postgraduate students of Computer Science and Information Technology offered by Indian universities because the contents of the book has been developed after paying due attention to the syllabi of various Indian universities. Another hallmark of the book is that it needs no previous knowledge of programming. The book takes the reader from the basic principles of Java programming towards advanced aspects like exception handling, multithreading, IO streams, etc. in an incremental fashion. The readers will, no doubt, experience comfort while assimilating the concepts and programming using them. The book has been organised in well-planned 18 chapters. Chapter 1 introduces the object oriented paradigm, its advantages and disadvantages; identifies the languages supporting the object oriented paradigm; and also sets the tone for learning the Java language. Chapter 2 highlights the importance of the Java language by discussing the striking features offered by it to align itself to support platform independence and thereby finding a predominant place in the internet programming. Chapter 3 talks about the preliminaries of the Java language. Chapter 4 discusses the operators supported by the Java language with suitable illustrations for each kind of operators. Chapter 5 throws light on the selection structures supported by xvii

xviii Preface Java with examples and programs for each variation of the structures. Chapter 6 throws light on the iterative structures supported by Java with examples and programs for each variation of the structures. Chapter 7 introduces the concepts of classes, objects and methods, the core concepts underlying the object oriented programming. Chapter 8 discusses another important feature of OOP, the concept of inheritance in detail. Chapter 9 deals with the concept of interfaces. Chapter 10 deals with the concept of packages, wherein we can logically group classes and interfaces depending on the requirement. The concept of packages enables us to compartmentalise the classes and interfaces for better management of them. Chapter 11 delves into the concept of arrays in detail. Here arrays of one dimension, two dimensions, three dimensions and array of objects, and methods with arrays are explained in detail. Chapter 12 details string handling in Java. The detailed discussion includes various string manipulation methods available in the String class and also the String buffer class. Chapter 13 delves into exception handling mechanism supported by Java. It also discusses types of exceptions and the ways they are handled. Chapter 14 focuses on multithreaded programming, which is one of the striking features of Java supporting optimisation of the systems resources and enhancement of the speed of execution of programs. Chapter 15 provides a thorough discuss on IO-Streams and their handling with the help of the built-in classes and their methods. Chapter 16 turns our attention towards applets, a special category of programs that are developed in Java and their relationship to web programming. Chapter 17 deals with the graphical user interface facility provided by Java through a group of classes embodied in a toolkit called AWT toolkit. The toolkit contains a number of classes each representing a type of window control used in the design of the graphical user interface. Chapter 18 details most of the commonly used utility classes housed in the java.lang package which are used frequently while developing applications with Java. Almost all the chapters are followed by a brief summary of the concepts covered to better enable the readers to consolidate their learning, review questions, true-false questions and programming exercises. Constructive criticism and suggestions from the readers are always welcome. They will go a long way in further improvement of the book. In fact, this is how the knowledge and the book grow. You may kindly reach us at somashekar_mt@hotmail.com or dsguruji@yahoo.com or kowshik.manjunath@gmail.com with your feedback. M.T. Somashekara D.S. Guru K.S. Manjunatha

16 16.1 INTRODUCTION Applets All the Java programs developed so far in the previous chapters are called application programs developed for the purpose of accomplishing a task. There is another type of programs which can be developed using Java. They are called applets that run on WWW. The applets are small Java programs written for the purpose of accomplishing a part of a task. The applets reside in web pages in the WWW and they are executed by the web browsers when the web pages containing them are loaded in the client systems. They are capable of displaying graphics, playing audio, etc. In all, the applets enable the Java programmers to provide the right graphical user interface. As we have noticed, the Java applications are characterised by the following features: 1. They are normally programs of bigger size. 2. They have main() method, from where the execution of the program starts. 3. The Java applications are run by the Java interpreter. 4. The Java applications are standalone programs as they can be executed directly by launching them. 5. They can access the files and other resources at the local system, where they are launched for execution. 6. They advocate character user interface. Because of the association of the Java language with the internet and ability to contribute to the internet application developers and the users powered by its inherent features, one more kind of Java programs originated are called applets. Following are the features of Applets which are different from the Java applications: 1. Applets are tiny programs. 2. Applets do not have main() method. They must be embedded in a web program to run them. 473

474 Object Oriented Programming with JAVA 3. Applets are run by Java enabled browsers and appletviewer tool shipped with the JDK. 4. They advocate graphical user interface. 5. Applets are web based programs. 16.2 TYPES OF APPLETS The applets can be classified into two types depending on where they originate from. They are (i) Local applets and (ii) Remote applets. Local applets, as the name itself indicates, are those that are created at the local system and they can be run in the system. Remote applets are those that are created in the remote systems and downloadable from the remote systems to the local systems and they can be run. As there are chances of security violations by the applets, certain restrictions are imposed on applets in the interest of the security of the systems. They are the following: 1. They cannot access the files and other resources at the local system for security reasons. 2. They cannot communicate with other servers in the network. 3. They cannot execute other programs. 4. They can not invoke routines of other languages like C, C++. The Applet class in the Java.applet package hierarchy is central to implementing the applets. The Java.applet.Applet class extends the Java.awt.panel class, the Java.awt.Container class, the Java.awt.Component class and the Java.lang.Object class in a multilevel hierarchy. The hierarchy is depicted in Figure 16.1. Applet class inheritance hierarchy. The most commonly used methods in the Applet class are given in Table 16.1 and important methods of the component class are given in Table 16.2.

Applets 475 Methods in the Applet class void init() void start() void stop() void destroy() Method with signature AppletContext getappletcontext() String getappletinfo() AudioClip getaudioclip(url url) URL getcodebase() URL getdocumentbase() Image getimage(url url) Image getimage(url url, String imagename) String getparameter(string param) void play(url url) void play(url url, String clipname) Purpose Begins the execution of the applet. This is the first method called on an applet. Starts the executing the applet. Gets called automatically when init() is called. It also called to resume the applet s execution if the applet had been stopped earlier. Stops the applet temporarily. Informs the applet to destroy itself after releasing the resources used by it. Returns the context associated with the applet. Returns a string that describes the applet. Returns an AudioClip object for the audio clip found at the location identified by URL. Returns the URL associated with the applet. Returns the URL of the html document of the applet. Returns an Image object for the image found at the location identified by url. Returns an Image object for the image found at the location identified by url and with the same name as imagename. Returns the parameter associated with the name param. Returns null if the parameter is not found. Plays an audio clip found at the location identified by url. Plays the audio clip found at the location identified by url and having the name clipname. void resize(dimension d) Resizes the applet according to the dimension d. void showstatus(string str) Displays the string str in the status window of the browser or the appletviewer. No action takes place if the browser or the appletviewer does not support a status window. Methods of the Component class Component class void paint(graphics g) void update(graphics g) void repaint() void setbackground(colour bcolour) Purpose Draws text or graphics on the screen. Fills the screen with the background colour and calls the paint() method. Schedules call to the update() method. Sets the background colour of the component with bcolour. (Contd...)

476 Object Oriented Programming with JAVA Methods of the Component class (Contd...) Component class void setforeground(colour fcolor) Purpose Sets the foreground colour of the component with fcolour. synchronised void setfont(font f) Sets the font of the component with the font f. Font getfont() void setsize(dimension d) void setsize(int width, int height) Dimension getsize() Retrieves the font of the component. Sets the size of the component with the dimension d. The Dimension class has width and height as the data members. Sets the size of the component with the given width and height. Retrieves the size of the component. 16.3 THE LIFE CYCLE OF AN APPLET An applet goes through a number of states from the point of its creation to the point of destruction. They are: 1. Initialization state 2. Running state 3. Idle state or stopped state 4. Dead state The life cycle of an Applet is shown in Figure 16.2. Initialisation State Life cycle of an applet. When an applet is loaded into memory of the client machine by the web browser or the appletviewer, the init() method of the applet of the Applet class is invoked. The execution of the init() method brings the applet to the initialisation state. During the initialisation state, we can initialise the required variables, create the required objects, load the required images and fonts and set the required colours, etc. An applet assumes the initialisation state only once in its life cycle. The initialisation behaviour of an applet can be realised by overriding the init() method of the Applet class as follows:

Applets 477 void init() { // code for the expected behaviour here } Running State After the initialisation state, the start() method of the Applet class is invoked automatically. Then the applet is said to have moved to the running state. The start() method also gets invoked on the resumption of the execution of an applet automatically when the applet had been stopped for a while (when we leave a web page temporarily and return back to the same web page). We may override the start() method also of the Applet class to alter the course of action of the applet as follows: void start() { // code for the expected behaviour here }` Soon after the applet moves into the running state, the applet s paint() method gets executed which displays the outputs in a window of the applet on the screen. Idle State An applet enters into the idle state when its execution is stopped temporarily. Stopping the execution of the applet can be done by leaving the web page containing the applet temporarily or invoking the stop() method on the applet explicitly. An applet in the idle state can be brought back to running state by bringing the web page containing the applet into focus or by calling the start() method on the applet explicitly. In essence, an applet can switch from idle state to running state and vice-versa many times. Dead State An applet enters into dead state when the web browser or the appletviewer invokes the destroy() method on the applet. The dead state is the final state of an applet. Normally the destroy() method does not need to be overridden to reclaim the resources used by the applets as the Java has a built-in mechanism called garbage collector to do the job. However, if an applet has created threads, the destroy() is overridden to release them. The overridden destroy() method takes care of the expected behaviour has the following form: void destroy() { // code for the expected behaviour here }

478 Object Oriented Programming with JAVA Painting The process of displaying of outputs on the window of an applet is accomplished by paint() method of the Applet class. In fact, the paint()in the Applet class method does nothing. It needs to be overridden to display the required text, graphics on the window of the applet. It gets called automatically whenever the applet gets into the running state. It also gets called when the window of the applet is resized or when the window is moved from one location to another location. The overridden paint() method takes the form as: void paint(graphics g) { // painting code here } Note that the paint() method is the only method which takes an argument. Here the argument is of type Graphics class. The package Java.awt which contains the class should be imported into the program. 16.4 CREATING AND EXECUTING AN APPLET There are four steps involved in creating and executing an applet. They are: 1. Creating a Java source file for the applet (.java file ) 2. Compiling the Java source file to get the equivalent class file (.class file) 3. Creating an html file 4. Executing the applet Let us now follow these steps to create a simple applet and execute it. Creating a Java source file for the applet (.java file ) Here we create the Java source file namely AppletDemo.Java and write in it the required Java code for an applet. Creating the AppletDemo.Java file import Java.awt.*; import Java.applet.*; public class AppletDemo extends Applet { public void paint(graphics g) { g.drawstring( First Applet, 100, 100); } }

Applets 479 The classes in the packages Java.awt and Java.applet are imported with the statements import Java.awt.*; and import Java.applet.*;. The public class AppletDemo extends the class Applet and it overrides the paint() method. Note that the method paint() takes an object of type Graphics as its argument and in the body of the method, the drawstring() method of the Graphics class is invoked to display the string First Applet at the position 75, 75 in the window of the applet. Compiling the Java source file We compile the Java source file AppletDemo.java using the Java compiler Javac: Javac AppletDemo.Java [return] The class file AppletDemo.class is created on successful compilation of the source file AppletDemo.Java. Creating an html file Here we create an html file with the same name as that of the class for the applet in the Java source code with the extension.html. So the html file being created is AppletDemo.html. The AppletDemo.html file <html> <head> <body> <applet code = AppletDemo.class width = 50 height = 50> </applet> </body> </head> </html> Executing the applet Here we use the appletviewer tool of the JDK to run the applet. Note that the input to the appletviewer is the html file. appletviewer AppletDemo.html [return] The applet window appears as below on its execution.

480 Object Oriented Programming with JAVA Output We can even embed the applet tag within the Java source file itself and make it a comment and compile the source file using javac compiler and the program can also be run using the Java tool appletviewer. The argument to the appletviewer is the Java source file itself. Let us modify the AppletDemo.Java to have the applet tag as a comment and compile it using Javac and execute it using the Java tool appletviewer. // AppletDemo1.Java PROGRAM 16.1 To illustrate an applet import Java.awt.*; import Java.applet.*; /* <applet code = AppletDemo1.class width = 300 height = 300 align = top> </applet> */ public class AppletDemo1 extends Applet { public void paint(graphics g) { g.drawstring( First Applet, 125, 150); } }

Applets 481 Compiling AppletDemo.Java Javac AppletDemo1.Java [return] After successful compilation, we will run it using the Java interpreter as given below: Running the applet Appletviewer AppletDemo1.Java Output // AppletDemo2.Java PROGRAM 16.2 To illustrate an applet import Java.awt.*; import Java.applet.*; /* <applet code = AppletDemo2.class Height = 200 width = 200> </applet> */ public class AppletDemo2 extends Applet { public void paint(graphics g) { int length, breadth;

482 Object Oriented Programming with JAVA length = 10; breadth = 5; } } int area = length * breadth; String str1 = Length = + String.valueOf(length); String str2 = Breadth = + String.valueOf(breadth); String str3 = Area = + String.valueOf(area); String str = Area = + String.valueOf(area); g.drawstring(str1, 50, 60); g.drawstring(str2, 50, 75); g.drawstring(str3, 50, 100); Compiling the AppletDemo2.Java Javac AppletDemo2.Java [return] Running the applet Output Appletviewer AppletDemo2.Java [return]

Applets 483 16.5 THE ATTRIBUTES IN THE <APPLET> TAG Table 16.3 contains the attributes of the applet tag and their purposes. Attributes of the applet tag and their purposes Attribute CODEBASE = codebase_url (Optional) CODE = AppletFilename.class WIDTH = pixels HEIGHT = pixels NAME = instance name of the applet (Optional) ALIGN = alignment (Optional) HSPACE = pixels (Optional) Purpose Specifies the URL of the directory where the applet resides. If the applet and the html file reside in the same directory, then the codebase attribute may be omitted. Specifies the name of the applet class file and it should be specified. Specifies the width of the applet window. Specifies the height of the applet window. A name may be specified for an applet to identify it. Naming of applets is useful in case of inter-applet communication. Specifies the position of the applet on the webpage. This attribute can take any of the following values: TOP, BOTTOM, LEFT, RIGHT, MIDDLE, ABSMIDDLE, ABSBOTTOM, TEXTTOP, BASELINE Specifies the amount of horizontal space surrounding the applet. This is used only when the attribute ALIGN is set to either LEFT or RIGHT. VSPACE = pixels (Optional) Specifies the amount of vertical space surrounding the applet. This is used only when the attribute ALIGN is set to either TOP or BOTTOM. ALT = alternate text (Optional) Non-Java browsers will display this text. The syntax of the <APPLET> tag in its full form is as follows: <APPLET [CODEBASE = codebase_url] CODE = AppletFileaname.class [ALT = alternate text] [NAME = instance name of the applet] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] > [ <PARAM NAME = param1 VALUE = value1> ] [ <PARAM NAME = param2 VALUE = value2> ] </APPLET>

17 17.1 INTRODUCTION Introduction to AWT One of the notable things of the Java programming language is its ability to support graphical user interface (GUI). We have already seen the usage of the GUI elements like textboxes, buttons, labels, etc. that are used in applets in the previous chapter. These are user friendy as they offer ease of use and flexibility to interact with the applets. A separate package namely java.awt is dedicated for the purpose of encapsulating the facility of GUI elements like labels, buttons, textfields, scrollbars, lists, choices, etc. Each of these controls is implemented with the help of a separate dedicated class. All these classes are held in the java.awt package. The AWT facility uses the native GUI support of the system. It provides an abstraction of the native GUI and thus offers flexibility to the programmers shielding the internal details of the native GUI. The package java.awt should invariably be imported into the program which uses any of the classes in it. 17.2 AWT HIERARCHY The AWT hierarchy comprises of a number of classes useful for creating and using the AWT controls like Labels, TextField, TextArea, List, Choice, Window, Frame, Dialog, etc. The Figure 17.1 depicts the hierarchy of the classes for the AWT components. Component Component is the super class for all the classes related to AWT components. It represents an object having graphical representation that can be displayed on the screen and the user can interact with it. It has a number of methods for various operations like event handling, managing graphics, dealing with size of the component, etc. Labels, Buttons, Choices and Lists are all examples of components. 495

496 Object Oriented Programming with JAVA Container AWT window hierarchy. A Container is a component which can hold other components. Examples of Containers in the GUI are Frames, Dialogs, Windows and Panels. All these are inherited from the Container class. All the other components are discussed in detail in the sections to follow: 17.3 EVENT HANDLING Central to interaction with the GUI elements used by Java applets and Java applications are handling the events generated by the GUI elements. An event is defined to be a change in the state of an object. The object which generates the events is called the event source. Examples for event sources include the input devices such as keyboard, and mouse. The event sources also include all the AWT controls like Button, TextField, List, Choice, Scrollbar, etc. In the section to follow, we delve into the details of all the events and their sources. The Delegation Event Model The delegation event model is the modern and sophisticated approach towards handling events generated by different sources. Here the sources are registered with predefined interfaces designated as event listeners, which embody the signatures of the methods responsible for handling the events. The events handling is delegated to classes, which provide the implementation for the methods. Hence here we see a clean separation between the events sources and the event handlers. Event source is registered with event listener implemented by event handler. Registering an event listener for an event source is done with the method: void addeventlistener(eventlistener el) We can even unregister an event listener, if need be. Unregistering an event listener for an event source is done with the method:

497 void removeeventlistener(eventlistener el) The event handler class has the following form: class classname implements EventListener { Methods for handling the events } Let us now get to know the participants in the delegation event model which play their roles in handling events in a clean and efficient way. The participants include event classes, events, event listeners and event handling methods. Table 17.1 shows the list of events and the situations in which the events are generated. Name of the event class and situation in which the event is generated Name of the event class ActionEvent AdjustmentEvent ComponentEvent ContainerEvent FocusEvent InputEvent ItemEvent KeyEvent MouseEvent TextEvent WindowEvent Events and Event Listeners Situations in which the event is generated Whenever a menu item is selected or ENTER key is pressed, a list item is double-clicked in a TextField or in a TextArea Whenever a scrollbar is manipulated Whenever a component is hidden, moved, resized and made visible Whenever a component is added or removed from a container Whenever a component gains or losses keyboard focus Whenever a mouse event or key event occurs Whenever a checkbox is checked, an item in a list control is selected, a choice control is selected, and a checkable menu item is selected or deselected Whenever input from the keyboard is accepted Whenever the mouse is dragged, moved, pressed, released and when the mouse enters or leaves a component Whenever the content in a TextField or a TextArea is changed Whenever a window is activated, deactivated, iconified, deiconified, opened or closed Each event is associated with its corresponding listener. Table 17.2 shows the list of events and the corresponding event listeners. Events and event listeners Events ActionEvent AdjustmentEvent ComponentEvent ContainerEvent Event listeners ActionListener AdjustmentListener ComponentListener ContainerListener (Contd...)

498 Object Oriented Programming with JAVA FocusEvent ItemEvent KeyEvent MouseEvent TextEvent WindowEvent Events and event listeners Events Event listeners FocusListener ItemListener KeyListener MouseListener TextListener WindowListener Each event is associated with one or more methods for handling the event. Table 17.3 shows the list of events and the corresponding event handling methods. ActionEvent AdjustmentEvent ComponentEvent ContainerEvent FocusEvent ItemEvent KeyEvent MouseEvent TextEvent Events and event handling methods Events Event handling methods actionperformed() adjustmentvaluechanged() componenthidden() componentmoved() componentresized() componentshown() componentadded() componentremoved() focusgained() focuslost() itemstatechanged() keypressed() keyreleased() keytyped() MouseClicked() MouseEntered() MouseExited() MousePressed() MouseReleased() MouseDragged() MouseMoved() textvaluechanged() WindowEvent windowactivated() windowclosed() windowclosing() windowdeactivated() windowiconified() windowdeiconified() windowopened()

499 17.4 AWT CONTROLS The AWT controls that can be placed on the containers like Labels, Buttons, TextFields, etc. are discussed with the supporting programs in detail here. 17.4.1 Labels A Label is a control used for holding a static text. It is usually placed before a control which can hold text that can be changed, for instance a TextField. For example, a label with the text Name: is placed before a TextField which is meant for receiving a string for the name of a person from a user. Following are the constructors of the Label class which may be used for creating a label: Label() Creates a label with no string assigned to it. Label(String s) Creates a label with the string s assigned to it. Label(String s, int align) Creates a label with the string s assigned to it and also sets the alignment of the string within the label through the argument of int type align. The possible values that can be taken by the int argument align are LEFT, RIGHT and CENTRE to indicate that the string in the label be left justified, right justified and be centred respectively. The following are the other methods in the Label class which are used to write and read the text value and the alignment value of a label: void settext(string s) Sets the text of a label with the string s. String gettext() Retrieves the text of a label. void setalignment(int align) Sets the alignment of the text within a label. int getalign() Returns the alignment of the text in a label. The program 17.1 illustrates the usage of a label. The code for the applet to be created to demonstrate Label control is provided in the class LabelDemo in the program. PROGRAM 17.1 To illustrate Label control import java.awt.*; import java.applet.*;

18 Basic Utility Classes [java.lang Package] 18.1 INTRODUCTION The java.lang package houses a number of classes that are of importance. Here we discuss some of the most frequently used classes and their methods in a reasonable detail. 18.2 THE WRAPPER CLASSES A Wrapper class is one which wraps a primitive type within it. As there are eight primitive types in Java, there are eight wrapper classes, one for each primitive type. They are Byte, Short, Integer, Long, Float, Double, Character and Boolean for the primitive types byte, short, int, long, float, double, char and boolean respectively. The wrapper classes provide the ability to create object representations to the primitive types. The objects of wrapper classes are immutable, i.e., the values assigned to the objects cannot be altered. 18.2.1 The Number Class The Number class is the abstract class which is used as the super class for all the wrapper classes. Table 18.1 shows the list of abstract methods available in the class which are to be implemented by the wrapper classes. Methods with their signature and purpose Methods with their signature byte bytevalue() short shortvalue() Purpose Returns the value of the specified number as a byte Returns the value of the specified number as a short value (Contd...) 555

572 Object Oriented Programming with JAVA Boolean(String str) Creates an object of Boolean class wrapping the boolean value extracted out of the argument str of String type. Example 2: Boolean bt = new Boolaen( false ); Creates the object bt of Boolean type with the boolean value false. Table 18.9 depicts the methods of the s class. Methods boolean booleanvalue() boolean equals(object bool) String tostring() Static boolean valueof(string bool) Purposes Returns the Boolean value equivalent Returns true if the invoking object is equivalent to the object bool, otherwise, it returns false Returns the string equivalent of the invoking object Returns true if the string bool contains the string either true or TRUE, otherwise it returns false The following program illustrates the Boolean class by displaying the values of the constants Boolean.TRUE, Boolean.FALSE and Boolean.TYPE to be true, false and Boolean respectively. PROGRAM 18.10 To illustrate Boolean class Output public class Boolean1 { public static void main(string s[]) { System.out.println( Boolean.TRUE = + Boolean.TRUE); System.out.println( Boolean.FALSE = + Boolean.FALSE); System.out.println( Boolean.TYPE = + Boolean.TYPE); } } Boolean.TRUE = True Boolean.FALSE = False Boolean.TYPE = Boolean 18.3 THE SYSTEM CLASS The System class is at the core of the java.lang package. It holds a number of static member methods and variables. The standard input, output and error of the Java runtime are stored

579 } Output } System.out.println( Total Memory = + tm); System.out.println( Free Memory = + fm); System.out.println( Used Space = + (tm - fm)); System.out.println( Maximum Memory = + mm); System.out.println(); Total Memory = 12189696 Free Memory = 11682696 Used Space = 507000 Maximum Memory = 192610304 18.7 THE PROCESS CLASS The Process class is an abstract class in the java.lang package. It encapsulates a process, which is a program in the status of execution. The class process acts as a super class for the objects created by the method exec() in the Runtime class of the same Java package. The Process class contains a number of abstract methods. Following are the frequently used methods of the Process class (Table 18.14). void destroy() int exitvalue() Methods InputStream getinputstream() OutputStream getoutputstream() InputStream geterrorstream() 18.8 THE VOID CLASS Purposes Terminates the process Returns the exit code obtained from a subprocess Returns an input stream that reads input from the out output stream of the process Returns an output stream that writes output to the in input stream of the process Returns an input stream that reads input from the err output stream of the process The Void class has one field namely TYPE, which holds a reference to the Class instance for the primitive type void. The Void class cannot be instantiated. 18.9 THE MATH CLASS The Math class provides a number of static methods which are used for performing various mathematical operations. Table 18.5 furnishes the commonly used ones.